diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 34ccbbf8056..871b8f40a13 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -45,7 +45,7 @@ "rollForward": true }, "fantomas": { - "version": "6.2.3", + "version": "7.0.1", "commands": [ "fantomas" ], diff --git a/.config/service-branch-merge.json b/.config/service-branch-merge.json index 0c9d996e850..49561874be8 100644 --- a/.config/service-branch-merge.json +++ b/.config/service-branch-merge.json @@ -5,6 +5,10 @@ "MergeToBranch": "main", "ExtraSwitches": "-QuietComments" }, + "release/dev17.14": { + "MergeToBranch": "release/dev18.0", + "ExtraSwitches": "-QuietComments" + }, "main": { "MergeToBranch": "release/dev17.14", "ExtraSwitches": "-QuietComments" 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": {}, diff --git a/.fantomasignore b/.fantomasignore index bae15e0668b..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,45 +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/FSharp.Compiler.LanguageServer/Common/LifecycleManager.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/.gitignore b/.gitignore index 33c9666c14b..6ca107a5779 100644 --- a/.gitignore +++ b/.gitignore @@ -134,4 +134,6 @@ positive.exe /tests/FSharp.Compiler.ComponentTests/FSharpChecker/StandardOutput.txt # ilverify baseline result files -*.bsl.actual \ No newline at end of file +*.bsl.actual +/src/FSharp.DependencyManager.Nuget/StandardError.txt +/src/FSharp.DependencyManager.Nuget/StandardOutput.txt diff --git a/Directory.Build.props b/Directory.Build.props index c4f2bff9287..141c85ff4d2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -10,11 +10,6 @@ $(DotNetBuildSourceOnly) - - - $(NoWarn);FS0064;FS1182 - - $(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/FSharp.sln b/FSharp.sln index fdf3b68cdef..094d4302e5c 100644 --- a/FSharp.sln +++ b/FSharp.sln @@ -106,6 +106,7 @@ Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Benchmarks" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D58BFE8B-7C85-4D3B-B5F3-9A7BB90FF1EE}" ProjectSection(SolutionItems) = preProject + src\Compiler\default.win32manifest = src\Compiler\default.win32manifest src\Compiler\FSComp.txt = src\Compiler\FSComp.txt src\Compiler\FSCompCheck.fsx = src\Compiler\FSCompCheck.fsx EndProjectSection diff --git a/FSharpBuild.Directory.Build.props b/FSharpBuild.Directory.Build.props index 148d9c95116..1b7ecd6fa27 100644 --- a/FSharpBuild.Directory.Build.props +++ b/FSharpBuild.Directory.Build.props @@ -27,7 +27,8 @@ $(ArtifactsDir)\SymStore $(ArtifactsDir)\Bootstrap 4.4.0 - 1182;0025;$(WarningsAsErrors) + $(WarnOn);1182 + 0025;$(WarningsAsErrors) $(OtherFlags) --nowarn:3384 $(OtherFlags) --times --nowarn:75 $(OtherFlags) $(AdditionalFscCmdFlags) diff --git a/NuGet.config b/NuGet.config index d30d1402844..944ae5b686e 100644 --- a/NuGet.config +++ b/NuGet.config @@ -8,7 +8,7 @@ - + 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 5f722b11a12..f40ab0428ed 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md +++ b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md @@ -1,4 +1,5 @@ ### Fixed +* Fix missing TailCall warning in TOp.IntegerForLoop ([PR #18399](https://github.com/dotnet/fsharp/pull/18399)) * Fix classification of `nameof` in `nameof<'T>`, `match … with nameof ident -> …`. ([Issue #10026](https://github.com/dotnet/fsharp/issues/10026), [PR #18300](https://github.com/dotnet/fsharp/pull/18300)) * Fix Realsig+ generates nested closures with incorrect Generic ([Issue #17797](https://github.com/dotnet/fsharp/issues/17797), [PR #17877](https://github.com/dotnet/fsharp/pull/17877)) * Fix optimizer internal error for records with static fields ([Issue #18165](https://github.com/dotnet/fsharp/issues/18165), [PR #18280](https://github.com/dotnet/fsharp/pull/18280)) @@ -18,6 +19,7 @@ * Miscellanous parentheses analyzer fixes. ([PR #18350](https://github.com/dotnet/fsharp/pull/18350)) * 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)) ### Added * Added missing type constraints in FCS. ([PR #18241](https://github.com/dotnet/fsharp/pull/18241)) @@ -27,10 +29,10 @@ * 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 - * FSharpCheckFileResults.ProjectContext.ProjectOptions will not be available when using the experimental Transparent Compiler feature. ([PR #18205](https://github.com/dotnet/fsharp/pull/18205)) * Update `Obsolete` attribute checking to account for `DiagnosticId` and `UrlFormat` properties. ([PR #18224](https://github.com/dotnet/fsharp/pull/18224)) * Remove `Cancellable.UsingToken` from tests ([PR #18276](https://github.com/dotnet/fsharp/pull/18276)) diff --git a/docs/release-notes/.VisualStudio/17.14.md b/docs/release-notes/.VisualStudio/17.14.md index db5d628bb0c..f9b710ea122 100644 --- a/docs/release-notes/.VisualStudio/17.14.md +++ b/docs/release-notes/.VisualStudio/17.14.md @@ -1,4 +1,5 @@ ### Fixed +* Fix #r nuget ..." downloads unneeded packages ([Issue #18231](https://github.com/dotnet/fsharp/issues/18231), [PR #18393](https://github.com/dotnet/fsharp/pull/18393)) ### Added * 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) 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...) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index d01cf73cceb..a3b61734d48 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,32 +1,32 @@ - + https://github.com/dotnet/source-build-reference-packages - 27dfbb8d8a0344d845948109a5a1f0d9c7f17fa9 + 6968f7059f4418e985febe704a3b1320f9e5887d - + https://github.com/dotnet/msbuild - a4ef1e90fef9b56473708b7d308f982c7c9f46d9 + 0ca03f84b7848ce9d7d3e5d1f68c5e090efa4f30 - + https://github.com/dotnet/msbuild - a4ef1e90fef9b56473708b7d308f982c7c9f46d9 + 0ca03f84b7848ce9d7d3e5d1f68c5e090efa4f30 - + https://github.com/dotnet/msbuild - a4ef1e90fef9b56473708b7d308f982c7c9f46d9 + 0ca03f84b7848ce9d7d3e5d1f68c5e090efa4f30 - + https://github.com/dotnet/msbuild - a4ef1e90fef9b56473708b7d308f982c7c9f46d9 + 0ca03f84b7848ce9d7d3e5d1f68c5e090efa4f30 - + https://github.com/dotnet/msbuild - a4ef1e90fef9b56473708b7d308f982c7c9f46d9 + 0ca03f84b7848ce9d7d3e5d1f68c5e090efa4f30 https://github.com/dotnet/runtime diff --git a/eng/Versions.props b/eng/Versions.props index f4b5ae88140..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 @@ -94,7 +102,7 @@ 17.10.40152 17.10.526-pre-g1b474069f5 17.10.41 - 17.13.20 + 17.13.22 $(RoslynVersion) $(RoslynVersion) @@ -130,9 +138,9 @@ 15.0.25123-Dev15Preview - 17.13.20 - 17.13.20 - 17.13.20 + 17.13.22 + 17.13.22 + 17.13.22 $(VisualStudioEditorPackagesVersion) diff --git a/global.json b/global.json index 3883eb9db41..eca327e814a 100644 --- a/global.json +++ b/global.json @@ -1,10 +1,10 @@ { "sdk": { - "version": "9.0.200", + "version": "9.0.202", "allowPrerelease": true }, "tools": { - "dotnet": "9.0.200", + "dotnet": "9.0.202", "vs": { "version": "17.8", "components": [ 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/ilnativeres.fs b/src/Compiler/AbstractIL/ilnativeres.fs index 62961613b3f..2eb03ab674e 100644 --- a/src/Compiler/AbstractIL/ilnativeres.fs +++ b/src/Compiler/AbstractIL/ilnativeres.fs @@ -83,7 +83,7 @@ type CvtResFile() = pAdditional.DataSize <- cbData pAdditional.pstringType <- CvtResFile.ReadStringOrID reader pAdditional.pstringName <- CvtResFile.ReadStringOrID reader - stream.Position <- stream.Position + 3L &&& ~~~ 3L + stream.Position <- stream.Position + 3L &&& ~~~3L pAdditional.DataVersion <- reader.ReadUInt32() pAdditional.MemoryFlags <- reader.ReadUInt16() pAdditional.LanguageId <- reader.ReadUInt16() @@ -91,7 +91,7 @@ type CvtResFile() = pAdditional.Characteristics <- reader.ReadUInt32() pAdditional.data <- Array.zeroCreate (int pAdditional.DataSize) reader.Read(pAdditional.data, 0, pAdditional.data.Length) |> ignore - stream.Position <- stream.Position + 3L &&& ~~~ 3L + stream.Position <- stream.Position + 3L &&& ~~~3L if pAdditional.pstringType.theString = Unchecked.defaultof<_> @@ -174,6 +174,7 @@ type SectionCharacteristics = type ResourceSection() = new(sectionBytes: byte[], relocations: uint32[]) as this = (ResourceSection()) + then Debug.Assert(sectionBytes :> obj <> Unchecked.defaultof<_>) Debug.Assert(relocations :> obj <> Unchecked.defaultof<_>) @@ -374,13 +375,8 @@ type VersionHelper() = /// /// True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise. static member private TryParse - ( - s: string, - allowWildcard: bool, - maxValue: uint16, - allowPartialParse: bool, - [] version: byref - ) = + (s: string, allowWildcard: bool, maxValue: uint16, allowPartialParse: bool, [] version: byref) + = Debug.Assert(not allowWildcard || maxValue < UInt16.MaxValue) if String.IsNullOrWhiteSpace s then @@ -520,20 +516,24 @@ type VersionResourceSerializer() = member val private _isDll = Unchecked.defaultof with get, set - new(isDll: bool, - comments: string, - companyName: string, - fileDescription: string, - fileVersion: string, - internalName: string, - legalCopyright: string, - legalTrademark: string, - originalFileName: string, - productName: string, - productVersion: string, - assemblyVersion: Version) as this = + new + ( + isDll: bool, + comments: string, + companyName: string, + fileDescription: string, + fileVersion: string, + internalName: string, + legalCopyright: string, + legalTrademark: string, + originalFileName: string, + productName: string, + productVersion: string, + assemblyVersion: Version + ) as this = VersionResourceSerializer() + then this._isDll <- isDll this._commentsContents <- comments @@ -620,7 +620,7 @@ type VersionResourceSerializer() = static member private PadKeyLen(cb: int) = VersionResourceSerializer.PadToDword(cb + 3 * sizeof) - 3 * sizeof - static member private PadToDword(cb: int) = cb + 3 &&& ~~~ 3 + static member private PadToDword(cb: int) = cb + 3 &&& ~~~3 static member val private HDRSIZE = (int (3 * sizeof)) with get, set @@ -667,7 +667,7 @@ type VersionResourceSerializer() = let mutable (sum: int) = 0 for verString in this.GetVerStrings() do - sum <- sum + 3 &&& ~~~ 3 + sum <- sum + 3 &&& ~~~3 sum <- sum + VersionResourceSerializer.SizeofVerString(verString.Key, verString.Value) sum @@ -801,7 +801,7 @@ type VersionResourceSerializer() = for entry in this.GetVerStrings() do let mutable writerPos = writer.BaseStream.Position - writer.Write(Array.zeroCreate (int ((writerPos + 3L) &&& ~~~ 3L - writerPos)): byte[]) + writer.Write(Array.zeroCreate (int ((writerPos + 3L) &&& ~~~3L - writerPos)): byte[]) Debug.Assert(entry.Value <> Unchecked.defaultof<_>) VersionResourceSerializer.WriteVersionString(entry, writer) @@ -861,7 +861,7 @@ type Win32ResourceConversions() = let mutable (i: uint16) = 0us while (i < count) do - resStream.Position <- resStream.Position + 3L &&& ~~~ 3L + resStream.Position <- resStream.Position + 3L &&& ~~~3L resWriter.Write iconDirEntries[(int i)].dwBytesInRes resWriter.Write 0x00000020u resWriter.Write 0xFFFFus @@ -878,7 +878,7 @@ type Win32ResourceConversions() = i <- i + 1us let mutable (RT_GROUP_ICON: WORD) = (RT_ICON + 11us) - resStream.Position <- resStream.Position + 3L &&& ~~~ 3L + resStream.Position <- resStream.Position + 3L &&& ~~~3L resWriter.Write(uint32 (3 * sizeof + int count * 14)) resWriter.Write 0x00000020u resWriter.Write 0xFFFFus @@ -933,7 +933,7 @@ type Win32ResourceConversions() = let comments = (defaultArg comments) Unchecked.defaultof<_> let companyName = (defaultArg companyName) Unchecked.defaultof<_> let mutable resWriter = new BinaryWriter(resStream, Encoding.Unicode) - resStream.Position <- resStream.Position + 3L &&& ~~~ 3L + resStream.Position <- resStream.Position + 3L &&& ~~~3L let mutable (RT_VERSION: DWORD) = 16u let mutable ver = @@ -970,7 +970,7 @@ type Win32ResourceConversions() = Debug.Assert(resStream.Position - startPos = int64 dataSize + int64 headerSize) static member AppendManifestToResourceStream(resStream: Stream, manifestStream: Stream, isDll: bool) = - resStream.Position <- resStream.Position + 3L &&& ~~~ 3L (* ERROR UnknownPrefixOperator "~" *) + resStream.Position <- resStream.Position + 3L &&& ~~~3L (* ERROR UnknownPrefixOperator "~" *) let mutable (RT_MANIFEST: WORD) = 24us let mutable resWriter = new BinaryWriter(resStream) resWriter.Write(uint32 manifestStream.Length) diff --git a/src/Compiler/AbstractIL/ilread.fs b/src/Compiler/AbstractIL/ilread.fs index 14af625419b..4f280f8ad29 100644 --- a/src/Compiler/AbstractIL/ilread.fs +++ b/src/Compiler/AbstractIL/ilread.fs @@ -4180,16 +4180,8 @@ and seekReadTopExportedTypes (ctxt: ILMetadataReader) = // Note, pectxtEager and pevEager must not be captured by the results of this function let openMetadataReader - ( - fileName, - mdfile: BinaryFile, - metadataPhysLoc, - peinfo, - pectxtEager: PEReader, - pevEager, - pectxtCaptured, - reduceMemoryUsage - ) = + (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, pectxtEager: PEReader, pevEager, pectxtCaptured, reduceMemoryUsage) + = let mdv = mdfile.GetView() let magic = seekReadUInt16AsInt32 mdv metadataPhysLoc diff --git a/src/Compiler/AbstractIL/ilreflect.fs b/src/Compiler/AbstractIL/ilreflect.fs index 45c0652c59d..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 @@ -290,10 +290,7 @@ type OpCode with member opcode.RefEmitName = match opcode.Name with | null -> "" - | name -> - (string (Char.ToUpper(name[0])) + name[1..]) - .Replace(".", "_") - .Replace("_i4", "_I4") + | name -> (string (Char.ToUpper(name[0])) + name[1..]).Replace(".", "_").Replace("_i4", "_I4") type ILGenerator with @@ -713,7 +710,7 @@ let rec convTypeSpec cenv emEnv preferCreated (tspec: ILTypeSpec) = and convTypeAux cenv emEnv preferCreated ty = match ty with - | ILType.Void -> !! Type.GetType("System.Void") + | ILType.Void -> !!Type.GetType("System.Void") | ILType.Array(shape, eltType) -> let baseT = convTypeAux cenv emEnv preferCreated eltType let nDims = shape.Rank @@ -1491,7 +1488,7 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = ilG.EmitAndLog(OpCodes.Ldelema, convType cenv emEnv ty) else let arrayTy = convType cenv emEnv (ILType.Array(shape, ty)) - let elemTy = !! arrayTy.GetElementType() + let elemTy = !!arrayTy.GetElementType() let argTys = Array.create shape.Rank typeof let retTy = elemTy.MakeByRefType() @@ -1517,7 +1514,7 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = ilG.EmitAndLog(OpCodes.Stelem, convType cenv emEnv ty) else let arrayTy = convType cenv emEnv (ILType.Array(shape, ty)) - let elemTy = !! arrayTy.GetElementType() + let elemTy = !!arrayTy.GetElementType() let meth = modB.GetArrayMethodAndLog( @@ -2497,7 +2494,7 @@ let mkDynamicAssemblyAndModule (assemblyName: string, optimize, collectible) = let daType = typeof let daCtor = - !! daType.GetConstructor([| typeof |]) + !!daType.GetConstructor([| typeof |]) let daBuilder = CustomAttributeBuilder( diff --git a/src/Compiler/AbstractIL/ilsupp.fs b/src/Compiler/AbstractIL/ilsupp.fs index 513d14d9f51..cd30137faaf 100644 --- a/src/Compiler/AbstractIL/ilsupp.fs +++ b/src/Compiler/AbstractIL/ilsupp.fs @@ -653,8 +653,7 @@ let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = for i = 0 to (nResNodes - 1) do size <- size - + pResNodes[i] - .Save(ulLinkedResourceBaseRVA, pbLinkedResource, Unchecked.defaultof, 0) + + pResNodes[i].Save(ulLinkedResourceBaseRVA, pbLinkedResource, Unchecked.defaultof, 0) let pResBuffer = Bytes.zeroCreate size @@ -670,7 +669,6 @@ let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = for i = 0 to (nResNodes - 1) do resBufferOffset <- resBufferOffset - + pResNodes[i] - .Save(ulLinkedResourceBaseRVA, pbLinkedResource, pResBuffer, resBufferOffset) + + pResNodes[i].Save(ulLinkedResourceBaseRVA, pbLinkedResource, pResBuffer, resBufferOffset) pResBuffer 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/Checking/Expressions/CheckComputationExpressions.fs b/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs index 22b603d211a..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 @@ -3083,9 +3090,7 @@ let TcComputationExpression (cenv: TcFileState) env (overallTy: OverallTy) tpenv TranslateComputationExpression ceenv CompExprTranslationPass.Initial hasCustomOperations (LazyWithContext.NotLazy([], env)) comp id let mDelayOrQuoteOrRun = - mBuilderVal - .NoteSourceConstruct(NotedSourceConstruct.DelayOrQuoteOrRun) - .MakeSynthetic() + mBuilderVal.NoteSourceConstruct(NotedSourceConstruct.DelayOrQuoteOrRun).MakeSynthetic() // Add a call to 'Delay' if the method is present let delayedExpr = diff --git a/src/Compiler/Checking/Expressions/CheckExpressions.fs b/src/Compiler/Checking/Expressions/CheckExpressions.fs index f1e6960cc21..7f1d22f0dd2 100644 --- a/src/Compiler/Checking/Expressions/CheckExpressions.fs +++ b/src/Compiler/Checking/Expressions/CheckExpressions.fs @@ -813,7 +813,7 @@ let TcConst (cenv: cenv) (overallTy: TType) m env synConst = warning(Error(FSComp.SR.tcImplicitMeasureFollowingSlash(), m)) let factor1 = ms1 |> Option.defaultValue (SynMeasure.One Range.Zero) Measure.Prod(tcMeasure factor1, Measure.Inv (tcMeasure ms2), ms.Range) - | SynMeasure.Divide(measure1 = ms1; measure2 = ms2; range= m) -> + | SynMeasure.Divide(measure1 = ms1; measure2 = ms2) -> let factor1 = ms1 |> Option.defaultValue (SynMeasure.One Range.Zero) Measure.Prod(tcMeasure factor1, Measure.Inv (tcMeasure ms2), ms.Range) | SynMeasure.Seq(mss, _) -> ProdMeasures (List.map tcMeasure mss) @@ -10686,7 +10686,7 @@ and TcMatchClauses cenv inputTy (resultTy: OverallTy) env tpenv clauses = resultList,tpEnv and TcMatchClause cenv inputTy (resultTy: OverallTy) env isFirst tpenv synMatchClause = - let (SynMatchClause(synPat, synWhenExprOpt, synResultExpr, patm, spTgt, trivia)) = synMatchClause + let (SynMatchClause(synPat, synWhenExprOpt, synResultExpr, patm, spTgt, _trivia)) = synMatchClause let isTrueMatchClause = if synMatchClause.IsTrueMatchClause then diff --git a/src/Compiler/Checking/Expressions/CheckSequenceExpressions.fs b/src/Compiler/Checking/Expressions/CheckSequenceExpressions.fs index 3c5f136d284..499ed2ca914 100644 --- a/src/Compiler/Checking/Expressions/CheckSequenceExpressions.fs +++ b/src/Compiler/Checking/Expressions/CheckSequenceExpressions.fs @@ -270,7 +270,7 @@ let TcSequenceExpression (cenv: TcFileState) env tpenv comp (overallTy: OverallT let tclauses, tpenv = (tpenv, clauses) - ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, _, sp, trivia) as clause) -> + ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, _, sp, _trivia) as clause) -> let isTrueMatchClause = if clause.IsTrueMatchClause then TcTrueMatchClause.Yes @@ -319,7 +319,7 @@ let TcSequenceExpression (cenv: TcFileState) env tpenv comp (overallTy: OverallT // Compile the pattern twice, once as a filter with all succeeding targets returning "1", and once as a proper catch block. let clauses, tpenv = (tpenv, withList) - ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, m, sp, trivia) as clause) -> + ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, m, sp, _trivia) as clause) -> let isTrueMatchClause = if clause.IsTrueMatchClause then TcTrueMatchClause.Yes diff --git a/src/Compiler/Checking/TailCallChecks.fs b/src/Compiler/Checking/TailCallChecks.fs index a7ea9ad802a..eba18dbeb4d 100644 --- a/src/Compiler/Checking/TailCallChecks.fs +++ b/src/Compiler/Checking/TailCallChecks.fs @@ -792,7 +792,12 @@ let CheckModuleBinding cenv (isRec: bool) (TBind _ as bind) = // warn for recursive calls in TryWith/TryFinally operations exprs |> Seq.iter (checkTailCall true) | Expr.Op(args = exprs) -> exprs |> Seq.iter (checkTailCall insideSubBindingOrTry) - | Expr.Sequential(expr2 = expr2) -> checkTailCall insideSubBindingOrTry expr2 + | Expr.Sequential(expr1 = expr1; expr2 = expr2) -> + match expr1 with + | Expr.Op(op = TOp.IntegerForLoop _) -> checkTailCall insideSubBindingOrTry expr1 + | _ -> () + + checkTailCall insideSubBindingOrTry expr2 | _ -> () checkTailCall false bodyExpr diff --git a/src/Compiler/Checking/infos.fs b/src/Compiler/Checking/infos.fs index 8dcc5dc8ac1..81c777c3685 100644 --- a/src/Compiler/Checking/infos.fs +++ b/src/Compiler/Checking/infos.fs @@ -1438,10 +1438,10 @@ type MethInfo = match retTy with | Some retTy -> isTyparTy g retTy | None -> false - | MethInfoWithModifiedReturnType(_,retTy) -> false + | MethInfoWithModifiedReturnType _ -> false | DefaultStructCtor _ -> false #if !NO_TYPEPROVIDERS - | ProvidedMeth(amap, mi, _, m) -> false + | ProvidedMeth _ -> false #endif /// Get the ParamData objects for the parameters of a MethInfo diff --git a/src/Compiler/CodeGen/EraseUnions.fs b/src/Compiler/CodeGen/EraseUnions.fs index e841010c837..3d5e9e4ec91 100644 --- a/src/Compiler/CodeGen/EraseUnions.fs +++ b/src/Compiler/CodeGen/EraseUnions.fs @@ -742,12 +742,14 @@ let mkMethodsAndPropertiesForFields basicProps, basicMethods let convAlternativeDef - (addMethodGeneratedAttrs, - addPropertyGeneratedAttrs, - addPropertyNeverAttrs, - addFieldGeneratedAttrs, - addFieldNeverAttrs, - mkDebuggerTypeProxyAttribute) + ( + addMethodGeneratedAttrs, + addPropertyGeneratedAttrs, + addPropertyNeverAttrs, + addFieldGeneratedAttrs, + addFieldNeverAttrs, + mkDebuggerTypeProxyAttribute + ) (g: TcGlobals) num (td: ILTypeDef) @@ -1209,7 +1211,6 @@ let convAlternativeDef let basicCtorFields = basicFields |> List.map (fun fdef -> - let existingAttrs = fdef.CustomAttrs.AsArray() let nullableAttr = getFieldsNullability g fdef |> Option.toList fdef.Name, fdef.FieldType, nullableAttr) @@ -1255,12 +1256,14 @@ let convAlternativeDef baseMakerMeths, baseMakerProps, altUniqObjMeths, typeDefs, altDebugTypeDefs, altNullaryFields let mkClassUnionDef - (addMethodGeneratedAttrs, - addPropertyGeneratedAttrs, - addPropertyNeverAttrs, - addFieldGeneratedAttrs: ILFieldDef -> ILFieldDef, - addFieldNeverAttrs: ILFieldDef -> ILFieldDef, - mkDebuggerTypeProxyAttribute) + ( + addMethodGeneratedAttrs, + addPropertyGeneratedAttrs, + addPropertyNeverAttrs, + addFieldGeneratedAttrs: ILFieldDef -> ILFieldDef, + addFieldNeverAttrs: ILFieldDef -> ILFieldDef, + mkDebuggerTypeProxyAttribute + ) (g: TcGlobals) tref (td: ILTypeDef) diff --git a/src/Compiler/CodeGen/IlxGen.fs b/src/Compiler/CodeGen/IlxGen.fs index 791fed38a3d..1be3b7be3a2 100644 --- a/src/Compiler/CodeGen/IlxGen.fs +++ b/src/Compiler/CodeGen/IlxGen.fs @@ -1510,18 +1510,7 @@ let GetMethodSpecForMemberVal cenv (memberInfo: ValMemberInfo) (vref: ValRef) = /// Determine how a top-level value is represented, when representing as a field, by computing an ILFieldSpec let ComputeFieldSpecForVal - ( - optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, - isInteractive, - g, - ilTyForProperty, - vspec: Val, - nm, - m, - cloc, - ilTy, - ilGetterMethRef - ) = + (optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, isInteractive, g, ilTyForProperty, vspec: Val, nm, m, cloc, ilTy, ilGetterMethRef) = assert vspec.IsCompiledAsTopLevel let generate () = @@ -1615,14 +1604,8 @@ let IsFSharpValCompiledAsMethod g (v: Val) = /// method (possibly and instance method). Otherwise it gets represented as a /// static field and property. let ComputeStorageForValWithValReprInfo - ( - cenv, - optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, - isInteractive, - optShadowLocal, - vref: ValRef, - cloc - ) = + (cenv, optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, isInteractive, optShadowLocal, vref: ValRef, cloc) + = if isUnitTy cenv.g vref.Type @@ -2420,9 +2403,7 @@ and AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf anonTypeTable.GrabExtraBindingsToGenerate() member _.AddTypeDef(tref: ILTypeRef, tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) = - gtdefs - .FindNestedTypeDefsBuilder(tref.Enclosing) - .AddTypeDef(tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) + gtdefs.FindNestedTypeDefsBuilder(tref.Enclosing).AddTypeDef(tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) member _.FindNestedTypeDefBuilder(tref: ILTypeRef) = gtdefs.FindNestedTypeDefBuilder(tref) @@ -5936,11 +5917,7 @@ and renameMethodDef nameOfOverridingMethod (mdef: ILMethodDef) = mdef.With(name = nameOfOverridingMethod) and fixupMethodImplFlags (mdef: ILMethodDef) = - mdef - .WithAccess(ILMemberAccess.Private) - .WithHideBySig() - .WithFinal(true) - .WithNewSlot + mdef.WithAccess(ILMemberAccess.Private).WithHideBySig().WithFinal(true).WithNewSlot and fixupStaticAbstractSlotFlags (mdef: ILMethodDef) = mdef.WithHideBySig(true) @@ -6464,15 +6441,17 @@ and GenSequenceExpr cenv (cgbuf: CodeGenBuffer) eenvouter - (nextEnumeratorValRef: ValRef, - pcvref: ValRef, - currvref: ValRef, - stateVars, - generateNextExpr, - closeExpr, - checkCloseExpr: Expr, - seqElemTy, - m) + ( + nextEnumeratorValRef: ValRef, + pcvref: ValRef, + currvref: ValRef, + stateVars, + generateNextExpr, + closeExpr, + checkCloseExpr: Expr, + seqElemTy, + m + ) sequel = @@ -6613,8 +6592,7 @@ and GenSequenceExpr |> AddNonUserCompilerGeneratedAttribs g let ilCtorBody = - mkILSimpleStorageCtor(Some ilCloBaseTy.TypeSpec, ilCloTyInner, [], [], ILMemberAccess.Assembly, None, eenvouter.imports) - .MethodBody + mkILSimpleStorageCtor(Some ilCloBaseTy.TypeSpec, ilCloTyInner, [], [], ILMemberAccess.Assembly, None, eenvouter.imports).MethodBody let cloMethods = [ @@ -6660,18 +6638,19 @@ and GenSequenceExpr /// Generate the class for a closure type definition and GenClosureTypeDefs cenv - (tref: ILTypeRef, - ilGenParams, - attrs, - ilCloAllFreeVars, - ilCloLambdas, - ilCtorBody, - mdefs, - mimpls, - ext, - ilIntfTys, - cloSpec: IlxClosureSpec option) - = + ( + tref: ILTypeRef, + ilGenParams, + attrs, + ilCloAllFreeVars, + ilCloLambdas, + ilCtorBody, + mdefs, + mimpls, + ext, + ilIntfTys, + cloSpec: IlxClosureSpec option + ) = let g = cenv.g let cloInfo = @@ -6699,8 +6678,7 @@ and GenClosureTypeDefs let cctor = mkILClassCtor (MethodBody.IL(notlazy ilCode)) let ilFieldDef = - mkILStaticField(fspec.Name, fspec.FormalType, None, None, ILMemberAccess.Assembly) - .WithInitOnly(true) + mkILStaticField(fspec.Name, fspec.FormalType, None, None, ILMemberAccess.Assembly).WithInitOnly(true) (cctor :: mdefs), [ ilFieldDef ] else @@ -6754,9 +6732,7 @@ and GenStaticDelegateClosureTypeDefs // Remove the redundant constructor. tdefs |> List.map (fun td -> - td - .WithAbstract(true) - .With(methods = mkILMethodsFromArray (td.Methods.AsArray() |> Array.filter (fun m -> not m.IsConstructor)))) + td.WithAbstract(true).With(methods = mkILMethodsFromArray (td.Methods.AsArray() |> Array.filter (fun m -> not m.IsConstructor)))) and GenGenericParams cenv eenv tps = tps |> DropErasedTypars |> List.map (GenGenericParam cenv eenv) @@ -8564,8 +8540,7 @@ and GenBindingAfterDebugPoint cenv cgbuf eenv bind isStateVar startMarkOpt = let ilMethodBody = MethodBody.IL(ilLazyCode) - (mkILStaticMethod ([], ilGetterMethSpec.Name, access, [], mkILReturn ilTy, ilMethodBody)) - .WithSpecialName + (mkILStaticMethod ([], ilGetterMethSpec.Name, access, [], mkILReturn ilTy, ilMethodBody)).WithSpecialName |> AddNonUserCompilerGeneratedAttribs g CountMethodDef() @@ -8742,8 +8717,7 @@ and GenBindingAfterDebugPoint cenv cgbuf eenv bind isStateVar startMarkOpt = let body = mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkNormalLdsfld fspec ], None, eenv.imports) - mkILStaticMethod([], ilGetterMethRef.Name, access, [], mkILReturn fty, body) - .WithSpecialName + mkILStaticMethod([], ilGetterMethRef.Name, access, [], mkILReturn fty, body).WithSpecialName cgbuf.mgbuf.AddMethodDef(ilTypeRefForProperty, getterMethod) @@ -9173,26 +9147,27 @@ and GenMethodForBinding cenv mgbuf eenv - (v: Val, - mspec, - hasWitnessEntry, - generateWitnessArgs, - access, - ctps, - mtps, - witnessInfos, - curriedArgInfos, - paramInfos, - argTys, - retInfo, - valReprInfo, - ctorThisValOpt, - baseValOpt, - methLambdaTypars, - methLambdaVars, - methLambdaBody, - returnTy) - = + ( + v: Val, + mspec, + hasWitnessEntry, + generateWitnessArgs, + access, + ctps, + mtps, + witnessInfos, + curriedArgInfos, + paramInfos, + argTys, + retInfo, + valReprInfo, + ctorThisValOpt, + baseValOpt, + methLambdaTypars, + methLambdaVars, + methLambdaBody, + returnTy + ) = let g = cenv.g let m = v.Range @@ -10181,18 +10156,8 @@ and CreatePermissionSets cenv eenv (securityAttributes: Attrib list) = /// Generate a static class at the given cloc and GenTypeDefForCompLoc - ( - cenv, - eenv, - mgbuf: AssemblyBuilder, - cloc, - hidden, - accessibility: Accessibility, - attribs, - initTrigger, - eliminateIfEmpty, - addAtEnd - ) = + (cenv, eenv, mgbuf: AssemblyBuilder, cloc, hidden, accessibility: Accessibility, attribs, initTrigger, eliminateIfEmpty, addAtEnd) + = let g = cenv.g let tref = TypeRefForCompLoc cloc @@ -10274,8 +10239,7 @@ and CodeGenInitMethod cenv (cgbuf: CodeGenBuffer) eenv tref (codeGenInitFunc: Co let ilReturn = mkILReturn ILType.Void let method = - (mkILNonGenericStaticMethod (eenv.staticInitializationName, access, [], ilReturn, ilBody)) - .WithSpecialName + (mkILNonGenericStaticMethod (eenv.staticInitializationName, access, [], ilReturn, ilBody)).WithSpecialName cgbuf.mgbuf.AddMethodDef(tref, method) CountMethodDef() @@ -12208,14 +12172,14 @@ let LookupGeneratedValue (cenv: cenv) (ctxt: ExecutionContext) eenv (v: Val) = if hasLiteralAttr then let staticTy = ctxt.LookupTypeRef fspec.DeclaringTypeRef // Checked: This FieldInfo (FieldBuilder) supports GetValue(). - (!! staticTy.GetField(fspec.Name)).GetValue(null: obj MaybeNull) + (!!staticTy.GetField(fspec.Name)).GetValue(null: obj MaybeNull) else let staticTy = ctxt.LookupTypeRef ilContainerTy.TypeRef // We can't call .Invoke on the ILMethodRef's MethodInfo, // because it is the MethodBuilder and that does not support Invoke. // Rather, we look for the getter MethodInfo from the built type and .Invoke on that. let methInfo = - !! staticTy.GetMethod(ilGetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) + !!staticTy.GetMethod(ilGetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) methInfo.Invoke(null, null) @@ -12228,7 +12192,7 @@ let LookupGeneratedValue (cenv: cenv) (ctxt: ExecutionContext) eenv (v: Val) = // because it is the MethodBuilder and that does not support Invoke. // Rather, we look for the getter MethodInfo from the built type and .Invoke on that. let methInfo = - !! staticTy.GetMethod(ilGetterMethSpec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) + !!staticTy.GetMethod(ilGetterMethSpec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) methInfo.Invoke(null, null) @@ -12255,14 +12219,14 @@ let SetGeneratedValue (ctxt: ExecutionContext) eenv isForced (v: Val) (value: ob let staticTy = ctxt.LookupTypeRef fspec.DeclaringTypeRef let fieldInfo = - !! staticTy.GetField(fspec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) + !!staticTy.GetField(fspec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) fieldInfo.SetValue(null, value) else let staticTy = ctxt.LookupTypeRef ilSetterMethRef.DeclaringTypeRef let methInfo = - !! staticTy.GetMethod(ilSetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) + !!staticTy.GetMethod(ilSetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) methInfo.Invoke(null, [| value |]) |> ignore | _ -> () diff --git a/src/Compiler/CodeGen/IlxGenSupport.fs b/src/Compiler/CodeGen/IlxGenSupport.fs index 2583e93fe79..0799dbde60a 100644 --- a/src/Compiler/CodeGen/IlxGenSupport.fs +++ b/src/Compiler/CodeGen/IlxGenSupport.fs @@ -83,12 +83,8 @@ let getFieldMemberAccess = | EncapsulatedProperties -> ILMemberAccess.Private let mkLocalPrivateAttributeWithPropertyConstructors - ( - g: TcGlobals, - name: string, - attrProperties: (string * ILType) list option, - codegenStyle: AttrDataGenerationStyle - ) = + (g: TcGlobals, name: string, attrProperties: (string * ILType) list option, codegenStyle: AttrDataGenerationStyle) + = let ilTypeRef = mkILTyRef (ILScopeRef.Local, name) let ilTy = mkILFormalNamedTy ILBoxity.AsObject ilTypeRef [] @@ -227,8 +223,7 @@ let mkLocalPrivateInt32Enum (g: TcGlobals, tref: ILTypeRef, values: (string * in |> Array.map (fun (name, value) -> mkILStaticLiteralField (name, ilType, ILFieldInit.Int32 value, None, ILMemberAccess.Public)) |> Array.append [| - (mkILInstanceField ("value__", g.ilg.typ_Int32, None, ILMemberAccess.Public)) - .WithSpecialName(true) + (mkILInstanceField ("value__", g.ilg.typ_Int32, None, ILMemberAccess.Public)).WithSpecialName(true) |] |> Array.toList @@ -290,9 +285,7 @@ let GetDynamicallyAccessedMemberTypes (g: TcGlobals) = ("Interfaces", 8192) |] - (mkLocalPrivateInt32Enum (g, tref, values)) - .WithSerializable(true) - .WithSealed(true)) + (mkLocalPrivateInt32Enum (g, tref, values)).WithSerializable(true).WithSealed(true)) ) ILType.Value(mkILNonGenericTySpec (tref)) diff --git a/src/Compiler/DependencyManager/AssemblyResolveHandler.fs b/src/Compiler/DependencyManager/AssemblyResolveHandler.fs index 1f20caa392e..75f8797341d 100644 --- a/src/Compiler/DependencyManager/AssemblyResolveHandler.fs +++ b/src/Compiler/DependencyManager/AssemblyResolveHandler.fs @@ -15,25 +15,24 @@ type AssemblyResolutionProbe = delegate of Unit -> seq /// Type that encapsulates AssemblyResolveHandler for managed packages type AssemblyResolveHandlerCoreclr(assemblyProbingPaths: AssemblyResolutionProbe option) as this = let loadContextType = - !! Type.GetType("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader", false) + !!Type.GetType("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader", false) let loadFromAssemblyPathMethod = - !! loadContextType.GetMethod("LoadFromAssemblyPath", [| typeof |]) + !!loadContextType.GetMethod("LoadFromAssemblyPath", [| typeof |]) - let eventInfo = !! loadContextType.GetEvent("Resolving") + let eventInfo = !!loadContextType.GetEvent("Resolving") let handler, defaultAssemblyLoadContext = let ti = typeof let gmi = - !! ti.GetMethod("ResolveAssemblyNetStandard", BindingFlags.Instance ||| BindingFlags.NonPublic) + !!ti.GetMethod("ResolveAssemblyNetStandard", BindingFlags.Instance ||| BindingFlags.NonPublic) let mi = gmi.MakeGenericMethod(loadContextType) let del = Delegate.CreateDelegate(!!eventInfo.EventHandlerType, this, mi) let prop = - (!! loadContextType.GetProperty("Default", BindingFlags.Static ||| BindingFlags.Public)) - .GetValue(null, null) + (!!loadContextType.GetProperty("Default", BindingFlags.Static ||| BindingFlags.Public)).GetValue(null, null) del, prop @@ -41,7 +40,7 @@ type AssemblyResolveHandlerCoreclr(assemblyProbingPaths: AssemblyResolutionProbe member _.ResolveAssemblyNetStandard (ctxt: 'T) (assemblyName: AssemblyName) : Assembly = let loadAssembly path = - !! loadFromAssemblyPathMethod.Invoke(ctxt, [| path |]) :?> Assembly + !!loadFromAssemblyPathMethod.Invoke(ctxt, [| path |]) :?> Assembly let assemblyPaths = match assemblyProbingPaths with 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.fs b/src/Compiler/DependencyManager/NativeDllResolveHandler.fs index 3c6bbe0a900..058dbedd0b7 100644 --- a/src/Compiler/DependencyManager/NativeDllResolveHandler.fs +++ b/src/Compiler/DependencyManager/NativeDllResolveHandler.fs @@ -72,9 +72,9 @@ type internal NativeDllResolveHandlerCoreClr(nativeProbingRoots: NativeResolutio let nativeLibraryTryLoad = let nativeLibraryType: Type = - !! Type.GetType("System.Runtime.InteropServices.NativeLibrary, System.Runtime.InteropServices", false) + !!Type.GetType("System.Runtime.InteropServices.NativeLibrary, System.Runtime.InteropServices", false) - !! nativeLibraryType.GetMethod("TryLoad", [| typeof; typeof.MakeByRefType() |]) + !!nativeLibraryType.GetMethod("TryLoad", [| typeof; typeof.MakeByRefType() |]) let loadNativeLibrary path = let arguments = [| path :> obj; IntPtr.Zero :> obj |] @@ -157,13 +157,12 @@ type internal NativeDllResolveHandlerCoreClr(nativeProbingRoots: NativeResolutio // netstandard 2.1 has this property, unfortunately we don't build with that yet //public event Func ResolvingUnmanagedDll let assemblyLoadContextType: Type = - !! Type.GetType("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader", false) + !!Type.GetType("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader", false) let eventInfo, handler, defaultAssemblyLoadContext = - !! assemblyLoadContextType.GetEvent("ResolvingUnmanagedDll"), + !!assemblyLoadContextType.GetEvent("ResolvingUnmanagedDll"), Func resolveUnmanagedDll, - (!! assemblyLoadContextType.GetProperty("Default", BindingFlags.Static ||| BindingFlags.Public)) - .GetValue(null, null) + (!!assemblyLoadContextType.GetProperty("Default", BindingFlags.Static ||| BindingFlags.Public)).GetValue(null, null) do eventInfo.AddEventHandler(defaultAssemblyLoadContext, handler) 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/CompilerConfig.fs b/src/Compiler/Driver/CompilerConfig.fs index cf875be4959..cccbcb15810 100644 --- a/src/Compiler/Driver/CompilerConfig.fs +++ b/src/Compiler/Driver/CompilerConfig.fs @@ -218,7 +218,7 @@ type VersionFlag = else use fs = FileSystem.OpenFileForReadShim(s) use is = new StreamReader(fs) - !! is.ReadLine() + !!is.ReadLine() | VersionNone -> "0.0.0.0" /// Represents a reference to an assembly. May be backed by a real assembly on disk, or a cross-project @@ -680,7 +680,7 @@ type TcConfigBuilder = yield! (tcConfigB.referencedDLLs - |> Seq.map (fun ref -> !! Path.GetDirectoryName(ref.Text))) + |> Seq.map (fun ref -> !!Path.GetDirectoryName(ref.Text))) tcConfigB.implicitIncludeDir } @@ -1203,7 +1203,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = ComputeMakePathAbsolute data.implicitIncludeDir primaryAssemblyFilename try - let clrRoot = Some(!! Path.GetDirectoryName(FileSystem.GetFullPathShim fileName)) + let clrRoot = Some(!!Path.GetDirectoryName(FileSystem.GetFullPathShim fileName)) clrRoot, data.legacyReferenceResolver.Impl.HighestInstalledNetFrameworkVersion() with e -> // We no longer expect the above to fail but leaving this just in case @@ -1504,7 +1504,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = /// 'framework' reference set that is potentially shared across multiple compilations. member tcConfig.IsSystemAssembly(fileName: string) = try - let dirName = !! Path.GetDirectoryName(fileName) + let dirName = !!Path.GetDirectoryName(fileName) let baseName = FileSystemUtils.fileNameWithoutExtension fileName FileSystem.FileExistsShim fileName diff --git a/src/Compiler/Driver/CompilerDiagnostics.fs b/src/Compiler/Driver/CompilerDiagnostics.fs index 7124c5ce1ac..68813e69a83 100644 --- a/src/Compiler/Driver/CompilerDiagnostics.fs +++ b/src/Compiler/Driver/CompilerDiagnostics.fs @@ -678,7 +678,7 @@ type Exception with showNullnessAnnotations = Some true } - let t1, t2, _cxs = NicePrint.minimalStringsOfTwoTypes denv ty1 ty2 + let t1, _t2, _cxs = NicePrint.minimalStringsOfTwoTypes denv ty1 ty2 os.Append(ConstraintSolverNullnessWarningEquivWithTypesE().Format t1) |> ignore @@ -721,10 +721,7 @@ type Exception with os.AppendString(SeeAlsoE().Format(stringOfRange m2)) | ConstraintSolverMissingConstraint(denv, tpr, tpc, m, m2) -> - os.AppendString( - ConstraintSolverMissingConstraintE() - .Format(NicePrint.stringOfTyparConstraint denv (tpr, tpc)) - ) + os.AppendString(ConstraintSolverMissingConstraintE().Format(NicePrint.stringOfTyparConstraint denv (tpr, tpc))) if m.StartLine <> m2.StartLine then os.AppendString(SeeAlsoE().Format(stringOfRange m)) @@ -1525,10 +1522,7 @@ type Exception with foundInContext |> ignore // suppress unused variable warning in RELEASE #endif let fix (s: string) = - s - .Replace(SR.GetString("FixKeyword"), "") - .Replace(SR.GetString("FixSymbol"), "") - .Replace(SR.GetString("FixReplace"), "") + s.Replace(SR.GetString("FixKeyword"), "").Replace(SR.GetString("FixSymbol"), "").Replace(SR.GetString("FixReplace"), "") let tokenNames = ctxt.ShiftTokens 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/Driver/CompilerOptions.fs b/src/Compiler/Driver/CompilerOptions.fs index 7c4c81efd40..cdeda6b6566 100644 --- a/src/Compiler/Driver/CompilerOptions.fs +++ b/src/Compiler/Driver/CompilerOptions.fs @@ -248,7 +248,7 @@ module ResponseFile = let data = seq { while not reader.EndOfStream do - !! reader.ReadLine() + !!reader.ReadLine() } |> Seq.choose parseLine |> List.ofSeq @@ -701,7 +701,7 @@ let SetEmbedAllSourceSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.embedAllSource <- false let setOutFileName tcConfigB (path: string) = - let outputDir = !! Path.GetDirectoryName(path) + let outputDir = !!Path.GetDirectoryName(path) tcConfigB.outputDir <- Some outputDir tcConfigB.outputFile <- Some path diff --git a/src/Compiler/Driver/CreateILModule.fs b/src/Compiler/Driver/CreateILModule.fs index 5ed836631d7..6c7dfeb31b6 100644 --- a/src/Compiler/Driver/CreateILModule.fs +++ b/src/Compiler/Driver/CreateILModule.fs @@ -523,7 +523,7 @@ module MainModuleBuilder = $"%d{fileVersionInfo.Major}.%d{fileVersionInfo.Minor}.%d{fileVersionInfo.Build}.%d{fileVersionInfo.Revision}") ("ProductVersion", productVersionString) match tcConfig.outputFile with - | Some f -> ("OriginalFilename", !! Path.GetFileName(f)) + | Some f -> ("OriginalFilename", !!Path.GetFileName(f)) | None -> () yield! FindAttribute "Comments" "System.Reflection.AssemblyDescriptionAttribute" yield! FindAttribute "FileDescription" "System.Reflection.AssemblyTitleAttribute" diff --git a/src/Compiler/Driver/FxResolver.fs b/src/Compiler/Driver/FxResolver.fs index dfeff2cabf3..5f55f6abe97 100644 --- a/src/Compiler/Driver/FxResolver.fs +++ b/src/Compiler/Driver/FxResolver.fs @@ -98,13 +98,9 @@ type internal FxResolver p.WaitForExit() #if DEBUG if workingDir.IsSome then - FileSystem - .OpenFileForWriteShim(Path.Combine(workingDir.Value, "StandardOutput.txt")) - .WriteAllLines(outputList) + FileSystem.OpenFileForWriteShim(Path.Combine(workingDir.Value, "StandardOutput.txt")).WriteAllLines(outputList) - FileSystem - .OpenFileForWriteShim(Path.Combine(workingDir.Value, "StandardError.txt")) - .WriteAllLines(errorsList) + FileSystem.OpenFileForWriteShim(Path.Combine(workingDir.Value, "StandardError.txt")).WriteAllLines(errorsList) #endif p.ExitCode, outputList.ToArray(), errorsList.ToArray() else @@ -284,10 +280,7 @@ type internal FxResolver try let asm = typeof>.Assembly - if - (!!asm.FullName) - .StartsWith("System.ValueTuple", StringComparison.OrdinalIgnoreCase) - then + if (!!asm.FullName).StartsWith("System.ValueTuple", StringComparison.OrdinalIgnoreCase) then Some asm.Location else let valueTuplePath = @@ -498,7 +491,7 @@ type internal FxResolver try if FileSystem.FileExistsShim(reference) then // Reference is a path to a file on disk - !! Path.GetFileNameWithoutExtension(reference), reference + !!Path.GetFileNameWithoutExtension(reference), reference else // Reference is a SimpleAssembly name reference, frameworkPathFromSimpleName reference diff --git a/src/Compiler/Driver/OptimizeInputs.fs b/src/Compiler/Driver/OptimizeInputs.fs index 36eae5734ce..c79af5b33bc 100644 --- a/src/Compiler/Driver/OptimizeInputs.fs +++ b/src/Compiler/Driver/OptimizeInputs.fs @@ -28,9 +28,7 @@ let PrintWholeAssemblyImplementation (tcConfig: TcConfig) outfile header expr = let fileName = outfile + ".terms" use f = - FileSystem - .OpenFileForWriteShim(fileName + "-" + string showTermFileCount + "-" + header, FileMode.Create) - .GetWriter() + FileSystem.OpenFileForWriteShim(fileName + "-" + string showTermFileCount + "-" + header, FileMode.Create).GetWriter() showTermFileCount <- showTermFileCount + 1 LayoutRender.outL f (Display.squashTo 192 (DebugPrint.implFilesL expr)) @@ -306,17 +304,8 @@ let optimizeFilesSequentially optEnv (phases: PhaseInfo[]) implFiles = results, optEnvFirstLoop let ApplyAllOptimizations - ( - tcConfig: TcConfig, - tcGlobals, - tcVal, - outfile, - importMap, - isIncrementalFragment, - optEnv, - ccu: CcuThunk, - implFiles - ) = + (tcConfig: TcConfig, tcGlobals, tcVal, outfile, importMap, isIncrementalFragment, optEnv, ccu: CcuThunk, implFiles) + = // NOTE: optEnv - threads through // // Always optimize once - the results of this step give the x-module optimization @@ -562,15 +551,7 @@ let CreateIlxAssemblyGenerator (_tcConfig: TcConfig, tcImports: TcImports, tcGlo ilxGenerator let GenerateIlxCode - ( - ilxBackend, - isInteractiveItExpr, - tcConfig: TcConfig, - topAttrs: TopAttribs, - optimizedImpls, - fragName, - ilxGenerator: IlxAssemblyGenerator - ) = + (ilxBackend, isInteractiveItExpr, tcConfig: TcConfig, topAttrs: TopAttribs, optimizedImpls, fragName, ilxGenerator: IlxAssemblyGenerator) = let mainMethodInfo = if diff --git a/src/Compiler/Driver/ParseAndCheckInputs.fs b/src/Compiler/Driver/ParseAndCheckInputs.fs index 975bfeef66f..6b7171b5697 100644 --- a/src/Compiler/Driver/ParseAndCheckInputs.fs +++ b/src/Compiler/Driver/ParseAndCheckInputs.fs @@ -352,7 +352,7 @@ type ModuleNamesDict = Map> /// Checks if a module name is already given and deduplicates the name if needed. let DeduplicateModuleName (moduleNamesDict: ModuleNamesDict) (fileName: string) (qualNameOfFile: QualifiedNameOfFile) = - let path = !! Path.GetDirectoryName(fileName) + let path = !!Path.GetDirectoryName(fileName) let path = if FileSystem.IsPathRootedShim path then @@ -433,7 +433,7 @@ let ParseInput "ParseAndCheckFile.parseFile" [| Activity.Tags.fileName, fileName - Activity.Tags.buildPhase, !! BuildPhase.Parse.ToString() + Activity.Tags.buildPhase, !!BuildPhase.Parse.ToString() Activity.Tags.userOpName, userOpName |> Option.defaultValue "" |] @@ -703,15 +703,8 @@ let checkInputFile (tcConfig: TcConfig) fileName = error (Error(FSComp.SR.buildInvalidSourceFileExtension (SanitizeFileName fileName tcConfig.implicitIncludeDir), rangeStartup)) let parseInputStreamAux - ( - tcConfig: TcConfig, - lexResourceManager, - fileName, - isLastCompiland, - diagnosticsLogger, - retryLocked, - stream: Stream - ) = + (tcConfig: TcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, retryLocked, stream: Stream) + = use reader = stream.GetReader(tcConfig.inputCodePage, retryLocked) // Set up the LexBuffer for the file @@ -722,14 +715,8 @@ let parseInputStreamAux ParseOneInputLexbuf(tcConfig, lexResourceManager, lexbuf, fileName, isLastCompiland, diagnosticsLogger) let parseInputSourceTextAux - ( - tcConfig: TcConfig, - lexResourceManager, - fileName, - isLastCompiland, - diagnosticsLogger, - sourceText: ISourceText - ) = + (tcConfig: TcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, sourceText: ISourceText) + = // Set up the LexBuffer for the file let lexbuf = UnicodeLexing.SourceTextAsLexbuf(not tcConfig.compilingFSharpCore, tcConfig.langVersion, tcConfig.strictIndentation, sourceText) @@ -751,15 +738,8 @@ let parseInputFileAux (tcConfig: TcConfig, lexResourceManager, fileName, isLastC /// Parse an input from stream let ParseOneInputStream - ( - tcConfig: TcConfig, - lexResourceManager, - fileName, - isLastCompiland, - diagnosticsLogger, - retryLocked, - stream: Stream - ) = + (tcConfig: TcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, retryLocked, stream: Stream) + = try parseInputStreamAux (tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, retryLocked, stream) with RecoverableException exn -> @@ -768,14 +748,8 @@ let ParseOneInputStream /// Parse an input from source text let ParseOneInputSourceText - ( - tcConfig: TcConfig, - lexResourceManager, - fileName, - isLastCompiland, - diagnosticsLogger, - sourceText: ISourceText - ) = + (tcConfig: TcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, sourceText: ISourceText) + = try parseInputSourceTextAux (tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, sourceText) with RecoverableException exn -> @@ -862,9 +836,11 @@ let ParseInputFiles (tcConfig: TcConfig, lexResourceManager, sourceFiles, diagno tcConfig.exiter.Exit 1 let ProcessMetaCommandsFromInput - (nowarnF: 'state -> range * string -> 'state, - hashReferenceF: 'state -> range * string * Directive -> 'state, - loadSourceF: 'state -> range * string -> unit) + ( + nowarnF: 'state -> range * string -> 'state, + hashReferenceF: 'state -> range * string * Directive -> 'state, + loadSourceF: 'state -> range * string -> unit + ) (tcConfig: TcConfigBuilder, inp: ParsedInput, pathOfMetaCommandSource, state0) = @@ -1520,16 +1496,18 @@ type NodeToTypeCheck = /// a callback functions that takes a `TcState` and will add the checked result to it. let CheckOneInputWithCallback (node: NodeToTypeCheck) - ((checkForErrors, - tcConfig: TcConfig, - tcImports: TcImports, - tcGlobals, - prefixPathOpt, - tcSink, - tcState: TcState, - input: ParsedInput, - _skipImplIfSigExists: bool): - (unit -> bool) * TcConfig * TcImports * TcGlobals * LongIdent option * TcResultsSink * TcState * ParsedInput * bool) + ( + (checkForErrors, + tcConfig: TcConfig, + tcImports: TcImports, + tcGlobals, + prefixPathOpt, + tcSink, + tcState: TcState, + input: ParsedInput, + _skipImplIfSigExists: bool): + (unit -> bool) * TcConfig * TcImports * TcGlobals * LongIdent option * TcResultsSink * TcState * ParsedInput * bool + ) : Cancellable> = cancellable { try @@ -1823,16 +1801,18 @@ let TransformDependencyGraph (graph: Graph, filePairs: FilePairMap) = /// Constructs a file dependency graph and type-checks the files in parallel where possible. let CheckMultipleInputsUsingGraphMode - ((ctok, checkForErrors, tcConfig: TcConfig, tcImports: TcImports, tcGlobals, prefixPathOpt, tcState, eagerFormat, inputs): - 'a * - (unit -> bool) * - TcConfig * - TcImports * - TcGlobals * - LongIdent option * - TcState * - (PhasedDiagnostic -> PhasedDiagnostic) * - ParsedInput list) + ( + (ctok, checkForErrors, tcConfig: TcConfig, tcImports: TcImports, tcGlobals, prefixPathOpt, tcState, eagerFormat, inputs): + 'a * + (unit -> bool) * + TcConfig * + TcImports * + TcGlobals * + LongIdent option * + TcState * + (PhasedDiagnostic -> PhasedDiagnostic) * + ParsedInput list + ) : FinalFileResult list * TcState = use cts = new CancellationTokenSource() @@ -1864,9 +1844,7 @@ let CheckMultipleInputsUsingGraphMode graph |> Graph.map (fun idx -> let friendlyFileName = - sourceFiles[idx] - .FileName.Replace(tcConfig.implicitIncludeDir, "") - .TrimStart([| '\\'; '/' |]) + sourceFiles[idx].FileName.Replace(tcConfig.implicitIncludeDir, "").TrimStart([| '\\'; '/' |]) (idx, friendlyFileName)) |> Graph.writeMermaidToFile graphFile) diff --git a/src/Compiler/Driver/ScriptClosure.fs b/src/Compiler/Driver/ScriptClosure.fs index 0e22231abb8..b97b11a8054 100644 --- a/src/Compiler/Driver/ScriptClosure.fs +++ b/src/Compiler/Driver/ScriptClosure.fs @@ -45,6 +45,9 @@ type LoadClosure = /// The resolved package references along with the ranges of the #r positions in each file. PackageReferences: (range * string list)[] + /// The raw package manager lines in the script + PackageManagerLines: Map + /// Whether we're decided to use .NET Framework analysis for this script UseDesktopFramework: bool @@ -82,7 +85,8 @@ type CodeContext = module ScriptPreprocessClosure = /// Represents an input to the closure finding process - type ClosureSource = ClosureSource of fileName: string * referenceRange: range * sourceText: ISourceText * parseRequired: bool + type ClosureSource = + | ClosureSource of fileName: string * referenceRange: range * sourceText: ISourceText * Position option * parseRequired: bool /// Represents an output of the closure finding process type ClosureFile = @@ -159,7 +163,7 @@ module ScriptPreprocessClosure = reduceMemoryUsage ) = - let projectDir = !! Path.GetDirectoryName(fileName) + let projectDir = !!Path.GetDirectoryName(fileName) let isInteractive = (codeContext = CodeContext.CompilationAndEvaluation) let isInvalidationSupported = (codeContext = CodeContext.Editing) @@ -253,18 +257,14 @@ module ScriptPreprocessClosure = | Some(n: int) -> new StreamReader(stream, Encoding.GetEncoding n) let source = reader.ReadToEnd() - [ ClosureSource(fileName, m, SourceText.ofString source, parseRequired) ] + [ ClosureSource(fileName, m, SourceText.ofString source, None, parseRequired) ] with RecoverableException exn -> errorRecovery exn m [] let ApplyMetaCommandsFromInputToTcConfigAndGatherNoWarn - ( - tcConfig: TcConfig, - inp: ParsedInput, - pathOfMetaCommandSource, - dependencyProvider - ) = + (tcConfig: TcConfig, inp: ParsedInput, pathOfMetaCommandSource, dependencyProvider) + = let tcConfigB = tcConfig.CloneToBuilder() let mutable nowarns = [] @@ -313,16 +313,25 @@ module ScriptPreprocessClosure = let packageReferences = Dictionary(HashIdentity.Structural) // Resolve the packages - let rec resolveDependencyManagerSources scriptName = + let rec resolveDependencyManagerSources scriptName (caret: Position option) = + let caretLine = + match caret with + | None -> Int32.MinValue + | Some pos -> pos.Line + + let isEditorCursorInPackageLines (line: PackageManagerLine) = + caretLine >= line.Range.StartLine && caretLine <= line.Range.EndLine + [ if not (loadScripts.Contains scriptName) then for kv in tcConfig.packageManagerLines do let packageManagerKey, packageManagerLines = kv.Key, kv.Value - match packageManagerLines with + match packageManagerLines |> List.filter (not << isEditorCursorInPackageLines) with | [] -> () | packageManagerLine :: _ -> let m = packageManagerLine.Range + let packageManagerLines = packageManagerLines yield! processPackageManagerLines m packageManagerLines scriptName packageManagerKey ] @@ -426,7 +435,7 @@ module ScriptPreprocessClosure = let scriptText = stream.ReadAllText() loadScripts.Add script |> ignore let iSourceText = SourceText.ofString scriptText - yield! processClosureSource (ClosureSource(script, m, iSourceText, true)) + yield! processClosureSource (ClosureSource(script, m, iSourceText, None, true)) else // Send outputs via diagnostics @@ -443,7 +452,7 @@ module ScriptPreprocessClosure = tcConfig <- TcConfig.Create(tcConfigB, validate = false) ] - and processClosureSource (ClosureSource(fileName, m, sourceText, parseRequired)) = + and processClosureSource (ClosureSource(fileName, m, sourceText, caret, parseRequired)) = [ if not (observedSources.HaveSeen(fileName)) then observedSources.SetSeen(fileName) @@ -460,7 +469,7 @@ module ScriptPreprocessClosure = let diagnosticsLogger = CapturingDiagnosticsLogger("FindClosureMetaCommands") use _ = UseDiagnosticsLogger diagnosticsLogger - let pathOfMetaCommandSource = !! Path.GetDirectoryName(fileName) + let pathOfMetaCommandSource = !!Path.GetDirectoryName(fileName) let preSources = tcConfig.GetAvailableLoadedSources() let tcConfigResult, noWarns = @@ -473,7 +482,7 @@ module ScriptPreprocessClosure = tcConfig <- tcConfigResult // We accumulate the tcConfig in order to collect assembly references - yield! resolveDependencyManagerSources fileName + yield! resolveDependencyManagerSources fileName caret let postSources = tcConfig.GetAvailableLoadedSources() @@ -483,7 +492,7 @@ module ScriptPreprocessClosure = else [] - yield! resolveDependencyManagerSources fileName + yield! resolveDependencyManagerSources fileName caret for m, subFile in sources do if IsScript subFile then @@ -540,7 +549,7 @@ module ScriptPreprocessClosure = | _ -> lastClosureFile /// Reduce the full directive closure into LoadClosure - let GetLoadClosure (rootFilename, closureFiles, tcConfig: TcConfig, codeContext, packageReferences, earlierDiagnostics) = + let GetLoadClosure (rootFilename, closureFiles, tcConfig: TcConfig, codeContext, packageReferences, earlierDiagnostics) : LoadClosure = // Mark the last file as isLastCompiland. let closureFiles = @@ -612,23 +621,21 @@ module ScriptPreprocessClosure = // Filter out non-root errors and warnings let allRootDiagnostics = allRootDiagnostics |> List.filter (fst >> isRootRange) - let result: LoadClosure = - { - SourceFiles = List.groupBy fst sourceFiles |> List.map (map2Of2 (List.map snd)) - References = List.groupBy fst references |> List.map (map2Of2 (List.map snd)) - PackageReferences = packageReferences - UseDesktopFramework = (tcConfig.primaryAssembly = PrimaryAssembly.Mscorlib) - SdkDirOverride = tcConfig.sdkDirOverride - UnresolvedReferences = unresolvedReferences - Inputs = sourceInputs - NoWarns = List.groupBy fst globalNoWarns |> List.map (map2Of2 (List.map snd)) - OriginalLoadReferences = tcConfig.loadedSources - ResolutionDiagnostics = resolutionDiagnostics - AllRootFileDiagnostics = allRootDiagnostics - LoadClosureRootFileDiagnostics = loadClosureRootDiagnostics - } - - result + { + SourceFiles = List.groupBy fst sourceFiles |> List.map (map2Of2 (List.map snd)) + References = List.groupBy fst references |> List.map (map2Of2 (List.map snd)) + PackageReferences = packageReferences + PackageManagerLines = tcConfig.packageManagerLines + UseDesktopFramework = (tcConfig.primaryAssembly = PrimaryAssembly.Mscorlib) + SdkDirOverride = tcConfig.sdkDirOverride + UnresolvedReferences = unresolvedReferences + Inputs = sourceInputs + NoWarns = List.groupBy fst globalNoWarns |> List.map (map2Of2 (List.map snd)) + OriginalLoadReferences = tcConfig.loadedSources + ResolutionDiagnostics = resolutionDiagnostics + AllRootFileDiagnostics = allRootDiagnostics + LoadClosureRootFileDiagnostics = loadClosureRootDiagnostics + } /// Given source text, find the full load closure. Used from service.fs, when editing a script file let GetFullClosureOfScriptText @@ -637,6 +644,7 @@ module ScriptPreprocessClosure = defaultFSharpBinariesDir, fileName, sourceText, + caret, codeContext, useSimpleResolution, useFsiAuxLib, @@ -649,7 +657,6 @@ module ScriptPreprocessClosure = reduceMemoryUsage, dependencyProvider ) = - // Resolve the basic references such as FSharp.Core.dll first, before processing any #I directives in the script // // This is tries to mimic the action of running the script in F# Interactive - the initial context for scripting is created @@ -700,7 +707,7 @@ module ScriptPreprocessClosure = reduceMemoryUsage ) - let closureSources = [ ClosureSource(fileName, range0, sourceText, true) ] + let closureSources = [ ClosureSource(fileName, range0, sourceText, caret, true) ] let closureFiles, tcConfig, packageReferences = FindClosureFiles(fileName, closureSources, tcConfig, codeContext, lexResourceManager, dependencyProvider) @@ -710,13 +717,8 @@ module ScriptPreprocessClosure = /// Given source file fileName, find the full load closure /// Used from fsi.fs and fsc.fs, for #load and command line let GetFullClosureOfScriptFiles - ( - tcConfig: TcConfig, - files: (string * range) list, - codeContext, - lexResourceManager: Lexhelp.LexResourceManager, - dependencyProvider - ) = + (tcConfig: TcConfig, files: (string * range) list, codeContext, lexResourceManager: Lexhelp.LexResourceManager, dependencyProvider) + = let mainFile, _mainFileRange = List.last files @@ -742,6 +744,7 @@ type LoadClosure with defaultFSharpBinariesDir, fileName: string, sourceText: ISourceText, + caret: Position option, implicitDefines, useSimpleResolution: bool, useFsiAuxLib, @@ -762,6 +765,7 @@ type LoadClosure with defaultFSharpBinariesDir, fileName, sourceText, + caret, implicitDefines, useSimpleResolution, useFsiAuxLib, diff --git a/src/Compiler/Driver/ScriptClosure.fsi b/src/Compiler/Driver/ScriptClosure.fsi index 6f764b299a9..249885036cd 100644 --- a/src/Compiler/Driver/ScriptClosure.fsi +++ b/src/Compiler/Driver/ScriptClosure.fsi @@ -42,6 +42,9 @@ type LoadClosure = /// The resolved package references along with the ranges of the #r positions in each file. PackageReferences: (range * string list)[] + /// The raw package manager lines in the script + PackageManagerLines: Map + /// Whether we're decided to use .NET Framework analysis for this script UseDesktopFramework: bool @@ -80,6 +83,7 @@ type LoadClosure = defaultFSharpBinariesDir: string * fileName: string * sourceText: ISourceText * + caret: Position option * implicitDefines: CodeContext * useSimpleResolution: bool * useFsiAuxLib: bool * diff --git a/src/Compiler/Driver/StaticLinking.fs b/src/Compiler/Driver/StaticLinking.fs index 53916744622..3624ecef9b2 100644 --- a/src/Compiler/Driver/StaticLinking.fs +++ b/src/Compiler/Driver/StaticLinking.fs @@ -104,13 +104,8 @@ let debugStaticLinking = isEnvVarSet "FSHARP_DEBUG_STATIC_LINKING" #endif let StaticLinkILModules - ( - tcConfig: TcConfig, - ilGlobals, - tcImports, - ilxMainModule, - dependentILModules: (CcuThunk option * ILModuleDef) list - ) = + (tcConfig: TcConfig, ilGlobals, tcImports, ilxMainModule, dependentILModules: (CcuThunk option * ILModuleDef) list) + = if isNil dependentILModules then ilxMainModule, id else diff --git a/src/Compiler/Driver/fsc.fs b/src/Compiler/Driver/fsc.fs index 0e26f2db4ac..3518d9d4884 100644 --- a/src/Compiler/Driver/fsc.fs +++ b/src/Compiler/Driver/fsc.fs @@ -139,18 +139,8 @@ let AbortOnError (diagnosticsLogger: DiagnosticsLogger, exiter: Exiter) = exiter.Exit 1 let TypeCheck - ( - ctok, - tcConfig, - tcImports, - tcGlobals, - diagnosticsLogger: DiagnosticsLogger, - assemblyName, - tcEnv0, - openDecls0, - inputs, - exiter: Exiter - ) = + (ctok, tcConfig, tcImports, tcGlobals, diagnosticsLogger: DiagnosticsLogger, assemblyName, tcEnv0, openDecls0, inputs, exiter: Exiter) + = try if isNil inputs then error (Error(FSComp.SR.fscNoImplementationFiles (), rangeStartup)) @@ -346,9 +336,7 @@ module InterfaceFileWriter = if String.IsNullOrEmpty(tcConfig.printSignatureFile) then Console.Out else - FileSystem - .OpenFileForWriteShim(tcConfig.printSignatureFile, FileMode.Create) - .GetWriter() + FileSystem.OpenFileForWriteShim(tcConfig.printSignatureFile, FileMode.Create).GetWriter() writeHeader tcConfig.printSignatureFile os @@ -367,7 +355,7 @@ module InterfaceFileWriter = let writeToSeparateFiles (declaredImpls: CheckedImplFile list) = for CheckedImplFile(qualifiedNameOfFile = name) as impl in declaredImpls do let fileName = - !! Path.ChangeExtension(name.Range.FileName, extensionForFile name.Range.FileName) + !!Path.ChangeExtension(name.Range.FileName, extensionForFile name.Range.FileName) printfn "writing impl file to %s" fileName use os = FileSystem.OpenFileForWriteShim(fileName, FileMode.Create).GetWriter() @@ -388,7 +376,7 @@ module InterfaceFileWriter = // 2) If not, but FSharp.Core.dll exists beside the compiler binaries, it will copy it to output directory. // 3) If not, it will produce an error. let CopyFSharpCore (outFile: string, referencedDlls: AssemblyReference list) = - let outDir = !! Path.GetDirectoryName(outFile) + let outDir = !!Path.GetDirectoryName(outFile) let fsharpCoreAssemblyName = GetFSharpCoreLibraryName() + ".dll" let fsharpCoreDestinationPath = Path.Combine(outDir, fsharpCoreAssemblyName) @@ -408,7 +396,7 @@ let CopyFSharpCore (outFile: string, referencedDlls: AssemblyReference list) = | Some referencedFsharpCoreDll -> copyFileIfDifferent referencedFsharpCoreDll.Text fsharpCoreDestinationPath | None -> let executionLocation = Assembly.GetExecutingAssembly().Location - let compilerLocation = !! Path.GetDirectoryName(executionLocation) + let compilerLocation = !!Path.GetDirectoryName(executionLocation) let compilerFsharpCoreDllPath = Path.Combine(compilerLocation, fsharpCoreAssemblyName) diff --git a/src/Compiler/FSharp.Compiler.Service.fsproj b/src/Compiler/FSharp.Compiler.Service.fsproj index 59c316483af..30d3d918fde 100644 --- a/src/Compiler/FSharp.Compiler.Service.fsproj +++ b/src/Compiler/FSharp.Compiler.Service.fsproj @@ -10,12 +10,11 @@ $(NoWarn);75 $(NoWarn);1204 $(NoWarn);NU5125 - $(NoWarn);64;1182;1204 - $(OtherFlags) --warnaserror-:1182 + $(NoWarn);64;1204 FSharp.Compiler.Service true $(DefineConstants);COMPILER - true + enable - $(FSharpNetCoreProductDefaultTargetFramework);$(TargetFrameworks) + $(FSharpNetCoreProductTargetFramework);$(TargetFrameworks) $(DefineConstants);FSHARPCORE_USE_PACKAGE $(OtherFlags) --extraoptimizationloops:1 - - - - $(OtherFlags) --nowarn:1182 - $(OtherFlags) --warnon:3218 $(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 ec2ff8def2a..ac52eaf8607 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) |> Option.ofObj |> Option.defaultValue "" + 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,20 +179,22 @@ 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" + let _name = defaultArg name "N/A" let cancelUnawaitedJobs = defaultArg cancelUnawaitedJobs true let cancelDuplicateRunningJobs = defaultArg cancelDuplicateRunningJobs false 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,36 +224,42 @@ 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 { let otherVersions, job = lock cache getOrAdd @@ -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/Facilities/CompilerLocation.fs b/src/Compiler/Facilities/CompilerLocation.fs index 2e9137fc75d..7d902aefc27 100644 --- a/src/Compiler/Facilities/CompilerLocation.fs +++ b/src/Compiler/Facilities/CompilerLocation.fs @@ -14,9 +14,7 @@ open Internal.Utilities.Library module internal FSharpEnvironment = - type private TypeInThisAssembly = - class - end + type private TypeInThisAssembly = class end /// The F# version reported in the banner let FSharpBannerVersion = @@ -90,7 +88,7 @@ module internal FSharpEnvironment = let fallback () = let d = Assembly.GetExecutingAssembly() - Some(!! Path.GetDirectoryName(d.Location)) + Some(!!Path.GetDirectoryName(d.Location)) match tryCurrentDomain () with | None -> fallback () @@ -171,12 +169,8 @@ module internal FSharpEnvironment = } let getTypeProviderAssembly - ( - runTimeAssemblyFileName: string, - designTimeAssemblyName: string, - compilerToolPaths: string list, - raiseError - ) = + (runTimeAssemblyFileName: string, designTimeAssemblyName: string, compilerToolPaths: string list, raiseError) + = // Find and load the designer assembly for the type provider component. // We look in the directories stepping up from the location of the runtime assembly. let loadFromLocation designTimeAssemblyPath = @@ -213,7 +207,7 @@ module internal FSharpEnvironment = | Some res -> loadFromLocation res | None -> // The search failed, just load from the first location and report an error - let runTimeAssemblyPath = !! Path.GetDirectoryName(runTimeAssemblyFileName) + let runTimeAssemblyPath = !!Path.GetDirectoryName(runTimeAssemblyFileName) loadFromLocation (Path.Combine(runTimeAssemblyPath, designTimeAssemblyName)) if designTimeAssemblyName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) then @@ -224,7 +218,7 @@ module internal FSharpEnvironment = // design-time DLLs specified using "x.DesignTIme, Version= ..." long assembly names and GAC loads. // These kind of design-time assembly specifications are no longer used to our knowledge so that comparison is basically legacy // and will always succeed. - let name = AssemblyName(!! Path.GetFileNameWithoutExtension(designTimeAssemblyName)) + let name = AssemblyName(!!Path.GetFileNameWithoutExtension(designTimeAssemblyName)) if name.FullName.Equals(name.Name, StringComparison.OrdinalIgnoreCase) then let designTimeFileName = designTimeAssemblyName + ".dll" @@ -276,7 +270,7 @@ module internal FSharpEnvironment = // Must be alongside the location of FSharp.CompilerService.dll let getDefaultFsiLibraryLocation () = - Path.Combine(!! Path.GetDirectoryName(getFSharpCompilerLocation ()), fsiLibraryName + ".dll") + Path.Combine(!!Path.GetDirectoryName(getFSharpCompilerLocation ()), fsiLibraryName + ".dll") let isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) @@ -355,12 +349,12 @@ module internal FSharpEnvironment = [| match getDotnetHostPath (), getDotnetGlobalHostPath () with | Some hostPath, Some globalHostPath -> - yield !! Path.GetDirectoryName(hostPath) + yield !!Path.GetDirectoryName(hostPath) if isDotnetMultilevelLookup && hostPath <> globalHostPath then - yield !! Path.GetDirectoryName(globalHostPath) - | Some hostPath, None -> yield !! Path.GetDirectoryName(hostPath) - | None, Some globalHostPath -> yield !! Path.GetDirectoryName(globalHostPath) + yield !!Path.GetDirectoryName(globalHostPath) + | Some hostPath, None -> yield !!Path.GetDirectoryName(hostPath) + | None, Some globalHostPath -> yield !!Path.GetDirectoryName(globalHostPath) | None, None -> () |] diff --git a/src/Compiler/Facilities/DiagnosticsLogger.fs b/src/Compiler/Facilities/DiagnosticsLogger.fs index e5869fe04b2..eb96a5f6e0b 100644 --- a/src/Compiler/Facilities/DiagnosticsLogger.fs +++ b/src/Compiler/Facilities/DiagnosticsLogger.fs @@ -435,8 +435,7 @@ module DiagnosticsLoggerExtensions = try if not tryAndDetectDev15 then let preserveStackTrace = - !!typeof - .GetMethod("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) + !!typeof.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) preserveStackTrace.Invoke(exn, null) |> ignore with _ -> diff --git a/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs b/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs index c9f84390367..dc0e30cac72 100644 --- a/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs +++ b/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs @@ -82,7 +82,7 @@ let private SimulatedMSBuildResolver = if Environment.OSVersion.Platform = PlatformID.Win32NT then let PF = match Environment.GetEnvironmentVariable("ProgramFiles(x86)") with - | null -> !! Environment.GetEnvironmentVariable("ProgramFiles") // if PFx86 is null, then we are 32-bit and just get PF + | null -> !!Environment.GetEnvironmentVariable("ProgramFiles") // if PFx86 is null, then we are 32-bit and just get PF | s -> s PF + @"\Reference Assemblies\Microsoft\Framework\.NETFramework" @@ -150,7 +150,7 @@ let private SimulatedMSBuildResolver = let fscoreDir0 = let PF = match Environment.GetEnvironmentVariable("ProgramFiles(x86)") with - | null -> !! Environment.GetEnvironmentVariable("ProgramFiles") + | null -> !!Environment.GetEnvironmentVariable("ProgramFiles") | s -> s PF @@ -198,7 +198,7 @@ let private SimulatedMSBuildResolver = let netFx = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() let gac = - Path.Combine(!! Path.GetDirectoryName(Path.GetDirectoryName(netFx.TrimEnd('\\'))), "assembly") + Path.Combine(!!Path.GetDirectoryName(Path.GetDirectoryName(netFx.TrimEnd('\\'))), "assembly") match n.Version, n.GetPublicKeyToken() with | null, _ diff --git a/src/Compiler/Facilities/prim-lexing.fs b/src/Compiler/Facilities/prim-lexing.fs index c305052587c..381e11eaa3a 100644 --- a/src/Compiler/Facilities/prim-lexing.fs +++ b/src/Compiler/Facilities/prim-lexing.fs @@ -192,7 +192,7 @@ module SourceTextNew = member _.GetChecksum() = // TODO: something better... - !! sourceText.ToString() + !!sourceText.ToString() |> Md5Hasher.hashString |> fun byteArray -> ImmutableArray.Create(byteArray, 0, byteArray.Length) } @@ -356,12 +356,8 @@ and [] internal LexBuffer<'Char> FSharp.Compiler.DiagnosticsLogger.checkLanguageFeatureAndRecover langVersion featureId range static member FromFunction - ( - reportLibraryOnlyFeatures, - langVersion, - strictIndentation, - f: 'Char[] * int * int -> int - ) : LexBuffer<'Char> = + (reportLibraryOnlyFeatures, langVersion, strictIndentation, f: 'Char[] * int * int -> int) + : LexBuffer<'Char> = let extension = Array.zeroCreate 4096 let filler (lexBuffer: LexBuffer<'Char>) = @@ -385,8 +381,7 @@ and [] internal LexBuffer<'Char> static member FromArray(reportLibraryOnlyFeatures, langVersion, strictIndentation, s: 'Char[]) : LexBuffer<'Char> = let buffer = Array.copy s - LexBuffer<'Char> - .FromArrayNoCopy(reportLibraryOnlyFeatures, langVersion, strictIndentation, buffer) + LexBuffer<'Char>.FromArrayNoCopy(reportLibraryOnlyFeatures, langVersion, strictIndentation, buffer) // Important: This method takes ownership of the array static member FromChars(reportLibraryOnlyFeatures, langVersion, strictIndentation, arr: char[]) = diff --git a/src/Compiler/Interactive/fsi.fs b/src/Compiler/Interactive/fsi.fs index eaba5aa6582..78d5cb94dcd 100644 --- a/src/Compiler/Interactive/fsi.fs +++ b/src/Compiler/Interactive/fsi.fs @@ -128,7 +128,7 @@ module internal Utilities = } else let specialized = typedefof>.MakeGenericType [| ty |] - !! Activator.CreateInstance(specialized) :?> IAnyToLayoutCall + !!Activator.CreateInstance(specialized) :?> IAnyToLayoutCall let callStaticMethod (ty: Type) name args = ty.InvokeMember( @@ -395,7 +395,7 @@ type ILMultiInMemoryAssemblyEmitEnv and convTypeAux ty = match ty with - | ILType.Void -> !! Type.GetType("System.Void") + | ILType.Void -> !!Type.GetType("System.Void") | ILType.Array(shape, eltType) -> let baseT = convTypeAux eltType @@ -442,7 +442,7 @@ type ILMultiInMemoryAssemblyEmitEnv let ltref = mkRefForNestedILTypeDef ILScopeRef.Local (enc, tdef) let tref = mkRefForNestedILTypeDef ilScopeRef (enc, tdef) let key = tref.BasicQualifiedName - let typ = !! asm.GetType(key) + let typ = !!asm.GetType(key) //printfn "Adding %s --> %s" key typ.FullName let rtref = rescopeILTypeRef dynamicCcuScopeRef tref typeMap.Add(ltref, (typ, tref)) @@ -1581,7 +1581,7 @@ let rec ConvReflectionTypeToILType (reflectionTy: Type) = let elementOrItemTref = if reflectionTy.HasElementType then - !! reflectionTy.GetElementType() + !!reflectionTy.GetElementType() else reflectionTy |> ConvReflectionTypeToILTypeRef @@ -1904,7 +1904,7 @@ type internal FsiDynamicCompiler if edef.ArgCount = 0 then yield (fun () -> - let typ = !! asm.GetType(edef.DeclaringTypeRef.BasicQualifiedName) + let typ = !!asm.GetType(edef.DeclaringTypeRef.BasicQualifiedName) try ignore ( @@ -2438,14 +2438,8 @@ type internal FsiDynamicCompiler /// Evaluate the given definitions and produce a new interactive state. member _.EvalParsedDefinitions - ( - ctok, - diagnosticsLogger: DiagnosticsLogger, - istate, - showTypes, - isInteractiveItExpr, - defs: SynModuleDecl list - ) = + (ctok, diagnosticsLogger: DiagnosticsLogger, istate, showTypes, isInteractiveItExpr, defs: SynModuleDecl list) + = let fileName = stdinMockFileName let m = @@ -2681,12 +2675,8 @@ type internal FsiDynamicCompiler member _.HasDelayedDependencyManagerText = hasDelayedDependencyManagerText member fsiDynamicCompiler.ProcessDelayedDependencyManagerText - ( - ctok, - istate: FsiDynamicCompilerState, - lexResourceManager, - diagnosticsLogger - ) = + (ctok, istate: FsiDynamicCompilerState, lexResourceManager, diagnosticsLogger) + = if not hasDelayedDependencyManagerText then istate else @@ -2828,12 +2818,8 @@ type internal FsiDynamicCompiler /// Scrape #r, #I and package manager commands from a #load member fsiDynamicCompiler.ProcessMetaCommandsFromParsedInputAsInteractiveCommands - ( - ctok, - istate: FsiDynamicCompilerState, - sourceFile, - input - ) = + (ctok, istate: FsiDynamicCompilerState, sourceFile, input) + = WithImplicitHome (tcConfigB, directoryName sourceFile) (fun () -> ProcessMetaCommandsFromInput ((fun st (m, nm) -> @@ -2845,7 +2831,7 @@ type internal FsiDynamicCompiler st), (fun _ _ -> ())) - (tcConfigB, input, !! Path.GetDirectoryName(sourceFile), istate)) + (tcConfigB, input, !!Path.GetDirectoryName(sourceFile), istate)) member fsiDynamicCompiler.EvalSourceFiles(ctok, istate, m, sourceFiles, lexResourceManager, diagnosticsLogger: DiagnosticsLogger) = let tcConfig = TcConfig.Create(tcConfigB, validate = false) @@ -4468,11 +4454,8 @@ let internal SpawnThread name f = th.Start() let internal SpawnInteractiveServer - ( - fsi: FsiEvaluationSessionHostConfig, - fsiOptions: FsiCommandLineOptions, - fsiConsoleOutput: FsiConsoleOutput - ) = + (fsi: FsiEvaluationSessionHostConfig, fsiOptions: FsiCommandLineOptions, fsiConsoleOutput: FsiConsoleOutput) + = //printf "Spawning fsi server on channel '%s'" !fsiServerName; SpawnThread "ServerThread" (fun () -> use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID @@ -4486,11 +4469,8 @@ let internal SpawnInteractiveServer /// /// This gives us a last chance to catch an abort on the main execution thread. let internal DriveFsiEventLoop - ( - fsi: FsiEvaluationSessionHostConfig, - fsiInterruptController: FsiInterruptController, - fsiConsoleOutput: FsiConsoleOutput - ) = + (fsi: FsiEvaluationSessionHostConfig, fsiInterruptController: FsiInterruptController, fsiConsoleOutput: FsiConsoleOutput) + = if progress then fprintfn fsiConsoleOutput.Out "GUI thread runLoop" @@ -4770,7 +4750,7 @@ type FsiEvaluationSession let makeNestedException (userExn: #Exception) = // clone userExn -- make userExn the inner exception, to retain the stacktrace on raise let arguments = [| userExn.Message :> obj; userExn :> obj |] - !! Activator.CreateInstance(userExn.GetType(), arguments) :?> Exception + !!Activator.CreateInstance(userExn.GetType(), arguments) :?> Exception let commitResult res = match res with diff --git a/src/Compiler/Service/BackgroundCompiler.fs b/src/Compiler/Service/BackgroundCompiler.fs index 329fd21c63d..5eb8bd35f99 100644 --- a/src/Compiler/Service/BackgroundCompiler.fs +++ b/src/Compiler/Service/BackgroundCompiler.fs @@ -112,6 +112,7 @@ type internal IBackgroundCompiler = abstract member GetProjectOptionsFromScript: fileName: string * sourceText: ISourceText * + caret: Position option * previewEnabled: bool option * loadedTimeStamp: System.DateTime option * otherFlags: string array option * @@ -126,6 +127,7 @@ type internal IBackgroundCompiler = abstract GetProjectSnapshotFromScript: fileName: string * sourceText: ISourceTextNew * + caret: Position option * documentSource: DocumentSource * previewEnabled: bool option * loadedTimeStamp: System.DateTime option * @@ -578,14 +580,8 @@ type internal BackgroundCompiler res) member _.ParseFile - ( - fileName: string, - sourceText: ISourceText, - options: FSharpParsingOptions, - cache: bool, - flatErrors: bool, - userOpName: string - ) = + (fileName: string, sourceText: ISourceText, options: FSharpParsingOptions, cache: bool, flatErrors: bool, userOpName: string) + = async { use _ = Activity.start @@ -781,14 +777,8 @@ type internal BackgroundCompiler /// Type-check the result obtained by parsing, but only if the antecedent type checking context is available. member bc.CheckFileInProjectAllowingStaleCachedResults - ( - parseResults: FSharpParseFileResults, - fileName, - fileVersion, - sourceText: ISourceText, - options, - userOpName - ) = + (parseResults: FSharpParseFileResults, fileName, fileVersion, sourceText: ISourceText, options, userOpName) + = async { use _ = Activity.start @@ -841,14 +831,8 @@ type internal BackgroundCompiler /// Type-check the result obtained by parsing. Force the evaluation of the antecedent type checking context if needed. member bc.CheckFileInProject - ( - parseResults: FSharpParseFileResults, - fileName, - fileVersion, - sourceText: ISourceText, - options, - userOpName - ) = + (parseResults: FSharpParseFileResults, fileName, fileVersion, sourceText: ISourceText, options, userOpName) + = async { use _ = Activity.start @@ -890,13 +874,8 @@ type internal BackgroundCompiler /// Parses and checks the source file and returns untyped AST and check results. member bc.ParseAndCheckFileInProject - ( - fileName: string, - fileVersion, - sourceText: ISourceText, - options: FSharpProjectOptions, - userOpName - ) = + (fileName: string, fileVersion, sourceText: ISourceText, options: FSharpProjectOptions, userOpName) + = async { use _ = Activity.start @@ -1090,13 +1069,8 @@ type internal BackgroundCompiler } member _.FindReferencesInFile - ( - fileName: string, - options: FSharpProjectOptions, - symbol: FSharpSymbol, - canInvalidateProject: bool, - userOpName: string - ) = + (fileName: string, options: FSharpProjectOptions, symbol: FSharpSymbol, canInvalidateProject: bool, userOpName: string) + = async { use _ = Activity.start @@ -1150,12 +1124,8 @@ type internal BackgroundCompiler /// Try to get recent approximate type check results for a file. member _.TryGetRecentCheckResultsForFile - ( - fileName: string, - options: FSharpProjectOptions, - sourceText: ISourceText option, - _userOpName: string - ) = + (fileName: string, options: FSharpProjectOptions, sourceText: ISourceText option, _userOpName: string) + = use _ = Activity.start "BackgroundCompiler.GetSemanticClassificationForFile" @@ -1308,6 +1278,7 @@ type internal BackgroundCompiler ( fileName, sourceText, + caret, previewEnabled, loadedTimeStamp, otherFlags, @@ -1358,6 +1329,7 @@ type internal BackgroundCompiler FSharpCheckerResultsSettings.defaultFSharpBinariesDir, fileName, sourceText, + caret, CodeContext.Editing, useSimpleResolution, useFsiAuxLib, @@ -1539,13 +1511,8 @@ type internal BackgroundCompiler member _.FileParsed: IEvent = self.FileParsed member _.FindReferencesInFile - ( - fileName: string, - options: FSharpProjectOptions, - symbol: FSharpSymbol, - canInvalidateProject: bool, - userOpName: string - ) : Async> = + (fileName: string, options: FSharpProjectOptions, symbol: FSharpSymbol, canInvalidateProject: bool, userOpName: string) + : Async> = self.FindReferencesInFile(fileName, options, symbol, canInvalidateProject, userOpName) member this.FindReferencesInFile(fileName, projectSnapshot, symbol, userOpName) = @@ -1557,42 +1524,30 @@ type internal BackgroundCompiler self.GetAssemblyData(options, userOpName) member _.GetAssemblyData - ( - projectSnapshot: FSharpProjectSnapshot, - _fileName: string, - userOpName: string - ) : Async = + (projectSnapshot: FSharpProjectSnapshot, _fileName: string, userOpName: string) + : Async = self.GetAssemblyData(projectSnapshot.ToOptions(), userOpName) member _.GetBackgroundCheckResultsForFileInProject - ( - fileName: string, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, options: FSharpProjectOptions, userOpName: string) + : Async = self.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName) member _.GetBackgroundParseResultsForFileInProject - ( - fileName: string, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, options: FSharpProjectOptions, userOpName: string) + : Async = self.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName) member _.GetCachedCheckFileResult - ( - builder: IncrementalBuilder, - fileName: string, - sourceText: ISourceText, - options: FSharpProjectOptions - ) : Async<(FSharpParseFileResults * FSharpCheckFileResults) option> = + (builder: IncrementalBuilder, fileName: string, sourceText: ISourceText, options: FSharpProjectOptions) + : Async<(FSharpParseFileResults * FSharpCheckFileResults) option> = self.GetCachedCheckFileResult(builder, fileName, sourceText, options) member _.GetProjectOptionsFromScript ( fileName: string, sourceText: ISourceText, + caret: Position option, previewEnabled: bool option, loadedTimeStamp: DateTime option, otherFlags: string array option, @@ -1606,6 +1561,7 @@ type internal BackgroundCompiler self.GetProjectOptionsFromScript( fileName, sourceText, + caret, previewEnabled, loadedTimeStamp, otherFlags, @@ -1621,6 +1577,7 @@ type internal BackgroundCompiler ( fileName: string, sourceText: ISourceTextNew, + caret: Position option, documentSource: DocumentSource, previewEnabled: bool option, loadedTimeStamp: DateTime option, @@ -1637,6 +1594,7 @@ type internal BackgroundCompiler self.GetProjectOptionsFromScript( fileName, sourceText, + caret, previewEnabled, loadedTimeStamp, otherFlags, @@ -1653,19 +1611,13 @@ type internal BackgroundCompiler } member _.GetSemanticClassificationForFile - ( - fileName: string, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, options: FSharpProjectOptions, userOpName: string) + : Async = self.GetSemanticClassificationForFile(fileName, options, userOpName) member _.GetSemanticClassificationForFile - ( - fileName: string, - snapshot: FSharpProjectSnapshot, - userOpName: string - ) : Async = + (fileName: string, snapshot: FSharpProjectSnapshot, userOpName: string) + : Async = self.GetSemanticClassificationForFile(fileName, snapshot.ToOptions(), userOpName) member _.InvalidateConfiguration(options: FSharpProjectOptions, userOpName: string) : unit = @@ -1682,21 +1634,13 @@ type internal BackgroundCompiler self.NotifyProjectCleaned(options, userOpName) member _.ParseAndCheckFileInProject - ( - fileName: string, - fileVersion: int, - sourceText: ISourceText, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, fileVersion: int, sourceText: ISourceText, options: FSharpProjectOptions, userOpName: string) + : Async = self.ParseAndCheckFileInProject(fileName, fileVersion, sourceText, options, userOpName) member _.ParseAndCheckFileInProject - ( - fileName: string, - projectSnapshot: FSharpProjectSnapshot, - userOpName: string - ) : Async = + (fileName: string, projectSnapshot: FSharpProjectSnapshot, userOpName: string) + : Async = async { let fileSnapshot = projectSnapshot.ProjectSnapshot.SourceFiles @@ -1715,14 +1659,8 @@ type internal BackgroundCompiler self.ParseAndCheckProject(projectSnapshot.ToOptions(), userOpName) member _.ParseFile - ( - fileName: string, - sourceText: ISourceText, - options: FSharpParsingOptions, - cache: bool, - flatErrors: bool, - userOpName: string - ) = + (fileName: string, sourceText: ISourceText, options: FSharpParsingOptions, cache: bool, flatErrors: bool, userOpName: string) + = self.ParseFile(fileName, sourceText, options, cache, flatErrors, userOpName) member _.ParseFile(fileName: string, projectSnapshot: FSharpProjectSnapshot, userOpName: string) = @@ -1733,18 +1671,11 @@ type internal BackgroundCompiler member _.ProjectChecked: IEvent = self.ProjectChecked member _.TryGetRecentCheckResultsForFile - ( - fileName: string, - options: FSharpProjectOptions, - sourceText: ISourceText option, - userOpName: string - ) : (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option = + (fileName: string, options: FSharpProjectOptions, sourceText: ISourceText option, userOpName: string) + : (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option = self.TryGetRecentCheckResultsForFile(fileName, options, sourceText, userOpName) member _.TryGetRecentCheckResultsForFile - ( - fileName: string, - projectSnapshot: FSharpProjectSnapshot, - userOpName: string - ) : (FSharpParseFileResults * FSharpCheckFileResults) option = + (fileName: string, projectSnapshot: FSharpProjectSnapshot, userOpName: string) + : (FSharpParseFileResults * FSharpCheckFileResults) option = self.TryGetRecentCheckResultsForFile(fileName, projectSnapshot, userOpName) diff --git a/src/Compiler/Service/BackgroundCompiler.fsi b/src/Compiler/Service/BackgroundCompiler.fsi index d93ece6217b..6192b23e3f9 100644 --- a/src/Compiler/Service/BackgroundCompiler.fsi +++ b/src/Compiler/Service/BackgroundCompiler.fsi @@ -90,6 +90,7 @@ type internal IBackgroundCompiler = abstract GetProjectOptionsFromScript: fileName: string * sourceText: ISourceText * + caret: Position option * previewEnabled: bool option * loadedTimeStamp: System.DateTime option * otherFlags: string array option * @@ -104,6 +105,7 @@ type internal IBackgroundCompiler = abstract GetProjectSnapshotFromScript: fileName: string * sourceText: ISourceTextNew * + caret: Position option * documentSource: DocumentSource * previewEnabled: bool option * loadedTimeStamp: System.DateTime option * diff --git a/src/Compiler/Service/FSharpCheckerResults.fs b/src/Compiler/Service/FSharpCheckerResults.fs index 8cb27875075..57d322c81a8 100644 --- a/src/Compiler/Service/FSharpCheckerResults.fs +++ b/src/Compiler/Service/FSharpCheckerResults.fs @@ -188,7 +188,7 @@ and FSharpProjectOptions = && options1.ReferencedProjects = options2.ReferencedProjects && options1.LoadTime = options2.LoadTime - member po.ProjectDirectory = !! Path.GetDirectoryName(po.ProjectFileName) + member po.ProjectDirectory = !!Path.GetDirectoryName(po.ProjectFileName) override this.ToString() = "FSharpProjectOptions(" + this.ProjectFileName + ")" @@ -2042,15 +2042,8 @@ type internal TypeCheckInfo /// Get the auto-complete items at a location member _.GetDeclarations - ( - parseResultsOpt, - line, - lineStr, - partialName, - completionContextAtPos, - getAllEntities, - genBodyForOverriddenMeth - ) = + (parseResultsOpt, line, lineStr, partialName, completionContextAtPos, getAllEntities, genBodyForOverriddenMeth) + = let isSigFile = SourceFileImpl.IsSignatureFile mainInputFileName DiagnosticsScope.Protect @@ -3109,14 +3102,8 @@ module internal ParseAndCheckFile = errHandler.CollectedDiagnostics(None), parseResult, errHandler.AnyErrors let ApplyLoadClosure - ( - tcConfig, - parsedMainInput, - mainInputFileName: string, - loadClosure: LoadClosure option, - tcImports: TcImports, - backgroundDiagnostics - ) = + (tcConfig, parsedMainInput, mainInputFileName: string, loadClosure: LoadClosure option, tcImports: TcImports, backgroundDiagnostics) + = // If additional references were brought in by the preprocessor then we need to process them match loadClosure with @@ -3204,7 +3191,7 @@ module internal ParseAndCheckFile = ApplyMetaCommandsFromInputToTcConfig( tcConfig, parsedMainInput, - !! Path.GetDirectoryName(mainInputFileName), + !!Path.GetDirectoryName(mainInputFileName), tcImports.DependencyProvider ) |> ignore @@ -3255,7 +3242,7 @@ module internal ParseAndCheckFile = // Apply nowarns to tcConfig (may generate errors, so ensure diagnosticsLogger is installed) let tcConfig = - ApplyNoWarnsToTcConfig(tcConfig, parsedMainInput, !! Path.GetDirectoryName(mainInputFileName)) + ApplyNoWarnsToTcConfig(tcConfig, parsedMainInput, !!Path.GetDirectoryName(mainInputFileName)) // update the error handler with the modified tcConfig errHandler.DiagnosticOptions <- tcConfig.diagnosticsOptions @@ -3383,15 +3370,8 @@ type FSharpCheckFileResults /// Intellisense autocompletions member _.GetDeclarationListInfo - ( - parsedFileResults, - line, - lineText, - partialName, - ?getAllEntities, - ?completionContextAtPos, - ?genBodyForOverriddenMeth - ) = + (parsedFileResults, line, lineText, partialName, ?getAllEntities, ?completionContextAtPos, ?genBodyForOverriddenMeth) + = let getAllEntities = defaultArg getAllEntities (fun () -> []) let genBodyForOverriddenMeth = defaultArg genBodyForOverriddenMeth true @@ -3638,12 +3618,7 @@ type FSharpCheckFileResults FSharpCheckFileResults(fileName, creationErrors, None, [||], None, keepAssemblyContents) static member JoinErrors - ( - isIncompleteTypeCheckEnvironment, - creationErrors: FSharpDiagnostic[], - parseErrors: FSharpDiagnostic[], - tcErrors: FSharpDiagnostic[] - ) = + (isIncompleteTypeCheckEnvironment, creationErrors: FSharpDiagnostic[], parseErrors: FSharpDiagnostic[], tcErrors: FSharpDiagnostic[]) = [| yield! creationErrors yield! parseErrors @@ -4006,6 +3981,7 @@ type FsiInteractiveChecker(legacyReferenceResolver, tcConfig: TcConfig, tcGlobal defaultFSharpBinariesDir, fileName, sourceText, + None, CodeContext.Editing, tcConfig.useSimpleResolution, tcConfig.useFsiAuxLib, diff --git a/src/Compiler/Service/FSharpProjectSnapshot.fs b/src/Compiler/Service/FSharpProjectSnapshot.fs index f7d2786d244..91a6efd472a 100644 --- a/src/Compiler/Service/FSharpProjectSnapshot.fs +++ b/src/Compiler/Service/FSharpProjectSnapshot.fs @@ -436,15 +436,18 @@ and [] Proj ((projectFileName, outputFileNameValue.Value |> Option.defaultValue "") |> FSharpProjectIdentifier) - new(projectFileName: string, - outputFileName: string option, - referencesOnDisk: string seq, - otherOptions: string seq, - ?isIncompleteTypeCheckEnvironment: bool, - ?useScriptResolutionRules: bool, - ?loadTime: DateTime, - ?stamp: int64, - ?projectId: string) = + new + ( + projectFileName: string, + outputFileName: string option, + referencesOnDisk: string seq, + otherOptions: string seq, + ?isIncompleteTypeCheckEnvironment: bool, + ?useScriptResolutionRules: bool, + ?loadTime: DateTime, + ?stamp: int64, + ?projectId: string + ) = let referencesOnDisk = referencesOnDisk @@ -469,7 +472,7 @@ and [] Proj projectId = projectId ) - member val ProjectDirectory = !! Path.GetDirectoryName(projectFileName) + member val ProjectDirectory = !!Path.GetDirectoryName(projectFileName) member _.OutputFileName = outputFileNameValue.Value member _.Identifier = identifier.Value member _.Version = fullHash.Value @@ -727,13 +730,8 @@ and [] FSha ) static member FromOptions - ( - options: FSharpProjectOptions, - fileName: string, - fileVersion: int, - sourceText: ISourceText, - documentSource: DocumentSource - ) = + (options: FSharpProjectOptions, fileName: string, fileVersion: int, sourceText: ISourceText, documentSource: DocumentSource) + = let getFileSnapshot _ fName = if fName = fileName then diff --git a/src/Compiler/Service/FSharpWorkspaceState.fs b/src/Compiler/Service/FSharpWorkspaceState.fs index deda0a607b7..ff112a7977c 100644 --- a/src/Compiler/Service/FSharpWorkspaceState.fs +++ b/src/Compiler/Service/FSharpWorkspaceState.fs @@ -150,10 +150,8 @@ module internal WorkspaceDependencyGraphExtensions = [] static member AddProjectWithoutFiles - ( - this: GraphBuilder<_, _, (ProjectConfig * FSharpProjectSnapshot seq), _>, - computeProjectWithoutFiles - ) = + (this: GraphBuilder<_, _, (ProjectConfig * FSharpProjectSnapshot seq), _>, computeProjectWithoutFiles) + = this.AddDependentNode( WorkspaceNodeKey.ProjectWithoutFiles this.State, computeProjectWithoutFiles >> WorkspaceNodeValue.ProjectWithoutFiles, @@ -176,10 +174,8 @@ module internal WorkspaceDependencyGraphExtensions = [] static member AddProjectSnapshot - ( - this: GraphBuilder<_, _, (ProjectWithoutFiles * FSharpFileSnapshot seq), _>, - computeProjectSnapshot - ) = + (this: GraphBuilder<_, _, (ProjectWithoutFiles * FSharpFileSnapshot seq), _>, computeProjectSnapshot) + = this.AddDependentNode( WorkspaceNodeKey.ProjectSnapshot this.State, @@ -201,9 +197,7 @@ module internal WorkspaceDependencyGraphExtensions = [] static member GetProjectSnapshot(this: IDependencyGraph<_, _>, project) = - this - .GetValue(WorkspaceNodeKey.ProjectSnapshot project) - .Unpack(WorkspaceNode.projectSnapshot) + this.GetValue(WorkspaceNodeKey.ProjectSnapshot project).Unpack(WorkspaceNode.projectSnapshot) [] static member GetProjectReferencesOf(this: IDependencyGraph<_, _>, project) = @@ -212,9 +206,7 @@ module internal WorkspaceDependencyGraphExtensions = [] static member GetProjectsThatReference(this: IDependencyGraph<_, _>, dllPath) = - this - .GetDependentsOf(WorkspaceNodeKey.ReferenceOnDisk dllPath) - .UnpackMany(WorkspaceNode.projectConfigKey) + this.GetDependentsOf(WorkspaceNodeKey.ReferenceOnDisk dllPath).UnpackMany(WorkspaceNode.projectConfigKey) [] static member GetProjectsContaining(this: IDependencyGraph<_, _>, file) = @@ -438,7 +430,7 @@ type FSharpWorkspaceProjects internal (depGraph: IThreadSafeDependencyGraph<_, _ Activity.start "Projects.Update" [ - Activity.Tags.project, !! projectIdentifier.ToString() + Activity.Tags.project, !!projectIdentifier.ToString() "sourceFiles", newSourceFiles |> String.concat "; " ] diff --git a/src/Compiler/Service/SemanticClassification.fs b/src/Compiler/Service/SemanticClassification.fs index 3de24222311..f384cabebdc 100644 --- a/src/Compiler/Service/SemanticClassification.fs +++ b/src/Compiler/Service/SemanticClassification.fs @@ -135,12 +135,8 @@ module TcResolutionsExtensions = type TcResolutions with member sResolutions.GetSemanticClassification - ( - g: TcGlobals, - amap: ImportMap, - formatSpecifierLocations: (range * int)[], - range: range option - ) : SemanticClassificationItem[] = + (g: TcGlobals, amap: ImportMap, formatSpecifierLocations: (range * int)[], range: range option) + : SemanticClassificationItem[] = DiagnosticsScope.Protect range0 (fun () -> diff --git a/src/Compiler/Service/ServiceInterfaceStubGenerator.fs b/src/Compiler/Service/ServiceInterfaceStubGenerator.fs index fb3e8dfbecc..94051957876 100644 --- a/src/Compiler/Service/ServiceInterfaceStubGenerator.fs +++ b/src/Compiler/Service/ServiceInterfaceStubGenerator.fs @@ -41,7 +41,7 @@ module internal CodeGenerationUtils = member _.Unindent i = indentWriter.Indent <- max 0 (indentWriter.Indent - i) - member _.Dump() = !! indentWriter.InnerWriter.ToString() + member _.Dump() = !!indentWriter.InnerWriter.ToString() interface IDisposable with member _.Dispose() = diff --git a/src/Compiler/Service/ServiceLexing.fs b/src/Compiler/Service/ServiceLexing.fs index 083bae1d6d8..8e97816290f 100644 --- a/src/Compiler/Service/ServiceLexing.fs +++ b/src/Compiler/Service/ServiceLexing.fs @@ -1920,17 +1920,8 @@ module FSharpLexerImpl = type FSharpLexer = static member Tokenize - ( - text: ISourceText, - tokenCallback, - ?langVersion, - ?strictIndentation, - ?filePath: string, - ?conditionalDefines, - ?flags, - ?pathMap, - ?ct - ) = + (text: ISourceText, tokenCallback, ?langVersion, ?strictIndentation, ?filePath: string, ?conditionalDefines, ?flags, ?pathMap, ?ct) + = let langVersion = defaultArg langVersion "latestmajor" |> LanguageVersion let flags = defaultArg flags FSharpLexerFlags.Default ignore filePath // can be removed at later point diff --git a/src/Compiler/Service/ServiceParseTreeWalk.fs b/src/Compiler/Service/ServiceParseTreeWalk.fs index b55844e51ae..659f4c4bc60 100644 --- a/src/Compiler/Service/ServiceParseTreeWalk.fs +++ b/src/Compiler/Service/ServiceParseTreeWalk.fs @@ -56,12 +56,8 @@ type SyntaxVisitorBase<'T>() = 'T option default _.VisitExpr - ( - path: SyntaxVisitorPath, - traverseSynExpr: SynExpr -> 'T option, - defaultTraverse: SynExpr -> 'T option, - synExpr: SynExpr - ) = + (path: SyntaxVisitorPath, traverseSynExpr: SynExpr -> 'T option, defaultTraverse: SynExpr -> 'T option, synExpr: SynExpr) + = ignore (path, traverseSynExpr, defaultTraverse, synExpr) None diff --git a/src/Compiler/Service/ServiceParsedInputOps.fs b/src/Compiler/Service/ServiceParsedInputOps.fs index 374f648947a..f5b15936902 100644 --- a/src/Compiler/Service/ServiceParsedInputOps.fs +++ b/src/Compiler/Service/ServiceParsedInputOps.fs @@ -1520,11 +1520,8 @@ module ParsedInput = | _ -> None member _.VisitBinding - ( - path, - defaultTraverse, - (SynBinding(headPat = headPat; trivia = trivia; returnInfo = returnInfo) as synBinding) - ) = + (path, defaultTraverse, (SynBinding(headPat = headPat; trivia = trivia; returnInfo = returnInfo) as synBinding)) + = let isOverrideOrMember leadingKeyword = match leadingKeyword with diff --git a/src/Compiler/Service/TransparentCompiler.fs b/src/Compiler/Service/TransparentCompiler.fs index d3f89bbd989..12f864ec54d 100644 --- a/src/Compiler/Service/TransparentCompiler.fs +++ b/src/Compiler/Service/TransparentCompiler.fs @@ -496,6 +496,7 @@ type internal TransparentCompiler defaultFSharpBinariesDir, fileName, source, + None, CodeContext.Editing, useSimpleResolution, useFsiAuxLib, @@ -907,7 +908,7 @@ type internal TransparentCompiler { new IXmlDocumentationInfoLoader with /// Try to load xml documentation associated with an assembly by the same file path with the extension ".xml". member _.TryLoad(assemblyFileName) = - let xmlFileName = !! Path.ChangeExtension(assemblyFileName, ".xml") + let xmlFileName = !!Path.ChangeExtension(assemblyFileName, ".xml") // REVIEW: File IO - Will eventually need to change this to use a file system interface of some sort. XmlDocumentationInfo.TryCreateFromFile(xmlFileName) @@ -1393,7 +1394,7 @@ type internal TransparentCompiler // Apply nowarns to tcConfig (may generate errors, so ensure diagnosticsLogger is installed) let tcConfig = - ApplyNoWarnsToTcConfig(tcConfig, parsedMainInput, !! Path.GetDirectoryName(mainInputFileName)) + ApplyNoWarnsToTcConfig(tcConfig, parsedMainInput, !!Path.GetDirectoryName(mainInputFileName)) let diagnosticsLogger = errHandler.DiagnosticsLogger @@ -1751,11 +1752,8 @@ type internal TransparentCompiler ) let TryGetRecentCheckResultsForFile - ( - fileName: string, - projectSnapshot: FSharpProjectSnapshot, - userOpName: string - ) : (FSharpParseFileResults * FSharpCheckFileResults) option = + (fileName: string, projectSnapshot: FSharpProjectSnapshot, userOpName: string) + : (FSharpParseFileResults * FSharpCheckFileResults) option = ignore userOpName let cacheKey = @@ -1872,7 +1870,7 @@ type internal TransparentCompiler } ) - let ComputeAssemblyData (projectSnapshot: ProjectSnapshot) fileName = + let ComputeAssemblyData (projectSnapshot: ProjectSnapshot) _fileName = caches.AssemblyData.Get( projectSnapshot.SignatureKey, async { @@ -1887,11 +1885,11 @@ type internal TransparentCompiler try - let availableOnDiskModifiedTime = - if FileSystem.FileExistsShim fileName then - Some <| FileSystem.GetLastWriteTimeShim fileName - else - None + //let availableOnDiskModifiedTime = + // if FileSystem.FileExistsShim fileName then + // Some <| FileSystem.GetLastWriteTimeShim fileName + // else + // None // TODO: This kinda works, but the problem is that in order to switch a project to "in-memory" mode // - some file needs to be edited (this triggers a re-check, but LastModifiedTimeOnDisk won't change) @@ -2111,14 +2109,8 @@ type internal TransparentCompiler } member _.ParseFileWithoutProject - ( - fileName: string, - sourceText: ISourceText, - options: FSharpParsingOptions, - cache: bool, - flatErrors: bool, - userOpName: string - ) : Async = + (fileName: string, sourceText: ISourceText, options: FSharpParsingOptions, cache: bool, flatErrors: bool, userOpName: string) + : Async = let parseFileAsync = async { let! ct = Async.CancellationToken @@ -2272,13 +2264,8 @@ type internal TransparentCompiler member _.ProjectChecked = projectChecked.Publish member this.FindReferencesInFile - ( - fileName: string, - options: FSharpProjectOptions, - symbol: FSharpSymbol, - canInvalidateProject: bool, - userOpName: string - ) : Async> = + (fileName: string, options: FSharpProjectOptions, symbol: FSharpSymbol, canInvalidateProject: bool, userOpName: string) + : Async> = async { ignore canInvalidateProject @@ -2301,19 +2288,13 @@ type internal TransparentCompiler } member this.GetAssemblyData - ( - projectSnapshot: FSharpProjectSnapshot, - fileName, - userOpName: string - ) : Async = + (projectSnapshot: FSharpProjectSnapshot, fileName, userOpName: string) + : Async = this.GetAssemblyData(projectSnapshot.ProjectSnapshot, fileName, userOpName) member this.GetBackgroundCheckResultsForFileInProject - ( - fileName: string, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, options: FSharpProjectOptions, userOpName: string) + : Async = async { let! snapshot = FSharpProjectSnapshot.FromOptions(options, documentSource) @@ -2323,11 +2304,8 @@ type internal TransparentCompiler } member this.GetBackgroundParseResultsForFileInProject - ( - fileName: string, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, options: FSharpProjectOptions, userOpName: string) + : Async = async { let! snapshot = FSharpProjectSnapshot.FromOptions(options, documentSource) @@ -2335,12 +2313,8 @@ type internal TransparentCompiler } member this.GetCachedCheckFileResult - ( - builder: IncrementalBuilder, - fileName: string, - sourceText: ISourceText, - options: FSharpProjectOptions - ) : Async<(FSharpParseFileResults * FSharpCheckFileResults) option> = + (builder: IncrementalBuilder, fileName: string, sourceText: ISourceText, options: FSharpProjectOptions) + : Async<(FSharpParseFileResults * FSharpCheckFileResults) option> = async { ignore builder @@ -2355,6 +2329,7 @@ type internal TransparentCompiler ( fileName: string, sourceText: ISourceText, + caret: Position option, previewEnabled: bool option, loadedTimeStamp: DateTime option, otherFlags: string array option, @@ -2372,6 +2347,7 @@ type internal TransparentCompiler bc.GetProjectSnapshotFromScript( fileName, SourceTextNew.ofISourceText sourceText, + caret, DocumentSource.FileSystem, previewEnabled, loadedTimeStamp, @@ -2392,6 +2368,7 @@ type internal TransparentCompiler ( fileName: string, sourceText: ISourceTextNew, + _caret: Position option, documentSource: DocumentSource, previewEnabled: bool option, loadedTimeStamp: DateTime option, @@ -2535,11 +2512,8 @@ type internal TransparentCompiler } member this.GetSemanticClassificationForFile - ( - fileName: string, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, options: FSharpProjectOptions, userOpName: string) + : Async = async { ignore userOpName @@ -2561,13 +2535,8 @@ type internal TransparentCompiler backgroundCompiler.NotifyProjectCleaned(options, userOpName) member this.ParseAndCheckFileInProject - ( - fileName: string, - fileVersion: int, - sourceText: ISourceText, - options: FSharpProjectOptions, - userOpName: string - ) : Async = + (fileName: string, fileVersion: int, sourceText: ISourceText, options: FSharpProjectOptions, userOpName: string) + : Async = async { let! snapshot = FSharpProjectSnapshot.FromOptions(options, fileName, fileVersion, sourceText, documentSource) @@ -2596,29 +2565,16 @@ type internal TransparentCompiler this.ParseFile(fileName, projectSnapshot.ProjectSnapshot, userOpName) member this.ParseFile - ( - fileName: string, - sourceText: ISourceText, - options: FSharpParsingOptions, - cache: bool, - flatErrors: bool, - userOpName: string - ) : Async = + (fileName: string, sourceText: ISourceText, options: FSharpParsingOptions, cache: bool, flatErrors: bool, userOpName: string) + : Async = this.ParseFileWithoutProject(fileName, sourceText, options, cache, flatErrors, userOpName) member this.TryGetRecentCheckResultsForFile - ( - fileName: string, - options: FSharpProjectOptions, - sourceText: ISourceText option, - userOpName: string - ) : (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option = + (fileName: string, options: FSharpProjectOptions, sourceText: ISourceText option, userOpName: string) + : (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option = backgroundCompiler.TryGetRecentCheckResultsForFile(fileName, options, sourceText, userOpName) member this.TryGetRecentCheckResultsForFile - ( - fileName: string, - projectSnapshot: FSharpProjectSnapshot, - userOpName: string - ) : (FSharpParseFileResults * FSharpCheckFileResults) option = + (fileName: string, projectSnapshot: FSharpProjectSnapshot, userOpName: string) + : (FSharpParseFileResults * FSharpCheckFileResults) option = TryGetRecentCheckResultsForFile(fileName, projectSnapshot, userOpName) diff --git a/src/Compiler/Service/TransparentCompiler.fsi b/src/Compiler/Service/TransparentCompiler.fsi index 93df10b29e2..8703df0fe7f 100644 --- a/src/Compiler/Service/TransparentCompiler.fsi +++ b/src/Compiler/Service/TransparentCompiler.fsi @@ -156,8 +156,11 @@ type internal CompilerCaches = member ParseAndCheckAllFilesInProject: AsyncMemoizeDisabled member ParseAndCheckFileInProject: - AsyncMemoize<(string * FSharpProjectIdentifier), string * string, (FSharpParseFileResults * - FSharpCheckFileAnswer)> + AsyncMemoize< + (string * FSharpProjectIdentifier), + string * string, + (FSharpParseFileResults * FSharpCheckFileAnswer) + > member ParseAndCheckProject: AsyncMemoize diff --git a/src/Compiler/Service/service.fs b/src/Compiler/Service/service.fs index 4835b784bf8..1e053fde7ff 100644 --- a/src/Compiler/Service/service.fs +++ b/src/Compiler/Service/service.fs @@ -389,14 +389,8 @@ type FSharpChecker /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. member _.CheckFileInProjectAllowingStaleCachedResults - ( - parseResults: FSharpParseFileResults, - fileName: string, - fileVersion: int, - source: string, - options: FSharpProjectOptions, - ?userOpName: string - ) = + (parseResults: FSharpParseFileResults, fileName: string, fileVersion: int, source: string, options: FSharpProjectOptions, ?userOpName: string) + = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.CheckFileInProjectAllowingStaleCachedResults( @@ -426,13 +420,8 @@ type FSharpChecker /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. member _.ParseAndCheckFileInProject - ( - fileName: string, - fileVersion: int, - sourceText: ISourceText, - options: FSharpProjectOptions, - ?userOpName: string - ) = + (fileName: string, fileVersion: int, sourceText: ISourceText, options: FSharpProjectOptions, ?userOpName: string) + = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.ParseAndCheckFileInProject(fileName, fileVersion, sourceText, options, userOpName) @@ -453,14 +442,8 @@ type FSharpChecker backgroundCompiler.ParseAndCheckProject(projectSnapshot, userOpName) member _.FindBackgroundReferencesInFile - ( - fileName: string, - options: FSharpProjectOptions, - symbol: FSharpSymbol, - ?canInvalidateProject: bool, - ?fastCheck: bool, - ?userOpName: string - ) = + (fileName: string, options: FSharpProjectOptions, symbol: FSharpSymbol, ?canInvalidateProject: bool, ?fastCheck: bool, ?userOpName: string) + = let canInvalidateProject = defaultArg canInvalidateProject true let userOpName = defaultArg userOpName "Unknown" @@ -509,6 +492,7 @@ type FSharpChecker ( fileName, source, + ?caret, ?previewEnabled, ?loadedTimeStamp, ?otherFlags, @@ -524,6 +508,7 @@ type FSharpChecker backgroundCompiler.GetProjectOptionsFromScript( fileName, source, + caret, previewEnabled, loadedTimeStamp, otherFlags, @@ -540,6 +525,7 @@ type FSharpChecker ( fileName, source, + ?caret, ?documentSource, ?previewEnabled, ?loadedTimeStamp, @@ -557,6 +543,7 @@ type FSharpChecker backgroundCompiler.GetProjectSnapshotFromScript( fileName, source, + caret, documentSource, previewEnabled, loadedTimeStamp, diff --git a/src/Compiler/Service/service.fsi b/src/Compiler/Service/service.fsi index 58c4a8c1dfb..69ae46b16b5 100644 --- a/src/Compiler/Service/service.fsi +++ b/src/Compiler/Service/service.fsi @@ -226,6 +226,7 @@ type public FSharpChecker = /// /// Used to differentiate between scripts, to consider each script a separate project. Also used in formatted error messages. /// The source for the file. + /// The editor location for the cursor if available. /// Is the preview compiler enabled. /// Indicates when the script was loaded into the editing environment, /// so that an 'unload' and 'reload' action will cause the script to be considered as a new project, @@ -240,6 +241,7 @@ type public FSharpChecker = member GetProjectOptionsFromScript: fileName: string * source: ISourceText * + ?caret: Position * ?previewEnabled: bool * ?loadedTimeStamp: DateTime * ?otherFlags: string[] * @@ -253,6 +255,7 @@ type public FSharpChecker = /// Used to differentiate between scripts, to consider each script a separate project. Also used in formatted error messages. /// The source for the file. + /// The editor location for the cursor if available. /// DocumentSource to load any additional files. /// Is the preview compiler enabled. /// Indicates when the script was loaded into the editing environment, @@ -269,6 +272,7 @@ type public FSharpChecker = member GetProjectSnapshotFromScript: fileName: string * source: ISourceTextNew * + ?caret: Position * ?documentSource: DocumentSource * ?previewEnabled: bool * ?loadedTimeStamp: DateTime * diff --git a/src/Compiler/Symbols/FSharpDiagnostic.fsi b/src/Compiler/Symbols/FSharpDiagnostic.fsi index 8c79ee95232..0118cc41cf3 100644 --- a/src/Compiler/Symbols/FSharpDiagnostic.fsi +++ b/src/Compiler/Symbols/FSharpDiagnostic.fsi @@ -46,9 +46,7 @@ module public ExtendedData = /// Contextually-relevant data to each particular diagnostic [] - type public IFSharpDiagnosticExtendedData = - interface - end + type public IFSharpDiagnosticExtendedData = interface end /// Additional data for diagnostics about obsolete attributes. [] 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/SyntaxTree/LexHelpers.fs b/src/Compiler/SyntaxTree/LexHelpers.fs index f7f090a6b00..faf85ad811d 100644 --- a/src/Compiler/SyntaxTree/LexHelpers.fs +++ b/src/Compiler/SyntaxTree/LexHelpers.fs @@ -77,15 +77,8 @@ type LongUnicodeLexResult = | Invalid let mkLexargs - ( - conditionalDefines, - indentationSyntaxStatus, - resourceManager, - ifdefStack, - diagnosticsLogger, - pathMap: PathMap, - applyLineDirectives - ) = + (conditionalDefines, indentationSyntaxStatus, resourceManager, ifdefStack, diagnosticsLogger, pathMap: PathMap, applyLineDirectives) + = { conditionalDefines = conditionalDefines ifdefStack = ifdefStack @@ -499,7 +492,7 @@ module Keywords = else PathMap.applyDir args.pathMap dirname |> fun dir -> KEYWORD_STRING(s, dir) - | "__SOURCE_FILE__" -> KEYWORD_STRING(s, !! System.IO.Path.GetFileName(FileIndex.fileOfFileIndex lexbuf.StartPos.FileIndex)) + | "__SOURCE_FILE__" -> KEYWORD_STRING(s, !!System.IO.Path.GetFileName(FileIndex.fileOfFileIndex lexbuf.StartPos.FileIndex)) | "__LINE__" -> KEYWORD_STRING(s, string lexbuf.StartPos.Line) | _ -> IdentifierToken args lexbuf s 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/ParseHelpers.fs b/src/Compiler/SyntaxTree/ParseHelpers.fs index 1c0428eb835..a8a8724f58b 100644 --- a/src/Compiler/SyntaxTree/ParseHelpers.fs +++ b/src/Compiler/SyntaxTree/ParseHelpers.fs @@ -275,15 +275,8 @@ let mkSynMemberDefnGetSet let xmlDoc = grabXmlDocAtRangeStart (parseState, attrs, rangeStart) let tryMkSynMemberDefnMember - ( - mOptInline: range option, - optAttrs: SynAttributeList list, - (bindingPat, mBindLhs), - optReturnType, - mEquals, - expr, - mExpr - ) : (SynMemberDefn * Ident option) option = + (mOptInline: range option, optAttrs: SynAttributeList list, (bindingPat, mBindLhs), optReturnType, mEquals, expr, mExpr) + : (SynMemberDefn * Ident option) option = let optInline = Option.isSome opt_inline || Option.isSome mOptInline // optional attributes are only applied to getters and setters // the "top level" attrs will be applied to both @@ -810,13 +803,8 @@ let checkEndOfFileError t = type BindingSet = BindingSetPreAttrs of range * bool * bool * (SynAttributes -> SynAccess option -> SynAttributes * SynBinding list) * range let mkClassMemberLocalBindings - ( - isStatic, - initialRangeOpt, - attrs, - vis, - BindingSetPreAttrs(_, isRec, isUse, declsPreAttrs, bindingSetRange) - ) = + (isStatic, initialRangeOpt, attrs, vis, BindingSetPreAttrs(_, isRec, isUse, declsPreAttrs, bindingSetRange)) + = let ignoredFreeAttrs, decls = declsPreAttrs attrs vis let mWhole = 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/SyntaxTree/UnicodeLexing.fs b/src/Compiler/SyntaxTree/UnicodeLexing.fs index 5a2d4393ee7..abb3d0e3d83 100644 --- a/src/Compiler/SyntaxTree/UnicodeLexing.fs +++ b/src/Compiler/SyntaxTree/UnicodeLexing.fs @@ -9,16 +9,13 @@ open Internal.Utilities.Text.Lexing type Lexbuf = LexBuffer let StringAsLexbuf (reportLibraryOnlyFeatures, langVersion, strictIndentation, s: string) = - LexBuffer - .FromChars(reportLibraryOnlyFeatures, langVersion, strictIndentation, s.ToCharArray()) + LexBuffer.FromChars(reportLibraryOnlyFeatures, langVersion, strictIndentation, s.ToCharArray()) let FunctionAsLexbuf (reportLibraryOnlyFeatures, langVersion, strictIndentation, bufferFiller) = - LexBuffer - .FromFunction(reportLibraryOnlyFeatures, langVersion, strictIndentation, bufferFiller) + LexBuffer.FromFunction(reportLibraryOnlyFeatures, langVersion, strictIndentation, bufferFiller) let SourceTextAsLexbuf (reportLibraryOnlyFeatures, langVersion, strictIndentation, sourceText) = - LexBuffer - .FromSourceText(reportLibraryOnlyFeatures, langVersion, strictIndentation, sourceText) + LexBuffer.FromSourceText(reportLibraryOnlyFeatures, langVersion, strictIndentation, sourceText) let StreamReaderAsLexbuf (reportLibraryOnlyFeatures, langVersion, strictIndentation, reader: StreamReader) = let mutable isFinished = false 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/TcGlobals.fsi b/src/Compiler/TypedTree/TcGlobals.fsi index b172536d4f0..b8c3610ef91 100644 --- a/src/Compiler/TypedTree/TcGlobals.fsi +++ b/src/Compiler/TypedTree/TcGlobals.fsi @@ -835,7 +835,10 @@ type internal TcGlobals = member knownFSharpCoreModules: System.Collections.Generic.IDictionary member knownIntrinsics: - System.Collections.Concurrent.ConcurrentDictionary<(string * string option * string * int), FSharp.Compiler.TypedTree.ValRef> + System.Collections.Concurrent.ConcurrentDictionary< + (string * string option * string * int), + FSharp.Compiler.TypedTree.ValRef + > member knownWithNull: FSharp.Compiler.TypedTree.Nullness 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..21c9783713e 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 @@ -9252,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 @@ -9271,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/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/FileSystem.fs b/src/Compiler/Utilities/FileSystem.fs index 81d6113cc18..ce2488cd0aa 100644 --- a/src/Compiler/Utilities/FileSystem.fs +++ b/src/Compiler/Utilities/FileSystem.fs @@ -427,17 +427,17 @@ module internal FileSystemUtils = if not (hasExtensionWithValidate false path) then raise (ArgumentException("chopExtension")) // message has to be precisely this, for OCaml compatibility, and no argument name can be set - Path.Combine(!! Path.GetDirectoryName(path), !! Path.GetFileNameWithoutExtension(path)) + Path.Combine(!!Path.GetDirectoryName(path), !!Path.GetFileNameWithoutExtension(path)) let fileNameOfPath path = checkPathForIllegalChars path - !! Path.GetFileName(path) + !!Path.GetFileName(path) let fileNameWithoutExtensionWithValidate (validate: bool) path = if validate then checkPathForIllegalChars path - !! Path.GetFileNameWithoutExtension(path) + !!Path.GetFileNameWithoutExtension(path) let fileNameWithoutExtension path = !! fileNameWithoutExtensionWithValidate true path @@ -705,8 +705,7 @@ type DefaultFileSystem() as this = abstract ChangeExtensionShim: path: string * extension: string -> string - default _.ChangeExtensionShim(path: string, extension: string) : string = - !! Path.ChangeExtension(path, extension) + default _.ChangeExtensionShim(path: string, extension: string) : string = !!Path.ChangeExtension(path, extension) interface IFileSystem with member _.AssemblyLoader = this.AssemblyLoader @@ -824,7 +823,7 @@ module public StreamExtensions = use sr = new StreamReader(s, encoding, true) while not <| sr.EndOfStream do - yield !! sr.ReadLine() + yield !!sr.ReadLine() } member s.ReadAllLines(?encoding: Encoding) : string array = 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 9164ea596ce..0a56dd9d670 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/Compiler/Utilities/sr.fs b/src/Compiler/Utilities/sr.fs index 10a615846e3..968525e931e 100644 --- a/src/Compiler/Utilities/sr.fs +++ b/src/Compiler/Utilities/sr.fs @@ -14,9 +14,7 @@ module internal SR = let GetString (name: string) = let s = - resources - .Force() - .GetString(name, System.Globalization.CultureInfo.CurrentUICulture) + resources.Force().GetString(name, System.Globalization.CultureInfo.CurrentUICulture) #if DEBUG if isNull s then System.Diagnostics.Debug.Assert(false, sprintf "**RESOURCE ERROR**: Resource token %s does not exist!" name) 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/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/FSharpEmbedResXSource.fs b/src/FSharp.Build/FSharpEmbedResXSource.fs index 8a26386cf47..219ae5a4f2c 100644 --- a/src/FSharp.Build/FSharpEmbedResXSource.fs +++ b/src/FSharp.Build/FSharpEmbedResXSource.fs @@ -72,8 +72,7 @@ module internal {1} = printMessage "Generating code for target framework %s" _targetFramework let sb = - StringBuilder() - .AppendLine(String.Format(boilerplate, namespaceName, moduleName, justFileName)) + StringBuilder().AppendLine(String.Format(boilerplate, namespaceName, moduleName, justFileName)) if generateGetObject then sb.AppendLine(boilerplateGetObject) |> ignore @@ -103,9 +102,7 @@ module internal {1} = "_" + name let commentBody = - XElement(xname "summary", docComment) - .ToString() - .Split([| "\r\n"; "\r"; "\n" |], StringSplitOptions.None) + XElement(xname "summary", docComment).ToString().Split([| "\r\n"; "\r"; "\n" |], StringSplitOptions.None) |> Array.fold (fun (sb: StringBuilder) line -> sb.AppendLine(" /// " + line)) (StringBuilder()) // add the resource let accessorBody = diff --git a/src/FSharp.Build/FSharpEmbedResourceText.fs b/src/FSharp.Build/FSharpEmbedResourceText.fs index 3e3c79f82ee..1c5ffbfb68b 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 @@ -444,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) @@ -508,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 @@ -586,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 @@ -595,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 dc362420db0..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 = @@ -112,9 +109,7 @@ type public Fsi() as this = let warningsAsErrorsArray = match warningsAsErrors with | Null -> [| "76" |] - | NonNull warningsAsErrors -> - (warningsAsErrors + " 76 ") - .Split([| ' '; ';'; ',' |], StringSplitOptions.RemoveEmptyEntries) + | NonNull warningsAsErrors -> (warningsAsErrors + " 76 ").Split([| ' '; ';'; ',' |], StringSplitOptions.RemoveEmptyEntries) builder.AppendSwitchesIfNotNull("--warnaserror:", warningsAsErrorsArray, ",") 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.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 diff --git a/src/FSharp.Compiler.LanguageServer/Common/FSharpRequestContext.fs b/src/FSharp.Compiler.LanguageServer/Common/FSharpRequestContext.fs index 85085a8bb8d..fd096d3e582 100644 --- a/src/FSharp.Compiler.LanguageServer/Common/FSharpRequestContext.fs +++ b/src/FSharp.Compiler.LanguageServer/Common/FSharpRequestContext.fs @@ -177,10 +177,10 @@ type FShapRequestContextFactory(lspServices: ILspServices) = override _.CreateRequestContextAsync<'TRequestParam> ( - queueItem: IQueueItem, - methodHandler: IMethodHandler, - requestParam: 'TRequestParam, - cancellationToken: CancellationToken + _queueItem: IQueueItem, + _methodHandler: IMethodHandler, + _requestParam: 'TRequestParam, + _cancellationToken: CancellationToken ) = lspServices.GetRequiredService() |> _.GetContext() diff --git a/src/FSharp.Compiler.LanguageServer/Common/LifecycleManager.fs b/src/FSharp.Compiler.LanguageServer/Common/LifecycleManager.fs index 13a97cf4a68..1919512375e 100644 --- a/src/FSharp.Compiler.LanguageServer/Common/LifecycleManager.fs +++ b/src/FSharp.Compiler.LanguageServer/Common/LifecycleManager.fs @@ -11,7 +11,7 @@ open Microsoft.Extensions.DependencyInjection type LspServiceLifeCycleManager() = interface ILifeCycleManager with - member _.ShutdownAsync(message: string) = + member _.ShutdownAsync(_message: string) = task { try printfn "Shutting down" diff --git a/src/FSharp.Compiler.LanguageServer/Executable.fs b/src/FSharp.Compiler.LanguageServer/Executable.fs index 9e9034e0275..acc8e869fdc 100644 --- a/src/FSharp.Compiler.LanguageServer/Executable.fs +++ b/src/FSharp.Compiler.LanguageServer/Executable.fs @@ -4,11 +4,11 @@ open System open StreamJsonRpc [] -let main argv = +let main _argv = let jsonRpc = new JsonRpc(Console.OpenStandardOutput(), Console.OpenStandardInput()) - let s = new FSharpLanguageServer(jsonRpc, (LspLogger Console.Out.Write)) + let _s = new FSharpLanguageServer(jsonRpc, (LspLogger Console.Out.Write)) jsonRpc.StartListening() diff --git a/src/FSharp.Compiler.LanguageServer/Handlers/DocumentStateHandler.fs b/src/FSharp.Compiler.LanguageServer/Handlers/DocumentStateHandler.fs index 76135d84fe7..b7f281ed9e8 100644 --- a/src/FSharp.Compiler.LanguageServer/Handlers/DocumentStateHandler.fs +++ b/src/FSharp.Compiler.LanguageServer/Handlers/DocumentStateHandler.fs @@ -16,11 +16,8 @@ type DocumentStateHandler() = interface IRequestHandler with [] member _.HandleRequestAsync - ( - request: DidOpenTextDocumentParams, - context: FSharpRequestContext, - cancellationToken: CancellationToken - ) = + (request: DidOpenTextDocumentParams, context: FSharpRequestContext, _cancellationToken: CancellationToken) + = let contextHolder = context.LspServices.GetRequiredService() contextHolder.UpdateWorkspace _.Files.Open(request.TextDocument.Uri, request.TextDocument.Text) @@ -30,11 +27,8 @@ type DocumentStateHandler() = interface IRequestHandler with [] member _.HandleRequestAsync - ( - request: DidChangeTextDocumentParams, - context: FSharpRequestContext, - cancellationToken: CancellationToken - ) = + (request: DidChangeTextDocumentParams, context: FSharpRequestContext, _cancellationToken: CancellationToken) + = let contextHolder = context.LspServices.GetRequiredService() contextHolder.UpdateWorkspace _.Files.Edit(request.TextDocument.Uri, request.ContentChanges.[0].Text) @@ -44,11 +38,8 @@ type DocumentStateHandler() = interface INotificationHandler with [] member _.HandleNotificationAsync - ( - request: DidCloseTextDocumentParams, - context: FSharpRequestContext, - cancellationToken: CancellationToken - ) = + (request: DidCloseTextDocumentParams, context: FSharpRequestContext, _cancellationToken: CancellationToken) + = let contextHolder = context.LspServices.GetRequiredService() contextHolder.UpdateWorkspace _.Files.Close(request.TextDocument.Uri) diff --git a/src/FSharp.Compiler.LanguageServer/Handlers/LanguageFeaturesHandler.fs b/src/FSharp.Compiler.LanguageServer/Handlers/LanguageFeaturesHandler.fs index a144cf1832b..474758924d0 100644 --- a/src/FSharp.Compiler.LanguageServer/Handlers/LanguageFeaturesHandler.fs +++ b/src/FSharp.Compiler.LanguageServer/Handlers/LanguageFeaturesHandler.fs @@ -16,14 +16,15 @@ type LanguageFeaturesHandler() = interface IMethodHandler with member _.MutatesSolutionState = false - interface IRequestHandler, FSharpRequestContext> with + interface IRequestHandler< + DocumentDiagnosticParams, + SumType, + FSharpRequestContext + > with [] member _.HandleRequestAsync - ( - request: DocumentDiagnosticParams, - context: FSharpRequestContext, - cancellationToken: CancellationToken - ) = + (request: DocumentDiagnosticParams, context: FSharpRequestContext, cancellationToken: CancellationToken) + = cancellableTask { let! fsharpDiagnosticReport = context.Workspace.Query.GetDiagnosticsForFile request.TextDocument.Uri 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/async.fs b/src/FSharp.Core/async.fs index 2b117be0b16..170b30cce0f 100644 --- a/src/FSharp.Core/async.fs +++ b/src/FSharp.Core/async.fs @@ -235,8 +235,7 @@ type TrampolineHolder() = // This should be the only call to Thread.Start in this library. We must always install a trampoline. member this.StartThreadWithTrampoline(f: unit -> AsyncReturn) = - Thread(getThreadStartCallbackForStartThreadWithTrampoline (this), IsBackground = true) - .Start(f |> box) + Thread(getThreadStartCallbackForStartThreadWithTrampoline (this), IsBackground = true).Start(f |> box) AsyncReturn.Fake() @@ -1741,13 +1740,8 @@ type Async = /// StartWithContinuations, except the exception continuation is given an ExceptionDispatchInfo static member StartWithContinuationsUsingDispatchInfo - ( - computation: Async<'T>, - continuation, - exceptionContinuation, - cancellationContinuation, - ?cancellationToken - ) : unit = + (computation: Async<'T>, continuation, exceptionContinuation, cancellationContinuation, ?cancellationToken) + : unit = let cancellationToken = defaultArg cancellationToken defaultCancellationTokenSource.Token @@ -1759,13 +1753,8 @@ type Async = cancellationContinuation static member StartWithContinuations - ( - computation: Async<'T>, - continuation, - exceptionContinuation, - cancellationContinuation, - ?cancellationToken - ) : unit = + (computation: Async<'T>, continuation, exceptionContinuation, cancellationContinuation, ?cancellationToken) + : unit = Async.StartWithContinuationsUsingDispatchInfo( computation, continuation, @@ -1939,11 +1928,8 @@ type Async = /// it happens the child computation will be cancelled. The resulting async doesn't support cancellation /// directly, rather the underlying computation must fill the result if cancellation occurs. static member AwaitAndBindChildResult - ( - innerCTS: CancellationTokenSource, - resultCell: ResultCell>, - millisecondsTimeout - ) : Async<'T> = + (innerCTS: CancellationTokenSource, resultCell: ResultCell>, millisecondsTimeout) + : Async<'T> = match millisecondsTimeout with | None | Some -1 -> resultCell |> Async.AwaitAndBindResult_NoDirectCancelOrTimeout 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/map.fs b/src/FSharp.Core/map.fs index b46bd9d357d..4eeed1465a1 100644 --- a/src/FSharp.Core/map.fs +++ b/src/FSharp.Core/map.fs @@ -1001,13 +1001,7 @@ type Map<[] 'Key, [ let txt1 = LanguagePrimitives.anyToStringShowingNull h1 let txt2 = LanguagePrimitives.anyToStringShowingNull h2 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/quotations.fs b/src/FSharp.Core/quotations.fs index 2f90f7a48ee..ea8b17d6f26 100644 --- a/src/FSharp.Core/quotations.fs +++ b/src/FSharp.Core/quotations.fs @@ -2531,13 +2531,8 @@ type Expr with mkStaticMethodCallW (methodInfo, methodInfoWithWitnesses, List.length witnesses, witnesses @ arguments) static member CallWithWitnesses - ( - obj: Expr, - methodInfo: MethodInfo, - methodInfoWithWitnesses: MethodInfo, - witnesses, - arguments - ) = + (obj: Expr, methodInfo: MethodInfo, methodInfoWithWitnesses: MethodInfo, witnesses, arguments) + = checkNonNull "methodInfo" methodInfo checkNonNull "methodInfoWithWitnesses" methodInfoWithWitnesses mkInstanceMethodCallW (obj, methodInfo, methodInfoWithWitnesses, List.length witnesses, witnesses @ arguments) diff --git a/src/FSharp.Core/reflect.fs b/src/FSharp.Core/reflect.fs index 32811ae604c..e0742b3dd06 100644 --- a/src/FSharp.Core/reflect.fs +++ b/src/FSharp.Core/reflect.fs @@ -1336,8 +1336,7 @@ type FSharpValue = static member PreComputeTupleConstructor(tupleType: Type) = checkTupleType ("tupleType", tupleType) - (compileTupleConstructor tupleEncField getTupleConstructorMethod tupleType) - .Invoke + (compileTupleConstructor tupleEncField getTupleConstructorMethod tupleType).Invoke static member PreComputeTupleConstructorInfo(tupleType: Type) = checkTupleType ("tupleType", tupleType) @@ -1445,10 +1444,8 @@ module FSharpReflectionExtensions = FSharpValue.GetRecordFields(record, bindingFlags) static member PreComputeRecordReader - ( - recordType: Type, - ?allowAccessToPrivateRepresentation - ) : (obj -> objnull array) = + (recordType: Type, ?allowAccessToPrivateRepresentation) + : (obj -> objnull array) = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.PreComputeRecordReader(recordType, bindingFlags) @@ -1481,18 +1478,14 @@ module FSharpReflectionExtensions = FSharpValue.GetUnionFields(value, unionType, bindingFlags) static member PreComputeUnionTagReader - ( - unionType: Type, - ?allowAccessToPrivateRepresentation - ) : (objnull -> int) = + (unionType: Type, ?allowAccessToPrivateRepresentation) + : (objnull -> int) = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.PreComputeUnionTagReader(unionType, bindingFlags) static member PreComputeUnionReader - ( - unionCase: UnionCaseInfo, - ?allowAccessToPrivateRepresentation - ) : (objnull -> objnull array) = + (unionCase: UnionCaseInfo, ?allowAccessToPrivateRepresentation) + : (objnull -> objnull array) = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.PreComputeUnionReader(unionCase, bindingFlags) 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/seq.fs b/src/FSharp.Core/seq.fs index 35adcdda557..20fcdefb159 100644 --- a/src/FSharp.Core/seq.fs +++ b/src/FSharp.Core/seq.fs @@ -478,8 +478,7 @@ module Internal = static member Bind(g: Generator<'T>, cont) = match g with | :? GenerateThen<'T> as g -> - GenerateThen<_> - .Bind(g.Generator, (fun () -> GenerateThen<_>.Bind(g.Cont(), cont))) + GenerateThen<_>.Bind(g.Generator, (fun () -> GenerateThen<_>.Bind(g.Cont(), cont))) | g -> (new GenerateThen<'T>(g, cont) :> Generator<'T>) let bindG g cont = @@ -854,7 +853,7 @@ module Seq = seq { use e = source.GetEnumerator() - for x in count .. - 1 .. 1 do + for x in count .. -1 .. 1 do if not (e.MoveNext()) then invalidOpFmt "{0}: tried to take {1} {2} past the end of the seq. Use Seq.truncate to get {3} or less elements" diff --git a/src/FSharp.Core/set.fs b/src/FSharp.Core/set.fs index 85fc718c461..f6ac7f99490 100644 --- a/src/FSharp.Core/set.fs +++ b/src/FSharp.Core/set.fs @@ -990,13 +990,7 @@ type Set<[] 'T when 'T: comparison>(comparer: IComparer<' let txt1 = LanguagePrimitives.anyToStringShowingNull h1 let txt2 = LanguagePrimitives.anyToStringShowingNull h2 - StringBuilder() - .Append("set [") - .Append(txt1) - .Append("; ") - .Append(txt2) - .Append("]") - .ToString() + StringBuilder().Append("set [").Append(txt1).Append("; ").Append(txt2).Append("]").ToString() | [ h1; h2; h3 ] -> let txt1 = LanguagePrimitives.anyToStringShowingNull h1 let txt2 = LanguagePrimitives.anyToStringShowingNull h2 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/FSharp.DependencyManager.Nuget/FSDependencyManager.txt b/src/FSharp.DependencyManager.Nuget/FSDependencyManager.txt index e70d2691151..6eb22c00f7a 100644 --- a/src/FSharp.DependencyManager.Nuget/FSDependencyManager.txt +++ b/src/FSharp.DependencyManager.Nuget/FSDependencyManager.txt @@ -9,4 +9,5 @@ highestVersion,"with the highest version" sourceDirectoryDoesntExist,"The source directory '%s' not found" timedoutResolvingPackages,"Timed out resolving packages, process: '%s' '%s'" invalidTimeoutValue,"Invalid value for timeout '%s', valid values: none, -1 and integer milliseconds to wait" -missingTimeoutValue,"Missing value for timeout" \ No newline at end of file +missingTimeoutValue,"Missing value for timeout" +invalidBooleanValue,"Invalid value for boolean '%s', valid values: true or false" \ No newline at end of file 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/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs index 553c97dc60f..f25d31a1ba7 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs @@ -11,6 +11,7 @@ type PackageReference = Version: string RestoreSources: string Script: string + UsePackageTargets: bool } module internal ProjectFile = diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs index 6b9d33ff663..ecfe86109aa 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs @@ -95,9 +95,7 @@ module internal Utilities = let getResolutionsFromFile resolutionsFile = let lines = try - File - .ReadAllText(resolutionsFile) - .Split([| '\r'; '\n' |], StringSplitOptions.None) + File.ReadAllText(resolutionsFile).Split([| '\r'; '\n' |], StringSplitOptions.None) |> Array.filter (String.IsNullOrEmpty >> not) with _ -> [||] diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs index fe0433f71cf..a1ff3c900bb 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs @@ -55,16 +55,30 @@ module FSharpDependencyManager = Version = ver RestoreSources = src Script = script + UsePackageTargets = usePackageTargets } = p + let usePackageTargets = + match usePackageTargets with + | false -> "ExcludeAssets='build;buildTransitive;buildMultitargeting'" + | true -> "" + seq { match not (String.IsNullOrEmpty(inc)), not (String.IsNullOrEmpty(ver)), not (String.IsNullOrEmpty(script)) with - | true, true, false -> yield sprintf @" " inc ver + | true, true, false -> + yield sprintf @" " inc ver usePackageTargets | true, true, true -> - yield sprintf @" " inc ver script - | true, false, false -> yield sprintf @" " inc - | true, false, true -> yield sprintf @" " inc script + yield + sprintf + @" " + inc + ver + script + usePackageTargets + | true, false, false -> yield sprintf @" " inc usePackageTargets + | true, false, true -> + yield sprintf @" " inc script usePackageTargets | _ -> () match not (String.IsNullOrEmpty(src)) with @@ -96,6 +110,7 @@ module FSharpDependencyManager = Version = "*" RestoreSources = "" Script = "" + UsePackageTargets = false } match options with @@ -114,11 +129,20 @@ module FSharpDependencyManager = let setVersion v = Some { current with Version = v } + let setUsePackageTargets v = + Some { current with UsePackageTargets = v } + match opt with | Some "include", Some v -> addInclude v |> parsePackageReferenceOption' rest implicitArgumentCount | Some "include", None -> raise (ArgumentException(SR.requiresAValue ("Include"))) | Some "version", Some v -> setVersion v |> parsePackageReferenceOption' rest implicitArgumentCount | Some "version", None -> setVersion "*" |> parsePackageReferenceOption' rest implicitArgumentCount + | Some "usepackagetargets", v -> + match v with + | Some v when v.ToLowerInvariant() = "true" -> setUsePackageTargets true + | Some v when v.ToLowerInvariant() = "false" -> setUsePackageTargets false + | _ -> raise (ArgumentException(SR.invalidBooleanValue ("usepackagetargets"))) + |> parsePackageReferenceOption' rest implicitArgumentCount | Some "restoresources", Some v -> Some { current with @@ -199,12 +223,8 @@ module FSharpDependencyManager = |> (fun l -> l, binLogPath, timeout) let computeHashForResolutionInputs - ( - scriptExt: string, - directiveLines: (string * string) seq, - targetFrameworkMoniker: string, - runtimeIdentifier: string - ) : string option = + (scriptExt: string, directiveLines: (string * string) seq, targetFrameworkMoniker: string, runtimeIdentifier: string) + : string option = let packageReferences, _, _ = directiveLines |> List.ofSeq |> parsePackageDirective scriptExt @@ -212,12 +232,12 @@ module FSharpDependencyManager = let referencesHaveWildCardVersion = // Verify to see if the developer specified a wildcard version. If they did then caching is not possible let hasWildCardVersion p = - // Todo: named record please let { Include = package Version = ver RestoreSources = _ Script = _ + UsePackageTargets = _ } = p diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.cs.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.cs.xlf index 800c2e40248..1df52699df6 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.cs.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.cs.xlf @@ -12,6 +12,11 @@ s nejvyšší verzí + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Neplatná hodnota pro časový limit {0}. Platné hodnoty: none, -1 a celočíselný počet milisekund, po které se má počkat diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.de.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.de.xlf index f3762130515..bb2ec8665b4 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.de.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.de.xlf @@ -12,6 +12,11 @@ mit der höchsten Version + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Ungültiger Wert für Timeout "{0}", gültige Werte: keine, -1 und ganzzahlige Millisekundenwerte für die Wartezeit diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.es.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.es.xlf index 2851c230dab..e9ee6650268 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.es.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.es.xlf @@ -12,6 +12,11 @@ con la última versión + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Valor de tiempo de espera "{0}" no válido. Valores válidos: ninguno, -1 y un número entero de milisegundos de espera diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.fr.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.fr.xlf index 8ab1dccc35f..60c4bb10953 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.fr.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.fr.xlf @@ -12,6 +12,11 @@ avec la version la plus récente + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Valeur non valide pour le délai d'expiration : '{0}'. Valeurs valides : aucune valeur, -1 ou un nombre entier pour le délai d'attente en millisecondes diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.it.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.it.xlf index c605c4af3ba..260e4879994 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.it.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.it.xlf @@ -12,6 +12,11 @@ con la versione massima + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Valore non valido per il timeout '{0}'. I valori validi sono: nessuno, -1 e numeri interi per i millisecondi di attesa diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ja.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ja.xlf index 2e19d06a10f..63bb78e5411 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ja.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ja.xlf @@ -12,6 +12,11 @@ 最新バージョン + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait タイムアウト '{0}' の値が無効です。有効な値: なし、-1、および整数 (待機するミリ秒) diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ko.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ko.xlf index 01d252b6243..2390149fd84 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ko.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ko.xlf @@ -12,6 +12,11 @@ 최상위 버전으로 + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait 시간 제한 '{0}'의 값이 잘못되었습니다. 유효한 값: 없음, -1 및 정수 대기 시간(밀리초) diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pl.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pl.xlf index 4ae0d2e448e..19b971eb1eb 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pl.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pl.xlf @@ -12,6 +12,11 @@ z najwyższą wersją + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Nieprawidłowa wartość limitu czasu „{0}”; prawidłowe wartości: none, -1 i liczba całkowita określająca liczbę milisekund oczekiwania diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pt-BR.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pt-BR.xlf index 7e8409fd8d7..fe73e35d112 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pt-BR.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.pt-BR.xlf @@ -12,6 +12,11 @@ com a versão mais recente + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Valor inválido para o tempo limite '{0}'. Valores válidos: none,-1 e milissegundos inteiros de espera diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ru.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ru.xlf index dafbfb8243d..c7f602855d5 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ru.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.ru.xlf @@ -12,6 +12,11 @@ с наивысшей версией + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Недопустимое значение времени ожидания "{0}". Допустимые значения: none, –1 и integer, мс ожидания. diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.tr.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.tr.xlf index 312793af714..585ac4950e4 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.tr.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.tr.xlf @@ -12,6 +12,11 @@ en yüksek sürümle + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait Zaman aşımı için '{0}' değeri geçersiz, geçerli değerler: none, -1 ve tamsayı milisaniye cinsinden bekleme süresi diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hans.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hans.xlf index 7e04d921b0a..2192ad1c9df 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hans.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hans.xlf @@ -12,6 +12,11 @@ 具有最高版本 + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait 超时 "{0}" 的值无效,有效值: none、-1 和要等待的毫秒数(整数) diff --git a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hant.xlf b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hant.xlf index d82293b0cf2..f7911a29659 100644 --- a/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hant.xlf +++ b/src/FSharp.DependencyManager.Nuget/xlf/FSDependencyManager.txt.zh-Hant.xlf @@ -12,6 +12,11 @@ 具有最高版本 + + Invalid value for boolean '{0}', valid values: true or false + Invalid value for boolean '{0}', valid values: true or false + + Invalid value for timeout '{0}', valid values: none, -1 and integer milliseconds to wait 逾時 '{0}' 值無效,有效的值: 無、-1 和要等候的整數毫秒 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/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.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) diff --git a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs index 693833ef4b8..1b68505ab1e 100644 --- a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs +++ b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs @@ -773,13 +773,6 @@ namespace N |> compile |> shouldFail |> withResults [ - { Error = Warning 3569 - Range = { StartLine = 21 - StartColumn = 27 - EndLine = 21 - EndColumn = 35 } - Message = - "The member or function 'instType' has the 'TailCallAttribute' attribute, but is not being used in a tail recursive way." } { Error = Warning 3569 Range = { StartLine = 17 StartColumn = 32 @@ -787,6 +780,13 @@ namespace N EndColumn = 77 } Message = "The member or function 'instType' has the 'TailCallAttribute' attribute, but is not being used in a tail recursive way." } + { Error = Warning 3569 + Range = { StartLine = 21 + StartColumn = 27 + EndLine = 21 + EndColumn = 35 } + Message = + "The member or function 'instType' has the 'TailCallAttribute' attribute, but is not being used in a tail recursive way." } ] [] @@ -1769,3 +1769,72 @@ module M = |> withLangVersion80 |> compile |> shouldSucceed + + [] + let ``Warn successfully in Array-mapped recursive call`` () = + """ +namespace N + +module M = + + type Value = + { Code: string } + + [] + let rec fooArray (values: Value[], code: string) = + match values with + | [||] -> seq { code } + | values -> + let replicatedValues = + values + |> Array.map (fun value -> fooArray (values, value.Code)) + replicatedValues |> Seq.concat + """ + |> FSharp + |> withLangVersion80 + |> compile + |> shouldFail + |> withResults [ + { Error = Warning 3569 + Range = { StartLine = 16 + StartColumn = 20 + EndLine = 16 + EndColumn = 74 } + Message = + "The member or function 'fooArray' has the 'TailCallAttribute' attribute, but is not being used in a tail recursive way." } + ] + + [] + let ``Warn successfully in Seq-mapped recursive call`` () = + """ +namespace N + +module M = + + type Value = + { Code: string } + + [] + let rec fooSeq (values: Value[], code: string) = + match values with + | [||] -> seq { code } + | values -> + let replicatedValues = + values + |> Seq.map (fun value -> fooSeq (values, value.Code)) + |> Seq.toArray + replicatedValues |> Seq.concat + """ + |> FSharp + |> withLangVersion80 + |> compile + |> shouldFail + |> withResults [ + { Error = Warning 3569 + Range = { StartLine = 16 + StartColumn = 42 + EndLine = 16 + EndColumn = 48 } + Message = + "The member or function 'fooSeq' has the 'TailCallAttribute' attribute, but is not being used in a tail recursive way." } + ] 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/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 d085005d9ac..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" @@ -513,3 +513,21 @@ let add (col:IServiceCollection) = let _value,diag = script.Eval(code) Assert.Empty(diag) + [] + [] + [] + [] + [] + member _.``Eval script with usepackagetargets options``(code, shouldSucceed, error) = + use script = new FSharpScript() + let result, errors = script.Eval(code) + match shouldSucceed with + | true -> + Assert.Empty(errors) + match result with + | Ok(_) -> () + | Error _ -> Assert.True(false, "expected no failures") + | false -> + Assert.NotEmpty(errors) + Assert.Equal(1, errors.Length) + Assert.Equal(error, errors.[0].ToString()) 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.SurfaceArea.netstandard20.debug.bsl b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.debug.bsl index 3bca6ffb96d..876c50378dd 100755 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.debug.bsl +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.debug.bsl @@ -2066,7 +2066,7 @@ FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.CodeAnalysi FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.CodeAnalysis.FSharpSymbolUse[] GetUsesOfSymbolInFile(FSharp.Compiler.Symbols.FSharpSymbol, Microsoft.FSharp.Core.FSharpOption`1[System.Threading.CancellationToken]) FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.Diagnostics.FSharpDiagnostic[] Diagnostics FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.Diagnostics.FSharpDiagnostic[] get_Diagnostics() -FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.EditorServices.DeclarationListInfo GetDeclarationListInfo(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults], Int32, System.String, FSharp.Compiler.EditorServices.PartialLongName, Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.EditorServices.AssemblySymbol]]], Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`2[FSharp.Compiler.Text.Position,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.EditorServices.CompletionContext]]]) +FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.EditorServices.DeclarationListInfo GetDeclarationListInfo(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults], Int32, System.String, FSharp.Compiler.EditorServices.PartialLongName, Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.EditorServices.AssemblySymbol]]], Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`2[FSharp.Compiler.Text.Position,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.EditorServices.CompletionContext]]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.EditorServices.FindDeclResult GetDeclarationLocation(Int32, Int32, System.String, Microsoft.FSharp.Collections.FSharpList`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.EditorServices.MethodGroup GetMethods(Int32, Int32, System.String, Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[System.String]]) FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.EditorServices.SemanticClassificationItem[] GetSemanticClassification(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range]) @@ -2079,7 +2079,7 @@ FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.Symbols.FSh FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.Symbols.FSharpOpenDeclaration[] get_OpenDeclarations() FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: FSharp.Compiler.Text.Range[] GetFormatSpecifierLocations() FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.FSharpSymbolUse] GetSymbolUsesAtLocation(Int32, Int32, System.String, Microsoft.FSharp.Collections.FSharpList`1[System.String]) -FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: Microsoft.FSharp.Collections.FSharpList`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.FSharpSymbolUse]] GetDeclarationListSymbols(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults], Int32, System.String, FSharp.Compiler.EditorServices.PartialLongName, Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.EditorServices.AssemblySymbol]]]) +FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: Microsoft.FSharp.Collections.FSharpList`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.FSharpSymbolUse]] GetDeclarationListSymbols(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults], Int32, System.String, FSharp.Compiler.EditorServices.PartialLongName, Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.EditorServices.AssemblySymbol]]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpSymbolUse] GetSymbolUseAtLocation(Int32, Int32, System.String, Microsoft.FSharp.Collections.FSharpList`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Symbols.FSharpDisplayContext] GetDisplayContextForPos(FSharp.Compiler.Text.Position) FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Symbols.FSharpImplementationFileContents] ImplementationFile @@ -2136,8 +2136,8 @@ FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, Int32, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults]] GetBackgroundCheckResultsForFileInProject(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) -FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectOptionsFromScript(System.String, FSharp.Compiler.Text.ISourceText, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) -FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectSnapshotFromScript(System.String, FSharp.Compiler.Text.ISourceTextNew, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectOptionsFromScript(System.String, FSharp.Compiler.Text.ISourceText, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Position], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectSnapshotFromScript(System.String, FSharp.Compiler.Text.ISourceTextNew, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Position], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.Diagnostics.FSharpDiagnostic[],Microsoft.FSharp.Core.FSharpOption`1[System.Exception]]] Compile(System.String[], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.Text.Range,FSharp.Compiler.Text.Range][]] MatchBraces(System.String, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpParsingOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.Text.Range,FSharp.Compiler.Text.Range][]] MatchBraces(System.String, System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) @@ -2838,12 +2838,20 @@ FSharp.Compiler.Diagnostics.ExtendedData+DiagnosticContextInfo: Int32 GetHashCod FSharp.Compiler.Diagnostics.ExtendedData+DiagnosticContextInfo: Int32 Tag FSharp.Compiler.Diagnostics.ExtendedData+DiagnosticContextInfo: Int32 get_Tag() FSharp.Compiler.Diagnostics.ExtendedData+DiagnosticContextInfo: System.String ToString() +FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] DiagnosticId +FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] UrlFormat +FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_DiagnosticId() +FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_UrlFormat() FSharp.Compiler.Diagnostics.ExtendedData+ExpressionIsAFunctionExtendedData: FSharp.Compiler.Symbols.FSharpType ActualType FSharp.Compiler.Diagnostics.ExtendedData+ExpressionIsAFunctionExtendedData: FSharp.Compiler.Symbols.FSharpType get_ActualType() FSharp.Compiler.Diagnostics.ExtendedData+FieldNotContainedDiagnosticExtendedData: FSharp.Compiler.Symbols.FSharpField ImplementationField FSharp.Compiler.Diagnostics.ExtendedData+FieldNotContainedDiagnosticExtendedData: FSharp.Compiler.Symbols.FSharpField SignatureField FSharp.Compiler.Diagnostics.ExtendedData+FieldNotContainedDiagnosticExtendedData: FSharp.Compiler.Symbols.FSharpField get_ImplementationField() FSharp.Compiler.Diagnostics.ExtendedData+FieldNotContainedDiagnosticExtendedData: FSharp.Compiler.Symbols.FSharpField get_SignatureField() +FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] DiagnosticId +FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] UrlFormat +FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_DiagnosticId() +FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_UrlFormat() FSharp.Compiler.Diagnostics.ExtendedData+TypeMismatchDiagnosticExtendedData: DiagnosticContextInfo ContextInfo FSharp.Compiler.Diagnostics.ExtendedData+TypeMismatchDiagnosticExtendedData: DiagnosticContextInfo get_ContextInfo() FSharp.Compiler.Diagnostics.ExtendedData+TypeMismatchDiagnosticExtendedData: FSharp.Compiler.Symbols.FSharpDisplayContext DisplayContext @@ -2859,21 +2867,13 @@ FSharp.Compiler.Diagnostics.ExtendedData+ValueNotContainedDiagnosticExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+ArgumentsInSigAndImplMismatchExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+DefinitionsInSigAndImplNotCompatibleAbbreviationsDifferExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+DiagnosticContextInfo +FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+ExpressionIsAFunctionExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+FieldNotContainedDiagnosticExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+IFSharpDiagnosticExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+TypeMismatchDiagnosticExtendedData FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+ValueNotContainedDiagnosticExtendedData -FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] DiagnosticId -FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] UrlFormat -FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_DiagnosticId() -FSharp.Compiler.Diagnostics.ExtendedData+ObsoleteDiagnosticExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_UrlFormat() -FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] DiagnosticId -FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] UrlFormat -FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_DiagnosticId() -FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData: Microsoft.FSharp.Core.FSharpOption`1[System.String] get_UrlFormat() -FSharp.Compiler.Diagnostics.ExtendedData: FSharp.Compiler.Diagnostics.ExtendedData+ExperimentalExtendedData FSharp.Compiler.Diagnostics.FSharpDiagnostic: FSharp.Compiler.Diagnostics.FSharpDiagnostic Create(FSharp.Compiler.Diagnostics.FSharpDiagnosticSeverity, System.String, Int32, FSharp.Compiler.Text.Range, Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.Diagnostics.FSharpDiagnostic: FSharp.Compiler.Diagnostics.FSharpDiagnosticSeverity Severity FSharp.Compiler.Diagnostics.FSharpDiagnostic: FSharp.Compiler.Diagnostics.FSharpDiagnosticSeverity get_Severity() @@ -3055,7 +3055,9 @@ FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: FSharp.Compiler FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: FSharp.Compiler.EditorServices.MethodOverrideCompletionContext get_ctx() FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: FSharp.Compiler.Text.Range enclosingTypeNameRange FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: FSharp.Compiler.Text.Range get_enclosingTypeNameRange() +FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: Int32 get_spacesBeforeEnclosingDefinition() FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: Int32 get_spacesBeforeOverrideKeyword() +FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: Int32 spacesBeforeEnclosingDefinition FSharp.Compiler.EditorServices.CompletionContext+MethodOverride: Int32 spacesBeforeOverrideKeyword FSharp.Compiler.EditorServices.CompletionContext+OpenDeclaration: Boolean get_isOpenType() FSharp.Compiler.EditorServices.CompletionContext+OpenDeclaration: Boolean isOpenType @@ -3110,7 +3112,7 @@ FSharp.Compiler.EditorServices.CompletionContext: Boolean get_IsUnionCaseFieldsD FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext AttributeApplication FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext Invalid FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext NewInherit(FSharp.Compiler.EditorServices.InheritanceContext, System.Tuple`2[Microsoft.FSharp.Collections.FSharpList`1[System.String],Microsoft.FSharp.Core.FSharpOption`1[System.String]]) -FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext NewMethodOverride(FSharp.Compiler.EditorServices.MethodOverrideCompletionContext, FSharp.Compiler.Text.Range, Int32, Boolean, Boolean) +FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext NewMethodOverride(FSharp.Compiler.EditorServices.MethodOverrideCompletionContext, FSharp.Compiler.Text.Range, Int32, Boolean, Boolean, Int32) FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext NewOpenDeclaration(Boolean) FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext NewParameterList(FSharp.Compiler.Text.Position, System.Collections.Generic.HashSet`1[System.String]) FSharp.Compiler.EditorServices.CompletionContext: FSharp.Compiler.EditorServices.CompletionContext NewPattern(FSharp.Compiler.EditorServices.PatternContext) diff --git a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl index f888a85a1a3..876c50378dd 100755 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl @@ -2136,8 +2136,8 @@ FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, Int32, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults]] GetBackgroundCheckResultsForFileInProject(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) -FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectOptionsFromScript(System.String, FSharp.Compiler.Text.ISourceText, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) -FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectSnapshotFromScript(System.String, FSharp.Compiler.Text.ISourceTextNew, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectOptionsFromScript(System.String, FSharp.Compiler.Text.ISourceText, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Position], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectSnapshotFromScript(System.String, FSharp.Compiler.Text.ISourceTextNew, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Position], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.Diagnostics.FSharpDiagnostic[],Microsoft.FSharp.Core.FSharpOption`1[System.Exception]]] Compile(System.String[], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.Text.Range,FSharp.Compiler.Text.Range][]] MatchBraces(System.String, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpParsingOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.Text.Range,FSharp.Compiler.Text.Range][]] MatchBraces(System.String, System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) 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 71bffac7974..cef9b119c77 100644 --- a/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs @@ -1,6 +1,9 @@ module FSharp.Compiler.Service.Tests.ProjectAnalysisTests +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 @@ -128,8 +131,20 @@ module ClearLanguageServiceRootCachesTest = let weakTcImports = test () checker.InvalidateConfiguration Project1.options checker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() - GC.Collect() - System.Threading.SpinWait.SpinUntil(fun () -> not weakTcImports.IsAlive) + + task { + GC.Collect() + GC.WaitForPendingFinalizers() + // Try collecting many times, because GC has some problems, especially on Linux. + // See for example: https://github.com/dotnet/runtime/discussions/108081 + let mutable attempt = 1 + while weakTcImports.IsAlive && attempt < 10 do + GC.Collect() + GC.WaitForPendingFinalizers() + attempt <- attempt + 1 + do! Task.Delay(attempt * 1000) + Assert.False weakTcImports.IsAlive + } [] let ``Test Project1 should have protected FullName and TryFullName return same results`` () = @@ -5446,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 [||] @@ -5454,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 |] @@ -5462,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 [||] @@ -5470,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 |] @@ -5478,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/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl index de3366d582e..69842b9e059 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl @@ -21,9 +21,9 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.CodeAnalysis.Hosted.CompilerHelpers::fscCompile([FSharp.Compiler.Service]FSharp.Compiler.CodeAnalysis.LegacyReferenceResolver, string, string[])][offset 0x00000082][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CodeAnalysis.Hosted.CompilerHelpers::fscCompile([FSharp.Compiler.Service]FSharp.Compiler.CodeAnalysis.LegacyReferenceResolver, string, string[])][offset 0x0000008B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+MagicAssemblyResolution::ResolveAssemblyCore([FSharp.Compiler.Service]Internal.Utilities.Library.CompilationThreadToken, [FSharp.Compiler.Service]FSharp.Compiler.Text.Range, [FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, [FSharp.Compiler.Service]FSharp.Compiler.CompilerImports+TcImports, [FSharp.Compiler.Service]FSharp.Compiler.Interactive.Shell+FsiDynamicCompiler, [FSharp.Compiler.Service]FSharp.Compiler.Interactive.Shell+FsiConsoleOutput, string)][offset 0x00000015][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+clo@3516-807::Invoke([S.P.CoreLib]System.Tuple`3)][offset 0x000001E5][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+clo@3502-805::Invoke([S.P.CoreLib]System.Tuple`3)][offset 0x000001E5][found Char] Unexpected type on the stack. [IL]: Error [UnmanagedPointer]: : FSharp.Compiler.Interactive.Shell+Utilities+pointerToNativeInt@110::Invoke(object)][offset 0x00000007] Unmanaged pointers are not a verifiable type. -[IL]: Error [StackUnexpected]: : .$FSharpCheckerResults+dataTipOfReferences@2232::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000084][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : .$FSharpCheckerResults+dataTipOfReferences@2225::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000084][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-509::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x00000032][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-509::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x0000003B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-509::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x00000082][found Char] Unexpected type on the stack. @@ -37,8 +37,8 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions+getOptionArgList@307::Invoke([FSharp.Compiler.Service]FSharp.Compiler.CompilerOptions+CompilerOption, string)][offset 0x0000003E][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions+getSwitch@325::Invoke(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions+attempt@373::Invoke([FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1)][offset 0x00000E9F][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+Pipe #1 stage #1 at line 1865@1865::Invoke(int32)][offset 0x00000030][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+Pipe #1 stage #1 at line 1865@1865::Invoke(int32)][offset 0x00000039][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.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. @@ -50,12 +50,12 @@ [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. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::openMetadataReader(string, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+BinaryFile, int32, [S.P.CoreLib]System.Tuple`8,bool,bool,bool,bool,bool,System.Tuple`5,bool,int32,int32,int32>>, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+PEReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1, bool)][offset 0x00000799][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+rowKindSize@4453::Invoke([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+RowKind)][offset 0x00000128][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+rowKindSize@4445::Invoke([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+RowKind)][offset 0x00000128][found Byte] 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.DiagnosticsLogger::.cctor()][offset 0x000000CD][found Char] 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 ef86f8257da..fa36beeef27 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_netstandard2.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_netstandard2.0.bsl @@ -31,7 +31,7 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+clo@3516-807::Invoke([S.P.CoreLib]System.Tuple`3)][offset 0x000001E5][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+FsiInteractionProcessor::CompletionsForPartialLID([FSharp.Compiler.Service]FSharp.Compiler.Interactive.Shell+FsiDynamicCompilerState, string)][offset 0x0000001B][found Char] Unexpected type on the stack. [IL]: Error [UnmanagedPointer]: : FSharp.Compiler.Interactive.Shell+Utilities+pointerToNativeInt@110::Invoke(object)][offset 0x00000007] Unmanaged pointers are not a verifiable type. -[IL]: Error [StackUnexpected]: : .$FSharpCheckerResults+dataTipOfReferences@2232::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000084][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : .$FSharpCheckerResults+dataTipOfReferences@2225::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000084][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.EditorServices.AssemblyContent+traverseMemberFunctionAndValues@176::Invoke([FSharp.Compiler.Service]FSharp.Compiler.Symbols.FSharpMemberOrFunctionOrValue)][offset 0x00000059][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.EditorServices.AssemblyContent+traverseEntity@218::GenerateNext([S.P.CoreLib]System.Collections.Generic.IEnumerable`1&)][offset 0x000000DA][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.EditorServices.ParsedInput+visitor@1424-6::VisitExpr([FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, [FSharp.Compiler.Service]FSharp.Compiler.Syntax.SynExpr)][offset 0x00000605][found Char] Unexpected type on the stack. @@ -53,9 +53,9 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions+attempt@373::Invoke([FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1)][offset 0x00000E9F][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions+processArg@333::Invoke([FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1)][offset 0x0000004D][found Char] Unexpected type on the stack. [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 1865@1865::Invoke(int32)][offset 0x00000030][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+Pipe #1 stage #1 at line 1865@1865::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.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@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,18 +70,24 @@ [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. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::openMetadataReader(string, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+BinaryFile, int32, [S.P.CoreLib]System.Tuple`8,bool,bool,bool,bool,bool,System.Tuple`5,bool,int32,int32,int32>>, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+PEReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1, bool)][offset 0x00000799][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+rowKindSize@4453::Invoke([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+RowKind)][offset 0x00000128][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+rowKindSize@4445::Invoke([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+RowKind)][offset 0x00000128][found Byte] Unexpected type on the stack. [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. +<<<<<<< HEAD [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]: : Internal.Utilities.Collections.Utils::shortPath(string)][offset 0x00000048][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.FSharpEnvironment+probePathForDotnetHost@322::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000028][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. +>>>>>>> c01bc471ec95865b71b4a7f535bd6e2884e094f7 [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. [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.DiagnosticsLogger::.cctor()][offset 0x000000CD][found Char] Unexpected type on the stack. [IL]: Error [CallVirtOnValueType]: : FSharp.Compiler.Text.RangeModule+comparer@558::System.Collections.Generic.IEqualityComparer.GetHashCode([FSharp.Compiler.Service]FSharp.Compiler.Text.Range)][offset 0x00000002] Callvirt on a value type method. @@ -95,4 +101,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 3db64fc56e3..e23aa8e4433 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_net9.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_net9.0.bsl @@ -28,8 +28,8 @@ [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-530::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x00000064][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-530::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x0000006D][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-530::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x00000076][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@301-1::Invoke(string)][offset 0x0000000B][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@301-1::Invoke(string)][offset 0x00000014][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@291-1::Invoke(string)][offset 0x0000000B][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@291-1::Invoke(string)][offset 0x00000014][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.StaticLinking+TypeForwarding::followTypeForwardForILTypeRef([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILTypeRef)][offset 0x00000010][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions::getCompilerOption([FSharp.Compiler.Service]FSharp.Compiler.CompilerOptions+CompilerOption, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1)][offset 0x000000A7][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions::parseOption@266(string)][offset 0x0000000B][found Char] Unexpected type on the stack. @@ -39,12 +39,12 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions::attempt@372([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, string, string, string, string, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1)][offset 0x00000A99][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions::AddPathMapping([FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnderflow]: : FSharp.Compiler.CompilerOptions::DoWithColor([System.Console]System.ConsoleColor, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2)][offset 0x0000005E] Stack underflow. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+CheckMultipleInputsUsingGraphMode@1865::Invoke(int32)][offset 0x00000031][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+CheckMultipleInputsUsingGraphMode@1865::Invoke(int32)][offset 0x0000003A][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.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@1890-1'][expected ref '[FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,int32>'] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.IlxGen::HashRangeSorted([S.P.CoreLib]System.Collections.Generic.IDictionary`2>)][offset 0x00000012][found ref '[FSharp.Compiler.Service]FSharp.Compiler.IlxGen+HashRangeSorted@1890'][expected ref '[FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,T0>'] 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. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.IlxGen::HashRangeSorted([S.P.CoreLib]System.Collections.Generic.IDictionary`2>)][offset 0x00000012][found ref '[FSharp.Compiler.Service]FSharp.Compiler.IlxGen+HashRangeSorted@1873'][expected ref '[FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,T0>'] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.PatternMatchCompilation::isProblematicClause([FSharp.Compiler.Service]FSharp.Compiler.PatternMatchCompilation+MatchClause)][offset 0x00000040][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.PatternMatchCompilation::.cctor()][offset 0x0000000B][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.TypeProviders::ValidateExpectedName([FSharp.Compiler.Service]FSharp.Compiler.Text.Range, string[], string, [FSharp.Compiler.Service]FSharp.Compiler.Tainted`1)][offset 0x000000A8][found Char] Unexpected type on the stack. @@ -74,7 +74,7 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadNestedRowUncached([FSharp.Core]Microsoft.FSharp.Core.FSharpRef`1>, int32)][offset 0x00000038][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadNestedRowUncached([FSharp.Core]Microsoft.FSharp.Core.FSharpRef`1>, int32)][offset 0x00000058][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadGenericParamConstraintIdx([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+ILMetadataReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, int32)][offset 0x00000025][found Byte] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::rowKindSize$cont@4454(bool, bool, bool, bool[], bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x000000E5][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::rowKindSize$cont@4446(bool, bool, bool, bool[], bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x000000E5][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::openMetadataReader(string, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+BinaryFile, int32, [S.P.CoreLib]System.Tuple`8,bool,bool,bool,bool,bool,System.Tuple`5,bool,int32,int32,int32>>, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+PEReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1, bool)][offset 0x000006BF][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+seekReadInterfaceImpls@2263-3::Invoke(int32)][offset 0x0000002F][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+seekReadGenericParamConstraints@2328-2::Invoke(int32)][offset 0x0000002F][found Byte] Unexpected type on the stack. @@ -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 6f265143ee3..eaa05f7f314 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_netstandard2.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_netstandard2.0.bsl @@ -30,7 +30,7 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+MagicAssemblyResolution::ResolveAssemblyCore([FSharp.Compiler.Service]Internal.Utilities.Library.CompilationThreadToken, [FSharp.Compiler.Service]FSharp.Compiler.Text.Range, [FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, [FSharp.Compiler.Service]FSharp.Compiler.CompilerImports+TcImports, [FSharp.Compiler.Service]FSharp.Compiler.Interactive.Shell+FsiDynamicCompiler, [FSharp.Compiler.Service]FSharp.Compiler.Interactive.Shell+FsiConsoleOutput, string)][offset 0x00000015][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+clo@3516-850::Invoke([S.P.CoreLib]System.Tuple`3)][offset 0x000001C7][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.Interactive.Shell+FsiInteractionProcessor::CompletionsForPartialLID([FSharp.Compiler.Service]FSharp.Compiler.Interactive.Shell+FsiDynamicCompilerState, string)][offset 0x00000024][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : .$FSharpCheckerResults+GetReferenceResolutionStructuredToolTipText@2232::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000076][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : .$FSharpCheckerResults+GetReferenceResolutionStructuredToolTipText@2225::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000076][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.EditorServices.AssemblyContent+traverseMemberFunctionAndValues@176::Invoke([FSharp.Compiler.Service]FSharp.Compiler.Symbols.FSharpMemberOrFunctionOrValue)][offset 0x0000002B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.EditorServices.AssemblyContent+traverseEntity@218::GenerateNext([S.P.CoreLib]System.Collections.Generic.IEnumerable`1&)][offset 0x000000BB][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.EditorServices.ParsedInput+visitor@1424-11::VisitExpr([FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, [FSharp.Compiler.Service]FSharp.Compiler.Syntax.SynExpr)][offset 0x00000620][found Char] Unexpected type on the stack. @@ -40,8 +40,8 @@ [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-530::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x0000006D][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$ServiceLexing+clo@921-530::Invoke([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.Unit>)][offset 0x00000076][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$Symbols+fullName@2495-3::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000030][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@301-1::Invoke(string)][offset 0x0000000B][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@301-1::Invoke(string)][offset 0x00000014][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@291-1::Invoke(string)][offset 0x0000000B][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.Driver+ProcessCommandLineFlags@291-1::Invoke(string)][offset 0x00000014][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CreateILModule+MainModuleBuilder::ConvertProductVersionToILVersionInfo(string)][offset 0x00000010][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.StaticLinking+TypeForwarding::followTypeForwardForILTypeRef([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILTypeRef)][offset 0x00000010][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions::getCompilerOption([FSharp.Compiler.Service]FSharp.Compiler.CompilerOptions+CompilerOption, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1)][offset 0x000000A7][found Char] Unexpected type on the stack. @@ -55,14 +55,14 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions::subSystemVersionSwitch$cont@656([FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, string, [FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnderflow]: : FSharp.Compiler.CompilerOptions::DoWithColor([System.Console]System.ConsoleColor, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2)][offset 0x0000005E] Stack underflow. [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@1865::Invoke(int32)][offset 0x00000031][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+CheckMultipleInputsUsingGraphMode@1865::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.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@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@1890-1'][expected ref '[FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,int32>'] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.IlxGen::HashRangeSorted([S.P.CoreLib]System.Collections.Generic.IDictionary`2>)][offset 0x00000012][found ref '[FSharp.Compiler.Service]FSharp.Compiler.IlxGen+HashRangeSorted@1890'][expected ref '[FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,T0>'] 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. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.IlxGen::HashRangeSorted([S.P.CoreLib]System.Collections.Generic.IDictionary`2>)][offset 0x00000012][found ref '[FSharp.Compiler.Service]FSharp.Compiler.IlxGen+HashRangeSorted@1873'][expected ref '[FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,T0>'] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.PatternMatchCompilation::isProblematicClause([FSharp.Compiler.Service]FSharp.Compiler.PatternMatchCompilation+MatchClause)][offset 0x00000040][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.PatternMatchCompilation::.cctor()][offset 0x0000000B][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.NicePrint+TastDefinitionPrinting+meths@2092-3::Invoke([FSharp.Compiler.Service]FSharp.Compiler.Infos+MethInfo)][offset 0x000000B3][found Char] Unexpected type on the stack. @@ -95,7 +95,7 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadNestedRowUncached([FSharp.Core]Microsoft.FSharp.Core.FSharpRef`1>, int32)][offset 0x00000038][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadNestedRowUncached([FSharp.Core]Microsoft.FSharp.Core.FSharpRef`1>, int32)][offset 0x00000058][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadGenericParamConstraintIdx([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+ILMetadataReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, int32)][offset 0x00000025][found Byte] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::rowKindSize$cont@4454(bool, bool, bool, bool[], bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x000000E5][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::rowKindSize$cont@4446(bool, bool, bool, bool[], bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, [FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x000000E5][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::openMetadataReader(string, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+BinaryFile, int32, [S.P.CoreLib]System.Tuple`8,bool,bool,bool,bool,bool,System.Tuple`5,bool,int32,int32,int32>>, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+PEReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1, bool)][offset 0x000006BF][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+seekReadInterfaceImpls@2263-3::Invoke(int32)][offset 0x0000002F][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader+seekReadGenericParamConstraints@2328-2::Invoke(int32)][offset 0x0000002F][found Byte] Unexpected type on the stack. @@ -106,9 +106,15 @@ [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. +<<<<<<< HEAD [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]: : Internal.Utilities.Collections.Utils::shortPath(string)][offset 0x0000003A][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.FSharpEnvironment::probePathForDotnetHost@321([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x0000002A][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. +>>>>>>> c01bc471ec95865b71b4a7f535bd6e2884e094f7 [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. [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.DiagnosticsLogger::.cctor()][offset 0x000000B6][found Char] Unexpected type on the stack. [IL]: Error [CallVirtOnValueType]: : FSharp.Compiler.Text.RangeModule+comparer@558::System.Collections.Generic.IEqualityComparer.GetHashCode([FSharp.Compiler.Service]FSharp.Compiler.Text.Range)][offset 0x00000002] Callvirt on a value type method. @@ -122,4 +128,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. diff --git a/tests/fsharp/core/printing/output.1000.stdout.bsl b/tests/fsharp/core/printing/output.1000.stdout.bsl index 1d5c0fcbae2..e2f3a8d57c8 100644 --- a/tests/fsharp/core/printing/output.1000.stdout.bsl +++ b/tests/fsharp/core/printing/output.1000.stdout.bsl @@ -2787,7 +2787,7 @@ val ShortName: string = "hi" > val list2: int list = [1] module FSI_0319. - A8a951db8294f99e95ae1d276a7ddaefd93d1548e6bf749bdeae55d2649682b3 + Ee54a783c1b4e3fe8e3c42c5a10c384669fed24c7ffbdacfc9698816f925f337 {"ImmutableField0":6} type R1 = diff --git a/tests/fsharp/core/printing/output.200.stdout.bsl b/tests/fsharp/core/printing/output.200.stdout.bsl index 52926a6c17a..a707919336b 100644 --- a/tests/fsharp/core/printing/output.200.stdout.bsl +++ b/tests/fsharp/core/printing/output.200.stdout.bsl @@ -2032,7 +2032,7 @@ val ShortName: string = "hi" > val list2: int list = [1] module FSI_0319. - A8a951db8294f99e95ae1d276a7ddaefd93d1548e6bf749bdeae55d2649682b3 + Ee54a783c1b4e3fe8e3c42c5a10c384669fed24c7ffbdacfc9698816f925f337 {"ImmutableField0":6} type R1 = diff --git a/tests/fsharp/core/printing/output.multiemit.stdout.bsl b/tests/fsharp/core/printing/output.multiemit.stdout.bsl index 2933f92f8b5..9cdf63bcc36 100644 --- a/tests/fsharp/core/printing/output.multiemit.stdout.bsl +++ b/tests/fsharp/core/printing/output.multiemit.stdout.bsl @@ -6334,7 +6334,7 @@ val ShortName: string = "hi" > val list2: int list = [1] module FSI_0318. - A8a951db8294f99e95ae1d276a7ddaefd93d1548e6bf749bdeae55d2649682b3 + Ee54a783c1b4e3fe8e3c42c5a10c384669fed24c7ffbdacfc9698816f925f337 {"ImmutableField0":6} type R1 = diff --git a/tests/fsharp/core/printing/output.off.stdout.bsl b/tests/fsharp/core/printing/output.off.stdout.bsl index 66ff18c8fb9..5806de4d312 100644 --- a/tests/fsharp/core/printing/output.off.stdout.bsl +++ b/tests/fsharp/core/printing/output.off.stdout.bsl @@ -1801,7 +1801,7 @@ val ShortName: string = "hi" > val list2: int list module FSI_0319. - A8a951db8294f99e95ae1d276a7ddaefd93d1548e6bf749bdeae55d2649682b3 + Ee54a783c1b4e3fe8e3c42c5a10c384669fed24c7ffbdacfc9698816f925f337 {"ImmutableField0":6} type R1 = diff --git a/tests/fsharp/core/printing/output.stdout.bsl b/tests/fsharp/core/printing/output.stdout.bsl index 2933f92f8b5..9cdf63bcc36 100644 --- a/tests/fsharp/core/printing/output.stdout.bsl +++ b/tests/fsharp/core/printing/output.stdout.bsl @@ -6334,7 +6334,7 @@ val ShortName: string = "hi" > val list2: int list = [1] module FSI_0318. - A8a951db8294f99e95ae1d276a7ddaefd93d1548e6bf749bdeae55d2649682b3 + Ee54a783c1b4e3fe8e3c42c5a10c384669fed24c7ffbdacfc9698816f925f337 {"ImmutableField0":6} type R1 = 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 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.Editor/Classification/ClassificationDefinitions.fs b/vsintegration/src/FSharp.Editor/Classification/ClassificationDefinitions.fs index 2b194fe27fd..c39e608a4d1 100644 --- a/vsintegration/src/FSharp.Editor/Classification/ClassificationDefinitions.fs +++ b/vsintegration/src/FSharp.Editor/Classification/ClassificationDefinitions.fs @@ -128,10 +128,7 @@ module internal ClassificationDefinitions = ] let setIsDarkBackground () = - isDarkBackground <- - VSColorTheme - .GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey) - .GetBrightness() < 0.5f + isDarkBackground <- VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey).GetBrightness() < 0.5f let setColors _ = diff --git a/vsintegration/src/FSharp.Editor/Classification/ClassificationService.fs b/vsintegration/src/FSharp.Editor/Classification/ClassificationService.fs index afdb990489b..fa17d938f10 100644 --- a/vsintegration/src/FSharp.Editor/Classification/ClassificationService.fs +++ b/vsintegration/src/FSharp.Editor/Classification/ClassificationService.fs @@ -149,12 +149,8 @@ type internal FSharpClassificationService [] () = member _.AddLexicalClassifications(_: SourceText, _: TextSpan, _: List, _: CancellationToken) = () member _.AddSyntacticClassificationsAsync - ( - document: Document, - textSpan: TextSpan, - result: List, - cancellationToken: CancellationToken - ) = + (document: Document, textSpan: TextSpan, result: List, cancellationToken: CancellationToken) + = cancellableTask { use _logBlock = Logger.LogBlock(LogEditorFunctionId.Classification_Syntactic) @@ -201,12 +197,8 @@ type internal FSharpClassificationService [] () = |> CancellableTask.startAsTask cancellationToken member _.AddSemanticClassificationsAsync - ( - document: Document, - textSpan: TextSpan, - result: List, - cancellationToken: CancellationToken - ) = + (document: Document, textSpan: TextSpan, result: List, cancellationToken: CancellationToken) + = cancellableTask { use _logBlock = Logger.LogBlock(LogEditorFunctionId.Classification_Semantic) diff --git a/vsintegration/src/FSharp.Editor/CodeFixes/ImplementInterface.fs b/vsintegration/src/FSharp.Editor/CodeFixes/ImplementInterface.fs index ca85c9621fe..1805428b8d7 100644 --- a/vsintegration/src/FSharp.Editor/CodeFixes/ImplementInterface.fs +++ b/vsintegration/src/FSharp.Editor/CodeFixes/ImplementInterface.fs @@ -123,14 +123,8 @@ type internal ImplementInterfaceCodeFixProvider [] () = | None -> [ stubChange ] let getSuggestions - ( - sourceText: SourceText, - results: FSharpCheckFileResults, - state: InterfaceState, - displayContext, - entity, - indentSize - ) = + (sourceText: SourceText, results: FSharpCheckFileResults, state: InterfaceState, displayContext, entity, indentSize) + = if InterfaceStubGenerator.HasNoInterfaceMember entity then CancellableTask.singleton Seq.empty else diff --git a/vsintegration/src/FSharp.Editor/CodeFixes/MakeOuterBindingRecursive.fs b/vsintegration/src/FSharp.Editor/CodeFixes/MakeOuterBindingRecursive.fs index 0d52dbdfa86..267832a1aff 100644 --- a/vsintegration/src/FSharp.Editor/CodeFixes/MakeOuterBindingRecursive.fs +++ b/vsintegration/src/FSharp.Editor/CodeFixes/MakeOuterBindingRecursive.fs @@ -34,9 +34,7 @@ type internal MakeOuterBindingRecursiveCodeFixProvider [] |> ValueOption.ofOption |> ValueOption.map (fun bindingRange -> RoslynHelpers.FSharpRangeToTextSpan(sourceText, bindingRange)) |> ValueOption.filter (fun bindingSpan -> - sourceText - .GetSubText(bindingSpan) - .ContentEquals(sourceText.GetSubText context.Span)) + sourceText.GetSubText(bindingSpan).ContentEquals(sourceText.GetSubText context.Span)) |> ValueOption.map (fun bindingSpan -> let title = String.Format(SR.MakeOuterBindingRecursive(), sourceText.GetSubText(bindingSpan).ToString()) diff --git a/vsintegration/src/FSharp.Editor/Commands/XmlDocCommandService.fs b/vsintegration/src/FSharp.Editor/Commands/XmlDocCommandService.fs index 7fb2e008368..e87fda21539 100644 --- a/vsintegration/src/FSharp.Editor/Commands/XmlDocCommandService.fs +++ b/vsintegration/src/FSharp.Editor/Commands/XmlDocCommandService.fs @@ -108,10 +108,7 @@ type internal XmlDocCommandFilter(wpfTextView: IWpfTextView, filePath: string, w paramNames |> List.iter (fun p -> - toInsert - .AppendLine() - .Append(' ', indent) - .Append(sprintf "/// " p) + toInsert.AppendLine().Append(' ', indent).Append(sprintf "/// " p) |> ignore) let _newSS = diff --git a/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs b/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs index 73e984f934f..124f3de404c 100644 --- a/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs +++ b/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs @@ -8,6 +8,4 @@ open Microsoft.VisualStudio.Shell // This adds $PackageFolder$ to the directories probed for assemblies to load. // The attribute is inexplicably class-targeted, hence the dummy class. [] -type private BindingPathForUIResources = - class - end +type private BindingPathForUIResources = class end diff --git a/vsintegration/src/FSharp.Editor/Common/CodeAnalysisExtensions.fs b/vsintegration/src/FSharp.Editor/Common/CodeAnalysisExtensions.fs index 4776a963a5c..e0b29c8f9f1 100644 --- a/vsintegration/src/FSharp.Editor/Common/CodeAnalysisExtensions.fs +++ b/vsintegration/src/FSharp.Editor/Common/CodeAnalysisExtensions.fs @@ -9,17 +9,11 @@ type Project with /// Returns the projectIds of all projects within the same solution that directly reference this project member this.GetDependentProjectIds() = - this.Solution - .GetProjectDependencyGraph() - .GetProjectsThatDirectlyDependOnThisProject - this.Id + this.Solution.GetProjectDependencyGraph().GetProjectsThatDirectlyDependOnThisProject this.Id /// Returns all projects within the same solution that directly reference this project. member this.GetDependentProjects() = - this.Solution - .GetProjectDependencyGraph() - .GetProjectsThatDirectlyDependOnThisProject - this.Id + this.Solution.GetProjectDependencyGraph().GetProjectsThatDirectlyDependOnThisProject this.Id |> Seq.map this.Solution.GetProject /// Returns the ProjectIds of all of the projects that this project directly or transitively depends on diff --git a/vsintegration/src/FSharp.Editor/Common/Extensions.fs b/vsintegration/src/FSharp.Editor/Common/Extensions.fs index 5b154deab73..2ed87e5ec82 100644 --- a/vsintegration/src/FSharp.Editor/Common/Extensions.fs +++ b/vsintegration/src/FSharp.Editor/Common/Extensions.fs @@ -7,9 +7,15 @@ open System open System.IO open System.Collections.Immutable open System.Collections.Generic +open System.Runtime.InteropServices open System.Threading open System.Threading.Tasks +open Microsoft.VisualStudio +open Microsoft.VisualStudio.Shell +open Microsoft.VisualStudio.Shell.Interop +open Microsoft.VisualStudio.TextManager.Interop + open Microsoft.CodeAnalysis open Microsoft.CodeAnalysis.Text open Microsoft.CodeAnalysis.Host @@ -19,6 +25,10 @@ open FSharp.Compiler.Syntax open FSharp.Compiler.Text open Microsoft.VisualStudio.FSharp.Editor +open Microsoft.VisualStudio.Editor +open Microsoft.VisualStudio.Text.Editor +open Microsoft.VisualStudio +open Microsoft.VisualStudio.OLE.Interop type private FSharpGlyph = FSharp.Compiler.EditorServices.FSharpGlyph type private FSharpRoslynGlyph = Microsoft.CodeAnalysis.ExternalAccess.FSharp.FSharpGlyph @@ -59,6 +69,56 @@ type Project with member this.IsFSharp = this.Language = LanguageNames.FSharp +type TextViewEventsHandler + ( + onChangeCaretHandler: (IVsTextView * int * int -> unit) option, + onKillFocus: (IVsTextView -> unit) option, + onSetFocus: (IVsTextView -> unit) option + ) = + interface IVsTextViewEvents with + member this.OnChangeCaretLine(view: IVsTextView, newline: int, oldline: int) = + onChangeCaretHandler + |> Option.iter (fun handler -> handler (view, newline, oldline)) + + member this.OnChangeScrollInfo + (_view: IVsTextView, _iBar: int, _iMinUnit: int, _iMaxUnits: int, _iVisibleUnits: int, _iFirstVisibleUnit: int) + = + () + + member this.OnKillFocus(view: IVsTextView) = + onKillFocus |> Option.iter (fun handler -> handler (view)) + + member this.OnSetBuffer(_view: IVsTextView, _buffer: IVsTextLines) = () + + member this.OnSetFocus(view: IVsTextView) = + onSetFocus |> Option.iter (fun handler -> handler (view)) + +type ConnectionPointSubscription = System.IDisposable option + +// Usage example: +// If a handler is None, to not handle that event +// 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) + + match textView with + | :? IConnectionPointContainer as cpContainer -> + let riid = typeof.GUID + let mutable cookie = 0u + + match cpContainer.FindConnectionPoint(ref riid) with + | null -> None + | cp -> + Some( + cp.Advise(handler, &cookie) + + { new IDisposable with + member _.Dispose() = cp.Unadvise(cookie) + } + ) + | _ -> None + type Document with member this.TryGetLanguageService<'T when 'T :> ILanguageService>() = @@ -69,6 +129,32 @@ type Document with | null -> None | languageServices -> languageServices.GetService<'T>() |> Some + member this.TryGetIVsTextView() : IVsTextView option = + match ServiceProvider.GlobalProvider.GetService(typeof) with + | :? IVsTextManager as textManager -> + // Grab IVsRunningDocumentTable + match ServiceProvider.GlobalProvider.GetService(typeof) with + | :? IVsRunningDocumentTable as rdt -> + match rdt.FindAndLockDocument(uint32 _VSRDTFLAGS.RDT_NoLock, this.FilePath) with + | hr, _, _, docData, _ when ErrorHandler.Succeeded(hr) && docData <> IntPtr.Zero -> + match Marshal.GetObjectForIUnknown docData with + | :? IVsTextBuffer as ivsTextBuffer -> + match textManager.GetActiveView(1, ivsTextBuffer) with + | hr, vsTextView when ErrorHandler.Succeeded(hr) -> Some vsTextView + | _ -> None + | _ -> None + | _ -> None + | _ -> None + | _ -> None + + member this.TryGetTextViewAndCaretPos() : (IVsTextView * Position) option = + match this.TryGetIVsTextView() with + | Some textView -> + match textView.GetCaretPos() with + | hr, line, column when ErrorHandler.Succeeded(hr) -> Some(textView, Position.fromZ line column) + | _ -> None + | None -> None + member this.IsFSharpScript = isScriptFile this.FilePath member this.IsFSharpSignatureFile = isSignatureFile this.FilePath @@ -208,11 +294,7 @@ module private SourceText = type SourceText with member this.ToFSharpSourceText() = - SourceText.weakTable.GetValue( - this, - Runtime.CompilerServices.ConditionalWeakTable<_, _> - .CreateValueCallback(SourceText.create) - ) + SourceText.weakTable.GetValue(this, Runtime.CompilerServices.ConditionalWeakTable<_, _>.CreateValueCallback(SourceText.create)) type NavigationItem with diff --git a/vsintegration/src/FSharp.Editor/Common/Logging.fs b/vsintegration/src/FSharp.Editor/Common/Logging.fs index cf531c65384..b0f56df3234 100644 --- a/vsintegration/src/FSharp.Editor/Common/Logging.fs +++ b/vsintegration/src/FSharp.Editor/Common/Logging.fs @@ -156,11 +156,7 @@ module Activity = OpenTelemetry.Sdk .CreateTracerProviderBuilder() .AddSource(ActivityNames.FscSourceName) - .SetResourceBuilder( - ResourceBuilder - .CreateDefault() - .AddService(serviceName = "F#", serviceVersion = "1.0.0") - ) + .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName = "F#", serviceVersion = "1.0.0")) .AddOtlpExporter() .Build() diff --git a/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs b/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs index 2c583555cb3..de1ed80a03c 100644 --- a/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs +++ b/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs @@ -71,8 +71,7 @@ type internal FSharpCompletionProvider // * let xs = [1..10] <<---- Don't commit autocomplete! (same for arrays) static let noCommitOnSpaceRules = let noCommitChars = - [| ' '; '='; ','; '.'; '<'; '>'; '('; ')'; '!'; ':'; '['; ']'; '|' |] - .ToImmutableArray() + [| ' '; '='; ','; '.'; '<'; '>'; '('; ')'; '!'; ':'; '['; ']'; '|' |].ToImmutableArray() CompletionItemRules.Default.WithCommitCharacterRules( ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, noCommitChars)) @@ -203,9 +202,7 @@ type internal FSharpCompletionProvider if n <> 0 then n else - n <- - (CompletionUtils.getKindPriority x.Kind) - .CompareTo(CompletionUtils.getKindPriority y.Kind) + n <- (CompletionUtils.getKindPriority x.Kind).CompareTo(CompletionUtils.getKindPriority y.Kind) if n <> 0 then n @@ -371,11 +368,8 @@ type internal FSharpCompletionProvider |> CancellableTask.startAsTask context.CancellationToken override _.GetDescriptionAsync - ( - document: Document, - completionItem: Completion.CompletionItem, - _cancellationToken: CancellationToken - ) : Task = + (document: Document, completionItem: Completion.CompletionItem, _cancellationToken: CancellationToken) + : Task = match completionItem.Properties.TryGetValue IndexPropName with | true, completionItemIndexStr when int completionItemIndexStr >= declarationItems.Length -> @@ -495,9 +489,6 @@ type internal FSharpCompletionProvider let changedText = finalSourceText.ToString(changedSpan) - return - CompletionChange - .Create(TextChange(fullChangingSpan, changedText)) - .WithNewPosition(Nullable(changedSpan.End)) + return CompletionChange.Create(TextChange(fullChangingSpan, changedText)).WithNewPosition(Nullable(changedSpan.End)) } |> CancellableTask.start cancellationToken diff --git a/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs b/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs index 13f7e3d3b30..450d8ed67ac 100644 --- a/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs +++ b/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs @@ -18,9 +18,7 @@ type internal FSharpCompletionService inherit FSharpCompletionServiceWithProviders(workspace) let projectInfoManager = - workspace.Services - .GetRequiredService() - .FSharpProjectOptionsManager + workspace.Services.GetRequiredService().FSharpProjectOptionsManager let builtInProviders = ImmutableArray.Create( @@ -38,10 +36,7 @@ type internal FSharpCompletionService | NewlineOnCompleteWord -> EnterKeyRule.AfterFullyTypedWord | AlwaysNewline -> EnterKeyRule.Always - CompletionRules.Default - .WithDismissIfEmpty(true) - .WithDismissIfLastCharacterDeleted(true) - .WithDefaultEnterKeyRule(enterKeyRule) + CompletionRules.Default.WithDismissIfEmpty(true).WithDismissIfLastCharacterDeleted(true).WithDefaultEnterKeyRule(enterKeyRule) /// Indicates the text span to be replaced by a committed completion list item. override _.GetDefaultCompletionListSpan(sourceText, caretIndex) = diff --git a/vsintegration/src/FSharp.Editor/Completion/CompletionUtils.fs b/vsintegration/src/FSharp.Editor/Completion/CompletionUtils.fs index 679caede1fd..1bb5958418c 100644 --- a/vsintegration/src/FSharp.Editor/Completion/CompletionUtils.fs +++ b/vsintegration/src/FSharp.Editor/Completion/CompletionUtils.fs @@ -148,16 +148,8 @@ module internal CompletionUtils = /// Indicates the text span to be replaced by a committed completion list item. let getDefaultCompletionListSpan - ( - sourceText: SourceText, - caretIndex, - documentId, - filePath, - defines, - langVersion, - strictIndentation, - ct: CancellationToken - ) = + (sourceText: SourceText, caretIndex, documentId, filePath, defines, langVersion, strictIndentation, ct: CancellationToken) + = // Gets connected identifier-part characters backward and forward from caret. let getIdentifierChars () = diff --git a/vsintegration/src/FSharp.Editor/Debugging/BreakpointResolutionService.fs b/vsintegration/src/FSharp.Editor/Debugging/BreakpointResolutionService.fs index 56ad5a26518..425dba181b4 100644 --- a/vsintegration/src/FSharp.Editor/Debugging/BreakpointResolutionService.fs +++ b/vsintegration/src/FSharp.Editor/Debugging/BreakpointResolutionService.fs @@ -48,11 +48,8 @@ type internal FSharpBreakpointResolutionService [] () = interface IFSharpBreakpointResolutionService with member _.ResolveBreakpointAsync - ( - document: Document, - textSpan: TextSpan, - cancellationToken: CancellationToken - ) : Task = + (document: Document, textSpan: TextSpan, cancellationToken: CancellationToken) + : Task = cancellableTask { let! range = FSharpBreakpointResolutionService.GetBreakpointLocation(document, textSpan) diff --git a/vsintegration/src/FSharp.Editor/Debugging/LanguageDebugInfoService.fs b/vsintegration/src/FSharp.Editor/Debugging/LanguageDebugInfoService.fs index 493750c06ec..3d815f92343 100644 --- a/vsintegration/src/FSharp.Editor/Debugging/LanguageDebugInfoService.fs +++ b/vsintegration/src/FSharp.Editor/Debugging/LanguageDebugInfoService.fs @@ -50,11 +50,8 @@ type internal FSharpLanguageDebugInfoService [] () = Task.FromResult(Unchecked.defaultof) member _.GetDataTipInfoAsync - ( - document: Document, - position: int, - cancellationToken: CancellationToken - ) : Task = + (document: Document, position: int, cancellationToken: CancellationToken) + : Task = cancellableTask { let defines, langVersion, strictIndentation = document.GetFsharpParsingOptions() diff --git a/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs b/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs index 3c708b8ab17..10db9697b56 100644 --- a/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs +++ b/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs @@ -281,9 +281,7 @@ module internal XmlDocumentation = collector.Add TaggedText.space WriteNodes collector (p.Nodes()) - type VsThreadToken() = - class - end + type VsThreadToken() = class end let vsToken = VsThreadToken() @@ -334,15 +332,8 @@ module internal XmlDocumentation = interface IDocumentationBuilder with /// Append the given processed XML formatted into the string builder override _.AppendDocumentationFromProcessedXML - ( - xmlCollector, - exnCollector, - processedXml, - showExceptions, - showParameters, - showRemarks, - paramName - ) = + (xmlCollector, exnCollector, processedXml, showExceptions, showParameters, showRemarks, paramName) + = match XmlDocReader.TryCreate processedXml with | Some xmlDocReader -> match paramName with @@ -449,12 +440,8 @@ module internal XmlDocumentation = } let BuildSingleTipText - ( - documentationProvider: IDocumentationBuilder, - dataTipElement: ToolTipElement, - limits: LineLimits, - showRemarks: bool - ) = + (documentationProvider: IDocumentationBuilder, dataTipElement: ToolTipElement, limits: LineLimits, showRemarks: bool) + = let { LineLimit = lineLimit diff --git a/vsintegration/src/FSharp.Editor/DocumentHighlights/DocumentHighlightsService.fs b/vsintegration/src/FSharp.Editor/DocumentHighlights/DocumentHighlightsService.fs index 7947b2dec99..972f64ad6b3 100644 --- a/vsintegration/src/FSharp.Editor/DocumentHighlights/DocumentHighlightsService.fs +++ b/vsintegration/src/FSharp.Editor/DocumentHighlights/DocumentHighlightsService.fs @@ -110,12 +110,8 @@ type internal FSharpDocumentHighlightsService [] () = interface IFSharpDocumentHighlightsService with member _.GetDocumentHighlightsAsync - ( - document, - position, - _documentsToSearch, - cancellationToken - ) : Task> = + (document, position, _documentsToSearch, cancellationToken) + : Task> = cancellableTask { let! spans = FSharpDocumentHighlightsService.GetDocumentHighlights(document, position) diff --git a/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs b/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs index bab1460f14a..d874656c176 100644 --- a/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs +++ b/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs @@ -23,13 +23,8 @@ open FSharp.Compiler.Tokenization type internal FSharpIndentationService [] () = static member IndentShouldFollow - ( - documentId: DocumentId, - sourceText: SourceText, - filePath: string, - position: int, - parsingOptions: FSharpParsingOptions - ) = + (documentId: DocumentId, sourceText: SourceText, filePath: string, position: int, parsingOptions: FSharpParsingOptions) + = let lastTokenOpt = let defines = CompilerEnvironment.GetConditionalDefinesForEditing parsingOptions diff --git a/vsintegration/src/FSharp.Editor/Hints/InlineParameterNameHints.fs b/vsintegration/src/FSharp.Editor/Hints/InlineParameterNameHints.fs index 867377cc335..f0712cb8e21 100644 --- a/vsintegration/src/FSharp.Editor/Hints/InlineParameterNameHints.fs +++ b/vsintegration/src/FSharp.Editor/Hints/InlineParameterNameHints.fs @@ -88,8 +88,7 @@ type InlineParameterNameHints(parseResults: FSharpParseFileResults) = symbol.HasAttribute() let getSourceTextAtRange (sourceText: SourceText) (range: range) = - (RoslynHelpers.FSharpRangeToTextSpan(sourceText, range) |> sourceText.GetSubText) - .ToString() + (RoslynHelpers.FSharpRangeToTextSpan(sourceText, range) |> sourceText.GetSubText).ToString() let isMemberOrFunctionOrValueValidForHint (symbol: FSharpMemberOrFunctionOrValue) (symbolUse: FSharpSymbolUse) = diff --git a/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs b/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs index c51db3021cf..edf31e68a57 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs @@ -16,6 +16,13 @@ open System.Threading open Microsoft.VisualStudio.FSharp.Interactive.Session open System.Runtime.CompilerServices open CancellableTasks +open Microsoft.VisualStudio.FSharp.Editor.Extensions +open System.Windows +open Microsoft.VisualStudio +open FSharp.Compiler.Text +open Microsoft.VisualStudio.TextManager.Interop + +#nowarn "57" [] module private FSharpProjectOptionsHelpers = @@ -118,7 +125,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = ConcurrentDictionary() let singleFileCache = - ConcurrentDictionary() + ConcurrentDictionary() // This is used to not constantly emit the same compilation. let weakPEReferences = ConditionalWeakTable() @@ -198,15 +205,29 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = | false, _ -> let! sourceText = document.GetTextAsync(ct) - let! scriptProjectOptions, _ = - checker.GetProjectOptionsFromScript( - document.FilePath, - sourceText.ToFSharpSourceText(), - previewEnabled = SessionsProperties.fsiPreview, - assumeDotNetFramework = not SessionsProperties.fsiUseNetCore, - userOpName = userOpName - ) + let getProjectOptionsFromScript textViewAndCaret = + match textViewAndCaret with + | None -> + checker.GetProjectOptionsFromScript( + document.FilePath, + sourceText.ToFSharpSourceText(), + previewEnabled = SessionsProperties.fsiPreview, + assumeDotNetFramework = not SessionsProperties.fsiUseNetCore, + userOpName = userOpName + ) + + | Some(_, caret) -> + checker.GetProjectOptionsFromScript( + document.FilePath, + sourceText.ToFSharpSourceText(), + caret, + previewEnabled = SessionsProperties.fsiPreview, + assumeDotNetFramework = not SessionsProperties.fsiUseNetCore, + userOpName = userOpName + ) + let textViewAndCaret = document.TryGetTextViewAndCaretPos() + let! scriptProjectOptions, _ = getProjectOptionsFromScript textViewAndCaret let project = document.Project let otherOptions = @@ -243,13 +264,46 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = let parsingOptions, _ = checker.GetParsingOptionsFromProjectOptions(projectOptions) - singleFileCache.[document.Id] <- (document.Project, fileStamp, parsingOptions, projectOptions) + let updateProjectOptions () = + async { + let! scriptProjectOptions, _ = getProjectOptionsFromScript None + + checker.NotifyFileChanged(document.FilePath, scriptProjectOptions) + |> Async.Start + } + |> Async.Start + + let onChangeCaretHandler (_, _newline: int, _oldline: int) = updateProjectOptions () + let onKillFocus (_) = updateProjectOptions () + let onSetFocus (_) = updateProjectOptions () + + let addToCacheAndSubscribe value = + match value with + | projectId, fileStamp, parsingOptions, projectOptions, _ -> + let subscription = + match textViewAndCaret with + | Some(textView, _) -> + subscribeToTextViewEvents (textView, (Some onChangeCaretHandler), (Some onKillFocus), (Some onSetFocus)) + | None -> None + + (projectId, fileStamp, parsingOptions, projectOptions, subscription) + + singleFileCache.AddOrUpdate( + document.Id, // The key to the cache + (fun _ value -> addToCacheAndSubscribe value), // Function to add the cached value if the key does not exist + (fun _ _ value -> value), // Function to update the value if the key exists + (document.Project, fileStamp, parsingOptions, projectOptions, None) // The value to add or update + ) + |> ignore return ValueSome(parsingOptions, projectOptions) - | true, (oldProject, oldFileStamp, parsingOptions, projectOptions) -> + | true, (oldProject, oldFileStamp, parsingOptions, projectOptions, _) -> if fileStamp <> oldFileStamp || isProjectInvalidated document.Project oldProject ct then - singleFileCache.TryRemove(document.Id) |> ignore + match singleFileCache.TryRemove(document.Id) with + | true, (_, _, _, _, Some subscription) -> subscription.Dispose() + | _ -> () + return! tryComputeOptionsBySingleScriptOrFile document userOpName else return ValueSome(parsingOptions, projectOptions) @@ -460,9 +514,10 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = legacyProjectSites.TryRemove(projectId) |> ignore | FSharpProjectOptionsMessage.ClearSingleFileOptionsCache(documentId) -> match singleFileCache.TryRemove(documentId) with - | true, (_, _, _, projectOptions) -> + | true, (_, _, _, projectOptions, subscription) -> lastSuccessfulCompilations.TryRemove(documentId.ProjectId) |> ignore checker.ClearCache([ projectOptions ]) + subscription |> Option.iter (fun handler -> handler.Dispose()) | _ -> () } diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 55cd1b622b3..5cc9cec2943 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -375,14 +375,10 @@ type internal FSharpPackage() as this = this.ComponentModel.DefaultExportProvider.GetExport() let optionsManager = - workspace.Services - .GetService() - .FSharpProjectOptionsManager + workspace.Services.GetService().FSharpProjectOptionsManager let metadataAsSource = - this.ComponentModel.DefaultExportProvider - .GetExport() - .Value + this.ComponentModel.DefaultExportProvider.GetExport().Value let! solution = this.GetServiceAsync(typeof) let solution = solution :?> IVsSolution @@ -440,9 +436,7 @@ type internal FSharpLanguageService(package: FSharpPackage) = let workspace = package.ComponentModel.GetService() let solutionAnalysis = - workspace.Services - .GetService() - .Advanced.SolutionBackgroundAnalysis + workspace.Services.GetService().Advanced.SolutionBackgroundAnalysis globalOptions.SetBackgroundAnalysisScope(openFilesOnly = not solutionAnalysis) diff --git a/vsintegration/src/FSharp.Editor/LanguageService/SingleFileWorkspaceMap.fs b/vsintegration/src/FSharp.Editor/LanguageService/SingleFileWorkspaceMap.fs index af619dad278..bf04e9a8a2d 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/SingleFileWorkspaceMap.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/SingleFileWorkspaceMap.fs @@ -18,9 +18,7 @@ type internal FSharpMiscellaneousFileService ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase) let optionsManager = - workspace.Services - .GetRequiredService() - .FSharpProjectOptionsManager + workspace.Services.GetRequiredService().FSharpProjectOptionsManager static let createSourceCodeKind (filePath: string) = if isScriptFile filePath then diff --git a/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs b/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs index bc025402485..83f6532b8ad 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs @@ -508,12 +508,8 @@ module internal Tokenizer = | _ -> ClassificationTypeNames.Text let private scanSourceLine - ( - sourceTokenizer: FSharpSourceTokenizer, - textLine: TextLine, - lineContents: string, - lexState: FSharpTokenizerLexState - ) : SourceLineData = + (sourceTokenizer: FSharpSourceTokenizer, textLine: TextLine, lineContents: string, lexState: FSharpTokenizerLexState) + : SourceLineData = let colorMap = Array.create textLine.Span.Length ClassificationTypeNames.Text let lineTokenizer = sourceTokenizer.CreateLineTokenizer(lineContents) let tokens = ResizeArray() diff --git a/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs b/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs index 6c3b04f1844..1c09806d0ca 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs @@ -347,11 +347,8 @@ module private CheckerExtensions = } member checker.ParseAndCheckDocumentUsingTransparentCompiler - ( - document: Document, - options: FSharpProjectOptions, - userOpName: string - ) = + (document: Document, options: FSharpProjectOptions, userOpName: string) + = cancellableTask { checker.TransparentCompiler.SetCacheSizeFactor(document.Project.TransparentCompilerCacheFactor) @@ -368,12 +365,8 @@ module private CheckerExtensions = /// Parse and check the source text from the Roslyn document with possible stale results. member checker.ParseAndCheckDocumentWithPossibleStaleResults - ( - document: Document, - options: FSharpProjectOptions, - allowStaleResults: bool, - userOpName: string - ) = + (document: Document, options: FSharpProjectOptions, allowStaleResults: bool, userOpName: string) + = cancellableTask { let! ct = CancellableTask.getCancellationToken () @@ -439,12 +432,8 @@ module private CheckerExtensions = /// Parse and check the source text from the Roslyn document. member checker.ParseAndCheckDocument - ( - document: Document, - options: FSharpProjectOptions, - userOpName: string, - ?allowStaleResults: bool - ) = + (document: Document, options: FSharpProjectOptions, userOpName: string, ?allowStaleResults: bool) + = cancellableTask { if checker.UsesTransparentCompiler then diff --git a/vsintegration/src/FSharp.Editor/Navigation/FindUsagesService.fs b/vsintegration/src/FSharp.Editor/Navigation/FindUsagesService.fs index 429b21ce64a..921d82650f1 100644 --- a/vsintegration/src/FSharp.Editor/Navigation/FindUsagesService.fs +++ b/vsintegration/src/FSharp.Editor/Navigation/FindUsagesService.fs @@ -83,13 +83,8 @@ module FSharpFindUsagesService = } let findReferencedSymbolsAsync - ( - document: Document, - position: int, - context: IFSharpFindUsagesContext, - allReferences: bool, - userOp: string - ) : CancellableTask = + (document: Document, position: int, context: IFSharpFindUsagesContext, allReferences: bool, userOp: string) + : CancellableTask = cancellableTask { let! cancellationToken = CancellableTask.getCancellationToken () let! sourceText = document.GetTextAsync(cancellationToken) diff --git a/vsintegration/src/FSharp.Editor/Navigation/GoToDefinition.fs b/vsintegration/src/FSharp.Editor/Navigation/GoToDefinition.fs index 69a97e9732f..94615461dc1 100644 --- a/vsintegration/src/FSharp.Editor/Navigation/GoToDefinition.fs +++ b/vsintegration/src/FSharp.Editor/Navigation/GoToDefinition.fs @@ -645,11 +645,8 @@ type internal GoToDefinition(metadataAsSource: FSharpMetadataAsSourceService) = } member this.NavigateToExternalDeclaration - ( - targetSymbolUse: FSharpSymbolUse, - metadataReferences: seq, - cancellationToken: CancellationToken - ) = + (targetSymbolUse: FSharpSymbolUse, metadataReferences: seq, cancellationToken: CancellationToken) + = let textOpt = match targetSymbolUse.Symbol with @@ -892,9 +889,7 @@ type FSharpCrossLanguageSymbolNavigationService() = let workspace = componentModel.GetService() let metadataAsSource = - componentModel.DefaultExportProvider - .GetExport() - .Value + componentModel.DefaultExportProvider.GetExport().Value let tryFindFieldByName (name: string) (e: FSharpEntity) = let fields = @@ -1060,11 +1055,8 @@ type FSharpCrossLanguageSymbolNavigationService() = interface IFSharpCrossLanguageSymbolNavigationService with member _.TryGetNavigableLocationAsync - ( - assemblyName: string, - documentationCommentId: string, - cancellationToken: CancellationToken - ) : Task = + (assemblyName: string, documentationCommentId: string, cancellationToken: CancellationToken) + : Task = let path = FSharpCrossLanguageSymbolNavigationService.DocCommentIdToPath documentationCommentId diff --git a/vsintegration/src/FSharp.Editor/Navigation/NavigateToSearchService.fs b/vsintegration/src/FSharp.Editor/Navigation/NavigateToSearchService.fs index 60ca208a2a0..546b00e1b16 100644 --- a/vsintegration/src/FSharp.Editor/Navigation/NavigateToSearchService.fs +++ b/vsintegration/src/FSharp.Editor/Navigation/NavigateToSearchService.fs @@ -189,13 +189,8 @@ type internal FSharpNavigateToSearchService interface IFSharpNavigateToSearchService with member _.SearchProjectAsync - ( - project, - _priorityDocuments, - searchPattern, - kinds, - cancellationToken - ) : Task> = + (project, _priorityDocuments, searchPattern, kinds, cancellationToken) + : Task> = cancellableTask { let tryMatch = createMatcherFor searchPattern diff --git a/vsintegration/src/FSharp.Editor/QuickInfo/Views.fs b/vsintegration/src/FSharp.Editor/QuickInfo/Views.fs index ec42d190c15..146c7d7dfcb 100644 --- a/vsintegration/src/FSharp.Editor/QuickInfo/Views.fs +++ b/vsintegration/src/FSharp.Editor/QuickInfo/Views.fs @@ -64,13 +64,8 @@ module internal QuickInfoViewProvider = let encloseRuns runs : obj = ClassifiedTextElement(runs |> List.rev) let provideContent - ( - imageId: ImageId option, - description: TaggedText list, - documentation: TaggedText list, - navigation: FSharpNavigation, - getTooltip - ) = + (imageId: ImageId option, description: TaggedText list, documentation: TaggedText list, navigation: FSharpNavigation, getTooltip) + = let encloseText text = let rec loop text runs stack = diff --git a/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs b/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs index 4f6a3922118..c92e4e99586 100644 --- a/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs +++ b/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs @@ -98,7 +98,7 @@ type internal FSharpLanguageServiceBackgroundRequests_DEPRECATED lazy // This portion is executed on the language service thread let timestamp = if source=null then System.DateTime(2000,1,1) else source.OpenedTime // source is null in unit tests let checker = getInteractiveChecker() - let checkOptions, _diagnostics = checker.GetProjectOptionsFromScript(fileName, FSharp.Compiler.Text.SourceText.ofString sourceText, SessionsProperties.fsiPreview, timestamp, [| |]) |> Async.RunImmediate + let checkOptions, _diagnostics = checker.GetProjectOptionsFromScript(fileName, FSharp.Compiler.Text.SourceText.ofString sourceText, previewEnabled=SessionsProperties.fsiPreview, loadedTimeStamp=timestamp, otherFlags=[| |]) |> Async.RunImmediate let referencedProjectFileNames = [| |] let projectSite = ProjectSitesAndFiles.CreateProjectSiteForScript(fileName, referencedProjectFileNames, checkOptions) { ProjectSite = projectSite 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/FSharp.Editor.Tests/BreakpointResolutionServiceTests.fs b/vsintegration/tests/FSharp.Editor.Tests/BreakpointResolutionServiceTests.fs index 403b342ff5b..de8b3c28ccd 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/BreakpointResolutionServiceTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/BreakpointResolutionServiceTests.fs @@ -69,9 +69,7 @@ let main argv = | ValueNone -> Assert.True(expectedResolution.IsNone, "BreakpointResolutionService failed to resolve breakpoint position") | ValueSome(actualResolutionRange) -> let actualResolution = - sourceText - .GetSubText(RoslynHelpers.FSharpRangeToTextSpan(sourceText, actualResolutionRange)) - .ToString() + sourceText.GetSubText(RoslynHelpers.FSharpRangeToTextSpan(sourceText, actualResolutionRange)).ToString() Assert.True( expectedResolution.IsSome, diff --git a/vsintegration/tests/FSharp.Editor.Tests/DocumentDiagnosticAnalyzerTests.fs b/vsintegration/tests/FSharp.Editor.Tests/DocumentDiagnosticAnalyzerTests.fs index 27db356ec4b..51efbb4fcf2 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/DocumentDiagnosticAnalyzerTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/DocumentDiagnosticAnalyzerTests.fs @@ -62,11 +62,8 @@ type DocumentDiagnosticAnalyzerTests() = |> Assert.shouldBeEqualWith expectedEnd "Error end positions should match" member private this.VerifyDiagnosticBetweenMarkers - ( - fileContents: string, - expectedMessage: string, - expectedSeverity: DiagnosticSeverity - ) = + (fileContents: string, expectedMessage: string, expectedSeverity: DiagnosticSeverity) + = let errors = this.getDiagnostics fileContents |> Seq.filter (fun e -> e.Severity = expectedSeverity) @@ -92,11 +89,8 @@ type DocumentDiagnosticAnalyzerTests() = |> Assert.shouldBeEqualWith expectedEnd "Error end positions should match" member private this.VerifyDiagnosticBetweenMarkers_HACK_PLEASE_REFER_TO_COMMENT_INSIDE - ( - fileContents: string, - expectedMessage: string, - expectedSeverity: DiagnosticSeverity - ) = + (fileContents: string, expectedMessage: string, expectedSeverity: DiagnosticSeverity) + = // TODO: once workaround (https://github.com/dotnet/fsharp/pull/15982) will not be needed, this should be reverted back to normal method (see PR) let errors = this.getDiagnostics fileContents @@ -127,11 +121,8 @@ type DocumentDiagnosticAnalyzerTests() = this.VerifyDiagnosticBetweenMarkers_HACK_PLEASE_REFER_TO_COMMENT_INSIDE(fileContents, expectedMessage, DiagnosticSeverity.Error) member private this.VerifyErrorAtMarker_HACK_PLEASE_REFER_TO_COMMENT_INSIDE - ( - fileContents: string, - expectedMarker: string, - ?expectedMessage: string - ) = + (fileContents: string, expectedMarker: string, ?expectedMessage: string) + = let errors = this.getDiagnostics fileContents |> Seq.filter (fun e -> e.Severity = DiagnosticSeverity.Error) diff --git a/vsintegration/tests/FSharp.Editor.Tests/FindReferencesTests.fs b/vsintegration/tests/FSharp.Editor.Tests/FindReferencesTests.fs index 4a10dacc6c6..1fc73fe81aa 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/FindReferencesTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/FindReferencesTests.fs @@ -73,9 +73,7 @@ module FindReferences = solution.TryGetDocumentFromPath documentPath |> ValueOption.defaultWith (fun _ -> failwith "Document not found") - findUsagesService - .FindReferencesAsync(document, getPositionOf "funcParam" documentPath, context) - .Wait() + findUsagesService.FindReferencesAsync(document, getPositionOf "funcParam" documentPath, context).Wait() // We cannot easily inspect what exactly was found here, but that should be verified // in FSharp.Compiler.ComponentTests.FSharpChecker.FindReferences @@ -96,9 +94,7 @@ module FindReferences = solution.TryGetDocumentFromPath documentPath |> ValueOption.defaultWith (fun _ -> failwith "Document not found") - findUsagesService - .FindReferencesAsync(document, getPositionOf "funcParam" documentPath, context) - .Wait() + findUsagesService.FindReferencesAsync(document, getPositionOf "funcParam" documentPath, context).Wait() if foundDefinitions.Count <> 1 then failwith $"Expected 1 definition but found {foundDefinitions.Count}" @@ -118,9 +114,7 @@ module FindReferences = solution.TryGetDocumentFromPath documentPath |> ValueOption.defaultWith (fun _ -> failwith "Document not found") - findUsagesService - .FindReferencesAsync(document, getPositionOf "sharedFunc" documentPath, context) - .Wait() + findUsagesService.FindReferencesAsync(document, getPositionOf "sharedFunc" documentPath, context).Wait() if foundDefinitions.Count <> 1 then failwith $"Expected 1 definition but found {foundDefinitions.Count}" @@ -159,9 +153,7 @@ module FindReferences = solution2.TryGetDocumentFromPath documentPath |> ValueOption.defaultWith (fun _ -> failwith "Document not found") - findUsagesService - .FindReferencesAsync(document, getPositionOf operator documentPath, context) - .Wait() + findUsagesService.FindReferencesAsync(document, getPositionOf operator documentPath, context).Wait() // We cannot easily inspect what exactly was found here, but that should be verified // in FSharp.Compiler.ComponentTests.FSharpChecker.FindReferences diff --git a/vsintegration/tests/FSharp.Editor.Tests/GoToDefinitionServiceTests.fs b/vsintegration/tests/FSharp.Editor.Tests/GoToDefinitionServiceTests.fs index cc6bdbae43c..d0e4b5efad1 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/GoToDefinitionServiceTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/GoToDefinitionServiceTests.fs @@ -17,13 +17,8 @@ module GoToDefinitionServiceTests = let userOpName = "GoToDefinitionServiceTests" let private findDefinition - ( - document: Document, - sourceText: SourceText, - position: int, - defines: string list, - langVersion: string option - ) : range option = + (document: Document, sourceText: SourceText, position: int, defines: string list, langVersion: string option) + : range option = maybe { let textLine = sourceText.Lines.GetLineFromPosition position let textLinePos = sourceText.Lines.GetLinePosition position diff --git a/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs b/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs index ca113f72bf3..85ad11c6e2e 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs @@ -67,9 +67,7 @@ module MefHelpers = let configuration = CompositionConfiguration.Create(catalog) - RuntimeComposition - .CreateRuntimeComposition(configuration) - .CreateExportProviderFactory() + RuntimeComposition.CreateRuntimeComposition(configuration).CreateExportProviderFactory() let createExportProvider () = exportProviderFactory.CreateExportProvider() diff --git a/vsintegration/tests/FSharp.Editor.Tests/NavigateToSearchServiceTests.fs b/vsintegration/tests/FSharp.Editor.Tests/NavigateToSearchServiceTests.fs index 549441d8bb3..08816ea6191 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/NavigateToSearchServiceTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/NavigateToSearchServiceTests.fs @@ -41,9 +41,7 @@ module HeyHo = let navigateToSearch pattern = let service: IFSharpNavigateToSearchService = provider.GetExportedValue() - service - .SearchProjectAsync(project, [] |> Seq.toImmutableArray, pattern, service.KindsProvided, CancellationToken.None) - .Result + service.SearchProjectAsync(project, [] |> Seq.toImmutableArray, pattern, service.KindsProvided, CancellationToken.None).Result let assertResultsContain pattern expected = navigateToSearch pattern diff --git a/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs b/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs index f85ee51a6c8..398ece88fa3 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs @@ -45,9 +45,7 @@ module SignatureHelpProvider = |> CancellableTask.runSynchronously ct let paramInfoLocations = - parseResults - .FindParameterLocations(Position.fromZ caretLinePos.Line caretLineColumn) - .Value + parseResults.FindParameterLocations(Position.fromZ caretLinePos.Line caretLineColumn).Value let triggered = FSharpSignatureHelpProvider.ProvideMethodsAsyncAux( diff --git a/vsintegration/tests/FSharp.Editor.Tests/SyntacticColorizationServiceTests.fs b/vsintegration/tests/FSharp.Editor.Tests/SyntacticColorizationServiceTests.fs index 35c5306d8ff..04ab8dd2448 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/SyntacticColorizationServiceTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/SyntacticColorizationServiceTests.fs @@ -13,13 +13,8 @@ open FSharp.Test type SyntacticClassificationServiceTests() = member private this.ExtractMarkerData - ( - fileContents: string, - marker: string, - defines: string list, - langVersion: string option, - isScriptFile: Option - ) = + (fileContents: string, marker: string, defines: string list, langVersion: string option, isScriptFile: Option) + = let textSpan = TextSpan(0, fileContents.Length) let fileName = @@ -49,14 +44,8 @@ type SyntacticClassificationServiceTests() = (tokens, markerPosition) member private this.VerifyColorizerAtStartOfMarker - ( - fileContents: string, - marker: string, - defines: string list, - classificationType: string, - ?isScriptFile: bool, - ?langVersion: string - ) = + (fileContents: string, marker: string, defines: string list, classificationType: string, ?isScriptFile: bool, ?langVersion: string) + = let langVersion = langVersion |> Option.orElse (Some "preview") let (tokens, markerPosition) = @@ -69,14 +58,8 @@ type SyntacticClassificationServiceTests() = |> Assert.shouldBeEqualWith classificationType "Classification data doesn't match for start of marker" member private this.VerifyColorizerAtEndOfMarker - ( - fileContents: string, - marker: string, - defines: string list, - classificationType: string, - ?isScriptFile: bool, - ?langVersion: string - ) = + (fileContents: string, marker: string, defines: string list, classificationType: string, ?isScriptFile: bool, ?langVersion: string) + = let langVersion = langVersion |> Option.orElse (Some "preview") let (tokens, markerPosition) = 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/Salsa/salsa.fs b/vsintegration/tests/Salsa/salsa.fs index 6ac626f9fcb..1730bd7ec93 100644 --- a/vsintegration/tests/Salsa/salsa.fs +++ b/vsintegration/tests/Salsa/salsa.fs @@ -1110,7 +1110,7 @@ module internal Salsa = member file.GetFileName() = fileName member file.GetProjectOptionsOfScript() = - project.Solution.Vs.LanguageService.FSharpChecker.GetProjectOptionsFromScript(fileName, FSharp.Compiler.Text.SourceText.ofString file.CombinedLines, false, System.DateTime(2000,1,1), [| |]) + project.Solution.Vs.LanguageService.FSharpChecker.GetProjectOptionsFromScript(fileName, FSharp.Compiler.Text.SourceText.ofString file.CombinedLines, previewEnabled=false, loadedTimeStamp=System.DateTime(2000,1,1), otherFlags=[| |]) |> Async.RunImmediate |> fst // drop diagnostics 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