diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 057b9c816db..9a25558c924 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "fantomas": { - "version": "5.0.0-alpha-008", + "version": "5.0.0-alpha-011", "commands": [ "fantomas" ] diff --git a/.editorconfig b/.editorconfig index 8f9f7fca164..342be6d710d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -26,3 +26,17 @@ fsharp_max_if_then_else_short_width=40 # fsharp_max_function_binding_width formats these over a single line. [src/Compiler/Driver/CompilerDiagnostics.fs] fsharp_max_function_binding_width=70 + +# This file contains long specifications of navigation items +[src/Compiler/Service/ServiceStructure.fs] +fsharp_max_value_binding_width=100 + +# This file contains long specifications of navigation items +[src/Compiler/Service/ServiceNavigation.fs] +max_line_length=170 +fsharp_max_value_binding_width=120 + +# This file contains long calls with explicitly named arguments +[src/Compiler/Service/service.fs] +max_line_length=150 +fsharp_max_value_binding_width=100 diff --git a/.fantomasignore b/.fantomasignore index 6fb09e40227..a3094f05991 100644 --- a/.fantomasignore +++ b/.fantomasignore @@ -5,7 +5,6 @@ docs/ eng/ fcs-samples/ scripts/ -service/ setup/ tests/ vsintegration/ @@ -14,17 +13,17 @@ artifacts/ # Explicitly unformatted implementation files src/Compiler/Checking/**/*.fs -src/Compiler/CodeGen/**/*.fs src/Compiler/DependencyManager/**/*.fs src/Compiler/Facilities/**/*.fs src/Compiler/Interactive/**/*.fs src/Compiler/Legacy/**/*.fs src/Compiler/Optimize/**/*.fs -src/Compiler/Service/**/*.fs src/Compiler/Symbols/**/*.fs -src/Compiler/SyntaxTree/**/*.fs src/Compiler/TypedTree/**/*.fs -src/Microsoft.FSharp.Compiler/**/*.fs + +# Explicitly unformatted file that needs more care to get it to format well + +src/Compiler/SyntaxTree/LexFilter.fs # Fantomas limitations on implementation files in FSharp.Core (to investigate) @@ -47,6 +46,10 @@ src/FSharp.Core/SI.fs src/Compiler/AbstractIL/ilwrite.fs src/Compiler/Utilities/lib.fs +src/Compiler/Service/IncrementalBuild.fs +src/Compiler/Service/ServiceAssemblyContent.fs +src/Compiler/Service/ServiceDeclarationLists.fs +src/Compiler/Service/ServiceErrorResolutionHints.fs # Fantomas limitations on signature files (to investigate) diff --git a/.gitignore b/.gitignore index f936ec0ef7a..7bb9a91aed9 100644 --- a/.gitignore +++ b/.gitignore @@ -69,10 +69,11 @@ ossreadme*.txt *.fsproj.user *.vbproj.user *.sln.DotSettings.user +launchSettings.json *.log *.jrs *.chk -*.bak +*.bak *.vserr *.err *.orig @@ -118,4 +119,7 @@ nCrunchTemp_* .fake *.pdb -*.dll \ No newline at end of file +*.dll + +/test.fs +/test.fsx diff --git a/DEVGUIDE.md b/DEVGUIDE.md index 9e0fbb2cd3f..65b7ea50728 100644 --- a/DEVGUIDE.md +++ b/DEVGUIDE.md @@ -128,8 +128,11 @@ If your changes involve modifying the list of language keywords in any way, (e.g ```shell dotnet build src\Compiler /t:UpdateXlf ``` +If you are on a Mac, you can run this command from the root of the repository: -This only works on Windows/.NETStandard framework, so changing this from any other platform requires editing and syncing all of the XLF files manually. +```shell +sh build.sh -c Release +``` ## Updating baselines in tests @@ -139,16 +142,35 @@ are updated using scripts or utilities that allow the following environment vari Windows: +CMD: + ```shell set TEST_UPDATE_BSL=1 ``` +PowerShell: + +```shell +$env:TEST_UPDATE_BSL=1 +``` + Linux/macOS: ```shell export TEST_UPDATE_BSL=1 ``` +Next, run a build script build (debug or release, desktop or coreclr, depending which baselines you need to update), and test as described [above](#Testing-from-the-command-line). For example: + +`./Build.cmd -c Release -testCoreClr` to update Release CoreCLR baselines. + +or + +`./Build.cmd -c Release -testDesktop` to update Release .NET Framework baselines. + +> **Note** +> Please note, that by default, **Release** version of IL baseline baseline tests will be running in CI, so when updating baseline files, make sure to add `-c Release` flag to the build command. + ## Automated Source Code Formatting Some of the code in this repository is formatted automatically by [Fantomas](https://github.com/fsprojects/fantomas). To format all files use: @@ -215,11 +237,11 @@ Where `` corresponds to the latest Visual Studio version on your machin * Format using [the F# style guide](https://docs.microsoft.com/en-us/dotnet/fsharp/style-guide/) -* Avoid tick identifiers like `body'`. They are generally harder to read and can't be inspected in the debugger as things stand. Generaly use R suffix instead, e.g. `bodyR`. The R can stand for "rewritten" or "result" +* Avoid tick identifiers like `body'`. They are generally harder to read and can't be inspected in the debugger as things stand. Generally use R suffix instead, e.g. `bodyR`. The R can stand for "rewritten" or "result" -* Avoid abbreviations like `bodyty` that run together lowercase are bad, really hard to head for newcomers. Use `bodyTy` instead. +* Avoid abbreviations like `bodyty` that are all lowercase. They are really hard to read for newcomers. Use `bodyTy` instead. -* See the comiler docs for common abbreviations +* See the compiler docs for common abbreviations * Don't use `List.iter` and `Array.iter` in the compiler, a `for ... do ...` loop is simpler to read and debug @@ -242,10 +264,10 @@ Existing compiler benchmarks can be found in `tests\benchmarks\`. 1. Perform a clean build of the compiler and FCS from source (as described in this document, build can be done with `-noVisualStudio` in case if FCS/FSharp.Core is being benchmarked/profiled). -2. Create a benchmark project (in this example, the project will be created in `tests\benchmarks\`). +2. Create a benchmark project (in this example, the project will be created in `tests\benchmarks\FCSBenchmarks`). ```shell - cd tests\benchmarks + cd tests\benchmarks\FCSBenchmarks dotnet new console -o FcsBench --name FcsBench -lang F# ``` @@ -257,7 +279,7 @@ Existing compiler benchmarks can be found in `tests\benchmarks\`. dotnet add reference ..\..\..\src\Compiler\FSharp.Compiler.Service.fsproj ``` -4. Additionally, if you want to test changes to the FSharp.Core +4. Additionally, if you want to test changes to the FSharp.Core (note that the relative path can be different) ```shell dotnet add reference ..\..\..\src\FSharp.Core\FSharp.Core.fsproj @@ -349,7 +371,7 @@ Existing compiler benchmarks can be found in `tests\benchmarks\`. ```shell > ls .\BenchmarkDotNet.Artifacts\results\ - Directory: C:\Users\vlza\code\fsharp\tests\benchmarks\FcsBench\BenchmarkDotNet.Artifacts\results + Directory: C:\Users\vlza\code\fsharp\tests\benchmarks\FCSBenchmarks\FcsBench\BenchmarkDotNet.Artifacts\results Mode LastWriteTime Length Name ---- ------------- ------ ---- diff --git a/FSharp.Compiler.Service.sln b/FSharp.Compiler.Service.sln index 2a082c06269..f5fd744f121 100644 --- a/FSharp.Compiler.Service.sln +++ b/FSharp.Compiler.Service.sln @@ -22,6 +22,11 @@ Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.ComponentTe {38A23D53-E2BF-4B76-907F-49F41D60C88E} = {38A23D53-E2BF-4B76-907F-49F41D60C88E} EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DD4D4A7E-D519-4409-89DA-16DCA3EF80AA}" + ProjectSection(SolutionItems) = preProject + src\Compiler\FSComp.txt = src\Compiler\FSComp.txt + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/FSharp.sln b/FSharp.sln index 998037bbb9f..5a3240182df 100644 --- a/FSharp.sln +++ b/FSharp.sln @@ -11,25 +11,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{CFE3259A EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Build", "src\FSharp.Build\FSharp.Build.fsproj", "{702A7979-BCF9-4C41-853E-3ADFC9897890}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsc", "src\fsc\fsc.fsproj", "{C94C257C-3C0A-4858-B5D8-D746498D1F08}" -EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Interactive.Settings", "src\FSharp.Compiler.Interactive.Settings\FSharp.Compiler.Interactive.Settings.fsproj", "{649FA588-F02E-457C-9FCF-87E46407481E}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsi", "src\fsi\fsi.fsproj", "{D0E98C0D-490B-4C61-9329-0862F6E87645}" -EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsiAnyCpu", "src\fsiAnyCpu\fsiAnyCpu.fsproj", "{8B3E283D-B5FE-4055-9D80-7E3A32F3967B}" - ProjectSection(ProjectDependencies) = postProject - {649FA588-F02E-457C-9FCF-87E46407481E} = {649FA588-F02E-457C-9FCF-87E46407481E} - EndProjectSection -EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Test.Utilities", "tests\FSharp.Test.Utilities\FSharp.Test.Utilities.fsproj", "{60D275B0-B14A-41CB-A1B2-E815A7448FCB}" EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharpSuite.Tests", "tests\fsharp\FSharpSuite.Tests.fsproj", "{C163E892-5BF7-4B59-AA99-B0E8079C67C4}" - ProjectSection(ProjectDependencies) = postProject - {D0E98C0D-490B-4C61-9329-0862F6E87645} = {D0E98C0D-490B-4C61-9329-0862F6E87645} - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} = {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} - {C94C257C-3C0A-4858-B5D8-D746498D1F08} = {C94C257C-3C0A-4858-B5D8-D746498D1F08} - EndProjectSection EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.UnitTests", "tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj", "{A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}" EndProject @@ -55,13 +41,13 @@ Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Service", " EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Benchmarks", "Benchmarks", "{CE70D631-C5DC-417E-9CDA-B16097BEF1AC}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicroPerfCSharp", "tests\benchmarks\MicroPerf\CS\MicroPerfCSharp.csproj", "{348DCC13-DD3E-4214-B040-5A74E8C6B782}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicroPerfCSharp", "tests\benchmarks\CompiledCodeBenchmarks\MicroPerf\CS\MicroPerfCSharp.csproj", "{348DCC13-DD3E-4214-B040-5A74E8C6B782}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "MicroPerf", "tests\benchmarks\MicroPerf\MicroPerf.fsproj", "{9735B522-37F7-478C-A0C6-6C60BCC53390}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "MicroPerf", "tests\benchmarks\CompiledCodeBenchmarks\MicroPerf\MicroPerf.fsproj", "{9735B522-37F7-478C-A0C6-6C60BCC53390}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TaskPerfCSharp", "tests\benchmarks\TaskPerfCSharp\TaskPerfCSharp.csproj", "{CF9F3F98-7BFB-4945-A4A5-668DF0AC65AB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TaskPerfCSharp", "tests\benchmarks\CompiledCodeBenchmarks\TaskPerf\TaskPerfCSharp\TaskPerfCSharp.csproj", "{CF9F3F98-7BFB-4945-A4A5-668DF0AC65AB}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "TaskPerf", "tests\benchmarks\TaskPerf\TaskPerf.fsproj", "{51B569A8-17C5-4EBD-8AAC-240E0B3AD8C4}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "TaskPerf", "tests\benchmarks\CompiledCodeBenchmarks\TaskPerf\TaskPerf\TaskPerf.fsproj", "{51B569A8-17C5-4EBD-8AAC-240E0B3AD8C4}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "FSharp.Compiler.Service.Tests support", "FSharp.Compiler.Service.Tests support", "{452EED3C-AA87-471F-B9AC-0F4479C5820C}" EndProject @@ -73,15 +59,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{4E4F41D9-8 ProjectSection(SolutionItems) = preProject docs\coding-standards.md = docs\coding-standards.md docs\compiler-startup-performance.md = docs\compiler-startup-performance.md + docs\debug-emit.md = docs\debug-emit.md docs\diagnostics.md = docs\diagnostics.md docs\fsharp-core-notes.md = docs\fsharp-core-notes.md + docs\fsi-emit.md = docs\fsi-emit.md docs\index.md = docs\index.md docs\large-inputs-and-stack-overflows.md = docs\large-inputs-and-stack-overflows.md docs\memory-usage.md = docs\memory-usage.md docs\optimizations.md = docs\optimizations.md docs\overview.md = docs\overview.md - docs\fsi-emit.md = docs\fsi-emit.md - docs\debug-emit.md = docs\debug-emit.md EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "fcs", "fcs", "{B86EBFF1-E03E-4FAE-89BF-60A4CAE2BC78}" @@ -101,10 +87,25 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "fcs", "fcs", "{B86EBFF1-E03 docs\fcs\untypedtree.fsx = docs\fcs\untypedtree.fsx EndProjectSection EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fscAnyCpu", "src\fscAnyCpu\fscAnyCpu.fsproj", "{8ACA60C2-7266-425A-B641-A2946396B7D1}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PEVerify", "tests\PEVerify\PEVerify.csproj", "{358821CB-4D63-4157-9EFF-65C06EBD4E36}" EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsc", "src\fsc\fscProject\fsc.fsproj", "{10D15DBB-EFF0-428C-BA83-41600A93EEC4}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fscAnyCpu", "src\fsc\fscAnyCpuProject\fscAnyCpu.fsproj", "{B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fscArm64", "src\fsc\fscArm64Project\fscArm64.fsproj", "{B71C454B-6556-49D3-9BDB-92D30EA524F2}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsi", "src\fsi\fsiProject\fsi.fsproj", "{68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsiAnyCpu", "src\fsi\fsiAnyCpuProject\fsiAnyCpu.fsproj", "{B6271954-3BCD-418A-BD24-56FEB923F3D3}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsiArm64", "src\fsi\fsiArm64Project\fsiArm64.fsproj", "{209C7D37-8C01-413C-8698-EC25F4C86976}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D58BFE8B-7C85-4D3B-B5F3-9A7BB90FF1EE}" + ProjectSection(SolutionItems) = preProject + src\Compiler\FSComp.txt = src\Compiler\FSComp.txt + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -151,18 +152,6 @@ Global {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|Any CPU.Build.0 = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|x86.ActiveCfg = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|x86.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.ActiveCfg = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.Build.0 = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|x86.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|x86.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|Any CPU.Build.0 = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -175,30 +164,6 @@ Global {649FA588-F02E-457C-9FCF-87E46407481E}.Release|Any CPU.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|x86.ActiveCfg = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|x86.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.ActiveCfg = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.Build.0 = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|x86.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|x86.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.ActiveCfg = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.Build.0 = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|x86.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|x86.Build.0 = Release|Any CPU {60D275B0-B14A-41CB-A1B2-E815A7448FCB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {60D275B0-B14A-41CB-A1B2-E815A7448FCB}.Debug|Any CPU.Build.0 = Debug|Any CPU {60D275B0-B14A-41CB-A1B2-E815A7448FCB}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -391,18 +356,6 @@ Global {7BFA159A-BF9D-4489-BF46-1B83ACCEEE0F}.Release|Any CPU.Build.0 = Release|Any CPU {7BFA159A-BF9D-4489-BF46-1B83ACCEEE0F}.Release|x86.ActiveCfg = Release|Any CPU {7BFA159A-BF9D-4489-BF46-1B83ACCEEE0F}.Release|x86.Build.0 = Release|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Debug|x86.ActiveCfg = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Debug|x86.Build.0 = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Proto|Any CPU.ActiveCfg = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Proto|Any CPU.Build.0 = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Proto|x86.ActiveCfg = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Proto|x86.Build.0 = Debug|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Release|Any CPU.Build.0 = Release|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Release|x86.ActiveCfg = Release|Any CPU - {8ACA60C2-7266-425A-B641-A2946396B7D1}.Release|x86.Build.0 = Release|Any CPU {358821CB-4D63-4157-9EFF-65C06EBD4E36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {358821CB-4D63-4157-9EFF-65C06EBD4E36}.Debug|Any CPU.Build.0 = Debug|Any CPU {358821CB-4D63-4157-9EFF-65C06EBD4E36}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -415,6 +368,78 @@ Global {358821CB-4D63-4157-9EFF-65C06EBD4E36}.Release|Any CPU.Build.0 = Release|Any CPU {358821CB-4D63-4157-9EFF-65C06EBD4E36}.Release|x86.ActiveCfg = Release|Any CPU {358821CB-4D63-4157-9EFF-65C06EBD4E36}.Release|x86.Build.0 = Release|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Debug|x86.ActiveCfg = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Debug|x86.Build.0 = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Proto|Any CPU.Build.0 = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Proto|x86.ActiveCfg = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Proto|x86.Build.0 = Debug|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Release|Any CPU.Build.0 = Release|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Release|x86.ActiveCfg = Release|Any CPU + {10D15DBB-EFF0-428C-BA83-41600A93EEC4}.Release|x86.Build.0 = Release|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Debug|x86.ActiveCfg = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Debug|x86.Build.0 = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Proto|Any CPU.Build.0 = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Proto|x86.ActiveCfg = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Proto|x86.Build.0 = Debug|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Release|Any CPU.Build.0 = Release|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Release|x86.ActiveCfg = Release|Any CPU + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA}.Release|x86.Build.0 = Release|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Debug|x86.ActiveCfg = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Debug|x86.Build.0 = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Proto|Any CPU.Build.0 = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Proto|x86.ActiveCfg = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Proto|x86.Build.0 = Debug|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Release|Any CPU.Build.0 = Release|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Release|x86.ActiveCfg = Release|Any CPU + {B71C454B-6556-49D3-9BDB-92D30EA524F2}.Release|x86.Build.0 = Release|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Debug|Any CPU.Build.0 = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Debug|x86.ActiveCfg = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Debug|x86.Build.0 = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Proto|Any CPU.Build.0 = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Proto|x86.ActiveCfg = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Proto|x86.Build.0 = Debug|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Release|Any CPU.ActiveCfg = Release|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Release|Any CPU.Build.0 = Release|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Release|x86.ActiveCfg = Release|Any CPU + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52}.Release|x86.Build.0 = Release|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Debug|x86.ActiveCfg = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Debug|x86.Build.0 = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Proto|Any CPU.Build.0 = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Proto|x86.ActiveCfg = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Proto|x86.Build.0 = Debug|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Release|Any CPU.Build.0 = Release|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Release|x86.ActiveCfg = Release|Any CPU + {B6271954-3BCD-418A-BD24-56FEB923F3D3}.Release|x86.Build.0 = Release|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Debug|Any CPU.Build.0 = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Debug|x86.ActiveCfg = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Debug|x86.Build.0 = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Proto|Any CPU.Build.0 = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Proto|x86.ActiveCfg = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Proto|x86.Build.0 = Debug|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Release|Any CPU.ActiveCfg = Release|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Release|Any CPU.Build.0 = Release|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Release|x86.ActiveCfg = Release|Any CPU + {209C7D37-8C01-413C-8698-EC25F4C86976}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -423,10 +448,7 @@ Global {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06} = {B8DDA694-7939-42E3-95E5-265C2217C142} {DED3BBD7-53F4-428A-8C9F-27968E768605} = {3058BC79-8E79-4645-B05D-48CC182FA8A6} {702A7979-BCF9-4C41-853E-3ADFC9897890} = {B8DDA694-7939-42E3-95E5-265C2217C142} - {C94C257C-3C0A-4858-B5D8-D746498D1F08} = {B8DDA694-7939-42E3-95E5-265C2217C142} {649FA588-F02E-457C-9FCF-87E46407481E} = {B8DDA694-7939-42E3-95E5-265C2217C142} - {D0E98C0D-490B-4C61-9329-0862F6E87645} = {B8DDA694-7939-42E3-95E5-265C2217C142} - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} = {B8DDA694-7939-42E3-95E5-265C2217C142} {60D275B0-B14A-41CB-A1B2-E815A7448FCB} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {C163E892-5BF7-4B59-AA99-B0E8079C67C4} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} @@ -445,7 +467,11 @@ Global {F8743670-C8D4-41B3-86BE-BBB1226C352F} = {452EED3C-AA87-471F-B9AC-0F4479C5820C} {7BFA159A-BF9D-4489-BF46-1B83ACCEEE0F} = {452EED3C-AA87-471F-B9AC-0F4479C5820C} {B86EBFF1-E03E-4FAE-89BF-60A4CAE2BC78} = {4E4F41D9-86A7-4F5D-B735-1A0744AB68AC} - {8ACA60C2-7266-425A-B641-A2946396B7D1} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {B9EFC4FB-E702-45C8-A885-A05A25C5BCAA} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {B71C454B-6556-49D3-9BDB-92D30EA524F2} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {68EEAB5F-8AED-42A2-BFEC-343D0AD5CB52} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {B6271954-3BCD-418A-BD24-56FEB923F3D3} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {209C7D37-8C01-413C-8698-EC25F4C86976} = {B8DDA694-7939-42E3-95E5-265C2217C142} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {BD5177C7-1380-40E7-94D2-7768E1A8B1B8} diff --git a/INTERNAL.md b/INTERNAL.md index 2dbfdcd20e0..d6e9913f71a 100644 --- a/INTERNAL.md +++ b/INTERNAL.md @@ -57,6 +57,25 @@ Note that insertions for other teams will also be listed. Insertions to any other VS branch (e.g., `main`) will have the auto-merge flag set and should handle themselves, but it's a good idea to check the previous link for any old or stalled insertions into VS `main`. +## Preparing for a new VS release branch + +### When a VS branch snaps from `main` to `rel/d*` and switches to ask mode: + +Update the `insertTargetBranch` value at the bottom of `azure-pipelines.yml` in the appropriate release branch. E.g., when VS 17.3 snapped and switched to ask mode, [this PR](https://github.com/dotnet/fsharp/pull/13456/files) correctly updates the insertion target so that future builds from that F# branch will get auto-inserted to VS. + +### When VS `main` is open for insertions for preview releases of VS: + +1. Create a new `release/dev*` branch (e.g., `release/dev17.4`) and initially set its HEAD commit to that of the previous release (e.g., `release/dev17.3` in this case). +2. Set the new branch to receive auto-merges from `main`, and also set the old release branch to flow into the new one. [This PR](https://github.com/dotnet/roslyn-tools/pull/1245/files) is a good example of what to do when a new `release/dev17.4` branch is created that should receive merges from both `main` and the previous release branch, `release/dev17.3`. +3. Set the packages from the new branch to flow into the correct package feeds via the `darc` tool. To do this: + 1. Ensure the latest `darc` tool is installed by running `eng/common/darc-init.ps1`. + 2. (only needed once) Run the command `darc authenticate`. A text file will be opened with instructions on how to populate access tokens. + 3. Check the current package/channel subscriptions by running `darc get-default-channels --source-repo fsharp`. For this example, notice that the latest subscription shows the F# branch `release/dev17.3` is getting added to the `VS 17.3` channel. + 4. Get the list of `darc` channels and determine the appropriate one to use for the new branch via the command `darc get-channels`. For this example, notice that a channel named `VS 17.4` is listed. + 5. Add the new F# branch to the appropriate `darc` channel. In this example, run `darc add-default-channel --channel "VS 17.4" --branch release/dev17.4 --repo https://github.com/dotnet/fsharp` + 6. Ensure the subscription was added by repeating step 3 above. + 7. Note, the help in the `darc` tool is really good. E.g., you can simply run `darc` to see a list of all commands available, and if you run `darc ` with no arguments, you'll be given a list of arguments you can use. + ## Less interesting links [FSharp.Core (Official NuGet Release)](https://dev.azure.com/dnceng/internal/_release?_a=releases&definitionId=72). diff --git a/VisualFSharp.sln b/VisualFSharp.sln index efaa3f6a864..c99c08c29c5 100644 --- a/VisualFSharp.sln +++ b/VisualFSharp.sln @@ -13,6 +13,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualFSharp", "VisualFShar EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Compiler", "Compiler", "{3881429D-A97A-49EB-B7AE-A82BA5FE9C77}" + ProjectSection(SolutionItems) = preProject + src\Compiler\FSComp.txt = src\Compiler\FSComp.txt + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F7876C9B-FB6A-4EFB-B058-D6967DB75FB2}" EndProject @@ -76,22 +79,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XmlDocAttributeWithNullComm EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Build", "src\FSharp.Build\FSharp.Build.fsproj", "{702A7979-BCF9-4C41-853E-3ADFC9897890}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsc", "src\fsc\fsc.fsproj", "{C94C257C-3C0A-4858-B5D8-D746498D1F08}" -EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Interactive.Settings", "src\FSharp.Compiler.Interactive.Settings\FSharp.Compiler.Interactive.Settings.fsproj", "{649FA588-F02E-457C-9FCF-87E46407481E}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsiAnyCpu", "src\fsiAnyCpu\fsiAnyCpu.fsproj", "{8B3E283D-B5FE-4055-9D80-7E3A32F3967B}" -EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsi", "src\fsi\fsi.fsproj", "{D0E98C0D-490B-4C61-9329-0862F6E87645}" -EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Test.Utilities", "tests\FSharp.Test.Utilities\FSharp.Test.Utilities.fsproj", "{60D275B0-B14A-41CB-A1B2-E815A7448FCB}" EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharpSuite.Tests", "tests\fsharp\FSharpSuite.Tests.fsproj", "{C163E892-5BF7-4B59-AA99-B0E8079C67C4}" - ProjectSection(ProjectDependencies) = postProject - {D0E98C0D-490B-4C61-9329-0862F6E87645} = {D0E98C0D-490B-4C61-9329-0862F6E87645} - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} = {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} - {C94C257C-3C0A-4858-B5D8-D746498D1F08} = {C94C257C-3C0A-4858-B5D8-D746498D1F08} - EndProjectSection EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.UnitTests", "tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj", "{A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}" EndProject @@ -147,9 +139,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryProject", "vsintegra EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TutorialProject", "vsintegration\ProjectTemplates\TutorialProject\TutorialProject.csproj", "{2937CBEC-262D-4C94-BE1D-291FAB72E3E8}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TaskPerfCSharp", "tests\benchmarks\TaskPerfCSharp\TaskPerfCSharp.csproj", "{D5ECF8DF-E150-4AE3-B613-AB2B0FFA93E0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TaskPerfCSharp", "tests\benchmarks\CompiledCodeBenchmarks\TaskPerf\TaskPerfCSharp\TaskPerfCSharp.csproj", "{D5ECF8DF-E150-4AE3-B613-AB2B0FFA93E0}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "TaskPerf", "tests\benchmarks\TaskPerf\TaskPerf.fsproj", "{03596D51-754D-4644-8E23-84EC9532ABDC}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "TaskPerf", "tests\benchmarks\CompiledCodeBenchmarks\TaskPerf\TaskPerf\TaskPerf.fsproj", "{03596D51-754D-4644-8E23-84EC9532ABDC}" EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.ComponentTests", "tests\FSharp.Compiler.ComponentTests\FSharp.Compiler.ComponentTests.fsproj", "{0610FB97-7C15-422A-86FD-32335C6DF14D}" EndProject @@ -165,20 +157,30 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VisualFSharpDebug", "vsinte EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Benchmarks", "Benchmarks", "{DFB6ADD7-3149-43D9-AFA0-FC4A818B472B}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Benchmarks", "tests\benchmarks\CompilerServiceBenchmarks\FSharp.Compiler.Benchmarks.fsproj", "{564E7DC5-11CB-4FCF-ABDD-23AD93AF3A61}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Benchmarks", "tests\benchmarks\FCSBenchmarks\CompilerServiceBenchmarks\FSharp.Compiler.Benchmarks.fsproj", "{564E7DC5-11CB-4FCF-ABDD-23AD93AF3A61}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicroPerfCSharp", "tests\benchmarks\MicroPerf\CS\MicroPerfCSharp.csproj", "{208E36EE-665C-42D2-B767-C6DB03C4FEB2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicroPerfCSharp", "tests\benchmarks\CompiledCodeBenchmarks\MicroPerf\CS\MicroPerfCSharp.csproj", "{208E36EE-665C-42D2-B767-C6DB03C4FEB2}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "MicroPerf", "tests\benchmarks\MicroPerf\MicroPerf.fsproj", "{EE08E954-AE91-4EFA-8595-10931D29E628}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "MicroPerf", "tests\benchmarks\CompiledCodeBenchmarks\MicroPerf\MicroPerf.fsproj", "{EE08E954-AE91-4EFA-8595-10931D29E628}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MicroPerf", "MicroPerf", "{47112E07-9FF1-43E7-8021-F2A21D6A19A0}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fscAnyCpu", "src\fscAnyCpu\fscAnyCpu.fsproj", "{52DCA91F-3843-43E3-8FE1-FB2B66658CBD}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "shims", "vsintegration\shims\shims.csproj", "{B1E30F2C-894F-47A9-9C8A-3324831E7D26}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PEVerify", "tests\PEVerify\PEVerify.csproj", "{035CF639-9704-44C0-96AA-BCB132AA881A}" EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fscAnyCpu", "src\fsc\fscAnyCpuProject\fscAnyCpu.fsproj", "{597D9896-4B90-4E9E-9C99-445C2CB9FF60}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fscArm64", "src\fsc\fscArm64Project\fscArm64.fsproj", "{0973C362-585C-4838-9459-D7E45C6B784B}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsc", "src\fsc\fscProject\fsc.fsproj", "{E54456F4-D51A-4334-B225-92EBBED92B40}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsi", "src\fsi\fsiProject\fsi.fsproj", "{511C95D9-3BA6-451F-B6F8-F033F40878A5}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsiAnyCpu", "src\fsi\fsiAnyCpuProject\fsiAnyCpu.fsproj", "{37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}" +EndProject +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsiArm64", "src\fsi\fsiArm64Project\fsiArm64.fsproj", "{EB015235-1E07-4CDA-9CC6-3FBCC27910D1}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -489,18 +491,6 @@ Global {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|Any CPU.Build.0 = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|x86.ActiveCfg = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|x86.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.ActiveCfg = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.Build.0 = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.Build.0 = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|x86.ActiveCfg = Release|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|x86.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|Any CPU.Build.0 = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -513,30 +503,6 @@ Global {649FA588-F02E-457C-9FCF-87E46407481E}.Release|Any CPU.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|x86.ActiveCfg = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|x86.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.ActiveCfg = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.Build.0 = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|x86.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|x86.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.ActiveCfg = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.Build.0 = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.Build.0 = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|x86.ActiveCfg = Release|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|x86.Build.0 = Release|Any CPU {60D275B0-B14A-41CB-A1B2-E815A7448FCB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {60D275B0-B14A-41CB-A1B2-E815A7448FCB}.Debug|Any CPU.Build.0 = Debug|Any CPU {60D275B0-B14A-41CB-A1B2-E815A7448FCB}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -969,18 +935,6 @@ Global {EE08E954-AE91-4EFA-8595-10931D29E628}.Release|Any CPU.Build.0 = Release|Any CPU {EE08E954-AE91-4EFA-8595-10931D29E628}.Release|x86.ActiveCfg = Release|Any CPU {EE08E954-AE91-4EFA-8595-10931D29E628}.Release|x86.Build.0 = Release|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Debug|x86.ActiveCfg = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Debug|x86.Build.0 = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Proto|Any CPU.ActiveCfg = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Proto|Any CPU.Build.0 = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Proto|x86.ActiveCfg = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Proto|x86.Build.0 = Debug|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Release|Any CPU.Build.0 = Release|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Release|x86.ActiveCfg = Release|Any CPU - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD}.Release|x86.Build.0 = Release|Any CPU {B1E30F2C-894F-47A9-9C8A-3324831E7D26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B1E30F2C-894F-47A9-9C8A-3324831E7D26}.Debug|Any CPU.Build.0 = Debug|Any CPU {B1E30F2C-894F-47A9-9C8A-3324831E7D26}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -1005,6 +959,78 @@ Global {035CF639-9704-44C0-96AA-BCB132AA881A}.Release|Any CPU.Build.0 = Release|Any CPU {035CF639-9704-44C0-96AA-BCB132AA881A}.Release|x86.ActiveCfg = Release|Any CPU {035CF639-9704-44C0-96AA-BCB132AA881A}.Release|x86.Build.0 = Release|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Debug|Any CPU.Build.0 = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Debug|x86.ActiveCfg = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Debug|x86.Build.0 = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Proto|Any CPU.Build.0 = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Proto|x86.ActiveCfg = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Proto|x86.Build.0 = Debug|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Release|Any CPU.ActiveCfg = Release|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Release|Any CPU.Build.0 = Release|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Release|x86.ActiveCfg = Release|Any CPU + {597D9896-4B90-4E9E-9C99-445C2CB9FF60}.Release|x86.Build.0 = Release|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Debug|x86.ActiveCfg = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Debug|x86.Build.0 = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Proto|Any CPU.Build.0 = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Proto|x86.ActiveCfg = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Proto|x86.Build.0 = Debug|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Release|Any CPU.Build.0 = Release|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Release|x86.ActiveCfg = Release|Any CPU + {0973C362-585C-4838-9459-D7E45C6B784B}.Release|x86.Build.0 = Release|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Debug|x86.ActiveCfg = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Debug|x86.Build.0 = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Proto|Any CPU.Build.0 = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Proto|x86.ActiveCfg = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Proto|x86.Build.0 = Debug|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Release|Any CPU.Build.0 = Release|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Release|x86.ActiveCfg = Release|Any CPU + {E54456F4-D51A-4334-B225-92EBBED92B40}.Release|x86.Build.0 = Release|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Debug|x86.ActiveCfg = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Debug|x86.Build.0 = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Proto|Any CPU.Build.0 = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Proto|x86.ActiveCfg = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Proto|x86.Build.0 = Debug|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Release|Any CPU.Build.0 = Release|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Release|x86.ActiveCfg = Release|Any CPU + {511C95D9-3BA6-451F-B6F8-F033F40878A5}.Release|x86.Build.0 = Release|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Debug|x86.ActiveCfg = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Debug|x86.Build.0 = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Proto|Any CPU.Build.0 = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Proto|x86.ActiveCfg = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Proto|x86.Build.0 = Debug|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Release|Any CPU.Build.0 = Release|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Release|x86.ActiveCfg = Release|Any CPU + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1}.Release|x86.Build.0 = Release|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Debug|x86.ActiveCfg = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Debug|x86.Build.0 = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Proto|Any CPU.Build.0 = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Proto|x86.ActiveCfg = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Proto|x86.Build.0 = Debug|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Release|Any CPU.Build.0 = Release|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Release|x86.ActiveCfg = Release|Any CPU + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1040,10 +1066,7 @@ Global {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9} = {3F044931-FB83-4433-B934-AE66AB27B278} {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C} = {3F044931-FB83-4433-B934-AE66AB27B278} {702A7979-BCF9-4C41-853E-3ADFC9897890} = {B8DDA694-7939-42E3-95E5-265C2217C142} - {C94C257C-3C0A-4858-B5D8-D746498D1F08} = {B8DDA694-7939-42E3-95E5-265C2217C142} {649FA588-F02E-457C-9FCF-87E46407481E} = {B8DDA694-7939-42E3-95E5-265C2217C142} - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} = {B8DDA694-7939-42E3-95E5-265C2217C142} - {D0E98C0D-490B-4C61-9329-0862F6E87645} = {B8DDA694-7939-42E3-95E5-265C2217C142} {60D275B0-B14A-41CB-A1B2-E815A7448FCB} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {C163E892-5BF7-4B59-AA99-B0E8079C67C4} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} @@ -1082,9 +1105,14 @@ Global {208E36EE-665C-42D2-B767-C6DB03C4FEB2} = {47112E07-9FF1-43E7-8021-F2A21D6A19A0} {EE08E954-AE91-4EFA-8595-10931D29E628} = {47112E07-9FF1-43E7-8021-F2A21D6A19A0} {47112E07-9FF1-43E7-8021-F2A21D6A19A0} = {DFB6ADD7-3149-43D9-AFA0-FC4A818B472B} - {52DCA91F-3843-43E3-8FE1-FB2B66658CBD} = {B8DDA694-7939-42E3-95E5-265C2217C142} {B1E30F2C-894F-47A9-9C8A-3324831E7D26} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {035CF639-9704-44C0-96AA-BCB132AA881A} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} + {597D9896-4B90-4E9E-9C99-445C2CB9FF60} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {0973C362-585C-4838-9459-D7E45C6B784B} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {E54456F4-D51A-4334-B225-92EBBED92B40} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {511C95D9-3BA6-451F-B6F8-F033F40878A5} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {37EB3E54-ABC6-4CF5-8273-7CE4B61A42C1} = {B8DDA694-7939-42E3-95E5-265C2217C142} + {EB015235-1E07-4CDA-9CC6-3FBCC27910D1} = {B8DDA694-7939-42E3-95E5-265C2217C142} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {48EDBBBE-C8EE-4E3C-8B19-97184A487B37} diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 6d3e01ed917..93e24046b2d 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -12,6 +12,7 @@ trigger: exclude: - .github/* - docs/ + - tests/scripts/ - attributions.md - CODE_OF_CONDUCT.md - DEVGUIDE.md @@ -56,6 +57,12 @@ variables: value: .NETCore - name: VisualStudioDropName value: Products/$(System.TeamProject)/$(Build.Repository.Name)/$(Build.SourceBranchName)/$(Build.BuildNumber) + - name: Codeql.Enabled + value: true + - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - name: _DotNetValidationArtifactsCategory + value: .NETCoreValidation + - group: DotNet-FSharp-SDLValidation-Params - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - name: RunningAsPullRequest value: true @@ -75,11 +82,11 @@ stages: # Signed build # #-------------------------------------------------------------------------------------------------------------------# - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/release/dev17.2') }}: + - ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/release/dev17.3') }}: - template: /eng/common/templates/job/onelocbuild.yml parameters: MirrorRepo: fsharp - MirrorBranch: release/dev17.2 + MirrorBranch: release/dev17.3 LclSource: lclFilesfromPackage LclPackageId: 'LCL-JUNO-PROD-FSHARP' - template: /eng/common/templates/jobs/jobs.yml @@ -179,6 +186,78 @@ stages: AccessToken: $(dn-bot-devdiv-drop-rw-code-rw) condition: succeeded() + #-------------------------------------------------------------------------------------------------------------------# + # PR builds without logs publishing # + #-------------------------------------------------------------------------------------------------------------------# + - ${{ if eq(variables['System.TeamProject'], 'public') }}: + - template: /eng/common/templates/jobs/jobs.yml + parameters: + enableMicrobuild: false + enablePublishBuildArtifacts: false + enablePublishTestResults: false + enablePublishBuildAssets: false + enablePublishUsingPipelines: $(_PublishUsingPipelines) + enableSourceBuild: false + enableTelemetry: true + helixRepo: dotnet/fsharp + jobs: + # Determinism, we want to run it only in PR builds + - job: Determinism_Debug + condition: eq(variables['Build.Reason'], 'PullRequest') + variables: + - name: _SignType + value: Test + pool: + name: NetCore1ESPool-Public + demands: ImageOverride -equals $(WindowsMachineQueueName) + timeoutInMinutes: 90 + steps: + - checkout: self + clean: true + - task: UseDotNet@2 + displayName: install SDK + inputs: + packageType: sdk + useGlobalJson: true + includePreviewVersions: false + workingDirectory: $(Build.SourcesDirectory) + installationPath: $(Build.SourcesDirectory)/.dotnet + - script: .\eng\test-determinism.cmd -configuration Debug + displayName: Determinism tests with Debug configuration + - task: PublishPipelineArtifact@1 + displayName: Publish Determinism Logs + inputs: + targetPath: '$(Build.SourcesDirectory)/artifacts/log/Debug' + artifactName: 'Determinism_Debug Attempt $(System.JobAttempt) Logs' + continueOnError: true + condition: not(succeeded()) + + # Check code formatting + - job: CheckCodeFormatting + pool: + vmImage: $(UbuntuMachineQueueName) + steps: + - checkout: self + clean: true + - script: dotnet --list-sdks + displayName: Report dotnet SDK versions + - task: UseDotNet@2 + displayName: install SDK + inputs: + packageType: sdk + useGlobalJson: true + includePreviewVersions: true + workingDirectory: $(Build.SourcesDirectory) + installationPath: $(Agent.ToolsDirectory)/dotnet + - script: dotnet tool restore + env: + DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1 + displayName: Install tools + - script: dotnet fantomas src -r --check + env: + DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1 + displayName: Check code formatting (run 'dotnet fantomas src -r' to fix) + #-------------------------------------------------------------------------------------------------------------------# # PR builds # #-------------------------------------------------------------------------------------------------------------------# @@ -199,7 +278,7 @@ stages: - job: Windows pool: # The PR build definition sets this variable: - # WindowsMachineQueueName=Build.Windows.10.Amd64.VS2019.Open + # WindowsMachineQueueName=Windows.vs2022.amd64.open # and there is an alternate build definition that sets this to a queue that is always scouting the # next preview of Visual Studio. name: NetCore1ESPool-Public @@ -264,32 +343,6 @@ stages: - pwsh: .\eng\MockBuild.ps1 displayName: Build with OfficialBuildId - # Check code formatting - - job: CheckCodeFormatting - pool: - vmImage: $(UbuntuMachineQueueName) - steps: - - checkout: self - clean: true - - script: dotnet --list-sdks - displayName: Report dotnet SDK versions - - task: UseDotNet@2 - displayName: install SDK - inputs: - packageType: sdk - useGlobalJson: true - includePreviewVersions: true - workingDirectory: $(Build.SourcesDirectory) - installationPath: $(Agent.ToolsDirectory)/dotnet - - script: dotnet tool restore - env: - DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1 - displayName: Install tools - - script: dotnet fantomas src -r --check - env: - DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1 - displayName: Check code formatting (run 'dotnet fantomas src -r' to fix) - # Linux - job: Linux pool: @@ -382,37 +435,6 @@ stages: - script: .\tests\EndToEndBuildTests\EndToEndBuildTests.cmd -c Release displayName: End to end build tests - # Determinism, we want to run it only in PR builds - - job: Determinism_Debug - condition: eq(variables['Build.Reason'], 'PullRequest') - variables: - - name: _SignType - value: Test - pool: - name: NetCore1ESPool-Public - demands: ImageOverride -equals $(WindowsMachineQueueName) - timeoutInMinutes: 90 - steps: - - checkout: self - clean: true - - task: UseDotNet@2 - displayName: install SDK - inputs: - packageType: sdk - useGlobalJson: true - includePreviewVersions: false - workingDirectory: $(Build.SourcesDirectory) - installationPath: $(Build.SourcesDirectory)/.dotnet - - script: .\eng\test-determinism.cmd -configuration Debug - displayName: Determinism tests with Debug configuration - - task: PublishPipelineArtifact@1 - displayName: Publish Determinism Logs - inputs: - targetPath: '$(Build.SourcesDirectory)/artifacts/log/Debug' - artifactName: 'Determinism_Debug Attempt $(System.JobAttempt) Logs' - continueOnError: true - condition: not(succeeded()) - # Up-to-date - disabled due to it being flaky #- job: UpToDate_Windows # pool: @@ -549,6 +571,20 @@ stages: enableSymbolValidation: false # SourceLink improperly looks for generated files. See https://github.com/dotnet/arcade/issues/3069 enableSourceLinkValidation: false + # Enable SDL validation, passing through values from the 'DotNet-FSharp-SDLValidation-Params' group. + SDLValidationParameters: + enable: true + params: >- + -SourceToolsList @("policheck","credscan") + -TsaInstanceURL $(_TsaInstanceURL) + -TsaProjectName $(_TsaProjectName) + -TsaNotificationEmail $(_TsaNotificationEmail) + -TsaCodebaseAdmin $(_TsaCodebaseAdmin) + -TsaBugAreaPath $(_TsaBugAreaPath) + -TsaIterationPath $(_TsaIterationPath) + -TsaRepositoryName "FSharp" + -TsaCodebaseName "FSharp-GitHub" + -TsaPublish $True #---------------------------------------------------------------------------------------------------------------------# # VS Insertion # @@ -556,8 +592,8 @@ stages: - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - template: eng/release/insert-into-vs.yml parameters: - componentBranchName: refs/heads/release/dev17.0 - insertTargetBranch: rel/d17.0 + componentBranchName: refs/heads/release/dev17.2 + insertTargetBranch: rel/d17.2 insertTeamEmail: fsharpteam@microsoft.com insertTeamName: 'F#' completeInsertion: 'auto' diff --git a/docs/coding-standards.md b/docs/coding-standards.md index 6ebb1daf606..fb86474d883 100644 --- a/docs/coding-standards.md +++ b/docs/coding-standards.md @@ -20,46 +20,48 @@ The future work includes The compiler codebase uses various abbreviations. Here are some of the most common ones. -| Abbreviation | Meaning | -|:------------------------------|:-----------| -| `ad` | Accessor domain, meaning the permissions the accessing code has to access other constructs | -| `amap` | Assembly map, saying how to map IL references to F# CCUs | -| `arg` | Argument (parameter) | -| `argty` | Argument (parameter) type | -| `arginfo` | Argument (parameter) metadata | -| `ccu` | Reference to an F# compilation unit = an F# DLL (possibly including the DLL being compiled) | -| `celem` | Custom attribute element | -| `cenv` | Compilation environment. Means different things in different contexts, but usually a parameter for a single compilation state object being passed through a set of related functions in a single phase. The compilation state is often mutable. | -| `cpath` | Compilation path, meaning A.B.C for the overall names containing a type or module definition | -| `css` | Constraint solver state. | -| `denv` | Display Environment. Parameters guiding the formatting of types | -| `einfo` | An info object for an event (whether a .NET event, an F# event or a provided event) | -| `e` | Expression | -| `env` | Environment. Means different things in different contexts, but usually immutable state being passed and adjusted through a set of related functions in a single phase. | -| `finfo` | An info object for a field (whether a .NET field or a provided field) | -| `fref` | A reference to an ILFieldRef Abstract IL node for a field reference. Would normally be modernized to `ilFieldRef` | -| `g` | The TcGlobals value | -| `id` | Identifier | -| `lid` | Long Identifier | -| `m` | A source code range marker | -| `mimpl` | IL interface method implementation | -| `minfo` | An info object for a method (whether a .NET method, an F# method or a provided method) | -| `modul` | a Typed Tree structure for a namespace or F# module | -| `pat` | Pattern, a syntactic AST node representing part of a pattern in a pattern match | -| `pinfo` | An info object for a property (whether a .NET property, an F# property or a provided property) | -| `rfref` | Record or class field reference, a reference to a Typed Tree node for a record or class field | -| `scoref` | The scope of a reference in IL metadata, either assembly, `.netmodule` or local | -| `spat` | Simple Pattern, a syntactic AST node representing part of a pattern in a pattern match | -| `tau` | A type with the "forall" nodes stripped off (i.e. the nodes which represent generic type parameters). Comes from the notation _𝛕_ used in type theory | -| `tcref` | Type constructor reference (an `EntityRef`) | -| `tinst` | Type instantiation | -| `tpenv` | Type parameter environment, tracks the type parameters in scope during type checking | -| `ty` (not: `typ`) | Type, usually a Typed Tree type | -| `tys` (not: `typs`) | List of types, usually Typed Tree types | -| `typar` | Type Parameter | -| `tyvar` | Type Variable, usually referring to an IL type variable, the compiled form of an F# type parameter | -| `ucref` | Union case reference, a reference to a Typed Tree node for a union case | -| `vref` | Value reference, a reference to a Typed Tree node for a value | +| Abbreviation | Meaning | +|:--------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `ad` | Accessor domain, meaning the permissions the accessing code has to access other constructs | +| `amap` | Assembly map, saying how to map IL references to F# CCUs | +| `arg` | Argument (parameter) | +| `argty` | Argument (parameter) type | +| `arginfo` | Argument (parameter) metadata | +| `ccu` | Reference to an F# compilation unit = an F# DLL (possibly including the DLL being compiled) | +| `celem` | Custom attribute element | +| `cenv` | Compilation environment. Means different things in different contexts, but usually a parameter for a single compilation state object being passed through a set of related functions in a single phase. The compilation state is often mutable. | +| `cpath` | Compilation path, meaning A.B.C for the overall names containing a type or module definition | +| `css` | Constraint solver state. | +| `denv` | Display Environment. Parameters guiding the formatting of types | +| `einfo` | An info object for an event (whether a .NET event, an F# event or a provided event) | +| `e` | Expression | +| `env` | Environment. Means different things in different contexts, but usually immutable state being passed and adjusted through a set of related functions in a single phase. | +| `finfo` | An info object for a field (whether a .NET field or a provided field) | +| `fref` | A reference to an ILFieldRef Abstract IL node for a field reference. Would normally be modernized to `ilFieldRef` | +| `g` | The TcGlobals value | +| `id` | Identifier | +| `lid` | Long Identifier | +| `m` | A source code range marker | +| `mimpl` | IL interface method implementation | +| `minfo` | An info object for a method (whether a .NET method, an F# method or a provided method) | +| `mk` | Means make in old fashioned F#/OCaml coding style | +| `modul` | a Typed Tree structure for a namespace or F# module | +| `pat` | Pattern, a syntactic AST node representing part of a pattern in a pattern match | +| `pinfo` | An info object for a property (whether a .NET property, an F# property or a provided property) | +| `rfref` | Record or class field reference, a reference to a Typed Tree node for a record or class field | +| `scoref` | The scope of a reference in IL metadata, either assembly, `.netmodule` or local | +| `sp` | Sequence points or debug points | +| `spat` | Simple Pattern, a syntactic AST node representing part of a pattern in a pattern match | +| `tau` | A type with the "forall" nodes stripped off (i.e. the nodes which represent generic type parameters). Comes from the notation _𝛕_ used in type theory | +| `tcref` | Type constructor reference (an `EntityRef`) | +| `tinst` | Type instantiation | +| `tpenv` | Type parameter environment, tracks the type parameters in scope during type checking | +| `ty` (not: `typ`) | Type, usually a Typed Tree type | +| `tys` (not: `typs`) | List of types, usually Typed Tree types | +| `typar` | Type Parameter | +| `tyvar` | Type Variable, usually referring to an IL type variable, the compiled form of an F# type parameter | +| `ucref` | Union case reference, a reference to a Typed Tree node for a union case | +| `vref` | Value reference, a reference to a Typed Tree node for a value | | Phase Abbreviation | Meaning | |:------------------------------|:-----------| diff --git a/docs/fcs/typedtree.fsx b/docs/fcs/typedtree.fsx index 65782a4b9df..e49a92385a0 100644 --- a/docs/fcs/typedtree.fsx +++ b/docs/fcs/typedtree.fsx @@ -189,7 +189,7 @@ let rec visitExpr f (e:FSharpExpr) = visitObjArg f objExprOpt; visitExprs f argExprs | FSharpExprPatterns.Coerce(targetType, inpExpr) -> visitExpr f inpExpr - | FSharpExprPatterns.FastIntegerForLoop(startExpr, limitExpr, consumeExpr, isUp) -> + | FSharpExprPatterns.FastIntegerForLoop(startExpr, limitExpr, consumeExpr, isUp, _, _) -> visitExpr f startExpr; visitExpr f limitExpr; visitExpr f consumeExpr | FSharpExprPatterns.ILAsm(asmCode, typeArgs, argExprs) -> visitExprs f argExprs @@ -201,10 +201,11 @@ let rec visitExpr f (e:FSharpExpr) = visitExpr f guardExpr; visitExpr f thenExpr; visitExpr f elseExpr | FSharpExprPatterns.Lambda(lambdaVar, bodyExpr) -> visitExpr f bodyExpr - | FSharpExprPatterns.Let((bindingVar, bindingExpr), bodyExpr) -> + | FSharpExprPatterns.Let((bindingVar, bindingExpr, dbg), bodyExpr) -> visitExpr f bindingExpr; visitExpr f bodyExpr - | FSharpExprPatterns.LetRec(recursiveBindings, bodyExpr) -> - List.iter (snd >> visitExpr f) recursiveBindings; visitExpr f bodyExpr + | FSharpExprPatterns.LetRec(recursiveBindings, bodyExpr) -> + for _,bindingExpr,_ in recursiveBindings do visitExpr f bindingExpr + visitExpr f bodyExpr | FSharpExprPatterns.NewArray(arrayType, argExprs) -> visitExprs f argExprs | FSharpExprPatterns.NewDelegate(delegateType, delegateBodyExpr) -> @@ -229,9 +230,9 @@ let rec visitExpr f (e:FSharpExpr) = visitObjArg f objExprOpt; visitExpr f argExpr | FSharpExprPatterns.Sequential(firstExpr, secondExpr) -> visitExpr f firstExpr; visitExpr f secondExpr - | FSharpExprPatterns.TryFinally(bodyExpr, finalizeExpr) -> + | FSharpExprPatterns.TryFinally(bodyExpr, finalizeExpr, dbgTry, dbgFinally) -> visitExpr f bodyExpr; visitExpr f finalizeExpr - | FSharpExprPatterns.TryWith(bodyExpr, _, _, catchVar, catchExpr) -> + | FSharpExprPatterns.TryWith(bodyExpr, _, _, catchVar, catchExpr, dbgTry, dbgWith) -> visitExpr f bodyExpr; visitExpr f catchExpr | FSharpExprPatterns.TupleGet(tupleType, tupleElemIndex, tupleExpr) -> visitExpr f tupleExpr @@ -259,7 +260,7 @@ let rec visitExpr f (e:FSharpExpr) = visitExprs f argExprs | FSharpExprPatterns.ValueSet(valToSet, valueExpr) -> visitExpr f valueExpr - | FSharpExprPatterns.WhileLoop(guardExpr, bodyExpr) -> + | FSharpExprPatterns.WhileLoop(guardExpr, bodyExpr, dbg) -> visitExpr f guardExpr; visitExpr f bodyExpr | FSharpExprPatterns.BaseValue baseType -> () | FSharpExprPatterns.DefaultValue defaultType -> () diff --git a/docs/fcs/untypedtree.fsx b/docs/fcs/untypedtree.fsx index dc05d875239..f53d69692fd 100644 --- a/docs/fcs/untypedtree.fsx +++ b/docs/fcs/untypedtree.fsx @@ -115,7 +115,7 @@ let rec visitPattern = function printfn " .. underscore pattern" | SynPat.Named(name, _, _, _) -> printfn " .. named as '%s'" name.idText - | SynPat.LongIdent(LongIdentWithDots(ident, _), _, _, _, _, _) -> + | SynPat.LongIdent(LongIdentWithDots(ident, _), _, _, _, _, _, _) -> let names = String.concat "." [ for i in ident -> i.idText ] printfn " .. identifier: %s" names | pat -> printfn " .. other pattern: %A" pat @@ -140,12 +140,14 @@ let rec visitExpression e = visitExpression trueBranch falseBranchOpt |> Option.iter visitExpression - | SynExpr.LetOrUse(_, _, bindings, body, _) -> + | SynExpr.LetOrUse(_, _, bindings, body, _, _) -> // Visit bindings (there may be multiple // for 'let .. = .. and .. = .. in ...' printfn "LetOrUse with the following bindings:" for binding in bindings do - let (SynBinding(access, kind, isInline, isMutable, attrs, xmlDoc, data, headPat, retInfo, equalsRange, init, m, debugPoint)) = binding + let (SynBinding( + access, kind, isInline, isMutable, attrs, xmlDoc, data, + headPat, retInfo, init, equalsRange, debugPoint, trivia)) = binding visitPattern headPat visitExpression init // Visit the body expression @@ -175,8 +177,9 @@ let visitDeclarations decls = // Let binding as a declaration is similar to let binding // as an expression (in visitExpression), but has no body for binding in bindings do - let (SynBinding(access, kind, isInline, isMutable, attrs, xmlDoc, - valData, pat, retInfo, equalsRange, body, m, sp)) = binding + let (SynBinding( + access, kind, isInline, isMutable, attrs, xmlDoc, + valData, pat, retInfo, body, equalsRange, debugPoint, trivia)) = binding visitPattern pat visitExpression body | _ -> printfn " - not supported declaration: %A" declaration @@ -191,7 +194,7 @@ with multiple `namespace Foo` declarations: /// does not explicitly define it.. let visitModulesAndNamespaces modulesOrNss = for moduleOrNs in modulesOrNss do - let (SynModuleOrNamespace(lid, isRec, isMod, decls, xml, attrs, _, m)) = moduleOrNs + let (SynModuleOrNamespace(lid, isRec, isMod, decls, xml, attrs, accessibility, range)) = moduleOrNs printfn "Namespace or module: %A" lid visitDeclarations decls (** @@ -235,7 +238,7 @@ in the previous step: match tree with | ParsedInput.ImplFile(implFile) -> // Extract declarations and walk over them - let (ParsedImplFileInput(fn, script, name, _, _, modules, _)) = implFile + let (ParsedImplFileInput(fn, script, name, _, _, modules, _, _)) = implFile visitModulesAndNamespaces modules | _ -> failwith "F# Interface file (*.fsi) not supported." (** diff --git a/docs/memory-usage.md b/docs/memory-usage.md index c2e2767a796..8894e0dd4af 100644 --- a/docs/memory-usage.md +++ b/docs/memory-usage.md @@ -29,7 +29,7 @@ In general, the F# compiler allocates a lot of memory. More than it needs to. Ho Some allocations are much more than others * Large Object Heap (LOH) allocations (> ~80K) are rarely collected and should only be used for long-lived items. * Ephemeral allocations that never escape the Gen0 seem to not matter that much, though of course should be considered. -* Don't try to remove all allocations, and don't assume copy large structs is better than allocating a reference type. Measure instead. +* Don't try to remove all allocations, and don't assume copying of large structs is better than allocating a reference type. Measure instead. To analyze memory usage of F# tooling, you have two primary avenues: @@ -38,6 +38,11 @@ To analyze memory usage of F# tooling, you have two primary avenues: You can analyze dumps and take samples with [dotMemory](https://www.jetbrains.com/dotmemory/) or [PerfView](https://github.com/Microsoft/perfview). +To analyze memory usage of the F# compiler itself: +* extract the compilation arguments out of msbuild output (or in the output pane of Visual Studio) +* put this content in a "response file" (a text file listing compiler arguments, one per line) +* use the memory profiler tool of choice, invoking the compiler (either fsc.exe, or through `dotnet path/to/fsc.dll`) giving it the argument `@name-of-response-file`, and setting the directory of the project that is compiled as `working directory` + ### Analyzing a process dump file Process dump files are extremely information-rich data files that can be used to see the distribution of memory usage across various types. Tools like [dotMemory](https://www.jetbrains.com/dotmemory/) will show these distributions and intelligently group things to help identify the biggest areas worth improving. Additionally, they will notice things like duplicate strings and sparse arrays, which are often great ways to improve memory usage since it means more memory is being used than is necessary. diff --git a/docs/overview.md b/docs/overview.md index a993ee5388c..f66d80ae613 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -27,7 +27,7 @@ The following are the key data formats and internal data representations of the * _Input command-line arguments_ See [CompilerOptions.fs](https://github.com/dotnet/fsharp/blob/main/src/Compiler/Driver/CompilerOptions.fs) for the full code implementing the arguments table. Command-line arguments are also accepted by the F# Compiler Service API in project specifications, and as optional input to F# Interactive. -* _Tokens_, see [pars.fsy](https://github.com/dotnet/fsharp/blob/main/src/Compiler/pars.fsy), [lex.fsl](https://github.com/dotnet/fsharp/blob/main/src/Compiler/lex.fsl), [lexhelp.fs](https://github.com/dotnet/fsharp/blob/main/src/Compiler/SyntaxTree/lexhelp.fs) and related files. +* _Tokens_, see [pars.fsy](https://github.com/dotnet/fsharp/blob/main/src/Compiler/pars.fsy), [lex.fsl](https://github.com/dotnet/fsharp/blob/main/src/Compiler/lex.fsl), [LexHelpers.fs](https://github.com/dotnet/fsharp/blob/main/src/Compiler/SyntaxTree/LexHelpers.fs) and related files. * _Abstract Syntax Tree (AST)_, see [SyntaxTree.fs](https://github.com/dotnet/fsharp/blob/main/src/Compiler/SyntaxTree/SyntaxTree.fs), the untyped syntax tree resulting from parsing. @@ -55,15 +55,85 @@ The following are the most relevant parts of the F# compiler tooling, making up The following is a diagram of how the different phases of the F# compiler work: -![F# compiler phases](http://fsharp.github.io/img/fscomp-phases.png) +```mermaid +stateDiagram-v2 + state "Compilation phases" as Flow { + Lexing: Lexing + Parsing: Parsing + Import: Import + Typechecking: Type checking + Codegen: Code generation + Emit: IL emit + Inputs --> Lexing: Source and signature files + Inputs --> Import: References + Lexing --> Parsing + Parsing --> Typechecking + Import --> Typechecking + Typechecking --> Codegen + Codegen --> Emit + state Lexing { + BasicLexing: Basic Lexing + WhitespaceSensitiveLexing: Whitespace Sensitive Lexing + [*] --> BasicLexing + BasicLexing --> WhitespaceSensitiveLexing: A token stream from input source text. + WhitespaceSensitiveLexing --> [*]: A token stream, augmented per the F# Language Specification. + } + state Parsing { + Parser: Parsing + [*] --> Parser + Parser --> [*]: AST per the grammar in the F# Language Specification. + } + state Import { + Resolving: Resolving references + ImportNET: Importing .NET references + ImportFS: Importing F# references + [*] --> Resolving + Resolving --> ImportNET + Resolving --> ImportFS + ImportNET --> [*] + ImportFS --> [*] + } + state Typechecking { + SequentialTypechecking: Sequentially type checking files + PatternMatchCompilation: Pattern match compilation + ConstraintSolving: Constraint solving + PostInferenceChecks: Post inference checks + [*] --> SequentialTypechecking + SequentialTypechecking --> PatternMatchCompilation + PatternMatchCompilation --> ConstraintSolving + ConstraintSolving --> PostInferenceChecks + PostInferenceChecks --> [*] + } + state Codegen { + QuotationTranslation: Quotation translation + Optimization: Optimization + Codegeneration: Code generation + AbstractILRewrite: Abstract IL rewriting + [*] --> QuotationTranslation + QuotationTranslation --> Optimization + Optimization --> Codegeneration + Codegeneration --> AbstractILRewrite + AbstractILRewrite --> [*] + } + state Emit { + Binary: Binary emit + Reflection: Reflection emit + Output: Output (assembly, references, PDBs, etc.) + [*] --> Binary + [*] --> Reflection + Binary --> Output + Reflection --> Output + } + } +``` The following are the key phases and high-level logical operations of the F# compiler code in its various configurations: -* _Basic lexing_. Produces a token stream from input source file text. +* _Basic lexing_. Produces a token stream from input source file text. F# uses the [FsLex](http://fsprojects.github.io/FsLexYacc/) tool to process a declarative specification of the tokenizer in [lex.fsl](https://github.com/dotnet/fsharp/blob/main/src/Compiler/lex.fsl). This compiles the tokenizer specification to a number of tables which are then interpreted by the code in [prim-lexing.fs](https://github.com/dotnet/fsharp/blob/main/src/Compiler/Facilities/prim-lexing.fs) (see also [prim-lexing.fsi](https://github.com/dotnet/fsharp/blob/main/src/Compiler/Facilities/prim-lexing.fsi). -* _White-space sensitive lexing_. Accepts and produces a token stream, augmenting per the F# Language Specification. +* _White-space sensitive lexing_. Accepts and produces a token stream, augmenting per the [F# Language Specification](https://fsharp.org/specs/language-spec/). -* _Parsing_. Accepts a token stream and produces an AST per the grammar in the F# Language Specification. +* _Parsing_. Accepts a token stream and produces an AST per the grammar in the [F# Language Specification](https://fsharp.org/specs/language-spec/). F# uses the [FsYacc](http://fsprojects.github.io/FsLexYacc/) tool to process a declarative specification of the parser in [pars.fsy](https://github.com/dotnet/fsharp/blob/main/src/Compiler/pars.fsy). This compiles the grammar to a number of tables which are then interpreted by the code in [prim-parsing.fs](https://github.com/dotnet/fsharp/blob/main/src/Compiler/Facilities/prim-parsing.fs) (see also [prim-parsing.fsi](https://github.com/dotnet/fsharp/blob/main/src/Compiler/Facilities/prim-parsing.fsi). * _Resolving references_. For .NET SDK generally references are resolved explicitly by external tooling. There is a legacy aspect to this if references use old .NET Framework references including for diff --git a/docs/representations.md b/docs/representations.md new file mode 100644 index 00000000000..abd8c9a0b3b --- /dev/null +++ b/docs/representations.md @@ -0,0 +1,58 @@ +--- +title: Representations +category: Compiler Internals +categoryindex: 200 +index: 350 +--- +# Representation Decisions in the F# Compiler + +Consider the following declarations, all of which look very similar. + +```fsharp +module M = + let z = 1 + let f = x + z + + +type C(w: int, z: int) = + + let f x = x + z + let f x = f 3 + x + + +let g (z: int) = + let f x = x + 1 +``` +Part of the job of the F# compiler is to "decide" how these declarations are compiled. The following acts as a guide to how these different bindings are represented and where these decisions are made. + +First for module-level `let` bindings. These representations are decided by code in `CheckExpressions.fs` and `CheckDeclarations.fs` based on syntax. + +```fsharp +module M = + let z = 1 // z --> static property + field, required by spec, compiled name mandated + let f x = x + z // f --> static method, required by spec, compiled name mandated +``` + +Next for class-level `let` bindings. These representations are decided by code in `CheckIncrementalClasses.fs` based on analysis of use. +```fsharp +// Decided in CheckIncrementalClasses.fs based on analysis of use +type C(w: int, z: int) = // w --> local to object constructor, required by spec + // z --> private instance field, required by spec + let f x = x + z // f --> private instance method, required by spec, compiled name not mandated + // Note: initially uses an ephemeral 'f' Val then creates a member Val with compiled name + + let f x = f 3 + x // f --> private instance method, required by spec, compiled name not mandated + // Note: initially uses an ephemeral 'f' Val then creates a member Val with compiled name + + static let g x = x + 1 // g --> private static method, required by spec, compiled name not mandated, initially uses an ephemeral 'g' Val then creates a member Val with compiled name + + static let g x = g 3 // g --> private static method, required by spec, compiled name not mandated, initially uses an ephemeral 'g' Val then creates a member Val with compiled name +``` +Next for expression-level `let` bindings. These representations are decided by code in various optimization phases. +```fsharp +let g (z: int) = // z --> local + field in closure for 'f', not mandated + let f x = x + 1 // f --> FSharpFunc value, or maybe a static method, not mandated + // Decided in various optimization phases +``` + +> NOTE: The representation decision is implied by the addition of ValReprInfo to the `Val` node. diff --git a/eng/Build.ps1 b/eng/Build.ps1 index 424cbe6c578..bacf90f8c4e 100644 --- a/eng/Build.ps1 +++ b/eng/Build.ps1 @@ -61,6 +61,7 @@ param ( [string]$officialSkipTests = "false", [switch]$noVisualStudio, [switch]$sourceBuild, + [switch]$skipBuild, [parameter(ValueFromRemainingArguments = $true)][string[]]$properties) @@ -114,6 +115,7 @@ function Print-Usage() { Write-Host " -useGlobalNuGetCache Use global NuGet cache." Write-Host " -noVisualStudio Only build fsc and fsi as .NET Core applications. No Visual Studio required. '-configuration', '-verbosity', '-norestore', '-rebuild' are supported." Write-Host " -sourceBuild Simulate building for source-build." + Write-Host " -skipbuild Skip building product" Write-Host "" Write-Host "Command line arguments starting with '/p:' are passed through to MSBuild." } @@ -423,6 +425,8 @@ try { [System.Environment]::SetEnvironmentVariable('DOTNET_ROLL_FORWARD_TO_PRERELEASE', '1', [System.EnvironmentVariableTarget]::User) + $env:NativeToolsOnMachine = $true + Process-Arguments . (Join-Path $PSScriptRoot "build-utils.ps1") @@ -458,7 +462,7 @@ try { } $script:BuildMessage = "Failure building product" - if ($restore -or $build -or $rebuild -or $pack -or $sign -or $publish) { + if ($restore -or $build -or $rebuild -or $pack -or $sign -or $publish -and -not $skipBuild) { if ($noVisualStudio) { BuildSolution "FSharp.sln" } diff --git a/eng/SourceBuild.props b/eng/SourceBuild.props index 903ee00d3f6..949c084ed77 100644 --- a/eng/SourceBuild.props +++ b/eng/SourceBuild.props @@ -5,28 +5,13 @@ true - - - - - - - - - $(InnerBuildArgs) /p:Projects="$(InnerSourceBuildRepoRoot)\FSharp.sln" + $(InnerBuildArgs) /p:Projects="$(InnerSourceBuildRepoRoot)\Microsoft.FSharp.Compiler.sln" diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 720cac644b0..0ff466b9e27 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -8,9 +8,9 @@ - + https://github.com/dotnet/arcade - 6e533ee7a479018586f2314295ad113f6ba1d5b1 + a264eb13fea14125f3ef8d4056586cd66fa55309 diff --git a/eng/Versions.props b/eng/Versions.props index 87774bad87e..6571c5fb21a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -15,7 +15,7 @@ 6 0 - 1 + 5 0 @@ -32,14 +32,14 @@ 41 0 - 1 + 5 $(FSRevisionVersion) $(FCSMajorVersion).$(FCSMinorVersion).$(FCSBuildVersion) $(FCSMajorVersion).$(FCSMinorVersion).$(FCSBuildVersion).$(FCSRevisionVersion) $(FCSMajorVersion)$(FCSMinorVersion)$(FCSBuildVersion) - 6.0.1 + 6.0.3 $(FSCorePackageVersionValue)-$(PreReleaseVersionLabel).* @@ -47,7 +47,7 @@ 12 0 - 0 + 4 $(FSRevisionVersion) $(FSToolsMajorVersion).$(FSToolsMinorVersion).$(FSToolsBuildVersion) $(FSToolsMajorVersion)-$(FSToolsMinorVersion)-$(FSToolsBuildVersion) @@ -55,7 +55,7 @@ 17 - 0 + 1 $(VSMajorVersion).0 $(VSMajorVersion).$(VSMinorVersion).0 $(VSAssemblyVersionPrefix).0 @@ -135,7 +135,7 @@ $(VisualStudioContractPackagesVersion) $(VisualStudioContractPackagesVersion) - 4.2.0-2.22103.11 + 4.2.0-3.22154.1 $(RoslynVersion) $(RoslynVersion) $(RoslynVersion) @@ -189,6 +189,7 @@ $(VisualStudioContractPackagesVersion) 17.0.46 9.0.30729 + 6.0.0 12.0.4 7.0.4 8.0.4 @@ -212,6 +213,7 @@ 13.0.1 3.13.2 4.1.0 + 3.11.0 2.1.80 1.0.0-beta2-dev3 2.11.34 diff --git a/eng/common/init-tools-native.ps1 b/eng/common/init-tools-native.ps1 index 413adea4365..24a5e65de1b 100644 --- a/eng/common/init-tools-native.ps1 +++ b/eng/common/init-tools-native.ps1 @@ -93,7 +93,7 @@ try { $ToolVersion = "" } $ArcadeToolsDirectory = "C:\arcade-tools" - if (Test-Path $ArcadeToolsDirectory -eq $False) { + if (-not (Test-Path $ArcadeToolsDirectory)) { Write-Error "Arcade tools directory '$ArcadeToolsDirectory' was not found; artifacts were not properly installed." exit 1 } @@ -103,13 +103,14 @@ try { exit 1 } $BinPathFile = "$($ToolDirectory.FullName)\binpath.txt" - if (Test-Path -Path "$BinPathFile" -eq $False) { + if (-not (Test-Path -Path "$BinPathFile")) { Write-Error "Unable to find binpath.txt in '$($ToolDirectory.FullName)' ($ToolName $ToolVersion); artifact is either installed incorrectly or is not a bootstrappable tool." exit 1 } $BinPath = Get-Content "$BinPathFile" - Write-Host "Adding $ToolName to the path ($(Convert-Path -Path $BinPath))..." - Write-Host "##vso[task.prependpath]$(Convert-Path -Path $BinPath)" + $ToolPath = Convert-Path -Path $BinPath + Write-Host "Adding $ToolName to the path ($ToolPath)..." + Write-Host "##vso[task.prependpath]$ToolPath" } } exit 0 @@ -188,7 +189,7 @@ try { Write-Host "##vso[task.prependpath]$(Convert-Path -Path $InstallBin)" return $InstallBin } - else { + elseif (-not ($PathPromotion)) { Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message 'Native tools install directory does not exist, installation failed' exit 1 } diff --git a/eng/common/internal/Tools.csproj b/eng/common/internal/Tools.csproj index beb9c4648ea..7f5ce6d6081 100644 --- a/eng/common/internal/Tools.csproj +++ b/eng/common/internal/Tools.csproj @@ -8,6 +8,9 @@ + + + diff --git a/eng/common/templates/steps/send-to-helix.yml b/eng/common/templates/steps/send-to-helix.yml index 09a223989f7..3eb7e2d5f84 100644 --- a/eng/common/templates/steps/send-to-helix.yml +++ b/eng/common/templates/steps/send-to-helix.yml @@ -3,7 +3,7 @@ parameters: HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number - HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues + HelixTargetQueues: '' # required -- semicolon-delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group HelixConfiguration: '' # optional -- additional property attached to a job HelixPreCommands: '' # optional -- commands to run before Helix work item execution @@ -12,7 +12,7 @@ parameters: WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects WorkItemTimeout: '' # optional -- a timeout in TimeSpan.Parse-ready value (e.g. 00:02:00) for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload - XUnitProjects: '' # optional -- semicolon delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true + XUnitProjects: '' # optional -- semicolon-delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true XUnitWorkItemTimeout: '' # optional -- the workitem timeout in seconds for all workitems created from the xUnit projects specified by XUnitProjects XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner @@ -22,14 +22,14 @@ parameters: DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set - HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting int) + HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting https://helix.int-dot.net ) Creator: '' # optional -- if the build is external, use this to specify who is sending the job DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false steps: - - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /restore /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' + - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /restore /p:TreatWarningsAsErrors=false /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' displayName: ${{ parameters.DisplayNamePrefix }} (Windows) env: BuildConfig: $(_BuildConfig) @@ -59,7 +59,7 @@ steps: SYSTEM_ACCESSTOKEN: $(System.AccessToken) condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} - - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /restore /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog + - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /restore /p:TreatWarningsAsErrors=false /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog displayName: ${{ parameters.DisplayNamePrefix }} (Unix) env: BuildConfig: $(_BuildConfig) diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 797f05292a8..395b43eebb6 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -573,7 +573,7 @@ function InitializeBuildTool() { ExitWithExitCode 1 } $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet') - $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'netcoreapp3.1' } + $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'net7.0' } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore @@ -635,6 +635,10 @@ function InitializeNativeTools() { InstallDirectory = "$ToolsDir" } } + if (Test-Path variable:NativeToolsOnMachine) { + Write-Host "Variable NativeToolsOnMachine detected, enabling native tool path promotion..." + $nativeArgs += @{ PathPromotion = $true } + } & "$PSScriptRoot/init-tools-native.ps1" @nativeArgs } } diff --git a/eng/common/tools.sh b/eng/common/tools.sh index 17f0a365805..c110d0ed410 100755 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -312,7 +312,7 @@ function InitializeBuildTool { # return values _InitializeBuildTool="$_InitializeDotNetCli/dotnet" _InitializeBuildToolCommand="msbuild" - _InitializeBuildToolFramework="netcoreapp3.1" + _InitializeBuildToolFramework="net7.0" } # Set RestoreNoCache as a workaround for https://github.com/NuGet/Home/issues/3116 diff --git a/eng/targets/NGenBinaries.targets b/eng/targets/NGenBinaries.targets index c084206d0a6..e0529d3bb61 100644 --- a/eng/targets/NGenBinaries.targets +++ b/eng/targets/NGenBinaries.targets @@ -29,25 +29,36 @@ $(windir)\Microsoft.NET\Framework\v4.0.30319\ngen.exe $(windir)\Microsoft.NET\Framework64\v4.0.30319\ngen.exe + $(windir)\Microsoft.NET\FrameworkArm64\v4.0.30319\ngen.exe + + + + @@ -61,10 +72,12 @@ $(WindowsSDK_ExecutablePath_x86)\sn.exe $(WindowsSDK_ExecutablePath_x64)\sn.exe + $(WindowsSDK_ExecutablePath_Arm64)\sn.exe + diff --git a/global.json b/global.json index 1f533b74406..f21d9785660 100644 --- a/global.json +++ b/global.json @@ -1,23 +1,24 @@ { "sdk": { - "version": "6.0.200", + "version": "6.0.301", "allowPrerelease": true, - "rollForward": "minor" + "rollForward": "latestMajor" }, "tools": { - "dotnet": "6.0.200", + "dotnet": "7.0.100-preview.2.22153.17", "vs": { - "version": "16.8", + "version": "17.0", "components": [ "Microsoft.VisualStudio.Component.FSharp" ] - } + }, + "xcopy-msbuild": "17.1.0" }, "native-tools": { "perl": "5.32.1.1" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.22259.5", + "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.22327.1", "Microsoft.DotNet.Helix.Sdk": "2.0.0-beta.19069.2" } } diff --git a/proto.proj b/proto.proj index 465502a5420..8973f53fbcd 100644 --- a/proto.proj +++ b/proto.proj @@ -9,10 +9,10 @@ TargetFramework=netstandard2.0 - + TargetFramework=net6.0 - + TargetFramework=net6.0 diff --git a/release-notes.md b/release-notes.md index 3919cdf5641..2b30ad027a9 100644 --- a/release-notes.md +++ b/release-notes.md @@ -34,6 +34,7 @@ These release notes track our current efforts to document changes to the F# proj `a + b` is parsed as `SynLongIdent([op_Addition], [], [Some (OriginalNotation "+")])`. * `SynMeasure` was extended with [SynMeasure.Paren](https://fsharp.github.io/fsharp-compiler-docs/reference/fsharp-compiler-syntax-synmeasure.html#Paren) case. * Dynamic expressions (like `x?y`) are now represented as [SynExpr.Dynamic](https://fsharp.github.io/fsharp-compiler-docs/reference/fsharp-compiler-syntax-synexpr.html#Dynamic) in the Untyped Syntax Tree. +* Members with `get` and/or `set` are now represented as [SynMemberDefn.GetSetMember](https://fsharp.github.io/fsharp-compiler-docs/reference/fsharp-compiler-syntax-synmemberdefn.html#GetSetMember) in the Untyped Syntax Tree. ### F# 6.0 / Visual Studio 17.0 diff --git a/setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj b/setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj index 04442b1e2ff..77de746c4ce 100644 --- a/setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj +++ b/setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj @@ -5,10 +5,12 @@ - - - - + + + + + + @@ -83,10 +85,14 @@ folder "InstallDir:Common7\IDE\CommonExtensions\Microsoft\FSharp\Tools" file source="$(BinariesFolder)fsc\$(Configuration)\$(TargetFramework)\fsc.exe.config" file source="$(BinariesFolder)fscAnyCpu\$(Configuration)\$(TargetFramework)\fscAnyCpu.exe" vs.file.ngen=yes vs.file.ngenArchitecture=X64 vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\Tools\fscAnyCpu.exe" file source="$(BinariesFolder)fscAnyCpu\$(Configuration)\$(TargetFramework)\fscAnyCpu.exe.config" + file source="$(BinariesFolder)fscArm64\$(Configuration)\$(TargetFramework)\fscArm64.exe" vs.file.ngen=yes vs.file.ngenArchitecture=arm64 vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\Tools\fscArm64.exe" + file source="$(BinariesFolder)fscArm64\$(Configuration)\$(TargetFramework)\fscArm64.exe.config" file source="$(BinariesFolder)fsi\$(Configuration)\$(TargetFramework)\fsi.exe" vs.file.ngen=yes vs.file.ngenArchitecture=X86 vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\Tools\fsi.exe" file source="$(BinariesFolder)fsi\$(Configuration)\$(TargetFramework)\fsi.exe.config" file source="$(BinariesFolder)fsiAnyCpu\$(Configuration)\$(TargetFramework)\fsiAnyCpu.exe" vs.file.ngen=yes vs.file.ngenArchitecture=X64 vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\Tools\fsiAnyCpu.exe" file source="$(BinariesFolder)fsiAnyCpu\$(Configuration)\$(TargetFramework)\fsiAnyCpu.exe.config" + file source="$(BinariesFolder)fsiArm64\$(Configuration)\$(TargetFramework)\fsiArm64.exe" vs.file.ngen=yes vs.file.ngenArchitecture=arm64 vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\Tools\fsiAnyCpu.exe" + file source="$(BinariesFolder)fsiArm64\$(Configuration)\$(TargetFramework)\fsiArm64.exe.config" file source="$(BinariesFolder)FSharp.Compiler.Interactive.Settings\$(Configuration)\netstandard2.0\FSharp.Compiler.Interactive.Settings.dll" vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 file source="$(BinariesFolder)FSharp.Compiler.Interactive.Settings\$(Configuration)\netstandard2.0\FSharp.Compiler.Interactive.Settings.xml" file source="$(BinariesFolder)fsc\$(Configuration)\$(TargetFramework)\FSharp.Compiler.Service.dll" vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 diff --git a/src/Compiler/AbstractIL/il.fs b/src/Compiler/AbstractIL/il.fs index ed951e0a03b..3600b0e2cf4 100644 --- a/src/Compiler/AbstractIL/il.fs +++ b/src/Compiler/AbstractIL/il.fs @@ -25,7 +25,9 @@ open Internal.Utilities let logging = false -let _ = if logging then dprintn "* warning: Il.logging is on" +let _ = + if logging then + dprintn "* warning: Il.logging is on" let int_order = LanguagePrimitives.FastGenericComparer @@ -68,11 +70,13 @@ let memoizeNamespaceRightTable = let memoizeNamespacePartTable = ConcurrentDictionary() let splitNameAt (nm: string) idx = - if idx < 0 then failwith "splitNameAt: idx < 0" + if idx < 0 then + failwith "splitNameAt: idx < 0" let last = nm.Length - 1 - if idx > last then failwith "splitNameAt: idx > last" + if idx > last then + failwith "splitNameAt: idx > last" (nm.Substring(0, idx)), (if idx < last then nm.Substring(idx + 1, last - idx) else "") @@ -551,7 +555,8 @@ type ILAssemblyRef(data) = addC (convDigit (int32 v / 16)) addC (convDigit (int32 v % 16)) // retargetable can be true only for system assemblies that definitely have Version - if aref.Retargetable then add ", Retargetable=Yes" + if aref.Retargetable then + add ", Retargetable=Yes" b.ToString() @@ -2497,8 +2502,10 @@ let typeKindOfFlags nm (super: ILType option) flags = if name = "System.Enum" then ILTypeDefKind.Enum - elif (name = "System.Delegate" && nm <> "System.MulticastDelegate") - || name = "System.MulticastDelegate" then + elif + (name = "System.Delegate" && nm <> "System.MulticastDelegate") + || name = "System.MulticastDelegate" + then ILTypeDefKind.Delegate elif name = "System.ValueType" && nm <> "System.Enum" then ILTypeDefKind.ValueType @@ -3925,7 +3932,8 @@ let cdef_cctorCode2CodeOrCreate tag imports f (cd: ILTypeDef) = [| yield f cctor for md in mdefs do - if md.Name <> ".cctor" then yield md + if md.Name <> ".cctor" then + yield md |]) cd.With(methods = methods) @@ -4888,7 +4896,8 @@ type ILTypeSigParser(tstring: string) = // Does the type name start with a leading '['? If so, ignore it // (if the specialization type is in another module, it will be wrapped in bracket) - if here () = '[' then drop () + if here () = '[' then + drop () // 1. Iterate over beginning of type, grabbing the type name and determining if it's generic or an array let typeName = @@ -4947,8 +4956,11 @@ type ILTypeSigParser(tstring: string) = let scope = if (here () = ',' || here () = ' ') && (peek () <> '[' && peekN 2 <> '[') then let grabScopeComponent () = - if here () = ',' then drop () // ditch the ',' - if here () = ' ' then drop () // ditch the ' ' + if here () = ',' then + drop () // ditch the ',' + + if here () = ' ' then + drop () // ditch the ' ' while (peek () <> ',' && peek () <> ']' && peek () <> nil) do step () @@ -4969,8 +4981,11 @@ type ILTypeSigParser(tstring: string) = ILScopeRef.Local // strip any extraneous trailing brackets or commas - if (here () = ']') then drop () - if (here () = ',') then drop () + if (here () = ']') then + drop () + + if (here () = ',') then + drop () // build the IL type let tref = mkILTyRef (scope, typeName) @@ -5549,17 +5564,18 @@ let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref: ILMethodRef) = let argTypes = mref.ArgTypes |> List.map r let retType: ILType = r mref.ReturnType - match possibles - |> List.filter (fun md -> - mref.CallingConv = md.CallingConv - && - // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct - (md.Parameters, argTypes) - ||> List.lengthsEqAndForall2 (fun p1 p2 -> r p1.Type = p2) - && - // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct - r md.Return.Type = retType) - with + match + possibles + |> List.filter (fun md -> + mref.CallingConv = md.CallingConv + && + // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct + (md.Parameters, argTypes) + ||> List.lengthsEqAndForall2 (fun p1 p2 -> r p1.Type = p2) + && + // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct + r md.Return.Type = retType) + with | [] -> failwith ( "no method named " diff --git a/src/Compiler/AbstractIL/ilnativeres.fs b/src/Compiler/AbstractIL/ilnativeres.fs index 3c0752ea8db..70846577d68 100644 --- a/src/Compiler/AbstractIL/ilnativeres.fs +++ b/src/Compiler/AbstractIL/ilnativeres.fs @@ -96,8 +96,10 @@ type CvtResFile() = reader.Read(pAdditional.data, 0, pAdditional.data.Length) |> ignore stream.Position <- stream.Position + 3L &&& ~~~ 3L - if pAdditional.pstringType.theString = Unchecked.defaultof<_> - && (pAdditional.pstringType.Ordinal = uint16 CvtResFile.RT_DLGINCLUDE) then + if + pAdditional.pstringType.theString = Unchecked.defaultof<_> + && (pAdditional.pstringType.Ordinal = uint16 CvtResFile.RT_DLGINCLUDE) + then () (* ERROR ContinueNotSupported *) else resourceNames.Add pAdditional @@ -454,7 +456,8 @@ type VersionHelper() = doBreak <- false () (* ERROR ContinueNotSupported *) (* ERROR BreakNotSupported *) - if not breakLoop then i <- i + 1 + if not breakLoop then + i <- i + 1 if hasWildcard then let mutable (i: int) = lastExplicitValue @@ -1149,7 +1152,8 @@ type NativeResourceWriter() = if id >= 0 then writer.WriteInt32 id else - if name = Unchecked.defaultof<_> then name <- String.Empty + if name = Unchecked.defaultof<_> then + name <- String.Empty writer.WriteUInt32(nameOffset ||| 0x80000000u) dataWriter.WriteUInt16(uint16 name.Length) diff --git a/src/Compiler/AbstractIL/ilprint.fs b/src/Compiler/AbstractIL/ilprint.fs index a9f95cbc1b0..1c777f278b9 100644 --- a/src/Compiler/AbstractIL/ilprint.fs +++ b/src/Compiler/AbstractIL/ilprint.fs @@ -661,16 +661,20 @@ let goutput_fdef _tref env os (fd: ILFieldDef) = output_member_access os fd.Access output_string os " " - if fd.IsStatic then output_string os " static " + if fd.IsStatic then + output_string os " static " - if fd.IsLiteral then output_string os " literal " + if fd.IsLiteral then + output_string os " literal " if fd.IsSpecialName then output_string os " specialname rtspecialname " - if fd.IsInitOnly then output_string os " initonly " + if fd.IsInitOnly then + output_string os " initonly " - if fd.NotSerialized then output_string os " notserialized " + if fd.NotSerialized then + output_string os " notserialized " goutput_typ env os fd.FieldType output_string os " " @@ -740,7 +744,8 @@ let output_code_label os lab = output_string os (formatCodeLabel lab) let goutput_local env os (l: ILLocal) = goutput_typ env os l.Type - if l.IsPinned then output_string os " pinned" + if l.IsPinned then + output_string os " pinned" let goutput_param env os (l: ILParameter) = match l.Name with @@ -985,7 +990,8 @@ let rec goutput_instr env os inst = let rank = shape.Rank output_parens (output_array ", " (goutput_typ env)) os (Array.create rank PrimaryAssemblyILGlobals.typ_Int32) | I_ldelema (ro, _, shape, tok) -> - if ro = ReadonlyAddress then output_string os "readonly. " + if ro = ReadonlyAddress then + output_string os "readonly. " if shape = ILArrayShape.SingleDimensional then output_string os "ldelema " @@ -1034,7 +1040,8 @@ let rec goutput_instr env os inst = | _ -> output_string os "" let goutput_ilmbody env os (il: ILMethodBody) = - if il.IsZeroInit then output_string os " .zeroinit\n" + if il.IsZeroInit then + output_string os " .zeroinit\n" output_string os " .maxstack " output_i32 os il.MaxStack @@ -1067,7 +1074,8 @@ let goutput_mbody is_entrypoint env os (md: ILMethodDef) = | MethodBody.IL il -> goutput_ilmbody env os il.Value | _ -> () - if is_entrypoint then output_string os " .entrypoint" + if is_entrypoint then + output_string os " .entrypoint" output_string os "\n" output_string os "}\n" @@ -1125,11 +1133,14 @@ let goutput_mdef env os (md: ILMethodDef) = let menv = ppenv_enter_method (List.length md.GenericParams) env output_string os " .method " - if md.IsHideBySig then output_string os "hidebysig " + if md.IsHideBySig then + output_string os "hidebysig " - if md.IsReqSecObj then output_string os "reqsecobj " + if md.IsReqSecObj then + output_string os "reqsecobj " - if md.IsSpecialName then output_string os "specialname " + if md.IsSpecialName then + output_string os "specialname " if md.IsUnmanagedExport then output_string os "unmanagedexp " @@ -1149,13 +1160,17 @@ let goutput_mdef env os (md: ILMethodDef) = (goutput_params menv) os md.Parameters output_string os " " - if md.IsSynchronized then output_string os "synchronized " + if md.IsSynchronized then + output_string os "synchronized " - if md.IsMustRun then output_string os "/* mustrun */ " + if md.IsMustRun then + output_string os "/* mustrun */ " - if md.IsPreserveSig then output_string os "preservesig " + if md.IsPreserveSig then + output_string os "preservesig " - if md.IsNoInline then output_string os "noinlining " + if md.IsNoInline then + output_string os "noinlining " if md.IsAggressiveInline then output_string os "aggressiveinlining " @@ -1255,13 +1270,17 @@ let rec goutput_tdef enc env contents os (cd: ILTypeDef) = output_string os layout_attr output_string os " " - if cd.IsSealed then output_string os "sealed " + if cd.IsSealed then + output_string os "sealed " - if cd.IsAbstract then output_string os "abstract " + if cd.IsAbstract then + output_string os "abstract " - if cd.IsSerializable then output_string os "serializable " + if cd.IsSerializable then + output_string os "serializable " - if cd.IsComInterop then output_string os "import " + if cd.IsComInterop then + output_string os "import " output_sqstring os cd.Name goutput_gparams env os cd.GenericParams @@ -1339,7 +1358,8 @@ let output_assemblyRef os (aref: ILAssemblyRef) = output_string os " .assembly extern " output_sqstring os aref.Name - if aref.Retargetable then output_string os " retargetable " + if aref.Retargetable then + output_string os " retargetable " output_string os " { " output_option output_hash os aref.Hash diff --git a/src/Compiler/AbstractIL/ilread.fs b/src/Compiler/AbstractIL/ilread.fs index dd32b630c70..6ec589b3115 100644 --- a/src/Compiler/AbstractIL/ilread.fs +++ b/src/Compiler/AbstractIL/ilread.fs @@ -1379,7 +1379,8 @@ let seekReadGuidIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadId let seekReadBlobIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadIdx ctxt.blobsBigness mdv &addr let seekReadModuleRow (ctxt: ILMetadataReader) mdv idx = - if idx = 0 then failwith "cannot read Module table row 0" + if idx = 0 then + failwith "cannot read Module table row 0" let mutable addr = ctxt.rowAddr TableNames.Module idx let generation = seekReadUInt16Adv mdv &addr @@ -1846,7 +1847,9 @@ let getDataEndPointsDelayed (pectxt: PEReader) ctxtH = |> List.sort let rvaToData (ctxt: ILMetadataReader) (pectxt: PEReader) nm rva = - if rva = 0x0 then failwith "rva is zero" + if rva = 0x0 then + failwith "rva is zero" + let start = pectxt.anyV2P (nm, rva) let endPoints = (Lazy.force ctxt.dataEndPoints) @@ -2178,7 +2181,7 @@ and seekReadInterfaceImpls (ctxt: ILMetadataReader) mdv numTypars tidx = fst, simpleIndexCompare tidx, isSorted ctxt TableNames.InterfaceImpl, - (snd >> seekReadTypeDefOrRef ctxt numTypars AsObject (*ok*) []) + (snd >> seekReadTypeDefOrRef ctxt numTypars AsObject []) ) and seekReadGenericParams ctxt numTypars (a, b) : ILGenericParameterDefs = @@ -2229,7 +2232,7 @@ and seekReadGenericParamConstraints (ctxt: ILMetadataReader) mdv numTypars gpidx fst, simpleIndexCompare gpidx, isSorted ctxt TableNames.GenericParamConstraint, - (snd >> seekReadTypeDefOrRef ctxt numTypars AsObject (*ok*) List.empty) + (snd >> seekReadTypeDefOrRef ctxt numTypars AsObject []) ) and seekReadTypeDefAsType (ctxt: ILMetadataReader) boxity (ginst: ILTypes) idx = @@ -2565,7 +2568,8 @@ and sigptrGetTy (ctxt: ILMetadataReader) numTypars bytes sigptr = let ccByte, sigptr = sigptrGetByte bytes sigptr let generic, cc = byteAsCallConv ccByte - if generic then failwith "fptr sig may not be generic" + if generic then + failwith "fptr sig may not be generic" let struct (numparams, sigptr) = sigptrGetZInt32 bytes sigptr let retTy, sigptr = sigptrGetTy ctxt numTypars bytes sigptr @@ -3082,16 +3086,15 @@ and seekReadEvents (ctxt: ILMetadataReader) numTypars tidx = let mdv = ctxt.mdfile.GetView() match - seekReadOptionalIndexedRow - ( - ctxt.getNumRows TableNames.EventMap, - (fun i -> i, seekReadEventMapRow ctxt mdv i), - (fun (_, row) -> fst row), - compare tidx, - false, - (fun (i, row) -> (i, snd row)) - ) - with + seekReadOptionalIndexedRow ( + ctxt.getNumRows TableNames.EventMap, + (fun i -> i, seekReadEventMapRow ctxt mdv i), + (fun (_, row) -> fst row), + compare tidx, + false, + (fun (i, row) -> (i, snd row)) + ) + with | None -> [] | Some (rowNum, beginEventIdx) -> let endEventIdx = @@ -3150,16 +3153,15 @@ and seekReadProperties (ctxt: ILMetadataReader) numTypars tidx = let mdv = ctxt.mdfile.GetView() match - seekReadOptionalIndexedRow - ( - ctxt.getNumRows TableNames.PropertyMap, - (fun i -> i, seekReadPropertyMapRow ctxt mdv i), - (fun (_, row) -> fst row), - compare tidx, - false, - (fun (i, row) -> (i, snd row)) - ) - with + seekReadOptionalIndexedRow ( + ctxt.getNumRows TableNames.PropertyMap, + (fun i -> i, seekReadPropertyMapRow ctxt mdv i), + (fun (_, row) -> fst row), + compare tidx, + false, + (fun (i, row) -> (i, snd row)) + ) + with | None -> [] | Some (rowNum, beginPropIdx) -> let endPropIdx = @@ -3592,17 +3594,21 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numTypars (sz: int) start s curr <- curr + 4 (* REVIEW: this incorrectly labels all MemberRef tokens as ILMethod's: we should go look at the MemberRef sig to determine if it is a field or method *) let token_info = - if tab = TableNames.Method - || tab = TableNames.MemberRef (* REVIEW: generics or tab = TableNames.MethodSpec *) then + if + tab = TableNames.Method + || tab = TableNames.MemberRef (* REVIEW: generics or tab = TableNames.MethodSpec *) + then let (MethodData (enclTy, cc, nm, argTys, retTy, methInst)) = seekReadMethodDefOrRefNoVarargs ctxt numTypars (uncodedTokenToMethodDefOrRef (tab, idx)) ILToken.ILMethod(mkILMethSpecInTy (enclTy, cc, nm, argTys, retTy, methInst)) elif tab = TableNames.Field then ILToken.ILField(seekReadFieldDefAsFieldSpec ctxt idx) - elif tab = TableNames.TypeDef - || tab = TableNames.TypeRef - || tab = TableNames.TypeSpec then + elif + tab = TableNames.TypeDef + || tab = TableNames.TypeRef + || tab = TableNames.TypeSpec + then ILToken.ILType(seekReadTypeDefOrRef ctxt numTypars AsObject [] (uncodedTokenToTypeDefOrRefOrSpec (tab, idx))) else failwith "bad token for ldtoken" @@ -3680,7 +3686,8 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let isFatFormat = (b &&& e_CorILMethod_FormatMask) = e_CorILMethod_FatFormat if not isTinyFormat && not isFatFormat then - if logging then failwith "unknown format" + if logging then + failwith "unknown format" MethodBody.Abstract else @@ -3924,7 +3931,8 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int nextSectionBase <- sectionBase + sectionSize // Convert the linear code format to the nested code format - if logging then dprintn "doing localPdbInfos2" + if logging then + dprintn "doing localPdbInfos2" let localPdbInfos2 = List.map (fun f -> f raw2nextLab) localPdbInfos @@ -3933,7 +3941,8 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let code = buildILCode nm lab2pc instrs seh localPdbInfos2 - if logging then dprintn "done checking code." + if logging then + dprintn "done checking code." { IsZeroInit = initlocals @@ -4254,10 +4263,10 @@ let openMetadataReader | Some positions -> positions let tablesStreamPhysLoc, _tablesStreamSize = - match tryFindStream [| 0x23; 0x7e |] (* #~ *) with + match tryFindStream [| 0x23; 0x7e |] (* #~ *) with | Some res -> res | None -> - match tryFindStream [| 0x23; 0x2d |] (* #-: at least one DLL I've seen uses this! *) with + match tryFindStream [| 0x23; 0x2d |] (* #-: at least one DLL I've seen uses this! *) with | Some res -> res | None -> let firstStreamOffset = seekReadInt32 mdv (streamHeadersStart + 0) @@ -5073,8 +5082,10 @@ let stableFileHeuristicApplies fileName = let createByteFileChunk opts fileName chunk = // If we're trying to reduce memory usage then we are willing to go back and re-read the binary, so we can use // a weakly-held handle to an array of bytes. - if opts.reduceMemoryUsage = ReduceMemoryFlag.Yes - && stableFileHeuristicApplies fileName then + if + opts.reduceMemoryUsage = ReduceMemoryFlag.Yes + && stableFileHeuristicApplies fileName + then WeakByteFile(fileName, chunk) :> BinaryFile else let bytes = diff --git a/src/Compiler/AbstractIL/ilreflect.fs b/src/Compiler/AbstractIL/ilreflect.fs index af089d2a8bc..a37fa6b1ae0 100644 --- a/src/Compiler/AbstractIL/ilreflect.fs +++ b/src/Compiler/AbstractIL/ilreflect.fs @@ -479,11 +479,11 @@ module Zmap = let equalTypes (s: Type) (t: Type) = s.Equals t -let equalTypeLists ss tt = - List.lengthsEqAndForall2 equalTypes ss tt +let equalTypeLists (tys1: Type list) (tys2: Type list) = + List.lengthsEqAndForall2 equalTypes tys1 tys2 -let equalTypeArrays ss tt = - Array.lengthsEqAndForall2 equalTypes ss tt +let equalTypeArrays (tys1: Type[]) (tys2: Type[]) = + Array.lengthsEqAndForall2 equalTypes tys1 tys2 let getGenericArgumentsOfType (typT: Type) = if typT.IsGenericType then @@ -583,7 +583,7 @@ let convTypeRefAux (cenv: cenv) (tref: ILTypeRef) = [] type ILDynamicAssemblyEmitEnv = { - emTypMap: Zmap + emTypMap: Zmap emConsMap: Zmap emMethMap: Zmap emFieldMap: Zmap @@ -638,11 +638,13 @@ let envUpdateCreatedTypeRef emEnv (tref: ILTypeRef) = // of objects. We use System.Runtime.Serialization.FormatterServices.GetUninitializedObject to do // the fake allocation - this creates an "empty" object, even if the object doesn't have // a constructor. It is not usable in partial trust code. - if runningOnMono - && ty.IsClass - && not ty.IsAbstract - && not ty.IsGenericType - && not ty.IsGenericTypeDefinition then + if + runningOnMono + && ty.IsClass + && not ty.IsAbstract + && not ty.IsGenericType + && not ty.IsGenericTypeDefinition + then try System.Runtime.Serialization.FormatterServices.GetUninitializedObject ty |> ignore @@ -972,7 +974,9 @@ let convFieldSpec cenv emEnv fspec = nonQueryableTypeGetField parentTI fieldB else // Prior type. - if typeIsNotQueryable parentTI then + if + typeIsNotQueryable parentTI + then let parentT = getTypeConstructor parentTI let fieldInfo = queryableTypeGetField emEnv parentT fref nonQueryableTypeGetField parentTI fieldInfo @@ -1009,10 +1013,12 @@ let queryableTypeGetMethodBySearch cenv emEnv parentT (mref: ILMethodRef) = | Some a -> if // obvious case - p.IsAssignableFrom a then + p.IsAssignableFrom a + then true elif - p.IsGenericType && a.IsGenericType + p.IsGenericType + && a.IsGenericType // non obvious due to contravariance: Action where T: IFoo accepts Action (for FooImpl: IFoo) && p.GetGenericTypeDefinition().IsAssignableFrom(a.GetGenericTypeDefinition()) then @@ -1124,8 +1130,10 @@ let queryableTypeGetMethod cenv emEnv parentT (mref: ILMethodRef) : MethodInfo = queryableTypeGetMethodBySearch cenv emEnv parentT mref let nonQueryableTypeGetMethod (parentTI: Type) (methInfo: MethodInfo) : MethodInfo MaybeNull = - if (parentTI.IsGenericType - && not (equalTypes parentTI (getTypeConstructor parentTI))) then + if + (parentTI.IsGenericType + && not (equalTypes parentTI (getTypeConstructor parentTI))) + then TypeBuilder.GetMethod(parentTI, methInfo) else methInfo @@ -1141,7 +1149,9 @@ let convMethodRef cenv emEnv (parentTI: Type) (mref: ILMethodRef) = nonQueryableTypeGetMethod parentTI methB else // Prior type. - if typeIsNotQueryable parentTI then + if + typeIsNotQueryable parentTI + then let parentT = getTypeConstructor parentTI let methInfo = queryableTypeGetMethod cenv emEnv parentT mref nonQueryableTypeGetMethod parentTI methInfo @@ -1216,7 +1226,9 @@ let convConstructorSpec cenv emEnv (mspec: ILMethodSpec) = nonQueryableTypeGetConstructor parentTI consB else // Prior type. - if typeIsNotQueryable parentTI then + if + typeIsNotQueryable parentTI + then let parentT = getTypeConstructor parentTI let ctorG = queryableTypeGetConstructor cenv emEnv parentT mref nonQueryableTypeGetConstructor parentTI ctorG @@ -2134,9 +2146,11 @@ let buildFieldPass2 cenv tref (typB: TypeBuilder) emEnv (fdef: ILFieldDef) = match fdef.LiteralValue with | None -> emEnv | Some initial -> - if not fieldT.IsEnum - // it is ok to init fields with type = enum that are defined in other assemblies - || not fieldT.Assembly.IsDynamic then + if + not fieldT.IsEnum + // it is ok to init fields with type = enum that are defined in other assemblies + || not fieldT.Assembly.IsDynamic + then fieldB.SetConstant(initial.AsObject()) emEnv else @@ -2267,9 +2281,10 @@ let typeAttributesOfTypeLayout cenv emEnv x = if p.Size = None && p.Pack = None then None else - match cenv.tryFindSysILTypeRef "System.Runtime.InteropServices.StructLayoutAttribute", - cenv.tryFindSysILTypeRef "System.Runtime.InteropServices.LayoutKind" - with + match + cenv.tryFindSysILTypeRef "System.Runtime.InteropServices.StructLayoutAttribute", + cenv.tryFindSysILTypeRef "System.Runtime.InteropServices.LayoutKind" + with | Some tref1, Some tref2 -> Some( convCustomAttr @@ -2564,7 +2579,8 @@ let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv t match emEnv.emTypMap.TryFind typeRef with | Some (_, tb, _, _) -> - if not (tb.IsCreated()) then tb.CreateTypeAndLog() |> ignore + if not (tb.IsCreated()) then + tb.CreateTypeAndLog() |> ignore tb.Assembly | None -> null) @@ -2590,7 +2606,8 @@ let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv t traverseTypeRef tref let rec buildTypeDefPass4 (visited, created) nesting emEnv (tdef: ILTypeDef) = - if verbose2 then dprintf "buildTypeDefPass4 %s\n" tdef.Name + if verbose2 then + dprintf "buildTypeDefPass4 %s\n" tdef.Name let tref = mkRefForNestedILTypeDef ILScopeRef.Local (nesting, tdef) createTypeRef (visited, created) emEnv tref diff --git a/src/Compiler/AbstractIL/ilsupp.fs b/src/Compiler/AbstractIL/ilsupp.fs index 1db894b1801..fea9a764487 100644 --- a/src/Compiler/AbstractIL/ilsupp.fs +++ b/src/Compiler/AbstractIL/ilsupp.fs @@ -611,7 +611,8 @@ type ResFormatNode(tid: int32, nid: int32, lid: int32, dataOffset: int32, pbLink let bNil = Bytes.zeroCreate 3 // Align remaining fields on DWORD (nb. poor bit twiddling code taken from ildasm's dres.cpp) - if (dwFiller &&& 0x1) <> 0 then SaveChunk(bNil, 2) + if (dwFiller &&& 0x1) <> 0 then + SaveChunk(bNil, 2) //---- Constant part of the header: DWORD, WORD, WORD, DWORD, DWORD SaveChunk(dwToBytes resHdr.DataVersion) @@ -627,7 +628,8 @@ type ResFormatNode(tid: int32, nid: int32, lid: int32, dataOffset: int32, pbLink dwFiller <- dataEntry.Size &&& 0x3 - if dwFiller <> 0 then SaveChunk(bNil, 4 - dwFiller) + if dwFiller <> 0 then + SaveChunk(bNil, 4 - dwFiller) size diff --git a/src/Compiler/AbstractIL/ilsupp.fsi b/src/Compiler/AbstractIL/ilsupp.fsi index a7b9ddefcfe..e0aa2785471 100644 --- a/src/Compiler/AbstractIL/ilsupp.fsi +++ b/src/Compiler/AbstractIL/ilsupp.fsi @@ -48,14 +48,14 @@ type PdbDebugPoint = pdbSeqPointEndLine: int pdbSeqPointEndColumn: int } -val pdbReadOpen: string (* module *) -> string (* path *) -> PdbReader +val pdbReadOpen: string (* module *) -> string (* path *) -> PdbReader val pdbReadClose: PdbReader -> unit -val pdbReaderGetMethod: PdbReader -> int32 (* token *) -> PdbMethod -val pdbReaderGetMethodFromDocumentPosition: PdbReader -> PdbDocument -> int (* line *) -> int (* col *) -> PdbMethod +val pdbReaderGetMethod: PdbReader -> int32 (* token *) -> PdbMethod +val pdbReaderGetMethodFromDocumentPosition: PdbReader -> PdbDocument -> int (* line *) -> int (* col *) -> PdbMethod val pdbReaderGetDocuments: PdbReader -> PdbDocument array val pdbReaderGetDocument: - PdbReader -> string (* url *) -> byte (* guid *) [] -> byte (* guid *) [] -> byte (* guid *) [] -> PdbDocument + PdbReader -> string (* url *) -> byte (* guid *) [] -> byte (* guid *) [] -> byte (* guid *) [] -> PdbDocument val pdbDocumentGetURL: PdbDocument -> string val pdbDocumentGetType: PdbDocument -> byte (* guid *) [] @@ -72,7 +72,7 @@ val pdbScopeGetLocals: PdbMethodScope -> PdbVariable array val pdbVariableGetName: PdbVariable -> string val pdbVariableGetSignature: PdbVariable -> byte[] -val pdbVariableGetAddressAttributes: PdbVariable -> int32 (* kind *) * int32 (* addrField1 *) +val pdbVariableGetAddressAttributes: PdbVariable -> int32 (* kind *) * int32 (* addrField1 *) #endif #if !FX_NO_PDB_WRITER @@ -89,7 +89,7 @@ type idd = iddType: int32 iddData: byte[] } -val pdbInitialize: string (* .exe/.dll already written and closed *) -> string (* .pdb to write *) -> PdbWriter +val pdbInitialize: string (* .exe/.dll already written and closed *) -> string (* .pdb to write *) -> PdbWriter val pdbClose: PdbWriter -> string -> string -> unit val pdbCloseDocument: PdbDocumentWriter -> unit val pdbSetUserEntryPoint: PdbWriter -> int32 -> unit diff --git a/src/Compiler/AbstractIL/ilwrite.fs b/src/Compiler/AbstractIL/ilwrite.fs index 8b8a13be429..44292305bd9 100644 --- a/src/Compiler/AbstractIL/ilwrite.fs +++ b/src/Compiler/AbstractIL/ilwrite.fs @@ -3881,9 +3881,11 @@ let writeBinaryAux (stream: Stream, options: options, modul, normalizeAssemblyRe let isItanium = modul.Platform = Some IA64 let isItaniumOrAMD = match modul.Platform with | Some IA64 | Some AMD64 -> true | _ -> false let hasEntryPointStub = match modul.Platform with | Some ARM64 | Some ARM -> false | _ -> true + let hasMvidSection = options.referenceAssemblyAttribOpt.IsSome let numSections = - if hasEntryPointStub then 3 // .text, .sdata, .reloc - else 2 // .text, .sdata + let ns = if hasMvidSection then 1 else 0 + if hasEntryPointStub then ns + 3 // [.mvid], .text, .sdata, .reloc + else ns + 2 // [.mvid], .text, .sdata // HEADERS let next = 0x0 @@ -3895,6 +3897,9 @@ let writeBinaryAux (stream: Stream, options: options, modul, normalizeAssemblyRe let peSignatureChunk, next = chunk 0x04 next let peFileHeaderChunk, next = chunk 0x14 next let peOptionalHeaderChunk, next = chunk (if modul.Is64Bit then 0xf0 else 0xe0) next + let mvidSectionHeaderChunk, next = + if hasMvidSection then chunk 0x28 next + else nochunk next let textSectionHeaderChunk, next = chunk 0x28 next let dataSectionHeaderChunk, next = chunk 0x28 next let relocSectionHeaderChunk, next = if hasEntryPointStub then chunk 0x28 next else nochunk next @@ -3904,8 +3909,16 @@ let writeBinaryAux (stream: Stream, options: options, modul, normalizeAssemblyRe let headerSectionPhysSize = nextPhys - headerSectionPhysLoc let next = align alignVirt (headerAddr + headerSize) - // TEXT SECTION: 8 bytes IAT table 72 bytes CLI header + // .MVID SECTION + let mvidSectionPhysLoc = nextPhys + let mvidSectionAddr = next + let mvidSectionChunk, next = if hasMvidSection then chunk sizeof next else nochunk next + let mvidSectionSize = if hasMvidSection then next - mvidSectionAddr else 0x00 + let nextPhys = if hasMvidSection then align alignPhys (mvidSectionPhysLoc + mvidSectionSize) else nextPhys + let mvidSectionPhysSize = if hasMvidSection then nextPhys - mvidSectionPhysLoc else 0x00 + let next = if hasMvidSection then align alignVirt (mvidSectionAddr + mvidSectionSize) else align alignVirt next + // TEXT SECTION: 8 bytes IAT table 72 bytes CLI header let textSectionPhysLoc = nextPhys let textSectionAddr = next let next = textSectionAddr @@ -4123,13 +4136,9 @@ let writeBinaryAux (stream: Stream, options: options, modul, normalizeAssemblyRe os.Write 0uy // Now we've computed all the offsets, write the image - write (Some msdosHeaderChunk.addr) os "msdos header" msdosHeader - write (Some peSignatureChunk.addr) os "pe signature" [| |] - writeInt32 os 0x4550 - write (Some peFileHeaderChunk.addr) os "pe file header" [| |] match modul.Platform with @@ -4141,33 +4150,35 @@ let writeBinaryAux (stream: Stream, options: options, modul, normalizeAssemblyRe writeInt32AsUInt16 os numSections + use sha = + match options.checksumAlgorithm with + | HashAlgorithm.Sha1 -> System.Security.Cryptography.SHA1.Create() :> System.Security.Cryptography.HashAlgorithm + | HashAlgorithm.Sha256 -> System.Security.Cryptography.SHA256.Create() :> System.Security.Cryptography.HashAlgorithm + + let hCode = sha.ComputeHash code + let hData = sha.ComputeHash data + let hMeta = sha.ComputeHash metadata + + // Not yet suitable for the mvidsection optimization + let deterministicId = [| hCode; hData; hMeta |] |> Array.collect id |> sha.ComputeHash + let deterministicMvid () = deterministicId[0..15] let pdbData = // Hash code, data and metadata if options.deterministic then - use sha = - match options.checksumAlgorithm with - | HashAlgorithm.Sha1 -> System.Security.Cryptography.SHA1.Create() :> System.Security.Cryptography.HashAlgorithm - | HashAlgorithm.Sha256 -> System.Security.Cryptography.SHA256.Create() :> System.Security.Cryptography.HashAlgorithm - - let hCode = sha.ComputeHash code - let hData = sha.ComputeHash data - let hMeta = sha.ComputeHash metadata - let final = [| hCode; hData; hMeta |] |> Array.collect id |> sha.ComputeHash - // Confirm we have found the correct data and aren't corrupting the metadata if metadata[ guidStart..guidStart+3] <> [| 4uy; 3uy; 2uy; 1uy |] then failwith "Failed to find MVID" if metadata[ guidStart+12..guidStart+15] <> [| 4uy; 3uy; 2uy; 1uy |] then failwith "Failed to find MVID" // Update MVID guid in metadata - Array.blit final 0 metadata guidStart 16 + Array.blit deterministicId 0 metadata guidStart 16 // Use last 4 bytes for timestamp - High bit set, to stop tool chains becoming confused - let timestamp = int final[16] ||| (int final[17] <<< 8) ||| (int final[18] <<< 16) ||| (int (final[19] ||| 128uy) <<< 24) + let timestamp = int deterministicId[16] ||| (int deterministicId[17] <<< 8) ||| (int deterministicId[18] <<< 16) ||| (int (deterministicId[19] ||| 128uy) <<< 24) writeInt32 os timestamp // Update pdbData with new guid and timestamp. Portable and embedded PDBs don't need the ModuleID // Full and PdbOnly aren't supported under deterministic builds currently, they rely on non-deterministic Windows native code - { pdbData with ModuleID = final[0..15] ; Timestamp = timestamp } + { pdbData with ModuleID = deterministicMvid() ; Timestamp = timestamp } else writeInt32 os timestamp // date since 1970 pdbData @@ -4288,6 +4299,19 @@ let writeBinaryAux (stream: Stream, options: options, modul, normalizeAssemblyRe writeInt32 os 0x00 // Reserved Always 0 (see Section 23.1). writeInt32 os 0x00 // Reserved Always 0 (see Section 23.1). + if hasMvidSection then + write (Some mvidSectionHeaderChunk.addr) os "mvid section header" [| |] + writeBytes os [| 0x2euy; 0x6Duy; 0x76uy; 0x69uy; 0x64uy; 0x00uy; 0x00uy; 0x00uy; |] // ".mvid\000\000\000" + writeInt32 os mvidSectionSize // VirtualSize: Total size of the section when loaded into memory in bytes rounded to Section Alignment. + writeInt32 os mvidSectionAddr // VirtualAddress For executable images this is the address of the first byte of the section + writeInt32 os mvidSectionPhysSize // SizeOfRawData Size of the initialized data on disk in bytes + writeInt32 os mvidSectionPhysLoc // PointerToRawData RVA to section's first page within the PE file. + writeInt32 os 0x00 // PointerToRelocations RVA of Relocation section. + writeInt32 os 0x00 // PointerToLineNumbers Always 0 (see Section 23.1). + writeInt32AsUInt16 os 0x00 // NumberOfRelocations Number of relocations, set to 0 if unused. + writeInt32AsUInt16 os 0x00 // NumberOfLinenumbers Always 0 (see Section 23.1). + writeBytes os [| 0x20uy; 0x00uy; 0x00uy; 0x60uy |] // Characteristics Flags IMAGE_SCN_CNT_CODE || IMAGE_SCN_MEM_EXECUTE || IMAGE_SCN_MEM_READ + write (Some textSectionHeaderChunk.addr) os "text section header" [| |] // 00000178 @@ -4340,10 +4364,15 @@ let writeBinaryAux (stream: Stream, options: options, modul, normalizeAssemblyRe writeInt32AsUInt16 os 0x00 // NumberOfLinenumbers Always 0 (see Section 23.1). writeBytes os [| 0x40uy; 0x00uy; 0x00uy; 0x42uy |] // Characteristics Flags: IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | - writePadding os "pad to text begin" (textSectionPhysLoc - headerSize) + writePadding os "pad to mvid begin" (mvidSectionPhysLoc - headerSize) - // TEXT SECTION: e.g. 0x200 + // MVID SECTION + if hasMvidSection then + ignore mvidSectionChunk + writeBytes os (deterministicMvid()) + writePadding os "pad to mvid begin" (textSectionPhysLoc - (mvidSectionPhysLoc + mvidSectionSize)) + // TEXT SECTION: e.g. 0x200 let textV2P v = v - textSectionAddr + textSectionPhysLoc // e.g. 0x0200 diff --git a/src/Compiler/AbstractIL/ilwritepdb.fs b/src/Compiler/AbstractIL/ilwritepdb.fs index c81cfc23ad3..55b23795bbc 100644 --- a/src/Compiler/AbstractIL/ilwritepdb.fs +++ b/src/Compiler/AbstractIL/ilwritepdb.fs @@ -751,10 +751,12 @@ type PortablePdbGenerator builder.WriteCompressedInteger offsetDelta // Check for hidden-sequence-point-record - if startLine = 0xfeefee - || endLine = 0xfeefee - || (startColumn = 0 && endColumn = 0) - || ((endLine - startLine) = 0 && (endColumn - startColumn) = 0) then + if + startLine = 0xfeefee + || endLine = 0xfeefee + || (startColumn = 0 && endColumn = 0) + || ((endLine - startLine) = 0 && (endColumn - startColumn) = 0) + then // Hidden-sequence-point-record builder.WriteCompressedInteger 0 builder.WriteCompressedInteger 0 @@ -1008,14 +1010,16 @@ let writePdbInfo showTimes outfile pdbfile info cvChunk = | Some p -> sco.StartOffset <> p.StartOffset || sco.EndOffset <> p.EndOffset | None -> true - if nested then pdbOpenScope pdbw sco.StartOffset + if nested then + pdbOpenScope pdbw sco.StartOffset sco.Locals |> Array.iter (fun v -> pdbDefineLocalVariable pdbw v.Name v.Signature v.Index) sco.Children |> Array.iter (writePdbScope (if nested then Some sco else parent)) - if nested then pdbCloseScope pdbw sco.EndOffset) + if nested then + pdbCloseScope pdbw sco.EndOffset) match minfo.RootScope with | None -> () @@ -1242,8 +1246,10 @@ and allNamesOfScopes acc (scopes: PdbMethodScope[]) = let rec pushShadowedLocals (stackGuard: StackGuard) (localsToPush: PdbLocalVar[]) (scope: PdbMethodScope) = stackGuard.Guard(fun () -> // Check if child scopes are properly nested - if scope.Children - |> Array.forall (fun child -> child.StartOffset >= scope.StartOffset && child.EndOffset <= scope.EndOffset) then + if + scope.Children + |> Array.forall (fun child -> child.StartOffset >= scope.StartOffset && child.EndOffset <= scope.EndOffset) + then let children = scope.Children |> Array.sortWith scopeSorter diff --git a/src/Compiler/AbstractIL/ilx.fs b/src/Compiler/AbstractIL/ilx.fs index 6a7adab880b..e91ad50d712 100644 --- a/src/Compiler/AbstractIL/ilx.fs +++ b/src/Compiler/AbstractIL/ilx.fs @@ -39,7 +39,7 @@ type IlxUnionHasHelpers = | SpecialFSharpListHelpers | SpecialFSharpOptionHelpers -type IlxUnionRef = IlxUnionRef of boxity: ILBoxity * ILTypeRef * IlxUnionCase[] * bool (* hasHelpers: *) * IlxUnionHasHelpers +type IlxUnionRef = IlxUnionRef of boxity: ILBoxity * ILTypeRef * IlxUnionCase[] * bool (* hasHelpers: *) * IlxUnionHasHelpers type IlxUnionSpec = | IlxUnionSpec of IlxUnionRef * ILGenericArgs @@ -75,7 +75,7 @@ type IlxClosureApps = let rec instAppsAux n inst apps = match apps with | Apps_tyapp (ty, rest) -> Apps_tyapp(instILTypeAux n inst ty, instAppsAux n inst rest) - | Apps_app (dty, rest) -> Apps_app(instILTypeAux n inst dty, instAppsAux n inst rest) + | Apps_app (domainTy, rest) -> Apps_app(instILTypeAux n inst domainTy, instAppsAux n inst rest) | Apps_done retTy -> Apps_done(instILTypeAux n inst retTy) let rec instLambdasAux n inst lambdas = diff --git a/src/Compiler/AbstractIL/ilx.fsi b/src/Compiler/AbstractIL/ilx.fsi index 901117867b7..a6a008434be 100644 --- a/src/Compiler/AbstractIL/ilx.fsi +++ b/src/Compiler/AbstractIL/ilx.fsi @@ -39,7 +39,7 @@ type IlxUnionRef = boxity: ILBoxity * ILTypeRef * IlxUnionCase[] * - bool (* IsNullPermitted *) * + bool (* IsNullPermitted *) * IlxUnionHasHelpers (* HasHelpers *) type IlxUnionSpec = diff --git a/src/Compiler/Checking/AttributeChecking.fs b/src/Compiler/Checking/AttributeChecking.fs index 9d1cc9ac5ca..2439cc4f794 100644 --- a/src/Compiler/Checking/AttributeChecking.fs +++ b/src/Compiler/Checking/AttributeChecking.fs @@ -391,27 +391,36 @@ let CheckILFieldAttributes g (finfo:ILFieldInfo) m = CheckProvidedAttributes amap.g m (fi.PApply((fun st -> (st :> IProvidedCustomAttributeProvider)), m)) |> CommitOperationResult #endif +/// Check the attributes on an entity, returning errors and warnings as data. +let CheckEntityAttributes g (x:TyconRef) m = + if x.IsILTycon then + CheckILAttributes g (isByrefLikeTyconRef g m x) x.ILTyconRawMetadata.CustomAttrs m + else + CheckFSharpAttributes g x.Attribs m + /// Check the attributes associated with a method, returning warnings and errors as data. -let CheckMethInfoAttributes g m tyargsOpt minfo = - let search = - BindMethInfoAttributes m minfo - (fun ilAttribs -> Some(CheckILAttributes g false ilAttribs m)) - (fun fsAttribs -> - let res = - CheckFSharpAttributes g fsAttribs m ++ (fun () -> - if Option.isNone tyargsOpt && HasFSharpAttribute g g.attrib_RequiresExplicitTypeArgumentsAttribute fsAttribs then - ErrorD(Error(FSComp.SR.tcFunctionRequiresExplicitTypeArguments(minfo.LogicalName), m)) - else - CompleteD) - Some res) +let CheckMethInfoAttributes g m tyargsOpt (minfo: MethInfo) = + CheckEntityAttributes g minfo.ApparentEnclosingTyconRef m ++ (fun () -> + let search = + BindMethInfoAttributes m minfo + (fun ilAttribs -> Some(CheckILAttributes g false ilAttribs m)) + (fun fsAttribs -> + let res = + CheckFSharpAttributes g fsAttribs m ++ (fun () -> + if Option.isNone tyargsOpt && HasFSharpAttribute g g.attrib_RequiresExplicitTypeArgumentsAttribute fsAttribs then + ErrorD(Error(FSComp.SR.tcFunctionRequiresExplicitTypeArguments(minfo.LogicalName), m)) + else + CompleteD) + Some res) #if !NO_TYPEPROVIDERS - (fun provAttribs -> Some (CheckProvidedAttributes g m provAttribs)) + (fun provAttribs -> Some (CheckProvidedAttributes g m provAttribs)) #else - (fun _provAttribs -> None) + (fun _provAttribs -> None) #endif - match search with - | Some res -> res - | None -> CompleteD // no attribute = no errors + match search with + | Some res -> res + | None -> CompleteD // no attribute = no errors + ) /// Indicate if a method has 'Obsolete', 'CompilerMessageAttribute' or 'TypeProviderEditorHideMethodsAttribute'. /// Used to suppress the item in intellisense. @@ -471,13 +480,6 @@ let PropInfoIsUnseen m pinfo = | ProvidedProp (_amap, pi, m) -> CheckProvidedAttributesForUnseen (pi.PApply((fun st -> (st :> IProvidedCustomAttributeProvider)), m)) m #endif - -/// Check the attributes on an entity, returning errors and warnings as data. -let CheckEntityAttributes g (x:TyconRef) m = - if x.IsILTycon then - CheckILAttributes g (isByrefLikeTyconRef g m x) x.ILTyconRawMetadata.CustomAttrs m - else - CheckFSharpAttributes g x.Attribs m /// Check the attributes on a union case, returning errors and warnings as data. let CheckUnionCaseAttributes g (x:UnionCaseRef) m = diff --git a/src/Compiler/Checking/AugmentWithHashCompare.fs b/src/Compiler/Checking/AugmentWithHashCompare.fs index f6faeb7bee7..cb7320006b7 100644 --- a/src/Compiler/Checking/AugmentWithHashCompare.fs +++ b/src/Compiler/Checking/AugmentWithHashCompare.fs @@ -888,8 +888,8 @@ let mkValSpec g (tcref: TyconRef) ty vis slotsig methn valTy argData = slotImplMethod(final, tcref, slotsig) let inl = ValInline.Optional let args = ValReprInfo.unnamedTopArg :: argData - let topValInfo = Some (ValReprInfo (ValReprInfo.InferTyparInfo tps, args, ValReprInfo.unnamedRetVal)) - Construct.NewVal (methn, m, None, valTy, Immutable, true, topValInfo, vis, ValNotInRecScope, Some membInfo, NormalVal, [], inl, XmlDoc.Empty, true, false, false, false, false, false, None, Parent tcref) + let valReprInfo = Some (ValReprInfo (ValReprInfo.InferTyparInfo tps, args, ValReprInfo.unnamedRetVal)) + Construct.NewVal (methn, m, None, valTy, Immutable, true, valReprInfo, vis, ValNotInRecScope, Some membInfo, NormalVal, [], inl, XmlDoc.Empty, true, false, false, false, false, false, None, Parent tcref) let MakeValsForCompareAugmentation g (tcref: TyconRef) = let m = tcref.Range diff --git a/src/Compiler/Checking/CheckComputationExpressions.fs b/src/Compiler/Checking/CheckComputationExpressions.fs index 4792a818dbb..c8a9501e475 100644 --- a/src/Compiler/Checking/CheckComputationExpressions.fs +++ b/src/Compiler/Checking/CheckComputationExpressions.fs @@ -224,10 +224,10 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol // Give bespoke error messages for the FSharp.Core "query" builder let isQuery = match stripDebugPoints interpExpr with - | Expr.Val (vf, _, m) -> - let item = Item.CustomBuilder (vf.DisplayName, vf) + | Expr.Val (vref, _, m) -> + let item = Item.CustomBuilder (vref.DisplayName, vref) CallNameResolutionSink cenv.tcSink (m, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) - valRefEq cenv.g vf cenv.g.query_value_vref + valRefEq cenv.g vref cenv.g.query_value_vref | _ -> false /// Make a builder.Method(...) call @@ -1175,7 +1175,7 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol // For 'query' check immediately if isQuery then match (List.map (BindingNormalization.NormalizeBinding ValOrMemberBinding cenv env) binds) with - | [NormalizedBinding(_, SynBindingKind.Normal, (*inline*)false, (*mutable*)false, _, _, _, _, _, _, _, _)] when not isRec -> + | [NormalizedBinding(_, SynBindingKind.Normal, false, false, _, _, _, _, _, _, _, _)] when not isRec -> () | normalizedBindings -> let failAt m = error(Error(FSComp.SR.tcNonSimpleLetBindingInQuery(), m)) @@ -1770,7 +1770,7 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol // Add a call to 'Quote' if the method is present let quotedSynExpr = if isAutoQuote then - SynExpr.Quote (mkSynIdGet mDelayOrQuoteOrRun (CompileOpName "<@ @>"), (*isRaw=*)false, delayedExpr, (*isFromQueryExpression=*)true, mWhole) + SynExpr.Quote (mkSynIdGet mDelayOrQuoteOrRun (CompileOpName "<@ @>"), false, delayedExpr, true, mWhole) else delayedExpr // Add a call to 'Run' if the method is present @@ -1909,8 +1909,8 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = // This transformation is visible in quotations and thus needs to remain. | (TPat_as (TPat_wild _, PatternValBinding (v, _), _), [_], - DebugPoints(Expr.App (Expr.Val (vf, _, _), _, [genEnumElemTy], [yieldExpr], _mYield), recreate)) - when valRefEq cenv.g vf cenv.g.seq_singleton_vref -> + DebugPoints(Expr.App (Expr.Val (vref, _, _), _, [genEnumElemTy], [yieldExpr], _mYield), recreate)) + when valRefEq cenv.g vref cenv.g.seq_singleton_vref -> // The debug point mFor is attached to the 'map' // The debug point mIn is attached to the lambda @@ -2051,11 +2051,11 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = error(Error(FSComp.SR.tcUseForInSequenceExpression(), m)) | SynExpr.Match (spMatch, expr, clauses, _m, _trivia) -> - let inputExpr, matchty, tpenv = TcExprOfUnknownType cenv env tpenv expr + let inputExpr, inputTy, tpenv = TcExprOfUnknownType cenv env tpenv expr let tclauses, tpenv = (tpenv, clauses) ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, _, sp, _)) -> - let patR, condR, vspecs, envinner, tpenv = TcMatchPattern cenv matchty env tpenv pat cond + let patR, condR, vspecs, envinner, tpenv = TcMatchPattern cenv inputTy env tpenv pat cond let envinner = match sp with | DebugPointAtTarget.Yes -> { envinner with eIsControlFlow = true } diff --git a/src/Compiler/Checking/CheckDeclarations.fs b/src/Compiler/Checking/CheckDeclarations.fs index f18b0d1e7ce..b8192ef5f01 100644 --- a/src/Compiler/Checking/CheckDeclarations.fs +++ b/src/Compiler/Checking/CheckDeclarations.fs @@ -15,6 +15,7 @@ open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.AttributeChecking open FSharp.Compiler.CheckComputationExpressions open FSharp.Compiler.CheckExpressions +open FSharp.Compiler.CheckIncrementalClasses open FSharp.Compiler.CheckPatterns open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ConstraintSolver @@ -253,9 +254,9 @@ let BuildRootModuleType enclosingNamespacePath (cpath: CompilationPath) moduleTy |> fun (_, (moduleTy, moduls)) -> moduleTy, List.rev moduls /// Given a resulting module expression, place that inside a namespace path implied by a "namespace X.Y.Z" definition -let BuildRootModuleContents enclosingNamespacePath (cpath: CompilationPath) moduleContents = +let BuildRootModuleContents (isModule: bool) enclosingNamespacePath (cpath: CompilationPath) moduleContents = (enclosingNamespacePath, (cpath, moduleContents)) - ||> List.foldBack (fun id (cpath, moduleContents) -> (cpath.ParentCompPath, wrapModuleOrNamespaceContentsInNamespace id cpath.ParentCompPath moduleContents)) + ||> List.foldBack (fun id (cpath, moduleContents) -> (cpath.ParentCompPath, wrapModuleOrNamespaceContentsInNamespace isModule id cpath.ParentCompPath moduleContents)) |> snd /// Try to take the "FSINNN" prefix off a namespace path @@ -290,9 +291,9 @@ let OpenModuleOrNamespaceRefs tcSink g amap scopem root env mvvs openDeclaration env /// Adjust the TcEnv to account for opening a type implied by an `open type` declaration -let OpenTypeContent tcSink g amap scopem env (typ: TType) openDeclaration = +let OpenTypeContent tcSink g amap scopem env (ty: TType) openDeclaration = let env = - { env with eNameResEnv = AddTypeContentsToNameEnv g amap env.eAccessRights scopem env.eNameResEnv typ } + { env with eNameResEnv = AddTypeContentsToNameEnv g amap env.eAccessRights scopem env.eNameResEnv ty } CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) CallOpenDeclarationSink tcSink openDeclaration env @@ -377,6 +378,8 @@ let ImplicitlyOpenOwnNamespace tcSink g amap scopem enclosingNamespacePath (env: exception NotUpperCaseConstructor of range: range +exception NotUpperCaseConstructorWithoutRQA of range: range + let CheckNamespaceModuleOrTypeName (g: TcGlobals) (id: Ident) = // type names '[]' etc. are used in fslib if not g.compilingFSharpCore && id.idText.IndexOfAny IllegalCharactersInTypeAndNamespaceNames <> -1 then @@ -422,7 +425,8 @@ module TcRecdUnionAndEnumDeclarations = error(Error(FSComp.SR.tcVolatileOnlyOnClassLetBindings(), m)) if isIncrClass && (not zeroInit || not isMutable) then errorR(Error(FSComp.SR.tcUninitializedValFieldsMustBeMutable(), m)) - if isStatic && (not zeroInit || not isMutable || vis <> Some SynAccess.Private ) then errorR(Error(FSComp.SR.tcStaticValFieldsMustBeMutableAndPrivate(), m)) + let isPrivate = match vis with | Some (SynAccess.Private _) -> true | _ -> false + if isStatic && (not zeroInit || not isMutable || not isPrivate) then errorR(Error(FSComp.SR.tcStaticValFieldsMustBeMutableAndPrivate(), m)) let konst = if zeroInit then Some Const.Zero else None let rfspec = MakeRecdFieldSpec cenv env parent (isStatic, konst, tyR, attrsForProperty, attrsForField, id, nameGenerated, isMutable, isVolatile, xmldoc, vis, m) match parent with @@ -451,7 +455,7 @@ module TcRecdUnionAndEnumDeclarations = // Bind other elements of type definitions (constructors etc.) //------------------------------------------------------------------------- - let CheckUnionCaseName (cenv: cenv) (id: Ident) = + let CheckUnionCaseName (cenv: cenv) (id: Ident) hasRQAAttribute = let g = cenv.g let name = id.idText if name = "Tags" then @@ -459,8 +463,13 @@ module TcRecdUnionAndEnumDeclarations = CheckNamespaceModuleOrTypeName g id - if not (String.isLeadingIdentifierCharacterUpperCase name) && name <> opNameCons && name <> opNameNil then - errorR(NotUpperCaseConstructor(id.idRange)) + if g.langVersion.SupportsFeature(LanguageFeature.LowercaseDUWhenRequireQualifiedAccess) then + + if not (String.isLeadingIdentifierCharacterUpperCase name) && not hasRQAAttribute && name <> opNameCons && name <> opNameNil then + errorR(NotUpperCaseConstructorWithoutRQA(id.idRange)) + else + if not (String.isLeadingIdentifierCharacterUpperCase name) && name <> opNameCons && name <> opNameNil then + errorR(NotUpperCaseConstructor(id.idRange)) let ValidateFieldNames (synFields: SynField list, tastFields: RecdField list) = let seen = Dictionary() @@ -477,13 +486,13 @@ module TcRecdUnionAndEnumDeclarations = | _ -> seen.Add(f.LogicalName, sf)) - let TcUnionCaseDecl (cenv: cenv) env parent thisTy thisTyInst tpenv (SynUnionCase(Attributes synAttrs, SynIdent(id, _), args, xmldoc, vis, m, _)) = + let TcUnionCaseDecl (cenv: cenv) env parent thisTy thisTyInst tpenv hasRQAAttribute (SynUnionCase(Attributes synAttrs, SynIdent(id, _), args, xmldoc, vis, m, _)) = let g = cenv.g let attrs = TcAttributes cenv env AttributeTargets.UnionCaseDecl synAttrs // the attributes of a union case decl get attached to the generated "static factory" method let vis, _ = ComputeAccessAndCompPath env None m vis None parent let vis = CombineReprAccess parent vis - CheckUnionCaseName cenv id + CheckUnionCaseName cenv id hasRQAAttribute let rfields, recordTy = match args with @@ -524,8 +533,8 @@ module TcRecdUnionAndEnumDeclarations = let xmlDoc = xmldoc.ToXmlDoc(true, Some names) Construct.NewUnionCase id rfields recordTy attrs xmlDoc vis - let TcUnionCaseDecls cenv env parent (thisTy: TType) thisTyInst tpenv unionCases = - let unionCasesR = unionCases |> List.map (TcUnionCaseDecl cenv env parent thisTy thisTyInst tpenv) + let TcUnionCaseDecls (cenv: cenv) env (parent: ParentRef) (thisTy: TType) (thisTyInst: TypeInst) hasRQAAttribute tpenv unionCases = + let unionCasesR = unionCases |> List.map (TcUnionCaseDecl cenv env parent thisTy thisTyInst tpenv hasRQAAttribute) unionCasesR |> CheckDuplicates (fun uc -> uc.Id) "union case" let TcEnumDecl cenv env parent thisTy fieldTy (SynEnumCase(attributes=Attributes synAttrs; ident= SynIdent(id,_); value=v; xmlDoc=xmldoc; range=m)) = @@ -656,16 +665,16 @@ let TcOpenTypeDecl (cenv: cenv) mOpenDecl scopem env (synType: SynType, m) = checkLanguageFeatureError g.langVersion LanguageFeature.OpenTypeDeclaration mOpenDecl - let typ, _tpenv = TcType cenv NoNewTypars CheckCxs ItemOccurence.Open env emptyUnscopedTyparEnv synType + let ty, _tpenv = TcType cenv NoNewTypars CheckCxs ItemOccurence.Open env emptyUnscopedTyparEnv synType - if not (isAppTy g typ) then + if not (isAppTy g ty) then error(Error(FSComp.SR.tcNamedTypeRequired("open type"), m)) - if isByrefTy g typ then + if isByrefTy g ty then error(Error(FSComp.SR.tcIllegalByrefsInOpenTypeDeclaration(), m)) - let openDecl = OpenDeclaration.Create (SynOpenDeclTarget.Type (synType, m), [], [typ], scopem, false) - let env = OpenTypeContent cenv.tcSink g cenv.amap scopem env typ openDecl + let openDecl = OpenDeclaration.Create (SynOpenDeclTarget.Type (synType, m), [], [ty], scopem, false) + let env = OpenTypeContent cenv.tcSink g cenv.amap scopem env ty openDecl env, [openDecl] let TcOpenDecl (cenv: cenv) mOpenDecl scopem env target = @@ -677,8 +686,6 @@ let TcOpenDecl (cenv: cenv) mOpenDecl scopem env target = | SynOpenDeclTarget.Type (synType, m) -> TcOpenTypeDecl cenv mOpenDecl scopem env (synType, m) -exception ParameterlessStructCtor of range: range - let MakeSafeInitField (g: TcGlobals) env m isStatic = let id = // Ensure that we have an g.CompilerGlobalState @@ -687,869 +694,6 @@ let MakeSafeInitField (g: TcGlobals) env m isStatic = let taccess = TAccess [env.eAccessPath] Construct.NewRecdField isStatic None id false g.int_ty true true [] [] XmlDoc.Empty taccess true -/// Incremental class definitions -module IncrClassChecking = - - /// Represents a single group of bindings in a class with an implicit constructor - type IncrClassBindingGroup = - | IncrClassBindingGroup of bindings: Binding list * isStatic: bool* isRecursive: bool - | IncrClassDo of expr: Expr * isStatic: bool * range: Range - - /// Typechecked info for implicit constructor and it's arguments - type IncrClassCtorLhs = - { - /// The TyconRef for the type being defined - TyconRef: TyconRef - - /// The type parameters allocated for the implicit instance constructor. - /// These may be equated with other (WillBeRigid) type parameters through equi-recursive inference, and so - /// should always be renormalized/canonicalized when used. - InstanceCtorDeclaredTypars: Typars - - /// The value representing the static implicit constructor. - /// Lazy to ensure the static ctor value is only published if needed. - StaticCtorValInfo: Lazy - - /// The value representing the implicit constructor. - InstanceCtorVal: Val - - /// The type of the implicit constructor, representing as a ValScheme. - InstanceCtorValScheme: ValScheme - - /// The values representing the arguments to the implicit constructor. - InstanceCtorArgs: Val list - - /// The reference cell holding the 'this' parameter within the implicit constructor so it can be referenced in the - /// arguments passed to the base constructor - InstanceCtorSafeThisValOpt: Val option - - /// Data indicating if safe-initialization checks need to be inserted for this type. - InstanceCtorSafeInitInfo: SafeInitData - - /// The value representing the 'base' variable within the implicit instance constructor. - InstanceCtorBaseValOpt: Val option - - /// The value representing the 'this' variable within the implicit instance constructor. - InstanceCtorThisVal: Val - - /// The name generator used to generate the names of fields etc. within the type. - NameGenerator: NiceNameGenerator - } - - /// Get the type parameters of the implicit constructor, after taking equi-recursive inference into account. - member ctorInfo.GetNormalizedInstanceCtorDeclaredTypars (cenv: cenv) denv m = - let g = cenv.g - let ctorDeclaredTypars = ctorInfo.InstanceCtorDeclaredTypars - let ctorDeclaredTypars = ChooseCanonicalDeclaredTyparsAfterInference g denv ctorDeclaredTypars m - ctorDeclaredTypars - - /// Check and elaborate the "left hand side" of the implicit class construction - /// syntax. - let TcImplicitCtorLhs_Phase2A(cenv: cenv, env, tpenv, tcref: TyconRef, vis, attrs, spats, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy, xmlDoc: PreXmlDoc) = - - let g = cenv.g - let baseValOpt = - match GetSuperTypeOfType g cenv.amap m objTy with - | Some superTy -> MakeAndPublishBaseVal cenv env (match baseValOpt with None -> None | Some v -> Some v.Id) superTy - | None -> None - - // Add class typars to env - let env = AddDeclaredTypars CheckForDuplicateTypars copyOfTyconTypars env - - // Type check arguments by processing them as 'simple' patterns - // NOTE: if we allow richer patterns here this is where we'd process those patterns - let ctorArgNames, patEnv = TcSimplePatsOfUnknownType cenv true CheckCxs env tpenv (SynSimplePats.SimplePats (spats, m)) - - let (TcPatLinearEnv(_, names, _)) = patEnv - - // Create the values with the given names - let _, vspecs = MakeAndPublishSimpleVals cenv env names - - if tcref.IsStructOrEnumTycon && isNil spats then - errorR (ParameterlessStructCtor(tcref.Range)) - - // Put them in order - let ctorArgs = List.map (fun v -> NameMap.find v vspecs) ctorArgNames - let safeThisValOpt = MakeAndPublishSafeThisVal cenv env thisIdOpt thisTy - - // NOTE: the type scheme here is not complete!!! The ctorTy is more or less - // just a type variable. The type and typars get fixed-up after inference - let ctorValScheme, ctorVal = - let argTy = mkRefTupledTy g (typesOfVals ctorArgs) - - // Initial type has known information - let ctorTy = mkFunTy g argTy objTy - - // NOTE: no attributes can currently be specified for the implicit constructor - let attribs = TcAttributes cenv env (AttributeTargets.Constructor ||| AttributeTargets.Method) attrs - let memberFlags = CtorMemberFlags SynMemberFlagsTrivia.Zero - - let synArgInfos = List.map (SynInfo.InferSynArgInfoFromSimplePat []) spats - let valSynData = SynValInfo([synArgInfos], SynInfo.unnamedRetVal) - let id = ident ("new", m) - - CheckForNonAbstractInterface ModuleOrMemberBinding tcref memberFlags id.idRange - let memberInfo = MakeMemberDataAndMangledNameForMemberVal(g, tcref, false, attribs, [], memberFlags, valSynData, id, false) - let prelimValReprInfo = TranslateSynValInfo m (TcAttributes cenv env) valSynData - let prelimTyschemeG = GeneralizedType(copyOfTyconTypars, ctorTy) - let isComplete = ComputeIsComplete copyOfTyconTypars [] ctorTy - let topValInfo = InferGenericArityFromTyScheme prelimTyschemeG prelimValReprInfo - let ctorValScheme = ValScheme(id, prelimTyschemeG, Some topValInfo, Some memberInfo, false, ValInline.Never, NormalVal, vis, false, true, false, false) - let paramNames = topValInfo.ArgNames - let xmlDoc = xmlDoc.ToXmlDoc(true, Some paramNames) - let ctorVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValInRecScope isComplete, ctorValScheme, attribs, xmlDoc, None, false) - ctorValScheme, ctorVal - - // We only generate the cctor on demand, because we don't need it if there are no cctor actions. - // The code below has a side-effect (MakeAndPublishVal), so we only want to run it once if at all. - // The .cctor is never referenced by any other code. - let cctorValInfo = - lazy - (let cctorArgs = [ fst(mkCompGenLocal m "unitVar" g.unit_ty) ] - - let cctorTy = mkFunTy g g.unit_ty g.unit_ty - let valSynData = SynValInfo([[]], SynInfo.unnamedRetVal) - let id = ident ("cctor", m) - CheckForNonAbstractInterface ModuleOrMemberBinding tcref (ClassCtorMemberFlags SynMemberFlagsTrivia.Zero) id.idRange - let memberInfo = MakeMemberDataAndMangledNameForMemberVal(g, tcref, false, [(*no attributes*)], [], (ClassCtorMemberFlags SynMemberFlagsTrivia.Zero), valSynData, id, false) - let prelimValReprInfo = TranslateSynValInfo m (TcAttributes cenv env) valSynData - let prelimTyschemeG = GeneralizedType(copyOfTyconTypars, cctorTy) - let topValInfo = InferGenericArityFromTyScheme prelimTyschemeG prelimValReprInfo - let cctorValScheme = ValScheme(id, prelimTyschemeG, Some topValInfo, Some memberInfo, false, ValInline.Never, NormalVal, Some SynAccess.Private, false, true, false, false) - - let cctorVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValNotInRecScope, cctorValScheme, [(* no attributes*)], XmlDoc.Empty, None, false) - cctorArgs, cctorVal, cctorValScheme) - - let thisVal = - // --- Create this for use inside constructor - let thisId = ident ("this", m) - let thisValScheme = ValScheme(thisId, NonGenericTypeScheme thisTy, None, None, false, ValInline.Never, CtorThisVal, None, true, false, false, false) - let thisVal = MakeAndPublishVal cenv env (ParentNone, false, ClassLetBinding false, ValNotInRecScope, thisValScheme, [], XmlDoc.Empty, None, false) - thisVal - - {TyconRef = tcref - InstanceCtorDeclaredTypars = copyOfTyconTypars - StaticCtorValInfo = cctorValInfo - InstanceCtorArgs = ctorArgs - InstanceCtorVal = ctorVal - InstanceCtorValScheme = ctorValScheme - InstanceCtorBaseValOpt = baseValOpt - InstanceCtorSafeThisValOpt = safeThisValOpt - InstanceCtorSafeInitInfo = safeInitInfo - InstanceCtorThisVal = thisVal - // For generating names of local fields - NameGenerator = NiceNameGenerator() - - } - - - // Partial class defns - local val mapping to fields - - /// Create the field for a "let" binding in a type definition. - /// - /// The "v" is the local typed w.r.t. tyvars of the implicit ctor. - /// The formalTyparInst does the formal-typars/implicit-ctor-typars subst. - /// Field specifications added to a tcref must be in terms of the tcrefs formal typars. - let private MakeIncrClassField(g, cpath, formalTyparInst: TyparInstantiation, v: Val, isStatic, rfref: RecdFieldRef) = - let name = rfref.FieldName - let id = ident (name, v.Range) - let ty = v.Type |> instType formalTyparInst - let taccess = TAccess [cpath] - let isVolatile = HasFSharpAttribute g g.attrib_VolatileFieldAttribute v.Attribs - - Construct.NewRecdField isStatic None id false ty v.IsMutable isVolatile [] v.Attribs v.XmlDoc taccess true - - /// Indicates how is a 'let' bound value in a class with implicit construction is represented in - /// the TAST ultimately produced by type checking. - type IncrClassValRepr = - - // e.g representation for 'let v = 3' if it is not used in anything given a method representation - | InVar of (* isArg: *) bool - - // e.g representation for 'let v = 3' - | InField of (*isStatic:*)bool * (*staticCountForSafeInit:*) int * RecdFieldRef - - // e.g representation for 'let f x = 3' - | InMethod of (*isStatic:*)bool * Val * ValReprInfo - - /// IncrClassReprInfo represents the decisions we make about the representation of 'let' and 'do' bindings in a - /// type defined with implicit class construction. - type IncrClassReprInfo = - { - /// Indicates the set of field names taken within one incremental class - TakenFieldNames: Set - - RepInfoTcGlobals: TcGlobals - - /// vals mapped to representations - ValReprs: Zmap - - /// vals represented as fields or members from this point on - ValsWithRepresentation: Zset - } - - static member Empty(g, names) = - { TakenFieldNames=Set.ofList names - RepInfoTcGlobals=g - ValReprs = Zmap.empty valOrder - ValsWithRepresentation = Zset.empty valOrder } - - /// Find the representation of a value - member localRep.LookupRepr (v: Val) = - match Zmap.tryFind v localRep.ValReprs with - | None -> error(InternalError("LookupRepr: failed to find representation for value", v.Range)) - | Some res -> res - - static member IsMethodRepr (cenv: cenv) (bind: Binding) = - let g = cenv.g - let v = bind.Var - // unit fields are not stored, just run rhs for effects - if isUnitTy g v.Type then - false - else - let arity = InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v bind.Expr - not arity.HasNoArgs && not v.IsMutable - - - /// - /// Choose how a binding is represented - /// - /// - /// - /// - /// - /// - /// The vars forced to be fields due to static member bindings, instance initialization expressions or instance member bindings - /// The vars forced to be fields due to instance member bindings - /// - /// - member localRep.ChooseRepresentation (cenv: cenv, env: TcEnv, isStatic, isCtorArg, - ctorInfo: IncrClassCtorLhs, - staticForcedFieldVars: FreeLocals, - instanceForcedFieldVars: FreeLocals, - takenFieldNames: Set, - bind: Binding) = - let g = cenv.g - let v = bind.Var - let relevantForcedFieldVars = (if isStatic then staticForcedFieldVars else instanceForcedFieldVars) - - let tcref = ctorInfo.TyconRef - let name, takenFieldNames = - - let isNameTaken = - // Check if a implicit field already exists with this name - takenFieldNames.Contains(v.LogicalName) || - // Check if a user-defined field already exists with this name. Struct fields have already been created - see bug FSharp 1.0 5304 - (tcref.GetFieldByName(v.LogicalName).IsSome && (isStatic || not tcref.IsFSharpStructOrEnumTycon)) - - let nm = - if isNameTaken then - ctorInfo.NameGenerator.FreshCompilerGeneratedName (v.LogicalName, v.Range) - else - v.LogicalName - nm, takenFieldNames.Add nm - - let reportIfUnused() = - if not v.HasBeenReferenced && not v.IsCompiledAsTopLevel && not (v.DisplayName.StartsWithOrdinal("_")) && not v.IsCompilerGenerated then - warning (Error(FSComp.SR.chkUnusedValue(v.DisplayName), v.Range)) - - let repr = - match InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v bind.Expr with - | arity when arity.HasNoArgs || v.IsMutable -> - // all mutable variables are forced into fields, since they may escape into closures within the implicit constructor - // e.g. - // type C() = - // let mutable m = 1 - // let n = ... (fun () -> m) .... - // - // All struct variables are forced into fields. Structs may not contain "let" bindings, so no new variables can be - // introduced. - - if v.IsMutable || relevantForcedFieldVars.Contains v || tcref.IsStructOrEnumTycon then - //dprintfn "Representing %s as a field %s" v.LogicalName name - let rfref = RecdFieldRef(tcref, name) - reportIfUnused() - InField (isStatic, localRep.ValReprs.Count, rfref) - else - //if not v.Attribs.IsEmpty then - // warning(Error(FSComp.SR.tcAttributesIgnoredOnLetBinding(), v.Range)) - //dprintfn - // "Representing %s as a local variable %s, staticForcedFieldVars = %s, instanceForcedFieldVars = %s" - // v.LogicalName name - // (staticForcedFieldVars |> Seq.map (fun v -> v.LogicalName) |> String.concat ",") - // (instanceForcedFieldVars |> Seq.map (fun v -> v.LogicalName) |> String.concat ",") - InVar isCtorArg - | topValInfo -> - //dprintfn "Representing %s as a method %s" v.LogicalName name - let tps, _, argInfos, _, _ = GetTopValTypeInCompiledForm g topValInfo 0 v.Type v.Range - - let valSynInfo = SynValInfo(argInfos |> List.mapSquared (fun (_, argInfo) -> SynArgInfo([], false, argInfo.Name)), SynInfo.unnamedRetVal) - let memberFlags = (if isStatic then StaticMemberFlags else NonVirtualMemberFlags) SynMemberFlagsTrivia.Zero SynMemberKind.Member - let id = mkSynId v.Range name - let memberInfo = MakeMemberDataAndMangledNameForMemberVal(g, tcref, false, [], [], memberFlags, valSynInfo, mkSynId v.Range name, true) - - let copyOfTyconTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv env.DisplayEnv ctorInfo.TyconRef.Range - // Add the 'this' pointer on to the function - let memberTauTy, topValInfo = - let tauTy = v.TauType - if isStatic then - tauTy, topValInfo - else - let tauTy = mkFunTy g ctorInfo.InstanceCtorThisVal.Type v.TauType - let (ValReprInfo(tpNames, args, ret)) = topValInfo - let topValInfo = ValReprInfo(tpNames, ValReprInfo.selfMetadata :: args, ret) - tauTy, topValInfo - - // Add the enclosing type parameters on to the function - let topValInfo = - let (ValReprInfo(tpNames, args, ret)) = topValInfo - ValReprInfo(tpNames@ValReprInfo.InferTyparInfo copyOfTyconTypars, args, ret) - - let prelimTyschemeG = GeneralizedType(copyOfTyconTypars@tps, memberTauTy) - - // NOTE: putting isCompilerGenerated=true here is strange. The method is not public, nor is - // it a "member" in the F# sense, but the F# spec says it is generated and it is reasonable to reflect on it. - let memberValScheme = ValScheme(id, prelimTyschemeG, Some topValInfo, Some memberInfo, false, ValInline.Never, NormalVal, None, true (* isCompilerGenerated *), true (* isIncrClass *), false, false) - - let methodVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValNotInRecScope, memberValScheme, v.Attribs, XmlDoc.Empty, None, false) - - reportIfUnused() - InMethod(isStatic, methodVal, topValInfo) - - repr, takenFieldNames - - /// Extend the known local representations by choosing a representation for a binding - member localRep.ChooseAndAddRepresentation(cenv: cenv, env: TcEnv, isStatic, isCtorArg, ctorInfo: IncrClassCtorLhs, staticForcedFieldVars: FreeLocals, instanceForcedFieldVars: FreeLocals, bind: Binding) = - let v = bind.Var - let repr, takenFieldNames = localRep.ChooseRepresentation (cenv, env, isStatic, isCtorArg, ctorInfo, staticForcedFieldVars, instanceForcedFieldVars, localRep.TakenFieldNames, bind ) - // OK, representation chosen, now add it - {localRep with - TakenFieldNames=takenFieldNames - ValReprs = Zmap.add v repr localRep.ValReprs} - - member localRep.ValNowWithRepresentation (v: Val) = - {localRep with ValsWithRepresentation = Zset.add v localRep.ValsWithRepresentation} - - member localRep.IsValWithRepresentation (v: Val) = - localRep.ValsWithRepresentation.Contains v - - member localRep.IsValRepresentedAsLocalVar (v: Val) = - match localRep.LookupRepr v with - | InVar false -> true - | _ -> false - - member localRep.IsValRepresentedAsMethod (v: Val) = - localRep.IsValWithRepresentation v && - match localRep.LookupRepr v with - | InMethod _ -> true - | _ -> false - - /// Make the elaborated expression that represents a use of a - /// a "let v = ..." class binding - member localRep.MakeValueLookup thisValOpt tinst safeStaticInitInfo v tyargs m = - let g = localRep.RepInfoTcGlobals - match localRep.LookupRepr v, thisValOpt with - | InVar _, _ -> - exprForVal m v - | InField(false, _idx, rfref), Some thisVal -> - let thise = exprForVal m thisVal - mkRecdFieldGetViaExprAddr (thise, rfref, tinst, m) - | InField(false, _idx, _rfref), None -> - error(InternalError("Unexpected missing 'this' variable in MakeValueLookup", m)) - | InField(true, idx, rfref), _ -> - let expr = mkStaticRecdFieldGet (rfref, tinst, m) - MakeCheckSafeInit g tinst safeStaticInitInfo (mkInt g m idx) expr - - | InMethod(isStatic, methodVal, topValInfo), _ -> - //dprintfn "Rewriting application of %s to be call to method %s" v.LogicalName methodVal.LogicalName - let expr, exprTy = AdjustValForExpectedArity g m (mkLocalValRef methodVal) NormalValUse topValInfo - // Prepend the the type arguments for the class - let tyargs = tinst @ tyargs - let thisArgs = - if isStatic then [] - else Option.toList (Option.map (exprForVal m) thisValOpt) - - MakeApplicationAndBetaReduce g (expr, exprTy, [tyargs], thisArgs, m) - - /// Make the elaborated expression that represents an assignment - /// to a "let mutable v = ..." class binding - member localRep.MakeValueAssign thisValOpt tinst safeStaticInitInfo v expr m = - let g = localRep.RepInfoTcGlobals - match localRep.LookupRepr v, thisValOpt with - | InField(false, _, rfref), Some thisVal -> - let thise = exprForVal m thisVal - mkRecdFieldSetViaExprAddr(thise, rfref, tinst, expr, m) - | InField(false, _, _rfref), None -> - error(InternalError("Unexpected missing 'this' variable in MakeValueAssign", m)) - | InVar _, _ -> - mkValSet m (mkLocalValRef v) expr - | InField (true, idx, rfref), _ -> - let expr = mkStaticRecdFieldSet(rfref, tinst, expr, m) - MakeCheckSafeInit g tinst safeStaticInitInfo (mkInt g m idx) expr - | InMethod _, _ -> - error(InternalError("Local was given method storage, yet later it's been assigned to", m)) - - member localRep.MakeValueGetAddress readonly thisValOpt tinst safeStaticInitInfo v m = - let g = localRep.RepInfoTcGlobals - match localRep.LookupRepr v, thisValOpt with - | InField(false, _, rfref), Some thisVal -> - let thise = exprForVal m thisVal - mkRecdFieldGetAddrViaExprAddr(readonly, thise, rfref, tinst, m) - | InField(false, _, _rfref), None -> - error(InternalError("Unexpected missing 'this' variable in MakeValueGetAddress", m)) - | InField(true, idx, rfref), _ -> - let expr = mkStaticRecdFieldGetAddr(readonly, rfref, tinst, m) - MakeCheckSafeInit g tinst safeStaticInitInfo (mkInt g m idx) expr - | InVar _, _ -> - mkValAddr m readonly (mkLocalValRef v) - | InMethod _, _ -> - error(InternalError("Local was given method storage, yet later it's address was required", m)) - - /// Mutate a type definition by adding fields - /// Used as part of processing "let" bindings in a type definition. - member localRep.PublishIncrClassFields (cenv, denv, cpath, ctorInfo: IncrClassCtorLhs, safeStaticInitInfo) = - let tcref = ctorInfo.TyconRef - let rfspecs = - [ for KeyValue(v, repr) in localRep.ValReprs do - match repr with - | InField(isStatic, _, rfref) -> - // Instance fields for structs are published earlier because the full set of fields is determined syntactically from the implicit - // constructor arguments. This is important for the "default value" and "does it have an implicit default constructor" - // semantic conditions for structs - see bug FSharp 1.0 5304. - if isStatic || not tcref.IsFSharpStructOrEnumTycon then - let ctorDeclaredTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv ctorInfo.TyconRef.Range - - // Note: tcrefObjTy contains the original "formal" typars, thisTy is the "fresh" one... f<>fresh. - let revTypeInst = List.zip ctorDeclaredTypars (tcref.TyparsNoRange |> List.map mkTyparTy) - - yield MakeIncrClassField(localRep.RepInfoTcGlobals, cpath, revTypeInst, v, isStatic, rfref) - | _ -> - () - match safeStaticInitInfo with - | SafeInitField (_, fld) -> yield fld - | NoSafeInitInfo -> () ] - - let recdFields = Construct.MakeRecdFieldsTable (rfspecs @ tcref.AllFieldsAsList) - - // Mutate the entity_tycon_repr to publish the fields - tcref.Deref.entity_tycon_repr <- TFSharpObjectRepr { tcref.FSharpObjectModelTypeInfo with fsobjmodel_rfields = recdFields} - - - /// Given localRep saying how locals have been represented, e.g. as fields. - /// Given an expr under a given thisVal context. - // - // Fix up the references to the locals, e.g. - // v -> this.fieldv - // f x -> this.method x - member localRep.FixupIncrClassExprPhase2C cenv thisValOpt safeStaticInitInfo (thisTyInst: TypeInst) expr = - // fixup: intercept and expr rewrite - let FixupExprNode rw e = - //dprintfn "Fixup %s" (showL (exprL e)) - let g = localRep.RepInfoTcGlobals - let e = NormalizeAndAdjustPossibleSubsumptionExprs g e - match e with - // Rewrite references to applied let-bound-functions-compiled-as-methods - // Rewrite references to applied recursive let-bound-functions-compiled-as-methods - // Rewrite references to applied recursive generic let-bound-functions-compiled-as-methods - | Expr.App (Expr.Val (ValDeref v, _, _), _, tyargs, args, m) - | Expr.App (Expr.Link {contents = Expr.Val (ValDeref v, _, _) }, _, tyargs, args, m) - | Expr.App (Expr.Link {contents = Expr.App (Expr.Val (ValDeref v, _, _), _, tyargs, [], _) }, _, [], args, m) - when localRep.IsValRepresentedAsMethod v && not (cenv.recUses.ContainsKey v) -> - - let expr = localRep.MakeValueLookup thisValOpt thisTyInst safeStaticInitInfo v tyargs m - let args = args |> List.map rw - Some (MakeApplicationAndBetaReduce g (expr, (tyOfExpr g expr), [], args, m)) - - // Rewrite references to values stored as fields and first class uses of method values - | Expr.Val (ValDeref v, _, m) - when localRep.IsValWithRepresentation v -> - - //dprintfn "Found use of %s" v.LogicalName - Some (localRep.MakeValueLookup thisValOpt thisTyInst safeStaticInitInfo v [] m) - - // Rewrite assignments to mutable values stored as fields - | Expr.Op (TOp.LValueOp (LSet, ValDeref v), [], [arg], m) - when localRep.IsValWithRepresentation v -> - let arg = rw arg - Some (localRep.MakeValueAssign thisValOpt thisTyInst safeStaticInitInfo v arg m) - - // Rewrite taking the address of mutable values stored as fields - | Expr.Op (TOp.LValueOp (LAddrOf readonly, ValDeref v), [], [], m) - when localRep.IsValWithRepresentation v -> - Some (localRep.MakeValueGetAddress readonly thisValOpt thisTyInst safeStaticInitInfo v m) - - | _ -> None - - RewriteExpr { PreIntercept = Some FixupExprNode - PostTransform = (fun _ -> None) - PreInterceptBinding = None - RewriteQuotations = true - StackGuard = StackGuard(TcClassRewriteStackGuardDepth) } expr - - type IncrClassConstructionBindingsPhase2C = - | Phase2CBindings of IncrClassBindingGroup list - | Phase2CCtorJustAfterSuperInit - | Phase2CCtorJustAfterLastLet - - /// - /// Given a set of 'let' bindings (static or not, recursive or not) that make up a class, - /// generate their initialization expression(s). - /// - /// - /// - /// The lhs information about the implicit constructor - /// The call to the super class constructor - /// Should we place a sequence point at the 'inheritedTys call? - /// The declarations - /// - /// Record any unconstrained type parameters generalized for the outer members as "free choices" in the let bindings - /// - let MakeCtorForIncrClassConstructionPhase2C( - cenv: cenv, - env: TcEnv, - ctorInfo: IncrClassCtorLhs, - inheritsExpr, - inheritsIsVisible, - decs: IncrClassConstructionBindingsPhase2C list, - memberBinds: Binding list, - generalizedTyparsForRecursiveBlock, - safeStaticInitInfo: SafeInitData - ) = - - - let denv = env.DisplayEnv - let g = cenv.g - let thisVal = ctorInfo.InstanceCtorThisVal - - let m = thisVal.Range - let ctorDeclaredTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv m - - ctorDeclaredTypars |> List.iter (SetTyparRigid env.DisplayEnv m) - - // Reconstitute the type with the correct quantified type variables. - ctorInfo.InstanceCtorVal.SetType (mkForallTyIfNeeded ctorDeclaredTypars ctorInfo.InstanceCtorVal.TauType) - - let freeChoiceTypars = ListSet.subtract typarEq generalizedTyparsForRecursiveBlock ctorDeclaredTypars - - let thisTyInst = List.map mkTyparTy ctorDeclaredTypars - - let accFreeInExpr acc expr = - unionFreeVars acc (freeInExpr CollectLocalsNoCaching expr) - - let accFreeInBinding acc (bind: Binding) = - accFreeInExpr acc bind.Expr - - let accFreeInBindings acc (binds: Binding list) = - (acc, binds) ||> List.fold accFreeInBinding - - // Find all the variables used in any method. These become fields. - // staticForcedFieldVars: FreeLocals: the vars forced to be fields due to static member bindings, instance initialization expressions or instance member bindings - // instanceForcedFieldVars: FreeLocals: the vars forced to be fields due to instance member bindings - - let staticForcedFieldVars, instanceForcedFieldVars = - let staticForcedFieldVars, instanceForcedFieldVars = - ((emptyFreeVars, emptyFreeVars), decs) ||> List.fold (fun (staticForcedFieldVars, instanceForcedFieldVars) dec -> - match dec with - | Phase2CCtorJustAfterLastLet - | Phase2CCtorJustAfterSuperInit -> - (staticForcedFieldVars, instanceForcedFieldVars) - | Phase2CBindings decs -> - ((staticForcedFieldVars, instanceForcedFieldVars), decs) ||> List.fold (fun (staticForcedFieldVars, instanceForcedFieldVars) dec -> - match dec with - | IncrClassBindingGroup(binds, isStatic, _) -> - let methodBinds = binds |> List.filter (IncrClassReprInfo.IsMethodRepr cenv) - let staticForcedFieldVars = - if isStatic then - // Any references to static variables in any static method force the variable to be represented as a field - (staticForcedFieldVars, methodBinds) ||> accFreeInBindings - else - // Any references to static variables in any instance bindings force the variable to be represented as a field - (staticForcedFieldVars, binds) ||> accFreeInBindings - - let instanceForcedFieldVars = - // Any references to instance variables in any methods force the variable to be represented as a field - (instanceForcedFieldVars, methodBinds) ||> accFreeInBindings - - (staticForcedFieldVars, instanceForcedFieldVars) - | IncrClassDo (e, isStatic, _) -> - let staticForcedFieldVars = - if isStatic then - staticForcedFieldVars - else - unionFreeVars staticForcedFieldVars (freeInExpr CollectLocalsNoCaching e) - (staticForcedFieldVars, instanceForcedFieldVars))) - let staticForcedFieldVars = (staticForcedFieldVars, memberBinds) ||> accFreeInBindings - let instanceForcedFieldVars = (instanceForcedFieldVars, memberBinds) ||> accFreeInBindings - - // Any references to static variables in the 'inherits' expression force those static variables to be represented as fields - let staticForcedFieldVars = (staticForcedFieldVars, inheritsExpr) ||> accFreeInExpr - - (staticForcedFieldVars.FreeLocals, instanceForcedFieldVars.FreeLocals) - - - // Compute the implicit construction side effects of single - // 'let' or 'let rec' binding in the implicit class construction sequence - let TransBind (reps: IncrClassReprInfo) (TBind(v, rhsExpr, spBind)) = - if v.MustInline then - error(Error(FSComp.SR.tcLocalClassBindingsCannotBeInline(), v.Range)) - let rhsExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst rhsExpr - - // The initialization of the 'ref cell' variable for 'this' is the only binding which comes prior to the super init - let isPriorToSuperInit = - match ctorInfo.InstanceCtorSafeThisValOpt with - | None -> false - | Some v2 -> valEq v v2 - - match reps.LookupRepr v with - | InMethod(isStatic, methodVal, _) -> - let _, chooseTps, tauExpr, tauTy, m = - match rhsExpr with - | Expr.TyChoose (chooseTps, b, _) -> [], chooseTps, b, (tyOfExpr g b), m - | Expr.TyLambda (_, tps, Expr.TyChoose (chooseTps, b, _), m, returnTy) -> tps, chooseTps, b, returnTy, m - | Expr.TyLambda (_, tps, b, m, returnTy) -> tps, [], b, returnTy, m - | e -> [], [], e, (tyOfExpr g e), e.Range - - let chooseTps = chooseTps @ (ListSet.subtract typarEq freeChoiceTypars methodVal.Typars) - - // Add the 'this' variable as an argument - let tauExpr, tauTy = - if isStatic then - tauExpr, tauTy - else - let e = mkLambda m thisVal (tauExpr, tauTy) - e, tyOfExpr g e - - // Replace the type parameters that used to be on the rhs with - // the full set of type parameters including the type parameters of the enclosing class - let rhsExpr = mkTypeLambda m methodVal.Typars (mkTypeChoose m chooseTps tauExpr, tauTy) - (isPriorToSuperInit, id), [TBind (methodVal, rhsExpr, spBind)] - - // If it's represented as a non-escaping local variable then just bind it to its value - // If it's represented as a non-escaping local arg then no binding necessary (ctor args are already bound) - - | InVar isArg -> - (isPriorToSuperInit, (fun e -> if isArg then e else mkLetBind m (TBind(v, rhsExpr, spBind)) e)), [] - - | InField (isStatic, idx, _) -> - // Use spBind if it available as the span for the assignment into the field - let m = - match spBind, rhsExpr with - // Don't generate big sequence points for functions in classes - | _, (Expr.Lambda _ | Expr.TyLambda _) -> v.Range - | DebugPointAtBinding.Yes m, _ -> m - | _ -> v.Range - - let assignExpr = reps.MakeValueAssign (Some thisVal) thisTyInst NoSafeInitInfo v rhsExpr m - - let adjustSafeInitFieldExprOpt = - if isStatic then - match safeStaticInitInfo with - | SafeInitField (rfref, _) -> - let setExpr = mkStaticRecdFieldSet (rfref, thisTyInst, mkInt g m idx, m) - let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) NoSafeInitInfo thisTyInst setExpr - Some setExpr - | NoSafeInitInfo -> - None - else - None - - (isPriorToSuperInit, (fun e -> - let e = - match adjustSafeInitFieldExprOpt with - | None -> e - | Some adjustExpr -> mkCompGenSequential m adjustExpr e - - let assignExpr = - match spBind with - | DebugPointAtBinding.Yes _ -> mkDebugPoint m assignExpr - | _ -> assignExpr - - mkSequential m assignExpr e)), [] - - /// Work out the implicit construction side effects of a 'let', 'let rec' or 'do' - /// binding in the implicit class construction sequence - let TransTrueDec isCtorArg (reps: IncrClassReprInfo) dec = - match dec with - | IncrClassBindingGroup(binds, isStatic, isRec) -> - let actions, reps, methodBinds = - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ChooseAndAddRepresentation(cenv, env, isStatic, isCtorArg, ctorInfo, staticForcedFieldVars, instanceForcedFieldVars, bind)) // extend - if isRec then - // Note: the recursive calls are made via members on the object - // or via access to fields. This means the recursive loop is "broken", - // and we can collapse to sequential bindings - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // in scope before - let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip // since can occur in RHS of own defns - actions, reps, methodBinds - else - let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // in scope after - actions, reps, methodBinds - let methodBinds = List.concat methodBinds - if isStatic then - (actions, [], methodBinds), reps - else - ([], actions, methodBinds), reps - - | IncrClassDo (doExpr, isStatic, mFull) -> - let doExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst doExpr - // Extend the range of any immediate debug point to include the 'do' - let doExpr = - match doExpr with - | Expr.DebugPoint(_, innerExpr) -> Expr.DebugPoint(DebugPointAtLeafExpr.Yes mFull, innerExpr) - | e -> e - let binder = (fun e -> mkSequential mFull doExpr e) - let isPriorToSuperInit = false - if isStatic then - ([(isPriorToSuperInit, binder)], [], []), reps - else - ([], [(isPriorToSuperInit, binder)], []), reps - - - /// Work out the implicit construction side effects of each declaration - /// in the implicit class construction sequence - let TransDec (reps: IncrClassReprInfo) dec = - match dec with - // The call to the base class constructor is done so we can set the ref cell - | Phase2CCtorJustAfterSuperInit -> - let binders = - [ match ctorInfo.InstanceCtorSafeThisValOpt with - | None -> () - | Some v -> - let setExpr = mkRefCellSet g m ctorInfo.InstanceCtorThisVal.Type (exprForVal m v) (exprForVal m ctorInfo.InstanceCtorThisVal) - let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst setExpr - let binder = (fun e -> mkSequential setExpr.Range setExpr e) - let isPriorToSuperInit = false - yield (isPriorToSuperInit, binder) ] - - ([], binders, []), reps - - // The last 'let' binding is done so we can set the initialization condition for the collection of object fields - // which now allows members to be called. - | Phase2CCtorJustAfterLastLet -> - let binders = - [ match ctorInfo.InstanceCtorSafeInitInfo with - | SafeInitField (rfref, _) -> - let setExpr = mkRecdFieldSetViaExprAddr (exprForVal m thisVal, rfref, thisTyInst, mkOne g m, m) - let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst setExpr - let binder = (fun e -> mkSequential setExpr.Range setExpr e) - let isPriorToSuperInit = false - yield (isPriorToSuperInit, binder) - | NoSafeInitInfo -> - () ] - - ([], binders, []), reps - - | Phase2CBindings decs -> - let initActions, reps = List.mapFold (TransTrueDec false) reps decs - let cctorInitActions, ctorInitActions, methodBinds = List.unzip3 initActions - (List.concat cctorInitActions, List.concat ctorInitActions, List.concat methodBinds), reps - - - - let takenFieldNames = - [ for b in memberBinds do - yield b.Var.CompiledName g.CompilerGlobalState - yield b.Var.DisplayName - yield b.Var.DisplayNameCoreMangled - yield b.Var.LogicalName ] - let reps = IncrClassReprInfo.Empty(g, takenFieldNames) - - // Bind the IsArg(true) representations of the object constructor arguments and assign them to fields - // if they escape to the members. We do this by running the instance bindings 'let x = x' through TransTrueDec - // for each constructor argument 'x', but with the special flag 'isCtorArg', which helps TransBind know that - // the value is already available as an argument, and that nothing special needs to be done unless the - // value is being stored into a field. - let (cctorInitActions1, ctorInitActions1, methodBinds1), reps = - let binds = ctorInfo.InstanceCtorArgs |> List.map (fun v -> mkInvisibleBind v (exprForVal v.Range v)) - TransTrueDec true reps (IncrClassBindingGroup(binds, false, false)) - - // We expect that only ctorInitActions1 will be non-empty here, and even then only if some elements are stored in the field - assert (isNil cctorInitActions1) - assert (isNil methodBinds1) - - // Now deal with all the 'let' and 'member' declarations - let initActions, reps = List.mapFold TransDec reps decs - let cctorInitActions2, ctorInitActions2, methodBinds2 = List.unzip3 initActions - let cctorInitActions = cctorInitActions1 @ List.concat cctorInitActions2 - let ctorInitActions = ctorInitActions1 @ List.concat ctorInitActions2 - let methodBinds = methodBinds1 @ List.concat methodBinds2 - - let ctorBody = - // Build the elements of the implicit constructor body, starting from the bottom - // - // - // - // return () - let ctorInitActionsPre, ctorInitActionsPost = ctorInitActions |> List.partition fst - - // This is the return result - let ctorBody = mkUnit g m - - // Add . - // That is, add any that come prior to the super init constructor call, - // This is only ever at most the init of the InstanceCtorSafeThisValOpt and InstanceCtorSafeInitInfo var/field - let ctorBody = List.foldBack (fun (_, binder) acc -> binder acc) ctorInitActionsPost ctorBody - - // Add the - let ctorBody = - // The inheritsExpr may refer to the this variable or to incoming arguments, e.g. in closure fields. - // References to the this variable go via the ref cell that gets created to help ensure coherent initialization. - // This ref cell itself may be stored in a field of the object and accessed via arg0. - // Likewise the incoming arguments will eventually be stored in fields and accessed via arg0. - // - // As a result, the most natural way to implement this would be to simply capture arg0 if needed - // and access all variables via that. This would be done by rewriting the inheritsExpr as follows: - // let inheritsExpr = reps.FixupIncrClassExprPhase2C (Some thisVal) thisTyInst inheritsExpr - // However, the rules of IL mean we are not actually allowed to capture arg0 - // and store it as a closure field before the base class constructor is called. - // - // As a result we do not rewrite the inheritsExpr and instead - // (a) wrap a let binding for the ref cell around the inheritsExpr if needed - // (b) rely on the fact that the input arguments are in scope and can be accessed from as argument variables - // (c) rely on the fact that there are no 'let' bindings prior to the inherits expr. - let inheritsExpr = - match ctorInfo.InstanceCtorSafeThisValOpt with - | Some v when not (reps.IsValRepresentedAsLocalVar v) -> - // Rewrite the expression to convert it to a load of a field if needed. - // We are allowed to load fields from our own object even though we haven't called - // the super class constructor yet. - let ldexpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst (exprForVal m v) - mkInvisibleLet m v ldexpr inheritsExpr - | _ -> - inheritsExpr - - // Add the debug point - let inheritsExpr = - if inheritsIsVisible then - Expr.DebugPoint(DebugPointAtLeafExpr.Yes inheritsExpr.Range, inheritsExpr) - else - inheritsExpr - - mkSequential m inheritsExpr ctorBody - - // Add the normal - let ctorBody = List.foldBack (fun (_, binder) acc -> binder acc) ctorInitActionsPre ctorBody - - // Add the final wrapping to make this into a method - let ctorBody = mkMemberLambdas g m [] (Some thisVal) ctorInfo.InstanceCtorBaseValOpt [ctorInfo.InstanceCtorArgs] (ctorBody, g.unit_ty) - - ctorBody - - let cctorBodyOpt = - // Omit the .cctor if it's empty - match cctorInitActions with - | [] -> None - | _ -> - let cctorInitAction = List.foldBack (fun (_, binder) acc -> binder acc) cctorInitActions (mkUnit g m) - let m = thisVal.Range - let cctorArgs, cctorVal, _ = ctorInfo.StaticCtorValInfo.Force() - // Reconstitute the type of the implicit class constructor with the correct quantified type variables. - cctorVal.SetType (mkForallTyIfNeeded ctorDeclaredTypars cctorVal.TauType) - let cctorBody = mkMemberLambdas g m [] None None [cctorArgs] (cctorInitAction, g.unit_ty) - Some cctorBody - - ctorBody, cctorBodyOpt, methodBinds, reps - // Checking of mutually recursive types, members and 'let' bindings in classes // // Technique: multiple passes. @@ -1559,8 +703,6 @@ module IncrClassChecking = // generalize definitions, fix up recursive instances, build ctor binding module MutRecBindingChecking = - open IncrClassChecking - /// Represents one element in a type definition, after the first phase type TyconBindingPhase2A = /// An entry corresponding to the definition of the implicit constructor for a class @@ -1925,25 +1067,25 @@ module MutRecBindingChecking = Phase2BInherit (inheritsExpr, baseValOpt), innerState // Phase2B: let and let rec value and function definitions - | Phase2AIncrClassBindings (tcref, binds, isStatic, isRec, bindsm) -> + | Phase2AIncrClassBindings (tcref, binds, isStatic, isRec, mBinds) -> let envForBinding = if isStatic then envStatic else envInstance let binds, bindRs, env, tpenv = if isRec then // Type check local recursive binding let binds = binds |> List.map (fun bind -> RecDefnBindingInfo(ExprContainerInfo, NoNewSlots, ClassLetBinding isStatic, bind)) - let binds, env, tpenv = TcLetrecBindings ErrorOnOverrides cenv envForBinding tpenv (binds, scopem(*bindsm*), scopem) + let binds, env, tpenv = TcLetrecBindings ErrorOnOverrides cenv envForBinding tpenv (binds, scopem, scopem) let bindRs = [IncrClassBindingGroup(binds, isStatic, true)] binds, bindRs, env, tpenv else // Type check local binding - let binds, env, tpenv = TcLetBindings cenv envForBinding ExprContainerInfo (ClassLetBinding isStatic) tpenv (binds, bindsm, scopem) + let binds, env, tpenv = TcLetBindings cenv envForBinding ExprContainerInfo (ClassLetBinding isStatic) tpenv (binds, mBinds, scopem) let binds, bindRs = binds |> List.map (function | TMDefLet(bind, _) -> [bind], IncrClassBindingGroup([bind], isStatic, false) - | TMDefDo(e, _) -> [], IncrClassDo(e, isStatic, bindsm) + | TMDefDo(e, _) -> [], IncrClassDo(e, isStatic, mBinds) | _ -> error(InternalError("unexpected definition kind", tcref.Range))) |> List.unzip List.concat binds, bindRs, env, tpenv @@ -2338,7 +1480,7 @@ module MutRecBindingChecking = envForDecls) /// Phase 2: Check the members and 'let' definitions in a mutually recursive group of definitions. - let TcMutRecDefns_Phase2_Bindings (cenv: cenv) envInitial tpenv bindsm scopem mutRecNSInfo (envMutRecPrelimWithReprs: TcEnv) (mutRecDefns: MutRecDefnsPhase2Info) = + let TcMutRecDefns_Phase2_Bindings (cenv: cenv) envInitial tpenv mBinds scopem mutRecNSInfo (envMutRecPrelimWithReprs: TcEnv) (mutRecDefns: MutRecDefnsPhase2Info) = let g = cenv.g let denv = envMutRecPrelimWithReprs.DisplayEnv @@ -2466,12 +1608,12 @@ module MutRecBindingChecking = (fun morpher shape -> shape |> MutRecShapes.iterTyconsAndLets (p23 >> morpher) morpher) MutRecShape.Lets (fun morpher shape -> shape |> MutRecShapes.mapTyconsAndLets (fun (tyconOpt, fixupValueExprBinds, methodBinds) -> tyconOpt, (morpher fixupValueExprBinds @ methodBinds)) morpher) - bindsm + mBinds defnsEs, envMutRec /// Check and generalize the interface implementations, members, 'let' definitions in a mutually recursive group of definitions. -let TcMutRecDefns_Phase2 (cenv: cenv) envInitial bindsm scopem mutRecNSInfo (envMutRec: TcEnv) (mutRecDefns: MutRecDefnsPhase2Data) = +let TcMutRecDefns_Phase2 (cenv: cenv) envInitial mBinds scopem mutRecNSInfo (envMutRec: TcEnv) (mutRecDefns: MutRecDefnsPhase2Data) = let g = cenv.g let interfacesFromTypeDefn envForTycon tyconMembersData = let (MutRecDefnsPhase2DataForTycon(_, _, declKind, tcref, _, _, declaredTyconTypars, members, _, _, _)) = tyconMembersData @@ -2530,6 +1672,7 @@ let TcMutRecDefns_Phase2 (cenv: cenv) envInitial bindsm scopem mutRecNSInfo (env | SynMemberDefn.LetBindings _ | SynMemberDefn.AutoProperty _ | SynMemberDefn.Member _ + | SynMemberDefn.GetSetMember _ | SynMemberDefn.Open _ -> Some(TyconBindingDefn(containerInfo, newslotsOK, declKind, memb, memb.Range)) @@ -2553,7 +1696,8 @@ let TcMutRecDefns_Phase2 (cenv: cenv) envInitial bindsm scopem mutRecNSInfo (env error(InternalError("Intrinsic augmentations of types are only permitted in the same file as the definition of the type", m)) members |> List.iter (fun mem -> match mem with - | SynMemberDefn.Member _ -> () + | SynMemberDefn.Member _ + | SynMemberDefn.GetSetMember _ | SynMemberDefn.Interface _ -> () | SynMemberDefn.Open _ | SynMemberDefn.AutoProperty _ @@ -2583,7 +1727,7 @@ let TcMutRecDefns_Phase2 (cenv: cenv) envInitial bindsm scopem mutRecNSInfo (env (intfTypes, slotImplSets) ||> List.map2 (interfaceMembersFromTypeDefn tyconData) |> List.concat MutRecDefnsPhase2InfoForTycon(tyconOpt, tcref, declaredTyconTypars, declKind, obinds @ ibinds, fixupFinalAttrs)) - MutRecBindingChecking.TcMutRecDefns_Phase2_Bindings cenv envInitial tpenv bindsm scopem mutRecNSInfo envMutRec binds + MutRecBindingChecking.TcMutRecDefns_Phase2_Bindings cenv envInitial tpenv mBinds scopem mutRecNSInfo envMutRec binds with exn -> errorRecovery exn scopem; [], envMutRec @@ -3254,7 +2398,7 @@ module EstablishTypeDefinitionCores = () ] let ComputeModuleOrNamespaceKind g isModule typeNames attribs nm = - if not isModule then Namespace + if not isModule then (Namespace true) elif ModuleNameIsMangled g attribs || Set.contains nm typeNames then FSharpModuleWithSuffix else ModuleOrType @@ -3985,7 +3129,13 @@ module EstablishTypeDefinitionCores = match fields' with | rf :: _ -> errorR (Error(FSComp.SR.tcInterfaceTypesAndDelegatesCannotContainFields(), rf.Range)) | _ -> () - + + let primaryConstructorInDelegateCheck(implicitCtorSynPats : SynSimplePats option) = + match implicitCtorSynPats with + | None -> () + | Some spats -> + let ctorArgNames, _ = TcSimplePatsOfUnknownType cenv true CheckCxs envinner tpenv spats + if not ctorArgNames.IsEmpty then errorR (Error(FSComp.SR.parsOnlyClassCanTakeValueArguments(), m)) let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars m) envinner let envinner = MakeInnerEnvForTyconRef envinner thisTyconRef false @@ -4045,7 +3195,9 @@ module EstablishTypeDefinitionCores = structLayoutAttributeCheck false noAllowNullLiteralAttributeCheck() - TcRecdUnionAndEnumDeclarations.CheckUnionCaseName cenv unionCaseName + + let hasRQAAttribute = HasFSharpAttribute cenv.g cenv.g.attrib_RequireQualifiedAccessAttribute tycon.Attribs + TcRecdUnionAndEnumDeclarations.CheckUnionCaseName cenv unionCaseName hasRQAAttribute let unionCase = Construct.NewUnionCase unionCaseName [] thisTy [] XmlDoc.Empty tycon.Accessibility writeFakeUnionCtorsToSink [ unionCase ] Construct.MakeUnionRepr [ unionCase ], None, NoSafeInitInfo @@ -4076,8 +3228,9 @@ module EstablishTypeDefinitionCores = noAbstractClassAttributeCheck() noAllowNullLiteralAttributeCheck() structLayoutAttributeCheck false - let unionCases = TcRecdUnionAndEnumDeclarations.TcUnionCaseDecls cenv envinner innerParent thisTy thisTyInst tpenv unionCases - + + let hasRQAAttribute = HasFSharpAttribute cenv.g cenv.g.attrib_RequireQualifiedAccessAttribute tycon.Attribs + let unionCases = TcRecdUnionAndEnumDeclarations.TcUnionCaseDecls cenv envinner innerParent thisTy thisTyInst hasRQAAttribute tpenv unionCases if tycon.IsStructRecordOrUnionTycon && unionCases.Length > 1 then let fieldNames = [ for uc in unionCases do for ft in uc.FieldTable.TrueInstanceFieldsAsList do yield ft.LogicalName ] if fieldNames |> List.distinct |> List.length <> fieldNames.Length then @@ -4182,6 +3335,7 @@ module EstablishTypeDefinitionCores = noAllowNullLiteralAttributeCheck() noAbstractClassAttributeCheck() noFieldsCheck userFields + primaryConstructorInDelegateCheck(implicitCtorSynPats) let tyR, _ = TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType envinner tpenv ty let _, _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm g (arity |> TranslateSynValInfo m (TcAttributes cenv envinner) |> TranslatePartialValReprInfo []) 0 tyR m if curriedArgInfos.Length < 1 then error(Error(FSComp.SR.tcInvalidDelegateSpecification(), m)) @@ -4282,37 +3436,37 @@ module EstablishTypeDefinitionCores = match stripTyparEqns ty with | TType_anon (_,l) | TType_tuple (_, l) -> accInAbbrevTypes l acc - | TType_ucase (UnionCaseRef(tc, _), tinst) - | TType_app (tc, tinst, _) -> - let tycon2 = tc.Deref + | TType_ucase (UnionCaseRef(tcref2, _), tinst) + | TType_app (tcref2, tinst, _) -> + let tycon2 = tcref2.Deref let acc = accInAbbrevTypes tinst acc // Record immediate recursive references if ListSet.contains (===) tycon2 tycons then (tycon, tycon2) :: acc // Expand the representation of abbreviations - elif tc.IsTypeAbbrev then - accInAbbrevType (reduceTyconRefAbbrev tc tinst) acc + elif tcref2.IsTypeAbbrev then + accInAbbrevType (reduceTyconRefAbbrev tcref2 tinst) acc // Otherwise H - explore the instantiation. else acc - | TType_fun (d, r, _) -> - accInAbbrevType d (accInAbbrevType r acc) + | TType_fun (domainTy, rangeTy, _) -> + accInAbbrevType domainTy (accInAbbrevType rangeTy acc) | TType_var _ -> acc - | TType_forall (_, r) -> accInAbbrevType r acc + | TType_forall (_, bodyTy) -> accInAbbrevType bodyTy acc - | TType_measure ms -> accInMeasure ms acc - - and accInMeasure ms acc = - match stripUnitEqns ms with - | Measure.Con tc when ListSet.contains (===) tc.Deref tycons -> - (tycon, tc.Deref) :: acc - | Measure.Con tc when tc.IsTypeAbbrev -> - accInMeasure (reduceTyconRefAbbrevMeasureable tc) acc + | TType_measure measureTy -> accInMeasure measureTy acc + + and accInMeasure measureTy acc = + match stripUnitEqns measureTy with + | Measure.Const tcref when ListSet.contains (===) tcref.Deref tycons -> + (tycon, tcref.Deref) :: acc + | Measure.Const tcref when tcref.IsTypeAbbrev -> + accInMeasure (reduceTyconRefAbbrevMeasureable tcref) acc | Measure.Prod (ms1, ms2) -> accInMeasure ms1 (accInMeasure ms2 acc) - | Measure.Inv ms -> accInMeasure ms acc + | Measure.Inv invTy -> accInMeasure invTy acc | _ -> acc and accInAbbrevTypes tys acc = @@ -4323,7 +3477,7 @@ module EstablishTypeDefinitionCores = | Some ty -> accInAbbrevType ty [] let edges = List.collect edgesFrom tycons - let graph = Graph ((fun tc -> tc.Stamp), tycons, edges) + let graph = Graph ((fun tycon -> tycon.Stamp), tycons, edges) graph.IterateCycles (fun path -> let tycon = path.Head // The thing is cyclic. Set the abbreviation and representation to be "None" to stop later VS crashes @@ -4805,10 +3959,12 @@ module TcDeclarations = /// where simpleRepr can contain inherit type, declared fields and virtual slots. /// body = members /// where members contain methods/overrides, also implicit ctor, inheritCall and local definitions. - let rec private SplitTyconDefn (SynTypeDefn(typeInfo=synTyconInfo;typeRepr=trepr; members=extraMembers)) = + let rec private SplitTyconDefn (SynTypeDefn(typeInfo=synTyconInfo;typeRepr=trepr; members=extraMembers)) = + let extraMembers = desugarGetSetMembers extraMembers let implements1 = List.choose (function SynMemberDefn.Interface (interfaceType=ty) -> Some(ty, ty.Range) | _ -> None) extraMembers match trepr with | SynTypeDefnRepr.ObjectModel(kind, cspec, m) -> + let cspec = desugarGetSetMembers cspec CheckMembersForm cspec let fields = cspec |> List.choose (function SynMemberDefn.ValField (f, _) -> Some f | _ -> None) let implements2 = cspec |> List.choose (function SynMemberDefn.Interface (interfaceType=ty) -> Some(ty, ty.Range) | _ -> None) @@ -4825,7 +3981,8 @@ module TcDeclarations = cspec |> List.filter (fun memb -> match memb with | SynMemberDefn.Interface _ - | SynMemberDefn.Member _ + | SynMemberDefn.Member _ + | SynMemberDefn.GetSetMember _ | SynMemberDefn.LetBindings _ | SynMemberDefn.ImplicitCtor _ | SynMemberDefn.AutoProperty _ @@ -4845,7 +4002,7 @@ module TcDeclarations = let attribs = attribs |> List.filter (fun a -> match a.Target with Some t when t.idText = "field" -> true | _ -> false) let mLetPortion = synExpr.Range let fldId = ident (CompilerGeneratedName id.idText, mLetPortion) - let headPat = SynPat.LongIdent (SynLongIdent([fldId], [], [None]), None, None, Some noInferredTypars, SynArgPats.Pats [], None, mLetPortion) + let headPat = SynPat.LongIdent (SynLongIdent([fldId], [], [None]), None, Some noInferredTypars, SynArgPats.Pats [], None, mLetPortion) let retInfo = match tyOpt with None -> None | Some ty -> Some (SynReturnInfo((ty, SynInfo.unnamedRetVal), ty.Range)) let isMutable = match propKind with @@ -4873,7 +4030,7 @@ module TcDeclarations = let attribs = attribs |> List.filter (fun a -> match a.Target with Some t when t.idText = "field" -> false | _ -> true) let fldId = ident (CompilerGeneratedName id.idText, mMemberPortion) let headPatIds = if isStatic then [id] else [ident ("__", mMemberPortion);id] - let headPat = SynPat.LongIdent (SynLongIdent(headPatIds, [], List.replicate headPatIds.Length None), None, None, Some noInferredTypars, SynArgPats.Pats [], None, mMemberPortion) + let headPat = SynPat.LongIdent (SynLongIdent(headPatIds, [], List.replicate headPatIds.Length None), None, Some noInferredTypars, SynArgPats.Pats [], None, mMemberPortion) match propKind, mGetSetOpt with | SynMemberKind.PropertySet, Some m -> errorR(Error(FSComp.SR.parsMutableOnAutoPropertyShouldBeGetSetNotJustSet(), m)) @@ -4898,7 +4055,7 @@ module TcDeclarations = | SynMemberKind.PropertyGetSet -> let setter = let vId = ident("v", mMemberPortion) - let headPat = SynPat.LongIdent (SynLongIdent(headPatIds, [], List.replicate headPatIds.Length None), None, None, Some noInferredTypars, SynArgPats.Pats [mkSynPatVar None vId], None, mMemberPortion) + let headPat = SynPat.LongIdent (SynLongIdent(headPatIds, [], List.replicate headPatIds.Length None), None, Some noInferredTypars, SynArgPats.Pats [mkSynPatVar None vId], None, mMemberPortion) let rhsExpr = mkSynAssign (SynExpr.Ident fldId) (SynExpr.Ident vId) //let retInfo = match tyOpt with None -> None | Some ty -> Some (SynReturnInfo((ty, SynInfo.unnamedRetVal), ty.Range)) let binding = mkSynBinding (xmlDoc, headPat) (access, false, false, mMemberPortion, DebugPointAtBinding.NoneAtInvisible, None, rhsExpr, rhsExpr.Range, [], [], Some (memberFlags SynMemberKind.PropertySet), SynBindingTrivia.Zero) @@ -5083,7 +4240,7 @@ module TcDeclarations = memberFlags.MemberKind=SynMemberKind.Constructor && // REVIEW: This is a syntactic approximation (match synValSig.SynType, synValSig.SynInfo.CurriedArgInfos with - | StripParenTypes (SynType.Fun (StripParenTypes (SynType.LongIdent (SynLongIdent([id], _, _))), _, _)), [[_]] when id.idText = "unit" -> true + | StripParenTypes (SynType.Fun (argType = StripParenTypes (SynType.LongIdent (SynLongIdent([id], _, _))))), [[_]] when id.idText = "unit" -> true | _ -> false) | _ -> false) @@ -5280,7 +4437,7 @@ let rec TcSignatureElementNonMutRec (cenv: cenv) parent typeNames endm (env: TcE else longId, defs - let envNS = LocateEnv cenv.thisCcu env enclosingNamespacePath + let envNS = LocateEnv kind.IsModule cenv.thisCcu env enclosingNamespacePath let envNS = ImplicitlyOpenOwnNamespace cenv.tcSink g cenv.amap m enclosingNamespacePath envNS // For 'namespace rec' and 'module rec' we add the thing being defined @@ -5602,7 +4759,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem else longId, defs - let envNS = LocateEnv cenv.thisCcu env enclosingNamespacePath + let envNS = LocateEnv kind.IsModule cenv.thisCcu env enclosingNamespacePath let envNS = ImplicitlyOpenOwnNamespace cenv.tcSink g cenv.amap m enclosingNamespacePath envNS let modTyNS = envNS.eModuleOrNamespaceTypeAccumulator.Value @@ -5640,7 +4797,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem CombineCcuContentFragments m [env.eModuleOrNamespaceTypeAccumulator.Value; modTyRoot] env, openDecls - let moduleContentsRoot = BuildRootModuleContents enclosingNamespacePath envNS.eCompPath moduleContents + let moduleContentsRoot = BuildRootModuleContents kind.IsModule enclosingNamespacePath envNS.eCompPath moduleContents let defns = match openDecls with @@ -5709,7 +4866,8 @@ and TcModuleOrNamespaceElementsMutRec (cenv: cenv) parent typeNames m envInitial let decls = [ MutRecShape.Open (MutRecDataForOpen(target, m, moduleRange, ref [])) ] decls, (openOk, moduleAbbrevOk, attrs) - | SynModuleDecl.Exception (SynExceptionDefn(repr, _, members, _), _m) -> + | SynModuleDecl.Exception (SynExceptionDefn(repr, _, members, _), _m) -> + let members = desugarGetSetMembers members let (SynExceptionDefnRepr(synAttrs, SynUnionCase(ident=SynIdent(id,_)), _repr, xmlDoc, vis, m)) = repr let compInfo = SynComponentInfo(synAttrs, None, [], [id], xmlDoc, false, vis, id.idRange) let decls = [ MutRecShape.Tycon(SynTypeDefn(compInfo, SynTypeDefnRepr.Exception repr, members, None, m, SynTypeDefnTrivia.Zero)) ] @@ -5856,7 +5014,7 @@ let emptyTcEnv g = eAccessRights = ComputeAccessRights cpath [] None // compute this field eInternalsVisibleCompPaths = [] eContextInfo = ContextInfo.NoContext - eModuleOrNamespaceTypeAccumulator = ref (Construct.NewEmptyModuleOrNamespaceType Namespace) + eModuleOrNamespaceTypeAccumulator = ref (Construct.NewEmptyModuleOrNamespaceType (Namespace true)) eFamilyType = None eCtorInfo = None eCallerMemberName = None @@ -5985,7 +5143,7 @@ let CheckModuleSignature g (cenv: cenv) m denvAtEnd rootSigOpt implFileTypePrior /// Make the initial type checking environment for a single file with an empty accumulator for the overall contents for the file let MakeInitialEnv env = // Note: here we allocate a new module type accumulator - let moduleTyAcc = ref (Construct.NewEmptyModuleOrNamespaceType Namespace) + let moduleTyAcc = ref (Construct.NewEmptyModuleOrNamespaceType (Namespace false)) { env with eModuleOrNamespaceTypeAccumulator = moduleTyAcc }, moduleTyAcc /// Check an entire implementation file diff --git a/src/Compiler/Checking/CheckDeclarations.fsi b/src/Compiler/Checking/CheckDeclarations.fsi index 47bfbc6577f..631e9fb5812 100644 --- a/src/Compiler/Checking/CheckDeclarations.fsi +++ b/src/Compiler/Checking/CheckDeclarations.fsi @@ -75,6 +75,6 @@ val CheckOneSigFile: ParsedSigFileInput -> Cancellable -exception ParameterlessStructCtor of range: range - exception NotUpperCaseConstructor of range: range + +exception NotUpperCaseConstructorWithoutRQA of range: range diff --git a/src/Compiler/Checking/CheckExpressions.fs b/src/Compiler/Checking/CheckExpressions.fs index 0d03bfead85..7e3baef258b 100644 --- a/src/Compiler/Checking/CheckExpressions.fs +++ b/src/Compiler/Checking/CheckExpressions.fs @@ -578,6 +578,7 @@ type ValScheme = id: Ident * typeScheme: GeneralizedType * valReprInfo: ValReprInfo option * + valReprInfoForDisplay: ValReprInfo option * memberInfo: PrelimMemberInfo option * isMutable: bool * inlineInfo: ValInline * @@ -860,7 +861,7 @@ let SetCurrAccumulatedModuleOrNamespaceType env x = env.eModuleOrNamespaceTypeAccumulator.Value <- x /// Set up the initial environment accounting for the enclosing "namespace X.Y.Z" definition -let LocateEnv ccu env enclosingNamespacePath = +let LocateEnv isModule ccu env enclosingNamespacePath = let cpath = compPathOfCcu ccu let env = {env with @@ -869,7 +870,8 @@ let LocateEnv ccu env enclosingNamespacePath = eAccessPath = cpath // update this computed field eAccessRights = ComputeAccessRights cpath env.eInternalsVisibleCompPaths env.eFamilyType } - let env = List.fold (fun env id -> MakeInnerEnv false env id Namespace |> fst) env enclosingNamespacePath + let isExplicitNamespace = not isModule + let env = List.fold (fun env id -> MakeInnerEnv false env id (Namespace isExplicitNamespace) |> fst) env enclosingNamespacePath let env = { env with eNameResEnv = { env.NameEnv with eDisplayEnv = env.DisplayEnv.AddOpenPath (pathOfLid env.ePath) } } env @@ -985,28 +987,28 @@ let UnifyFunctionType extraInfo cenv denv mFunExpr ty = let ReportImplicitlyIgnoredBoolExpression denv m ty expr = let checkExpr m expr = match stripDebugPoints expr with - | Expr.App (Expr.Val (vf, _, _), _, _, exprs, _) when vf.LogicalName = opNameEquals -> + | Expr.App (Expr.Val (vref, _, _), _, _, exprs, _) when vref.LogicalName = opNameEquals -> match List.map stripDebugPoints exprs with - | Expr.App (Expr.Val (propRef, _, _), _, _, Expr.Val (vf, _, _) :: _, _) :: _ -> + | Expr.App (Expr.Val (propRef, _, _), _, _, Expr.Val (vref, _, _) :: _, _) :: _ -> if propRef.IsPropertyGetterMethod then let propertyName = propRef.PropertyName let hasCorrespondingSetter = match propRef.DeclaringEntity with | Parent entityRef -> entityRef.MembersOfFSharpTyconSorted - |> List.exists (fun valRef -> valRef.IsPropertySetterMethod && valRef.PropertyName = propertyName) + |> List.exists (fun vref -> vref.IsPropertySetterMethod && vref.PropertyName = propertyName) | _ -> false if hasCorrespondingSetter then - UnitTypeExpectedWithPossiblePropertySetter (denv, ty, vf.DisplayName, propertyName, m) + UnitTypeExpectedWithPossiblePropertySetter (denv, ty, vref.DisplayName, propertyName, m) else UnitTypeExpectedWithEquality (denv, ty, m) else UnitTypeExpectedWithEquality (denv, ty, m) - | Expr.Op (TOp.ILCall (_, _, _, _, _, _, _, ilMethRef, _, _, _), _, Expr.Val (vf, _, _) :: _, _) :: _ when ilMethRef.Name.StartsWithOrdinal("get_") -> - UnitTypeExpectedWithPossiblePropertySetter (denv, ty, vf.DisplayName, ChopPropertyName(ilMethRef.Name), m) - | Expr.Val (vf, _, _) :: _ -> - UnitTypeExpectedWithPossibleAssignment (denv, ty, vf.IsMutable, vf.DisplayName, m) + | Expr.Op (TOp.ILCall (_, _, _, _, _, _, _, ilMethRef, _, _, _), _, Expr.Val (vref, _, _) :: _, _) :: _ when ilMethRef.Name.StartsWithOrdinal("get_") -> + UnitTypeExpectedWithPossiblePropertySetter (denv, ty, vref.DisplayName, ChopPropertyName(ilMethRef.Name), m) + | Expr.Val (vref, _, _) :: _ -> + UnitTypeExpectedWithPossibleAssignment (denv, ty, vref.IsMutable, vref.DisplayName, m) | _ -> UnitTypeExpectedWithEquality (denv, ty, m) | _ -> UnitTypeExpected (denv, ty, m) @@ -1039,8 +1041,8 @@ let UnifyUnitType (cenv: cenv) (env: TcEnv) m ty expr = match env.eContextInfo with | ContextInfo.SequenceExpression seqTy -> - let lifted = mkSeqTy g ty - if typeEquiv g seqTy lifted then + let liftedTy = mkSeqTy g ty + if typeEquiv g seqTy liftedTy then warning (Error (FSComp.SR.implicitlyDiscardedInSequenceExpression(NicePrint.prettyStringOfTy denv ty), m)) else if isListTy g ty || isArrayTy g ty || typeEquiv g seqTy ty then @@ -1098,7 +1100,7 @@ let TcConst (cenv: cenv) (overallTy: TType) m env synConst = let _, tcref = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.Use OpenQualified env.eNameResEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) match tcref.TypeOrMeasureKind with | TyparKind.Type -> error(Error(FSComp.SR.tcExpectedUnitOfMeasureNotType(), m)) - | TyparKind.Measure -> Measure.Con tcref + | TyparKind.Measure -> Measure.Const tcref | SynMeasure.Power(ms, exponent, _) -> Measure.RationalPower (tcMeasure ms, TcSynRationalConst exponent) | SynMeasure.Product(ms1, ms2, _) -> Measure.Prod(tcMeasure ms1, tcMeasure ms2) @@ -1112,7 +1114,7 @@ let TcConst (cenv: cenv) (overallTy: TType) m env synConst = | SynMeasure.Var(_, m) -> error(Error(FSComp.SR.tcNonZeroConstantCannotHaveGenericUnit(), m)) | SynMeasure.Paren(measure, _) -> tcMeasure measure - let unif expected = UnifyTypes cenv env m overallTy expected + let unif expectedTy = UnifyTypes cenv env m overallTy expectedTy let unifyMeasureArg iszero tcr = let measureTy = @@ -1310,7 +1312,7 @@ let MakeMemberDataAndMangledNameForMemberVal(g, tcref, isExtrinsic, attrs, implS // NOTE: This value is initially only set for interface implementations and those overrides // where we manage to pre-infer which abstract is overridden by the method. It is filled in // properly when we check the allImplemented implementation checks at the end of the inference scope. - ImplementedSlotSigs=implSlotTys |> List.map (fun ity -> TSlotSig(logicalName, ity, [], [], [], None)) } + ImplementedSlotSigs=implSlotTys |> List.map (fun intfTy -> TSlotSig(logicalName, intfTy, [], [], [], None)) } let isInstance = MemberIsCompiledAsInstance g tcref isExtrinsic memberInfo attrs @@ -1394,13 +1396,19 @@ let PublishValueDefnPrim cenv env (vspec: Val) = let PublishValueDefn (cenv: cenv) env declKind (vspec: Val) = let g = cenv.g + let isNamespace = + let kind = (GetCurrAccumulatedModuleOrNamespaceType env).ModuleOrNamespaceKind + match kind with + | Namespace _ -> true + | _ -> false + if (declKind = ModuleOrMemberBinding) && - ((GetCurrAccumulatedModuleOrNamespaceType env).ModuleOrNamespaceKind = Namespace) && + isNamespace && (Option.isNone vspec.MemberInfo) then errorR(Error(FSComp.SR.tcNamespaceCannotContainValues(), vspec.Range)) if (declKind = ExtrinsicExtensionBinding) && - ((GetCurrAccumulatedModuleOrNamespaceType env).ModuleOrNamespaceKind = Namespace) then + isNamespace then errorR(Error(FSComp.SR.tcNamespaceCannotContainExtensionMembers(), vspec.Range)) // Publish the value to the module type being generated. @@ -1446,9 +1454,9 @@ let ComputeAccessAndCompPath env declKindOpt m vis overrideVis actualParent = match overrideVis, vis with | Some v, _ -> v | _, None -> taccessPublic (* a module or member binding defaults to "public" *) - | _, Some SynAccess.Public -> taccessPublic - | _, Some SynAccess.Private -> taccessPrivate accessPath - | _, Some SynAccess.Internal -> taccessInternal + | _, Some (SynAccess.Public _) -> taccessPublic + | _, Some (SynAccess.Private _) -> taccessPrivate accessPath + | _, Some (SynAccess.Internal _) -> taccessInternal let vis = match actualParent with @@ -1493,7 +1501,7 @@ let MakeAndPublishVal (cenv: cenv) env (altActualParent, inSig, declKind, valRec let g = cenv.g - let (ValScheme(id, typeScheme, valReprInfo, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, isIncrClass, isTyFunc, hasDeclaredTypars)) = vscheme + let (ValScheme(id, typeScheme, valReprInfo, valReprInfoForDisplay, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, isIncrClass, isTyFunc, hasDeclaredTypars)) = vscheme let ty = GeneralizedTypeForTypeScheme typeScheme @@ -1521,8 +1529,8 @@ let MakeAndPublishVal (cenv: cenv) env (altActualParent, inSig, declKind, valRec let vis = if MemberIsExplicitImpl g memberInfo then let slotSig = List.head memberInfo.ImplementedSlotSigs - match slotSig.ImplementedType with - | TType_app (tyconref, _, _) -> Some tyconref.Accessibility + match slotSig.DeclaringType with + | TType_app (tcref, _, _) -> Some tcref.Accessibility | _ -> None else None @@ -1601,6 +1609,10 @@ let MakeAndPublishVal (cenv: cenv) env (altActualParent, inSig, declKind, valRec xmlDoc, isTopBinding, isExtrinsic, isIncrClass, isTyFunc, (hasDeclaredTypars || inSig), isGeneratedEventVal, konst, actualParent) + match valReprInfoForDisplay with + | Some info when not (ValReprInfo.IsEmpty info) -> + vspec.SetValReprInfoForDisplay valReprInfoForDisplay + | _ -> () CheckForAbnormalOperatorNames cenv id.idRange vspec.DisplayNameCoreMangled memberInfoOpt @@ -1634,10 +1646,11 @@ let MakeAndPublishVals cenv env (altActualParent, inSig, declKind, valRecInfo, v valSchemes Map.empty +/// Create a Val node for "base" in a class let MakeAndPublishBaseVal cenv env baseIdOpt ty = baseIdOpt |> Option.map (fun (id: Ident) -> - let valscheme = ValScheme(id, NonGenericTypeScheme ty, None, None, false, ValInline.Never, BaseVal, None, false, false, false, false) + let valscheme = ValScheme(id, NonGenericTypeScheme ty, None, None, None, false, ValInline.Never, BaseVal, None, false, false, false, false) MakeAndPublishVal cenv env (ParentNone, false, ExpressionBinding, ValNotInRecScope, valscheme, [], XmlDoc.Empty, None, false)) // Make the "delayed reference" value where the this pointer will reside after calling the base class constructor @@ -1650,7 +1663,7 @@ let MakeAndPublishSafeThisVal (cenv: cenv) env (thisIdOpt: Ident option) thisTy if not (isFSharpObjModelTy g thisTy) then errorR(Error(FSComp.SR.tcStructsCanOnlyBindThisAtMemberDeclaration(), thisId.idRange)) - let valScheme = ValScheme(thisId, NonGenericTypeScheme(mkRefCellTy g thisTy), None, None, false, ValInline.Never, CtorThisVal, None, false, false, false, false) + let valScheme = ValScheme(thisId, NonGenericTypeScheme(mkRefCellTy g thisTy), None, None, None, false, ValInline.Never, CtorThisVal, None, false, false, false, false) Some(MakeAndPublishVal cenv env (ParentNone, false, ExpressionBinding, ValNotInRecScope, valScheme, [], XmlDoc.Empty, None, false)) | None -> @@ -1701,14 +1714,14 @@ let AdjustRecType (v: Val) vscheme = /// Record the generated value expression as a place where we will have to /// adjust using AdjustAndForgetUsesOfRecValue at a letrec point. Every use of a value /// under a letrec gets used at the _same_ type instantiation. -let RecordUseOfRecValue cenv valRecInfo (vrefTgt: ValRef) vexp m = +let RecordUseOfRecValue cenv valRecInfo (vrefTgt: ValRef) vExpr m = match valRecInfo with | ValInRecScope isComplete -> - let fixupPoint = ref vexp + let fixupPoint = ref vExpr cenv.recUses <- cenv.recUses.Add (vrefTgt.Deref, (fixupPoint, m, isComplete)) Expr.Link fixupPoint | ValNotInRecScope -> - vexp + vExpr type RecursiveUseFixupPoints = RecursiveUseFixupPoints of (Expr ref * range) list @@ -1735,11 +1748,11 @@ let ChooseCanonicalDeclaredTyparsAfterInference g denv declaredTypars m = declaredTypars let ChooseCanonicalValSchemeAfterInference g denv vscheme m = - let (ValScheme(id, typeScheme, arityInfo, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, isIncrClass, isTyFunc, hasDeclaredTypars)) = vscheme + let (ValScheme(id, typeScheme, valReprInfo, valReprInfoForDisplay, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, isIncrClass, isTyFunc, hasDeclaredTypars)) = vscheme let (GeneralizedType(generalizedTypars, ty)) = typeScheme let generalizedTypars = ChooseCanonicalDeclaredTyparsAfterInference g denv generalizedTypars m let typeScheme = GeneralizedType(generalizedTypars, ty) - let valscheme = ValScheme(id, typeScheme, arityInfo, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, isIncrClass, isTyFunc, hasDeclaredTypars) + let valscheme = ValScheme(id, typeScheme, valReprInfo, valReprInfoForDisplay, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, isIncrClass, isTyFunc, hasDeclaredTypars) valscheme let PlaceTyparsInDeclarationOrder declaredTypars generalizedTypars = @@ -1810,10 +1823,11 @@ let ComputeIsTyFunc(id: Ident, hasDeclaredTypars, arityInfo: ValReprInfo option) | Some info -> info.NumCurriedArgs = 0) let UseSyntacticArity declKind typeScheme prelimValReprInfo = + let valReprInfo = InferGenericArityFromTyScheme typeScheme prelimValReprInfo if DeclKind.MustHaveArity declKind then - Some(InferGenericArityFromTyScheme typeScheme prelimValReprInfo) + Some valReprInfo, None else - None + None, Some valReprInfo /// Combine the results of InferSynValData and InferArityOfExpr. // @@ -1848,18 +1862,17 @@ let UseSyntacticArity declKind typeScheme prelimValReprInfo = // { new Base with // member x.M(v: unit) = () } // -let CombineSyntacticAndInferredArities g declKind rhsExpr prelimScheme = +let CombineSyntacticAndInferredArities g rhsExpr prelimScheme = let (PrelimVal2(_, typeScheme, partialValReprInfoOpt, memberInfoOpt, isMutable, _, _, ArgAndRetAttribs(argAttribs, retAttribs), _, _, _)) = prelimScheme - match partialValReprInfoOpt, DeclKind.MustHaveArity declKind with - | _, false -> None - | None, true -> Some(PrelimValReprInfo([], ValReprInfo.unnamedRetVal)) + match partialValReprInfoOpt with + | None -> Some(PrelimValReprInfo([], ValReprInfo.unnamedRetVal)) // Don't use any expression information for members, where syntax dictates the arity completely | _ when memberInfoOpt.IsSome -> partialValReprInfoOpt // Don't use any expression information for 'let' bindings where return attributes are present | _ when retAttribs.Length > 0 -> partialValReprInfoOpt - | Some partialValReprInfoFromSyntax, true -> + | Some partialValReprInfoFromSyntax -> let (PrelimValReprInfo(curriedArgInfosFromSyntax, retInfoFromSyntax)) = partialValReprInfoFromSyntax let partialArityInfo = if isMutable then @@ -1892,16 +1905,20 @@ let CombineSyntacticAndInferredArities g declKind rhsExpr prelimScheme = let BuildValScheme declKind partialArityInfoOpt prelimScheme = let (PrelimVal2(id, typeScheme, _, memberInfoOpt, isMutable, inlineFlag, baseOrThis, _, vis, isCompGen, hasDeclaredTypars)) = prelimScheme - let valReprInfo = + let valReprInfoOpt = + partialArityInfoOpt + |> Option.map (InferGenericArityFromTyScheme typeScheme) + + let valReprInfo, valReprInfoForDisplay = if DeclKind.MustHaveArity declKind then - Option.map (InferGenericArityFromTyScheme typeScheme) partialArityInfoOpt + valReprInfoOpt, None else - None + None, valReprInfoOpt let isTyFunc = ComputeIsTyFunc(id, hasDeclaredTypars, valReprInfo) - ValScheme(id, typeScheme, valReprInfo, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, false, isTyFunc, hasDeclaredTypars) + ValScheme(id, typeScheme, valReprInfo, valReprInfoForDisplay, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, isCompGen, false, isTyFunc, hasDeclaredTypars) let UseCombinedArity g declKind rhsExpr prelimScheme = - let partialArityInfoOpt = CombineSyntacticAndInferredArities g declKind rhsExpr prelimScheme + let partialArityInfoOpt = CombineSyntacticAndInferredArities g rhsExpr prelimScheme BuildValScheme declKind partialArityInfoOpt prelimScheme let UseNoArity prelimScheme = @@ -2144,9 +2161,9 @@ let rec ApplyUnionCaseOrExn (makerForUnionCase, makerForExnTag) m (cenv: cenv) e let ucref = ucinfo.UnionCaseRef CheckUnionCaseAttributes g ucref m |> CommitOperationResult CheckUnionCaseAccessible cenv.amap m ad ucref |> ignore - let gtyp2 = actualResultTyOfUnionCase ucinfo.TypeInst ucref + let resTy = actualResultTyOfUnionCase ucinfo.TypeInst ucref let inst = mkTyparInst ucref.TyconRef.TyparsNoRange ucinfo.TypeInst - UnifyTypes cenv env m overallTy gtyp2 + UnifyTypes cenv env m overallTy resTy let mkf = makerForUnionCase(ucref, ucinfo.TypeInst) mkf, actualTysOfUnionCaseFields inst ucref, [ for f in ucref.AllFieldsAsList -> f.Id ] | _ -> invalidArg "item" "not a union case or exception reference" @@ -2329,11 +2346,11 @@ module GeneralizationHelpers = let relevantUniqueSubtypeConstraint (tp: Typar) = // Find a single subtype constraint match tp.Constraints |> List.partition (function TyparConstraint.CoercesTo _ -> true | _ -> false) with - | [TyparConstraint.CoercesTo(cxty, _)], others -> + | [TyparConstraint.CoercesTo(tgtTy, _)], others -> // Throw away null constraints if they are implied - if others |> List.exists (function TyparConstraint.SupportsNull _ -> not (TypeSatisfiesNullConstraint g m cxty) | _ -> true) + if others |> List.exists (function TyparConstraint.SupportsNull _ -> not (TypeSatisfiesNullConstraint g m tgtTy) | _ -> true) then None - else Some cxty + else Some tgtTy | _ -> None @@ -2629,7 +2646,7 @@ module BindingNormalization = | SynPat.FromParseError(innerPat, _) -> normPattern innerPat - | SynPat.LongIdent (SynLongIdent(longId, _, _), _, toolId, tyargs, SynArgPats.Pats args, vis, m) -> + | SynPat.LongIdent (SynLongIdent(longId, _, _), toolId, tyargs, SynArgPats.Pats args, vis, m) -> let typars = match tyargs with None -> inferredTyparDecls | Some typars -> typars match memberFlagsOpt with | None -> @@ -2728,8 +2745,8 @@ module EventDeclarationNormalization = let rec private RenameBindingPattern f declPattern = match declPattern with - | SynPat.FromParseError(p, _) -> RenameBindingPattern f p - | SynPat.Typed(pat', _, _) -> RenameBindingPattern f pat' + | SynPat.FromParseError(innerPat, _) -> RenameBindingPattern f innerPat + | SynPat.Typed(innerPat, _, _) -> RenameBindingPattern f innerPat | SynPat.Named (SynIdent(id,_), x2, vis2, m) -> SynPat.Named (SynIdent(ident(f id.idText, id.idRange), None), x2, vis2, m) | SynPat.InstanceMember(thisId, id, toolId, vis2, m) -> SynPat.InstanceMember(thisId, ident(f id.idText, id.idRange), toolId, vis2, m) | _ -> error(Error(FSComp.SR.tcOnlySimplePatternsInLetRec(), declPattern.Range)) @@ -2831,11 +2848,11 @@ let TcValEarlyGeneralizationConsistencyCheck cenv (env: TcEnv) (v: Val, valRecIn match valRecInfo with | ValInRecScope isComplete when isComplete && not (isNil tinst) -> cenv.css.PushPostInferenceCheck (preDefaults=false, check=fun () -> - let tpsorig, tau2 = tryDestForallTy g vTy - if not (isNil tpsorig) then - let tpsorig = NormalizeDeclaredTyparsForEquiRecursiveInference g tpsorig - let tau3 = instType (mkTyparInst tpsorig tinst) tau2 - if not (AddCxTypeEqualsTypeUndoIfFailed env.DisplayEnv cenv.css m tau tau3) then + let vTypars, vTauTy = tryDestForallTy g vTy + if not (isNil vTypars) then + let vTypars = NormalizeDeclaredTyparsForEquiRecursiveInference g vTypars + let vTauTy = instType (mkTyparInst vTypars tinst) vTauTy + if not (AddCxTypeEqualsTypeUndoIfFailed env.DisplayEnv cenv.css m tau vTauTy) then let txt = buildString (fun buf -> NicePrint.outputQualifiedValSpec env.DisplayEnv cenv.infoReader buf (mkLocalValRef v)) error(Error(FSComp.SR.tcInferredGenericTypeGivesRiseToInconsistency(v.DisplayName, txt), m))) | _ -> () @@ -2916,26 +2933,26 @@ let TcVal checkAttributes (cenv: cenv) env (tpenv: UnscopedTyparEnv) (vref: ValR warning(Error(FSComp.SR.tcDoesNotAllowExplicitTypeArguments(v.DisplayName), m)) match valRecInfo with | ValInRecScope false -> - let tpsorig, tau = vref.GeneralizedType - let (tinst: TypeInst), tpenv = checkTys tpenv (tpsorig |> List.map (fun tp -> tp.Kind)) + let vTypars, vTauTy = vref.GeneralizedType + let tinst, tpenv = checkTys tpenv (vTypars |> List.map (fun tp -> tp.Kind)) checkInst tinst - if tpsorig.Length <> tinst.Length then error(Error(FSComp.SR.tcTypeParameterArityMismatch(tpsorig.Length, tinst.Length), m)) + if vTypars.Length <> tinst.Length then error(Error(FSComp.SR.tcTypeParameterArityMismatch(vTypars.Length, tinst.Length), m)) - let tau2 = instType (mkTyparInst tpsorig tinst) tau + let vRecTauTy = instType (mkTyparInst vTypars tinst) vTauTy - (tpsorig, tinst) ||> List.iter2 (fun tp ty -> + (vTypars, tinst) ||> List.iter2 (fun tp ty -> try UnifyTypes cenv env m (mkTyparTy tp) ty - with _ -> error (Recursion(env.DisplayEnv, v.Id, tau2, tau, m))) + with _ -> error (Recursion(env.DisplayEnv, v.Id, vRecTauTy, vTauTy, m))) - tpsorig, vrefFlags, tinst, tau2, tpenv + vTypars, vrefFlags, tinst, vRecTauTy, tpenv | ValInRecScope true | ValNotInRecScope -> - let tpsorig, tps, tpTys, tau = FreshenPossibleForallTy g m TyparRigidity.Flexible vTy + let vTypars, tps, tpTys, vTauTy = FreshenPossibleForallTy g m TyparRigidity.Flexible vTy - let (tinst: TypeInst), tpenv = checkTys tpenv (tps |> List.map (fun tp -> tp.Kind)) + let tinst, tpenv = checkTys tpenv (tps |> List.map (fun tp -> tp.Kind)) checkInst tinst @@ -2943,9 +2960,9 @@ let TcVal checkAttributes (cenv: cenv) env (tpenv: UnscopedTyparEnv) (vref: ValR List.iter2 (UnifyTypes cenv env m) tpTys tinst - TcValEarlyGeneralizationConsistencyCheck cenv env (v, valRecInfo, tinst, vTy, tau, m) + TcValEarlyGeneralizationConsistencyCheck cenv env (v, valRecInfo, tinst, vTy, vTauTy, m) - tpsorig, vrefFlags, tinst, tau, tpenv + vTypars, vrefFlags, tinst, vTauTy, tpenv let exprForVal = Expr.Val (vref, vrefFlags, m) let exprForVal = mkTyAppExpr m (exprForVal, vTy) tinst @@ -3242,7 +3259,7 @@ let BuildILFieldGet g amap m objExpr (finfo: ILFieldInfo) = let isStruct = finfo.IsValueType let boxity = if isStruct then AsValue else AsObject let tinst = finfo.TypeInst - let fieldType = finfo.FieldType (amap, m) + let fieldTy = finfo.FieldType (amap, m) #if !NO_TYPEPROVIDERS let ty = tyOfExpr g objExpr match finfo with @@ -3252,7 +3269,7 @@ let BuildILFieldGet g amap m objExpr (finfo: ILFieldInfo) = | None -> error (Error(FSComp.SR.tcTPFieldMustBeLiteral(), m)) | Some lit -> - Expr.Const (TcFieldInit m lit, m, fieldType) + Expr.Const (TcFieldInit m lit, m, fieldTy) | _ -> #endif let wrap, objExpr, _readonly, _writeonly = mkExprAddrOfExpr g isStruct false NeverMutates objExpr None m @@ -3261,7 +3278,7 @@ let BuildILFieldGet g amap m objExpr (finfo: ILFieldInfo) = // polymorphic code, after inlining etc. * let fspec = mkILFieldSpec(fref, mkILNamedTy boxity fref.DeclaringTypeRef []) // Add an I_nop if this is an initonly field to make sure we never recognize it as an lvalue. See mkExprAddrOfExpr. - wrap (mkAsmExpr (([ mkNormalLdfld fspec ] @ (if finfo.IsInitOnly then [ AI_nop ] else [])), tinst, [objExpr], [fieldType], m)) + wrap (mkAsmExpr (([ mkNormalLdfld fspec ] @ (if finfo.IsInitOnly then [ AI_nop ] else [])), tinst, [objExpr], [fieldTy], m)) /// Checks that setting a field value does not set a literal or initonly field let private CheckFieldLiteralArg (finfo: ILFieldInfo) argExpr m = @@ -3414,28 +3431,28 @@ let AnalyzeArbitraryExprAsEnumerable (cenv: cenv) (env: TcEnv) localAlloc m expr let tryType (exprToSearchForGetEnumeratorAndItem, tyToSearchForGetEnumeratorAndItem) = match findMethInfo true m "GetEnumerator" tyToSearchForGetEnumeratorAndItem with | Exception exn -> Exception exn - | Result getEnumerator_minfo -> + | Result getEnumeratorMethInfo -> - let getEnumerator_minst = FreshenMethInfo m getEnumerator_minfo - let retTypeOfGetEnumerator = getEnumerator_minfo.GetFSharpReturnType(cenv.amap, m, getEnumerator_minst) - if hasArgs getEnumerator_minfo getEnumerator_minst then err true tyToSearchForGetEnumeratorAndItem else + let getEnumeratorMethInst = FreshenMethInfo m getEnumeratorMethInfo + let getEnumeratorRetTy = getEnumeratorMethInfo.GetFSharpReturnType(cenv.amap, m, getEnumeratorMethInst) + if hasArgs getEnumeratorMethInfo getEnumeratorMethInst then err true tyToSearchForGetEnumeratorAndItem else - match findMethInfo false m "MoveNext" retTypeOfGetEnumerator with + match findMethInfo false m "MoveNext" getEnumeratorRetTy with | Exception exn -> Exception exn - | Result moveNext_minfo -> + | Result moveNextMethInfo -> - let moveNext_minst = FreshenMethInfo m moveNext_minfo - let retTypeOfMoveNext = moveNext_minfo.GetFSharpReturnType(cenv.amap, m, moveNext_minst) - if not (typeEquiv g g.bool_ty retTypeOfMoveNext) then err false retTypeOfGetEnumerator else - if hasArgs moveNext_minfo moveNext_minst then err false retTypeOfGetEnumerator else + let moveNextMethInst = FreshenMethInfo m moveNextMethInfo + let moveNextRetTy = moveNextMethInfo.GetFSharpReturnType(cenv.amap, m, moveNextMethInst) + if not (typeEquiv g g.bool_ty moveNextRetTy) then err false getEnumeratorRetTy else + if hasArgs moveNextMethInfo moveNextMethInst then err false getEnumeratorRetTy else - match findMethInfo false m "get_Current" retTypeOfGetEnumerator with + match findMethInfo false m "get_Current" getEnumeratorRetTy with | Exception exn -> Exception exn - | Result get_Current_minfo -> + | Result getCurrentMethInfo -> - let get_Current_minst = FreshenMethInfo m get_Current_minfo - if hasArgs get_Current_minfo get_Current_minst then err false retTypeOfGetEnumerator else - let enumElemTy = get_Current_minfo.GetFSharpReturnType(cenv.amap, m, get_Current_minst) + let getCurrentMethInst = FreshenMethInfo m getCurrentMethInfo + if hasArgs getCurrentMethInfo getCurrentMethInst then err false getEnumeratorRetTy else + let enumElemTy = getCurrentMethInfo.GetFSharpReturnType(cenv.amap, m, getCurrentMethInst) // Compute the element type of the strongly typed enumerator // @@ -3479,23 +3496,23 @@ let AnalyzeArbitraryExprAsEnumerable (cenv: cenv) (env: TcEnv) localAlloc m expr else enumElemTy - let isEnumeratorTypeStruct = isStructTy g retTypeOfGetEnumerator - let originalRetTypeOfGetEnumerator = retTypeOfGetEnumerator + let isEnumeratorTypeStruct = isStructTy g getEnumeratorRetTy + let originalRetTypeOfGetEnumerator = getEnumeratorRetTy - let (enumeratorVar, enumeratorExpr), retTypeOfGetEnumerator = + let (enumeratorVar, enumeratorExpr), getEnumeratorRetTy = if isEnumeratorTypeStruct then if localAlloc then - mkMutableCompGenLocal m "enumerator" retTypeOfGetEnumerator, retTypeOfGetEnumerator + mkMutableCompGenLocal m "enumerator" getEnumeratorRetTy, getEnumeratorRetTy else - let refCellTyForRetTypeOfGetEnumerator = mkRefCellTy g retTypeOfGetEnumerator + let refCellTyForRetTypeOfGetEnumerator = mkRefCellTy g getEnumeratorRetTy let v, e = mkMutableCompGenLocal m "enumerator" refCellTyForRetTypeOfGetEnumerator - (v, mkRefCellGet g m retTypeOfGetEnumerator e), refCellTyForRetTypeOfGetEnumerator + (v, mkRefCellGet g m getEnumeratorRetTy e), refCellTyForRetTypeOfGetEnumerator else - mkCompGenLocal m "enumerator" retTypeOfGetEnumerator, retTypeOfGetEnumerator + mkCompGenLocal m "enumerator" getEnumeratorRetTy, getEnumeratorRetTy let getEnumExpr, getEnumTy = - let getEnumExpr, getEnumTy as res = BuildPossiblyConditionalMethodCall cenv env PossiblyMutates m false getEnumerator_minfo NormalValUse getEnumerator_minst [exprToSearchForGetEnumeratorAndItem] [] + let getEnumExpr, getEnumTy as res = BuildPossiblyConditionalMethodCall cenv env PossiblyMutates m false getEnumeratorMethInfo NormalValUse getEnumeratorMethInst [exprToSearchForGetEnumeratorAndItem] [] if not isEnumeratorTypeStruct || localAlloc then res else // wrap enumerators that are represented as mutable structs into ref cells @@ -3503,8 +3520,8 @@ let AnalyzeArbitraryExprAsEnumerable (cenv: cenv) (env: TcEnv) localAlloc m expr let getEnumTy = mkRefCellTy g getEnumTy getEnumExpr, getEnumTy - let guardExpr, guardTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m false moveNext_minfo NormalValUse moveNext_minst [enumeratorExpr] [] - let currentExpr, currentTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m true get_Current_minfo NormalValUse get_Current_minst [enumeratorExpr] [] + let guardExpr, guardTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m false moveNextMethInfo NormalValUse moveNextMethInst [enumeratorExpr] [] + let currentExpr, currentTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m true getCurrentMethInfo NormalValUse getCurrentMethInst [enumeratorExpr] [] let currentExpr = mkCoerceExpr(currentExpr, enumElemTy, currentExpr.Range, currentTy) let currentExpr, enumElemTy = // Implicitly dereference byref for expr 'for x in ...' @@ -3514,7 +3531,7 @@ let AnalyzeArbitraryExprAsEnumerable (cenv: cenv) (env: TcEnv) localAlloc m expr else currentExpr, enumElemTy - Result(enumeratorVar, enumeratorExpr, retTypeOfGetEnumerator, enumElemTy, getEnumExpr, getEnumTy, guardExpr, guardTy, currentExpr) + Result(enumeratorVar, enumeratorExpr, getEnumeratorRetTy, enumElemTy, getEnumExpr, getEnumTy, guardExpr, guardTy, currentExpr) // First try the original known static type match (if isArray1DTy g exprTy then Exception (Failure "") else tryType (expr, exprTy)) with @@ -3553,12 +3570,12 @@ let ConvertArbitraryExprToEnumerable (cenv: cenv) ty (env: TcEnv) (expr: Expr) = expr, enumElemTy else let enumerableVar, enumerableExpr = mkCompGenLocal m "inputSequence" ty - let enumeratorVar, _, retTypeOfGetEnumerator, enumElemTy, getEnumExpr, _, guardExpr, guardTy, betterCurrentExpr = + let enumeratorVar, _, getEnumeratorRetTy, enumElemTy, getEnumExpr, _, guardExpr, guardTy, betterCurrentExpr = AnalyzeArbitraryExprAsEnumerable cenv env false m ty enumerableExpr let expr = mkCompGenLet m enumerableVar expr - (mkCallSeqOfFunctions g m retTypeOfGetEnumerator enumElemTy + (mkCallSeqOfFunctions g m getEnumeratorRetTy enumElemTy (mkUnitDelayLambda g m getEnumExpr) (mkLambda m enumeratorVar (guardExpr, guardTy)) (mkLambda m enumeratorVar (betterCurrentExpr, enumElemTy))) @@ -3904,28 +3921,28 @@ let buildApp cenv expr resultTy arg m = match expr, arg with // Special rule for building applications of the 'x && y' operator - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [x0], _), _), _ - when valRefEq g vf g.and_vref - || valRefEq g vf g.and2_vref -> + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [x0], _), _), _ + when valRefEq g vref g.and_vref + || valRefEq g vref g.and2_vref -> MakeApplicableExprNoFlex cenv (mkLazyAnd g m x0 arg), resultTy // Special rule for building applications of the 'x || y' operator - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [x0], _), _), _ - when valRefEq g vf g.or_vref - || valRefEq g vf g.or2_vref -> + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [x0], _), _), _ + when valRefEq g vref g.or_vref + || valRefEq g vref g.or2_vref -> MakeApplicableExprNoFlex cenv (mkLazyOr g m x0 arg ), resultTy // Special rule for building applications of the 'reraise' operator - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ - when valRefEq g vf g.reraise_vref -> + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [], _), _), _ + when valRefEq g vref g.reraise_vref -> // exprTy is of type: "unit -> 'a". Break it and store the 'a type here, used later as return type. MakeApplicableExprNoFlex cenv (mkCompGenSequential m arg (mkReraise m resultTy)), resultTy // Special rules for NativePtr.ofByRef to generalize result. // See RFC FS-1053.md - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ - when (valRefEq g vf g.nativeptr_tobyref_vref) -> + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [], _), _), _ + when (valRefEq g vref g.nativeptr_tobyref_vref) -> let argTy = NewInferenceType g let resultTy = mkByrefTyWithInference g argTy (NewByRefKindInferenceType g m) @@ -3935,10 +3952,10 @@ let buildApp cenv expr resultTy arg m = // address of an expression. // // See also RFC FS-1053.md - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ - when valRefEq g vf g.addrof_vref -> + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [], _), _), _ + when valRefEq g vref g.addrof_vref -> - let wrap, e1a', readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some vf) m + let wrap, e1a', readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some vref) m // Assert the result type to be readonly if we couldn't take the address let resultTy = let argTy = tyOfExpr g arg @@ -3960,11 +3977,11 @@ let buildApp cenv expr resultTy arg m = // Special rules for building applications of the &&expr' operators, which gets the // address of an expression. - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _), _ - when valRefEq g vf g.addrof2_vref -> + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [], _), _), _ + when valRefEq g vref g.addrof2_vref -> warning(UseOfAddressOfOperator m) - let wrap, e1a', _readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some vf) m + let wrap, e1a', _readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some vref) m MakeApplicableExprNoFlex cenv (wrap(e1a')), resultTy | _ when isByrefTy g resultTy -> @@ -4530,7 +4547,7 @@ and TcTypeOrMeasure kindOpt cenv newOk checkConstraints occ env (tpenv: Unscoped | SynType.AnonRecd(isStruct, args, m) -> TcAnonRecdType cenv newOk checkConstraints occ env tpenv isStruct args m - | SynType.Fun(domainTy, resultTy, _) -> + | SynType.Fun(argType = domainTy; returnType = resultTy) -> TcFunctionType cenv newOk checkConstraints occ env tpenv domainTy resultTy | SynType.Array (rank , elemTy, m) -> @@ -4581,7 +4598,7 @@ and TcLongIdent kindOpt cenv newOk checkConstraints occ env tpenv synLongId = error(Error(FSComp.SR.tcExpectedUnitOfMeasureNotType(), m)) TType_measure (NewErrorMeasure ()), tpenv | _, TyparKind.Measure -> - TType_measure (Measure.Con tcref), tpenv + TType_measure (Measure.Const tcref), tpenv | _, TyparKind.Type -> TcTypeApp cenv newOk checkConstraints occ env tpenv m tcref tinstEnclosing [] @@ -4614,7 +4631,7 @@ and TcLongIdentAppType kindOpt cenv newOk checkConstraints occ env tpenv longId match args, postfix with | [arg], true -> let ms, tpenv = TcMeasure cenv newOk checkConstraints occ env tpenv arg m - TType_measure (Measure.Prod(Measure.Con tcref, ms)), tpenv + TType_measure (Measure.Prod(Measure.Const tcref, ms)), tpenv | _, _ -> errorR(Error(FSComp.SR.tcUnitsOfMeasureInvalidInTypeConstructor(), m)) @@ -5094,8 +5111,8 @@ and TcNestedTypeApplication cenv newOk checkConstraints occ env tpenv mWholeType /// This means the range of syntactic expression forms that can be used here is limited. and ConvSynPatToSynExpr synPat = match synPat with - | SynPat.FromParseError(p, _) -> - ConvSynPatToSynExpr p + | SynPat.FromParseError(innerPat, _) -> + ConvSynPatToSynExpr innerPat | SynPat.Const (c, m) -> SynExpr.Const (c, m) @@ -5103,8 +5120,8 @@ and ConvSynPatToSynExpr synPat = | SynPat.Named (SynIdent(id,_), _, None, _) -> SynExpr.Ident id - | SynPat.Typed (p, cty, m) -> - SynExpr.Typed (ConvSynPatToSynExpr p, cty, m) + | SynPat.Typed (innerPat, tgtTy, m) -> + SynExpr.Typed (ConvSynPatToSynExpr innerPat, tgtTy, m) | SynPat.LongIdent (longDotId=SynLongIdent(longId, dotms, trivia) as synLongId; argPats=args; accessibility=None; range=m) -> let args = match args with SynArgPats.Pats args -> args | _ -> failwith "impossible: active patterns can be used only with SynConstructorArgs.Pats" @@ -5118,8 +5135,8 @@ and ConvSynPatToSynExpr synPat = | SynPat.Tuple (isStruct, args, m) -> SynExpr.Tuple (isStruct, List.map ConvSynPatToSynExpr args, [], m) - | SynPat.Paren (p, _) -> - ConvSynPatToSynExpr p + | SynPat.Paren (innerPat, _) -> + ConvSynPatToSynExpr innerPat | SynPat.ArrayOrList (isArray, args, m) -> SynExpr.ArrayOrList (isArray,List.map ConvSynPatToSynExpr args, m) @@ -5134,26 +5151,26 @@ and ConvSynPatToSynExpr synPat = error(Error(FSComp.SR.tcInvalidArgForParameterizedPattern(), synPat.Range)) /// Check a long identifier 'Case' or 'Case argsR' that has been resolved to an active pattern case -and TcPatLongIdentActivePatternCase warnOnUpper cenv (env: TcEnv) vFlags patEnv ty (lidRange, item, apref, args, m) = +and TcPatLongIdentActivePatternCase warnOnUpper cenv (env: TcEnv) vFlags patEnv ty (mLongId, item, apref, args, m) = let g = cenv.g let (TcPatLinearEnv(tpenv, names, takenNames)) = patEnv let (APElemRef (apinfo, vref, idx, isStructRetTy)) = apref // Report information about the 'active recognizer' occurrence to IDE - CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mLongId, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.eAccessRights) // TOTAL/PARTIAL ACTIVE PATTERNS - let _, vexp, _, _, tinst, _ = TcVal true cenv env tpenv vref None None m - let vexp = MakeApplicableExprWithFlex cenv env vexp - let vexpty = vexp.Type + let _, vExpr, _, _, tinst, _ = TcVal true cenv env tpenv vref None None m + let vExpr = MakeApplicableExprWithFlex cenv env vExpr + let vExprTy = vExpr.Type let activePatArgsAsSynPats, patArg = match args with | [] -> [], SynPat.Const(SynConst.Unit, m) | _ -> // This bit of type-directed analysis ensures that parameterized partial active patterns returning unit do not need to take an argument - let dtys, retTy = stripFunTy g vexpty + let dtys, retTy = stripFunTy g vExprTy if dtys.Length = args.Length + 1 && ((isOptionTy g retTy && isUnitTy g (destOptionTy g retTy)) || @@ -5172,9 +5189,9 @@ and TcPatLongIdentActivePatternCase warnOnUpper cenv (env: TcEnv) vFlags patEnv let delayed = activePatArgsAsSynExprs - |> List.map (fun arg -> DelayedApp(ExprAtomicFlag.NonAtomic, false, None, arg, unionRanges lidRange arg.Range)) + |> List.map (fun arg -> DelayedApp(ExprAtomicFlag.NonAtomic, false, None, arg, unionRanges mLongId arg.Range)) - let activePatExpr, tpenv = PropagateThenTcDelayed cenv (MustEqual activePatType) env tpenv m vexp vexpty ExprAtomicFlag.NonAtomic delayed + let activePatExpr, tpenv = PropagateThenTcDelayed cenv (MustEqual activePatType) env tpenv m vExpr vExprTy ExprAtomicFlag.NonAtomic delayed let patEnvR = TcPatLinearEnv(tpenv, names, takenNames) @@ -5703,6 +5720,12 @@ and TcExprUndelayed cenv (overallTy: OverallTy) env tpenv (synExpr: SynExpr) = ) | SynExpr.ObjExpr (synObjTy, argopt, _mWith, binds, members, extraImpls, mNewExpr, m) -> + let members = desugarGetSetMembers members + let extraImpls = + extraImpls + |> List.map (fun (SynInterfaceImpl(interfaceTy, withKeyword, bindings, members, m)) -> + SynInterfaceImpl(interfaceTy, withKeyword, bindings, desugarGetSetMembers members, m) + ) TcNonControlFlowExpr env <| fun env -> let binds = unionBindingAndMembers binds members TcExprObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, mNewExpr, m) @@ -6241,13 +6264,13 @@ and TcExprILAssembly cenv overallTy env tpenv (ilInstrs, synTyArgs, synArgs, syn and RewriteRangeExpr synExpr = match synExpr with // a..b..c (parsed as (a..b)..c ) - | SynExpr.IndexRange(Some (SynExpr.IndexRange(Some synExpr1, _, Some synStepExpr, _, _, _)), _, Some synExpr2, _m1, _m2, wholem) -> - Some (mkSynTrifix wholem ".. .." synExpr1 synStepExpr synExpr2) + | SynExpr.IndexRange(Some (SynExpr.IndexRange(Some synExpr1, _, Some synStepExpr, _, _, _)), _, Some synExpr2, _m1, _m2, mWhole) -> + Some (mkSynTrifix mWhole ".. .." synExpr1 synStepExpr synExpr2) // a..b - | SynExpr.IndexRange (Some synExpr1, mOperator, Some synExpr2, _m1, _m2, wholem) -> + | SynExpr.IndexRange (Some synExpr1, mOperator, Some synExpr2, _m1, _m2, mWhole) -> let otherExpr = match mkSynInfix mOperator synExpr1 ".." synExpr2 with - | SynExpr.App (a, b, c, d, _) -> SynExpr.App (a, b, c, d, wholem) + | SynExpr.App (a, b, c, d, _) -> SynExpr.App (a, b, c, d, mWhole) | _ -> failwith "impossible" Some otherExpr | _ -> None @@ -7673,8 +7696,8 @@ and TcForEachExpr cenv overallTy env tpenv (seqExprOnly, isFromSource, synPat, s match stripDebugPoints enumExpr with // optimize 'for i in n .. m do' - | Expr.App (Expr.Val (vf, _, _), _, [tyarg], [startExpr;finishExpr], _) - when valRefEq g vf g.range_op_vref && typeEquiv g tyarg g.int_ty -> + | Expr.App (Expr.Val (vref, _, _), _, [tyarg], [startExpr;finishExpr], _) + when valRefEq g vref g.range_op_vref && typeEquiv g tyarg g.int_ty -> (g.int32_ty, (fun _ x -> x), id, Choice1Of3 (startExpr, finishExpr)) // optimize 'for i in arr do' @@ -7860,9 +7883,9 @@ and Propagate cenv (overallTy: OverallTy) (env: TcEnv) tpenv (expr: ApplicableEx // See RFC FS-1053.md let isAddrOf = match expr with - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [], _), _) - when (valRefEq g vf g.addrof_vref || - valRefEq g vf g.nativeptr_tobyref_vref) -> true + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [], _), _) + when (valRefEq g vref g.addrof_vref || + valRefEq g vref g.nativeptr_tobyref_vref) -> true | _ -> false propagate isAddrOf delayedList' mExprAndArg resultTy @@ -8172,12 +8195,12 @@ and TcApplicationThen cenv (overallTy: OverallTy) env tpenv mExprAndArg synLeftE // will have debug points on "f expr1" and "g expr2" let env = match leftExpr with - | ApplicableExpr(_, Expr.Val (vf, _, _), _) - | ApplicableExpr(_, Expr.App (Expr.Val (vf, _, _), _, _, [_], _), _) - when valRefEq g vf g.and_vref - || valRefEq g vf g.and2_vref - || valRefEq g vf g.or_vref - || valRefEq g vf g.or2_vref -> + | ApplicableExpr(_, Expr.Val (vref, _, _), _) + | ApplicableExpr(_, Expr.App (Expr.Val (vref, _, _), _, _, [_], _), _) + when valRefEq g vref g.and_vref + || valRefEq g vref g.and2_vref + || valRefEq g vref g.or_vref + || valRefEq g vref g.or2_vref -> { env with eIsControlFlow = true } | _ -> env @@ -8527,8 +8550,10 @@ and TcMethodItemThen cenv overallTy env item methodName minfos tpenv mItem after TcMethodApplicationThen cenv env overallTy None tpenv None [] mItem mItem methodName ad NeverMutates false meths afterResolution NormalValUse [] ExprAtomicFlag.Atomic delayed and TcCtorItemThen cenv overallTy env item nm minfos tinstEnclosing tpenv mItem afterResolution delayed = +#if !NO_TYPEPROVIDERS let g = cenv.g let ad = env.eAccessRights +#endif let objTy = match minfos with | minfo :: _ -> minfo.ApparentEnclosingType @@ -8732,7 +8757,7 @@ and TcValueItemThen cenv overallTy env vref tpenv mItem afterResolution delayed vTy // Always allow subsumption on assignment to fields let expr2R, tpenv = TcExprFlex cenv true false vty2 env tpenv expr2 - let vexp = + let vExpr = if isInByrefTy g vTy then errorR(Error(FSComp.SR.writeToReadOnlyByref(), mStmt)) mkAddrSet mStmt vref expr2R @@ -8741,7 +8766,7 @@ and TcValueItemThen cenv overallTy env vref tpenv mItem afterResolution delayed else mkValSet mStmt vref expr2R - PropagateThenTcDelayed cenv overallTy env tpenv mStmt (MakeApplicableExprNoFlex cenv vexp) (tyOfExpr g vexp) ExprAtomicFlag.NonAtomic otherDelayed + PropagateThenTcDelayed cenv overallTy env tpenv mStmt (MakeApplicableExprNoFlex cenv vExpr) (tyOfExpr g vExpr) ExprAtomicFlag.NonAtomic otherDelayed // Value instantiation: v ... | DelayedTypeApp(tys, _mTypeArgs, mExprAndTypeArgs) :: otherDelayed -> @@ -8755,24 +8780,24 @@ and TcValueItemThen cenv overallTy env vref tpenv mItem afterResolution delayed match tys with | [SynType.Var(SynTypar(id, _, false) as tp, _m)] -> let _tpR, tpenv = TcTypeOrMeasureParameter None cenv env ImplicitlyBoundTyparsAllowed.NoNewTypars tpenv tp - let vexp = TcNameOfExprResult cenv id mExprAndTypeArgs - let vexpFlex = MakeApplicableExprNoFlex cenv vexp + let vExpr = TcNameOfExprResult cenv id mExprAndTypeArgs + let vexpFlex = MakeApplicableExprNoFlex cenv vExpr PropagateThenTcDelayed cenv overallTy env tpenv mExprAndTypeArgs vexpFlex g.string_ty ExprAtomicFlag.Atomic otherDelayed | _ -> error (Error(FSComp.SR.expressionHasNoName(), mExprAndTypeArgs)) | _ -> let checkTys tpenv kinds = TcTypesOrMeasures (Some kinds) cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv tys mItem - let _, vexp, isSpecial, _, _, tpenv = TcVal true cenv env tpenv vref (Some (NormalValUse, checkTys)) (Some afterResolution) mItem + let _, vExpr, isSpecial, _, _, tpenv = TcVal true cenv env tpenv vref (Some (NormalValUse, checkTys)) (Some afterResolution) mItem - let vexpFlex = (if isSpecial then MakeApplicableExprNoFlex cenv vexp else MakeApplicableExprWithFlex cenv env vexp) + let vexpFlex = (if isSpecial then MakeApplicableExprNoFlex cenv vExpr else MakeApplicableExprWithFlex cenv env vExpr) // We need to eventually record the type resolution for an expression, but this is done // inside PropagateThenTcDelayed, so we don't have to explicitly call 'CallExprHasTypeSink' here PropagateThenTcDelayed cenv overallTy env tpenv mExprAndTypeArgs vexpFlex vexpFlex.Type ExprAtomicFlag.Atomic otherDelayed // Value get | _ -> - let _, vexp, isSpecial, _, _, tpenv = TcVal true cenv env tpenv vref None (Some afterResolution) mItem - let vexpFlex = (if isSpecial then MakeApplicableExprNoFlex cenv vexp else MakeApplicableExprWithFlex cenv env vexp) + let _, vExpr, isSpecial, _, _, tpenv = TcVal true cenv env tpenv vref None (Some afterResolution) mItem + let vexpFlex = (if isSpecial then MakeApplicableExprNoFlex cenv vExpr else MakeApplicableExprWithFlex cenv env vExpr) PropagateThenTcDelayed cenv overallTy env tpenv mItem vexpFlex vexpFlex.Type ExprAtomicFlag.Atomic delayed and TcPropertyItemThen cenv overallTy env nm pinfos tpenv mItem afterResolution delayed = @@ -9029,8 +9054,8 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela PropagateThenTcDelayed cenv overallTy env tpenv mExprAndItem (MakeApplicableExprWithFlex cenv env objExpr') fieldTy ExprAtomicFlag.Atomic delayed | Item.AnonRecdField (anonInfo, tinst, n, _) -> - let tgty = TType_anon (anonInfo, tinst) - AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css mItem NoTrace tgty objExprTy + let tgtTy = TType_anon (anonInfo, tinst) + AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css mItem NoTrace tgtTy objExprTy let fieldTy = List.item n tinst match delayed with | DelayedSet _ :: _otherDelayed -> @@ -9082,7 +9107,7 @@ and TcEventItemThen cenv overallTy env tpenv mItem mExprAndItem objDetails (einf MethInfoChecks g cenv.amap true None objArgs env.eAccessRights mItem delInvokeMeth // This checks for and drops the 'object' sender - let argsTy = ArgsTypOfEventInfo cenv.infoReader mItem ad einfo + let argsTy = ArgsTypeOfEventInfo cenv.infoReader mItem ad einfo if not (slotSigHasVoidReturnTy (delInvokeMeth.GetSlotSig(cenv.amap, mItem))) then errorR (nonStandardEventError einfo.EventName mItem) let delEventTy = mkIEventType g delTy argsTy @@ -10214,7 +10239,7 @@ and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt | [] -> valSynData | {Range=mHead} :: _ -> let (SynValData(valMf, SynValInfo(args, SynArgInfo(attrs, opt, retId)), valId)) = valSynData - in SynValData(valMf, SynValInfo(args, SynArgInfo({Attributes=rotRetSynAttrs; Range=mHead} :: attrs, opt, retId)), valId) + SynValData(valMf, SynValInfo(args, SynArgInfo({Attributes=rotRetSynAttrs; Range=mHead} :: attrs, opt, retId)), valId) retAttribs, valAttribs, valSynData let isVolatile = HasFSharpAttribute g g.attrib_VolatileFieldAttribute valAttribs @@ -10764,7 +10789,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds // If the overall declaration is declaring statics or a module value, then force the patternInputTmp to also // have representation as module value. - if (DeclKind.MustHaveArity declKind) then + if DeclKind.MustHaveArity declKind then AdjustValToTopVal tmp altActualParent (InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes tmp rhsExpr) tmp, checkedPat @@ -11239,14 +11264,13 @@ and AnalyzeRecursiveDecl let rec analyzeRecursiveDeclPat tpenv pat = match pat with - | SynPat.FromParseError(pat', _) -> analyzeRecursiveDeclPat tpenv pat' - | SynPat.Typed(pat', cty, _) -> - let ctyR, tpenv = TcTypeAndRecover cenv NewTyparsOK CheckCxs ItemOccurence.UseInType envinner tpenv cty + | SynPat.FromParseError(innerPat, _) -> analyzeRecursiveDeclPat tpenv innerPat + | SynPat.Typed(innerPat, tgtTy, _) -> + let ctyR, tpenv = TcTypeAndRecover cenv NewTyparsOK CheckCxs ItemOccurence.UseInType envinner tpenv tgtTy UnifyTypes cenv envinner mBinding ty ctyR - analyzeRecursiveDeclPat tpenv pat' - | SynPat.Attrib(_pat', _attribs, m) -> + analyzeRecursiveDeclPat tpenv innerPat + | SynPat.Attrib(_innerPat, _attribs, m) -> error(Error(FSComp.SR.tcAttributesInvalidInPatterns(), m)) - //analyzeRecursiveDeclPat pat' // This is for the construct 'let rec x = ... and do ... and y = ...' (DEPRECATED IN pars.mly ) // @@ -11340,9 +11364,9 @@ and AnalyzeAndMakeAndPublishRecursiveValue // NOTE: top arity, type and typars get fixed-up after inference let prelimTyscheme = GeneralizedType(enclosingDeclaredTypars@declaredTypars, ty) let prelimValReprInfo = TranslateSynValInfo mBinding (TcAttributes cenv envinner) valSynInfo - let valReprInfo = UseSyntacticArity declKind prelimTyscheme prelimValReprInfo + let valReprInfo, valReprInfoForDisplay = UseSyntacticArity declKind prelimTyscheme prelimValReprInfo let hasDeclaredTypars = not (List.isEmpty declaredTypars) - let prelimValScheme = ValScheme(bindingId, prelimTyscheme, valReprInfo, memberInfoOpt, false, inlineFlag, NormalVal, vis, false, false, false, hasDeclaredTypars) + let prelimValScheme = ValScheme(bindingId, prelimTyscheme, valReprInfo, valReprInfoForDisplay, memberInfoOpt, false, inlineFlag, NormalVal, vis, false, false, false, hasDeclaredTypars) // Check the literal r.h.s., if any let _, literalValue = TcLiteral cenv ty envinner tpenv (bindingAttribs, bindingExpr) diff --git a/src/Compiler/Checking/CheckExpressions.fsi b/src/Compiler/Checking/CheckExpressions.fsi index 5ad78d6f5c0..2a83a61d50f 100644 --- a/src/Compiler/Checking/CheckExpressions.fsi +++ b/src/Compiler/Checking/CheckExpressions.fsi @@ -584,12 +584,13 @@ type RecursiveBindingInfo = [] type CheckedBindingInfo -/// Represnts the results of the second phase of checking simple values +/// Represents the results of the second phase of checking simple values type ValScheme = | ValScheme of id: Ident * typeScheme: GeneralizedType * valReprInfo: ValReprInfo option * + valReprInfoForDisplay: ValReprInfo option * memberInfo: PrelimMemberInfo option * isMutable: bool * inlineInfo: ValInline * @@ -783,7 +784,7 @@ val InferGenericArityFromTyScheme: GeneralizedType -> prelimValReprInfo: PrelimV /// Locate the environment within a particular namespace path, used to process a /// 'namespace' declaration. -val LocateEnv: ccu: CcuThunk -> env: TcEnv -> enclosingNamespacePath: Ident list -> TcEnv +val LocateEnv: isModule: bool -> ccu: CcuThunk -> env: TcEnv -> enclosingNamespacePath: Ident list -> TcEnv /// Make the check for safe initialization of a member val MakeCheckSafeInit: @@ -1179,7 +1180,7 @@ val TcPatLongIdentActivePatternCase: vFlags: TcPatValFlags -> patEnv: TcPatLinearEnv -> ty: TType -> - lidRange: range * item: Item * apref: ActivePatternElemRef * args: SynPat list * m: range -> + mLongId: range * item: Item * apref: ActivePatternElemRef * args: SynPat list * m: range -> (TcPatPhase2Input -> Pattern) * TcPatLinearEnv /// The pattern syntax can also represent active pattern arguments. This routine diff --git a/src/Compiler/Checking/CheckFormatStrings.fs b/src/Compiler/Checking/CheckFormatStrings.fs index f4a2e6f880a..96fb19c172e 100644 --- a/src/Compiler/Checking/CheckFormatStrings.fs +++ b/src/Compiler/Checking/CheckFormatStrings.fs @@ -22,9 +22,9 @@ let copyAndFixupFormatTypar m tp = let lowestDefaultPriority = 0 (* See comment on TyparConstraint.DefaultsTo *) -let mkFlexibleFormatTypar m tys dflt = +let mkFlexibleFormatTypar m tys dfltTy = let tp = Construct.NewTypar (TyparKind.Type, TyparRigidity.Rigid, SynTypar(mkSynId m "fmt",TyparStaticReq.HeadType,true),false,TyparDynamicReq.Yes,[],false,false) - tp.SetConstraints [ TyparConstraint.SimpleChoice (tys,m); TyparConstraint.DefaultsTo (lowestDefaultPriority,dflt,m)] + tp.SetConstraints [ TyparConstraint.SimpleChoice (tys,m); TyparConstraint.DefaultsTo (lowestDefaultPriority,dfltTy,m)] copyAndFixupFormatTypar m tp let mkFlexibleIntFormatTypar (g: TcGlobals) m = @@ -452,19 +452,19 @@ let parseFormatStringInternal | Some '+' -> collectSpecifierLocation fragLine fragCol 1 let i = skipPossibleInterpolationHole (i+1) - let xty = NewInferenceType g - percentATys.Add(xty) - parseLoop ((posi, xty) :: acc) (i, fragLine, fragCol+1) fragments + let aTy = NewInferenceType g + percentATys.Add(aTy) + parseLoop ((posi, aTy) :: acc) (i, fragLine, fragCol+1) fragments | Some n -> failwith (FSComp.SR.forDoesNotSupportPrefixFlag(ch.ToString(), n.ToString())) | 'a' -> checkOtherFlags ch - let xty = NewInferenceType g - let fty = mkFunTy g printerArgTy (mkFunTy g xty printerResidueTy) + let aTy = NewInferenceType g + let fTy = mkFunTy g printerArgTy (mkFunTy g aTy printerResidueTy) collectSpecifierLocation fragLine fragCol 2 let i = skipPossibleInterpolationHole (i+1) - parseLoop ((Option.map ((+)1) posi, xty) :: (posi, fty) :: acc) (i, fragLine, fragCol+1) fragments + parseLoop ((Option.map ((+)1) posi, aTy) :: (posi, fTy) :: acc) (i, fragLine, fragCol+1) fragments | 't' -> checkOtherFlags ch diff --git a/src/Compiler/Checking/CheckIncrementalClasses.fs b/src/Compiler/Checking/CheckIncrementalClasses.fs new file mode 100644 index 00000000000..f225a9927e8 --- /dev/null +++ b/src/Compiler/Checking/CheckIncrementalClasses.fs @@ -0,0 +1,892 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module internal FSharp.Compiler.CheckIncrementalClasses + +open System + +open Internal.Utilities.Collections +open Internal.Utilities.Library +open Internal.Utilities.Library.Extras +open FSharp.Compiler.CheckExpressions +open FSharp.Compiler.CheckPatterns +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.DiagnosticsLogger +open FSharp.Compiler.NameResolution +open FSharp.Compiler.Syntax +open FSharp.Compiler.SyntaxTrivia +open FSharp.Compiler.SyntaxTreeOps +open FSharp.Compiler.Text +open FSharp.Compiler.Xml +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeBasics +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.TypeHierarchy + +type cenv = TcFileState + +let TcClassRewriteStackGuardDepth = StackGuard.GetDepthOption "TcClassRewrite" + +exception ParameterlessStructCtor of range: range + +/// Represents a single group of bindings in a class with an implicit constructor +type IncrClassBindingGroup = + | IncrClassBindingGroup of bindings: Binding list * isStatic: bool* isRecursive: bool + | IncrClassDo of expr: Expr * isStatic: bool * range: Range + +/// Typechecked info for implicit constructor and it's arguments +type IncrClassCtorLhs = + { + /// The TyconRef for the type being defined + TyconRef: TyconRef + + /// The type parameters allocated for the implicit instance constructor. + /// These may be equated with other (WillBeRigid) type parameters through equi-recursive inference, and so + /// should always be renormalized/canonicalized when used. + InstanceCtorDeclaredTypars: Typars + + /// The value representing the static implicit constructor. + /// Lazy to ensure the static ctor value is only published if needed. + StaticCtorValInfo: Lazy + + /// The value representing the implicit constructor. + InstanceCtorVal: Val + + /// The type of the implicit constructor, representing as a ValScheme. + InstanceCtorValScheme: ValScheme + + /// The values representing the arguments to the implicit constructor. + InstanceCtorArgs: Val list + + /// The reference cell holding the 'this' parameter within the implicit constructor so it can be referenced in the + /// arguments passed to the base constructor + InstanceCtorSafeThisValOpt: Val option + + /// Data indicating if safe-initialization checks need to be inserted for this type. + InstanceCtorSafeInitInfo: SafeInitData + + /// The value representing the 'base' variable within the implicit instance constructor. + InstanceCtorBaseValOpt: Val option + + /// The value representing the 'this' variable within the implicit instance constructor. + InstanceCtorThisVal: Val + + /// The name generator used to generate the names of fields etc. within the type. + NameGenerator: NiceNameGenerator + } + + /// Get the type parameters of the implicit constructor, after taking equi-recursive inference into account. + member ctorInfo.GetNormalizedInstanceCtorDeclaredTypars (cenv: cenv) denv m = + let g = cenv.g + let ctorDeclaredTypars = ctorInfo.InstanceCtorDeclaredTypars + let ctorDeclaredTypars = ChooseCanonicalDeclaredTyparsAfterInference g denv ctorDeclaredTypars m + ctorDeclaredTypars + +/// Check and elaborate the "left hand side" of the implicit class construction +/// syntax. +let TcImplicitCtorLhs_Phase2A(cenv: cenv, env, tpenv, tcref: TyconRef, vis, attrs, spats, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy, xmlDoc: PreXmlDoc) = + + let g = cenv.g + let baseValOpt = + match GetSuperTypeOfType g cenv.amap m objTy with + | Some superTy -> MakeAndPublishBaseVal cenv env (match baseValOpt with None -> None | Some v -> Some v.Id) superTy + | None -> None + + // Add class typars to env + let env = AddDeclaredTypars CheckForDuplicateTypars copyOfTyconTypars env + + // Type check arguments by processing them as 'simple' patterns + // NOTE: if we allow richer patterns here this is where we'd process those patterns + let ctorArgNames, patEnv = TcSimplePatsOfUnknownType cenv true CheckCxs env tpenv (SynSimplePats.SimplePats (spats, m)) + + let (TcPatLinearEnv(_, names, _)) = patEnv + + // Create the values with the given names + let _, vspecs = MakeAndPublishSimpleVals cenv env names + + if tcref.IsStructOrEnumTycon && isNil spats then + errorR (ParameterlessStructCtor(tcref.Range)) + + // Put them in order + let ctorArgs = List.map (fun v -> NameMap.find v vspecs) ctorArgNames + let safeThisValOpt = MakeAndPublishSafeThisVal cenv env thisIdOpt thisTy + + // NOTE: the type scheme here is not complete!!! The ctorTy is more or less + // just a type variable. The type and typars get fixed-up after inference + let ctorValScheme, ctorVal = + let argTy = mkRefTupledTy g (typesOfVals ctorArgs) + + // Initial type has known information + let ctorTy = mkFunTy g argTy objTy + + // NOTE: no attributes can currently be specified for the implicit constructor + let attribs = TcAttributes cenv env (AttributeTargets.Constructor ||| AttributeTargets.Method) attrs + let memberFlags = CtorMemberFlags SynMemberFlagsTrivia.Zero + + let synArgInfos = List.map (SynInfo.InferSynArgInfoFromSimplePat []) spats + let valSynData = SynValInfo([synArgInfos], SynInfo.unnamedRetVal) + let id = ident ("new", m) + + CheckForNonAbstractInterface ModuleOrMemberBinding tcref memberFlags id.idRange + let memberInfo = MakeMemberDataAndMangledNameForMemberVal(g, tcref, false, attribs, [], memberFlags, valSynData, id, false) + let prelimValReprInfo = TranslateSynValInfo m (TcAttributes cenv env) valSynData + let prelimTyschemeG = GeneralizedType(copyOfTyconTypars, ctorTy) + let isComplete = ComputeIsComplete copyOfTyconTypars [] ctorTy + let varReprInfo = InferGenericArityFromTyScheme prelimTyschemeG prelimValReprInfo + let ctorValScheme = ValScheme(id, prelimTyschemeG, Some varReprInfo, None, Some memberInfo, false, ValInline.Never, NormalVal, vis, false, true, false, false) + let paramNames = varReprInfo.ArgNames + let xmlDoc = xmlDoc.ToXmlDoc(true, Some paramNames) + let ctorVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValInRecScope isComplete, ctorValScheme, attribs, xmlDoc, None, false) + ctorValScheme, ctorVal + + // We only generate the cctor on demand, because we don't need it if there are no cctor actions. + // The code below has a side-effect (MakeAndPublishVal), so we only want to run it once if at all. + // The .cctor is never referenced by any other code. + let cctorValInfo = + lazy + let cctorArgs = [ fst(mkCompGenLocal m "unitVar" g.unit_ty) ] + + let cctorTy = mkFunTy g g.unit_ty g.unit_ty + let valSynData = SynValInfo([[]], SynInfo.unnamedRetVal) + let id = ident ("cctor", m) + CheckForNonAbstractInterface ModuleOrMemberBinding tcref (ClassCtorMemberFlags SynMemberFlagsTrivia.Zero) id.idRange + let memberInfo = MakeMemberDataAndMangledNameForMemberVal(g, tcref, false, [], [], (ClassCtorMemberFlags SynMemberFlagsTrivia.Zero), valSynData, id, false) + let prelimValReprInfo = TranslateSynValInfo m (TcAttributes cenv env) valSynData + let prelimTyschemeG = GeneralizedType(copyOfTyconTypars, cctorTy) + let valReprInfo = InferGenericArityFromTyScheme prelimTyschemeG prelimValReprInfo + let cctorValScheme = ValScheme(id, prelimTyschemeG, Some valReprInfo, None, Some memberInfo, false, ValInline.Never, NormalVal, Some (SynAccess.Private Range.Zero), false, true, false, false) + + let cctorVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValNotInRecScope, cctorValScheme, [(* no attributes*)], XmlDoc.Empty, None, false) + cctorArgs, cctorVal, cctorValScheme + + let thisVal = + // --- Create this for use inside constructor + let thisId = ident ("this", m) + let thisValScheme = ValScheme(thisId, NonGenericTypeScheme thisTy, None, None, None, false, ValInline.Never, CtorThisVal, None, true, false, false, false) + let thisVal = MakeAndPublishVal cenv env (ParentNone, false, ClassLetBinding false, ValNotInRecScope, thisValScheme, [], XmlDoc.Empty, None, false) + thisVal + + { TyconRef = tcref + InstanceCtorDeclaredTypars = copyOfTyconTypars + StaticCtorValInfo = cctorValInfo + InstanceCtorArgs = ctorArgs + InstanceCtorVal = ctorVal + InstanceCtorValScheme = ctorValScheme + InstanceCtorBaseValOpt = baseValOpt + InstanceCtorSafeThisValOpt = safeThisValOpt + InstanceCtorSafeInitInfo = safeInitInfo + InstanceCtorThisVal = thisVal + // For generating names of local fields + NameGenerator = NiceNameGenerator() + } + + +// Partial class defns - local val mapping to fields + +/// Create the field for a "let" binding in a type definition. +/// +/// The "v" is the local typed w.r.t. tyvars of the implicit ctor. +/// The formalTyparInst does the formal-typars/implicit-ctor-typars subst. +/// Field specifications added to a tcref must be in terms of the tcrefs formal typars. +let private MakeIncrClassField(g, cpath, formalTyparInst: TyparInstantiation, v: Val, isStatic, rfref: RecdFieldRef) = + let name = rfref.FieldName + let id = ident (name, v.Range) + let ty = v.Type |> instType formalTyparInst + let taccess = TAccess [cpath] + let isVolatile = HasFSharpAttribute g g.attrib_VolatileFieldAttribute v.Attribs + + Construct.NewRecdField isStatic None id false ty v.IsMutable isVolatile [] v.Attribs v.XmlDoc taccess true + +/// Indicates how is a 'let' bound value in a class with implicit construction is represented in +/// the TAST ultimately produced by type checking. +type IncrClassValRepr = + + // e.g representation for 'let v = 3' if it is not used in anything given a method representation + | InVar of isArg: bool + + // e.g representation for 'let v = 3' + | InField of isStatic: bool * staticCountForSafeInit: int * fieldRef: RecdFieldRef + + // e.g representation for 'let f x = 3' + | InMethod of isStatic:bool * value: Val * valReprInfo: ValReprInfo + +/// IncrClassReprInfo represents the decisions we make about the representation of 'let' and 'do' bindings in a +/// type defined with implicit class construction. +type IncrClassReprInfo = + { + /// Indicates the set of field names taken within one incremental class + TakenFieldNames: Set + + RepInfoTcGlobals: TcGlobals + + /// vals mapped to representations + ValReprs: Zmap + + /// vals represented as fields or members from this point on + ValsWithRepresentation: Zset + } + + static member Empty(g, names) = + { TakenFieldNames=Set.ofList names + RepInfoTcGlobals=g + ValReprs = Zmap.empty valOrder + ValsWithRepresentation = Zset.empty valOrder } + + /// Find the representation of a value + member localRep.LookupRepr (v: Val) = + match Zmap.tryFind v localRep.ValReprs with + | None -> error(InternalError("LookupRepr: failed to find representation for value", v.Range)) + | Some res -> res + + static member IsMethodRepr (cenv: cenv) (bind: Binding) = + let g = cenv.g + let v = bind.Var + // unit fields are not stored, just run rhs for effects + if isUnitTy g v.Type then + false + else + let arity = InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v bind.Expr + not arity.HasNoArgs && not v.IsMutable + + + /// + /// Choose how a binding is represented + /// + /// + /// + /// + /// + /// + /// The vars forced to be fields due to static member bindings, instance initialization expressions or instance member bindings + /// The vars forced to be fields due to instance member bindings + /// + /// + member localRep.ChooseRepresentation (cenv: cenv, env: TcEnv, isStatic, isCtorArg, + ctorInfo: IncrClassCtorLhs, + staticForcedFieldVars: FreeLocals, + instanceForcedFieldVars: FreeLocals, + takenFieldNames: Set, + bind: Binding) = + let g = cenv.g + let v = bind.Var + let relevantForcedFieldVars = (if isStatic then staticForcedFieldVars else instanceForcedFieldVars) + + let tcref = ctorInfo.TyconRef + let name, takenFieldNames = + + let isNameTaken = + // Check if a implicit field already exists with this name + takenFieldNames.Contains(v.LogicalName) || + // Check if a user-defined field already exists with this name. Struct fields have already been created - see bug FSharp 1.0 5304 + (tcref.GetFieldByName(v.LogicalName).IsSome && (isStatic || not tcref.IsFSharpStructOrEnumTycon)) + + let nm = + if isNameTaken then + ctorInfo.NameGenerator.FreshCompilerGeneratedName (v.LogicalName, v.Range) + else + v.LogicalName + nm, takenFieldNames.Add nm + + let reportIfUnused() = + if not v.HasBeenReferenced && not v.IsCompiledAsTopLevel && not (v.DisplayName.StartsWithOrdinal("_")) && not v.IsCompilerGenerated then + warning (Error(FSComp.SR.chkUnusedValue(v.DisplayName), v.Range)) + + let repr = + match InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v bind.Expr with + | arity when arity.HasNoArgs || v.IsMutable -> + // all mutable variables are forced into fields, since they may escape into closures within the implicit constructor + // e.g. + // type C() = + // let mutable m = 1 + // let n = ... (fun () -> m) .... + // + // All struct variables are forced into fields. Structs may not contain "let" bindings, so no new variables can be + // introduced. + + if v.IsMutable || relevantForcedFieldVars.Contains v || tcref.IsStructOrEnumTycon then + //dprintfn "Representing %s as a field %s" v.LogicalName name + let rfref = RecdFieldRef(tcref, name) + reportIfUnused() + InField (isStatic, localRep.ValReprs.Count, rfref) + else + //if not v.Attribs.IsEmpty then + // warning(Error(FSComp.SR.tcAttributesIgnoredOnLetBinding(), v.Range)) + //dprintfn + // "Representing %s as a local variable %s, staticForcedFieldVars = %s, instanceForcedFieldVars = %s" + // v.LogicalName name + // (staticForcedFieldVars |> Seq.map (fun v -> v.LogicalName) |> String.concat ",") + // (instanceForcedFieldVars |> Seq.map (fun v -> v.LogicalName) |> String.concat ",") + InVar isCtorArg + | valReprInfo -> + //dprintfn "Representing %s as a method %s" v.LogicalName name + let tps, _, argInfos, _, _ = GetTopValTypeInCompiledForm g valReprInfo 0 v.Type v.Range + + let valSynInfo = SynValInfo(argInfos |> List.mapSquared (fun (_, argInfo) -> SynArgInfo([], false, argInfo.Name)), SynInfo.unnamedRetVal) + let memberFlags = (if isStatic then StaticMemberFlags else NonVirtualMemberFlags) SynMemberFlagsTrivia.Zero SynMemberKind.Member + let id = mkSynId v.Range name + let memberInfo = MakeMemberDataAndMangledNameForMemberVal(g, tcref, false, [], [], memberFlags, valSynInfo, mkSynId v.Range name, true) + + let copyOfTyconTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv env.DisplayEnv ctorInfo.TyconRef.Range + + AdjustValToTopVal v (Parent tcref) valReprInfo + + // Add the 'this' pointer on to the function + let memberTauTy, valReprInfo = + let tauTy = v.TauType + if isStatic then + tauTy, valReprInfo + else + let tauTy = mkFunTy g ctorInfo.InstanceCtorThisVal.Type v.TauType + let (ValReprInfo(tpNames, args, ret)) = valReprInfo + let valReprInfo = ValReprInfo(tpNames, ValReprInfo.selfMetadata :: args, ret) + tauTy, valReprInfo + + // Add the enclosing type parameters on to the function + let valReprInfo = + let (ValReprInfo(tpNames, args, ret)) = valReprInfo + ValReprInfo(tpNames@ValReprInfo.InferTyparInfo copyOfTyconTypars, args, ret) + + let prelimTyschemeG = GeneralizedType(copyOfTyconTypars@tps, memberTauTy) + + // NOTE: putting isCompilerGenerated=true here is strange. The method is not public, nor is + // it a "member" in the F# sense, but the F# spec says it is generated and it is reasonable to reflect on it. + let memberValScheme = ValScheme(id, prelimTyschemeG, Some valReprInfo, None, Some memberInfo, false, ValInline.Never, NormalVal, None, true (* isCompilerGenerated *), true (* isIncrClass *), false, false) + + let methodVal = MakeAndPublishVal cenv env (Parent tcref, false, ModuleOrMemberBinding, ValNotInRecScope, memberValScheme, v.Attribs, XmlDoc.Empty, None, false) + + reportIfUnused() + InMethod(isStatic, methodVal, valReprInfo) + + repr, takenFieldNames + + /// Extend the known local representations by choosing a representation for a binding + member localRep.ChooseAndAddRepresentation(cenv: cenv, env: TcEnv, isStatic, isCtorArg, ctorInfo: IncrClassCtorLhs, staticForcedFieldVars: FreeLocals, instanceForcedFieldVars: FreeLocals, bind: Binding) = + let v = bind.Var + let repr, takenFieldNames = localRep.ChooseRepresentation (cenv, env, isStatic, isCtorArg, ctorInfo, staticForcedFieldVars, instanceForcedFieldVars, localRep.TakenFieldNames, bind ) + // OK, representation chosen, now add it + {localRep with + TakenFieldNames=takenFieldNames + ValReprs = Zmap.add v repr localRep.ValReprs} + + member localRep.ValNowWithRepresentation (v: Val) = + {localRep with ValsWithRepresentation = Zset.add v localRep.ValsWithRepresentation} + + member localRep.IsValWithRepresentation (v: Val) = + localRep.ValsWithRepresentation.Contains v + + member localRep.IsValRepresentedAsLocalVar (v: Val) = + match localRep.LookupRepr v with + | InVar false -> true + | _ -> false + + member localRep.IsValRepresentedAsMethod (v: Val) = + localRep.IsValWithRepresentation v && + match localRep.LookupRepr v with + | InMethod _ -> true + | _ -> false + + /// Make the elaborated expression that represents a use of a + /// a "let v = ..." class binding + member localRep.MakeValueLookup thisValOpt tinst safeStaticInitInfo v tyargs m = + let g = localRep.RepInfoTcGlobals + match localRep.LookupRepr v, thisValOpt with + | InVar _, _ -> + exprForVal m v + | InField(false, _idx, rfref), Some thisVal -> + let thise = exprForVal m thisVal + mkRecdFieldGetViaExprAddr (thise, rfref, tinst, m) + | InField(false, _idx, _rfref), None -> + error(InternalError("Unexpected missing 'this' variable in MakeValueLookup", m)) + | InField(true, idx, rfref), _ -> + let expr = mkStaticRecdFieldGet (rfref, tinst, m) + MakeCheckSafeInit g tinst safeStaticInitInfo (mkInt g m idx) expr + + | InMethod(isStatic, methodVal, valReprInfo), _ -> + //dprintfn "Rewriting application of %s to be call to method %s" v.LogicalName methodVal.LogicalName + let expr, exprTy = AdjustValForExpectedArity g m (mkLocalValRef methodVal) NormalValUse valReprInfo + // Prepend the the type arguments for the class + let tyargs = tinst @ tyargs + let thisArgs = + if isStatic then [] + else Option.toList (Option.map (exprForVal m) thisValOpt) + + MakeApplicationAndBetaReduce g (expr, exprTy, [tyargs], thisArgs, m) + + /// Make the elaborated expression that represents an assignment + /// to a "let mutable v = ..." class binding + member localRep.MakeValueAssign thisValOpt tinst safeStaticInitInfo v expr m = + let g = localRep.RepInfoTcGlobals + match localRep.LookupRepr v, thisValOpt with + | InField(false, _, rfref), Some thisVal -> + let thise = exprForVal m thisVal + mkRecdFieldSetViaExprAddr(thise, rfref, tinst, expr, m) + | InField(false, _, _rfref), None -> + error(InternalError("Unexpected missing 'this' variable in MakeValueAssign", m)) + | InVar _, _ -> + mkValSet m (mkLocalValRef v) expr + | InField (true, idx, rfref), _ -> + let expr = mkStaticRecdFieldSet(rfref, tinst, expr, m) + MakeCheckSafeInit g tinst safeStaticInitInfo (mkInt g m idx) expr + | InMethod _, _ -> + error(InternalError("Local was given method storage, yet later it's been assigned to", m)) + + member localRep.MakeValueGetAddress readonly thisValOpt tinst safeStaticInitInfo v m = + let g = localRep.RepInfoTcGlobals + match localRep.LookupRepr v, thisValOpt with + | InField(false, _, rfref), Some thisVal -> + let thise = exprForVal m thisVal + mkRecdFieldGetAddrViaExprAddr(readonly, thise, rfref, tinst, m) + | InField(false, _, _rfref), None -> + error(InternalError("Unexpected missing 'this' variable in MakeValueGetAddress", m)) + | InField(true, idx, rfref), _ -> + let expr = mkStaticRecdFieldGetAddr(readonly, rfref, tinst, m) + MakeCheckSafeInit g tinst safeStaticInitInfo (mkInt g m idx) expr + | InVar _, _ -> + mkValAddr m readonly (mkLocalValRef v) + | InMethod _, _ -> + error(InternalError("Local was given method storage, yet later it's address was required", m)) + + /// Mutate a type definition by adding fields + /// Used as part of processing "let" bindings in a type definition. + member localRep.PublishIncrClassFields (cenv, denv, cpath, ctorInfo: IncrClassCtorLhs, safeStaticInitInfo) = + let tcref = ctorInfo.TyconRef + let rfspecs = + [ for KeyValue(v, repr) in localRep.ValReprs do + match repr with + | InField(isStatic, _, rfref) -> + // Instance fields for structs are published earlier because the full set of fields is determined syntactically from the implicit + // constructor arguments. This is important for the "default value" and "does it have an implicit default constructor" + // semantic conditions for structs - see bug FSharp 1.0 5304. + if isStatic || not tcref.IsFSharpStructOrEnumTycon then + let ctorDeclaredTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv ctorInfo.TyconRef.Range + + // Note: tcrefObjTy contains the original "formal" typars, thisTy is the "fresh" one... f<>fresh. + let revTypeInst = List.zip ctorDeclaredTypars (tcref.TyparsNoRange |> List.map mkTyparTy) + + yield MakeIncrClassField(localRep.RepInfoTcGlobals, cpath, revTypeInst, v, isStatic, rfref) + | _ -> + () + + match safeStaticInitInfo with + | SafeInitField (_, fld) -> yield fld + | NoSafeInitInfo -> () ] + + let recdFields = Construct.MakeRecdFieldsTable (rfspecs @ tcref.AllFieldsAsList) + + // Mutate the entity_tycon_repr to publish the fields + tcref.Deref.entity_tycon_repr <- TFSharpObjectRepr { tcref.FSharpObjectModelTypeInfo with fsobjmodel_rfields = recdFields} + + + /// Given localRep saying how locals have been represented, e.g. as fields. + /// Given an expr under a given thisVal context. + // + // Fix up the references to the locals, e.g. + // v -> this.fieldv + // f x -> this.method x + member localRep.FixupIncrClassExprPhase2C cenv thisValOpt safeStaticInitInfo (thisTyInst: TypeInst) expr = + // fixup: intercept and expr rewrite + let FixupExprNode rw e = + //dprintfn "Fixup %s" (showL (exprL e)) + let g = localRep.RepInfoTcGlobals + let e = NormalizeAndAdjustPossibleSubsumptionExprs g e + match e with + // Rewrite references to applied let-bound-functions-compiled-as-methods + // Rewrite references to applied recursive let-bound-functions-compiled-as-methods + // Rewrite references to applied recursive generic let-bound-functions-compiled-as-methods + | Expr.App (Expr.Val (ValDeref v, _, _), _, tyargs, args, m) + | Expr.App (Expr.Link {contents = Expr.Val (ValDeref v, _, _) }, _, tyargs, args, m) + | Expr.App (Expr.Link {contents = Expr.App (Expr.Val (ValDeref v, _, _), _, tyargs, [], _) }, _, [], args, m) + when localRep.IsValRepresentedAsMethod v && not (cenv.recUses.ContainsKey v) -> + + let expr = localRep.MakeValueLookup thisValOpt thisTyInst safeStaticInitInfo v tyargs m + let args = args |> List.map rw + Some (MakeApplicationAndBetaReduce g (expr, (tyOfExpr g expr), [], args, m)) + + // Rewrite references to values stored as fields and first class uses of method values + | Expr.Val (ValDeref v, _, m) + when localRep.IsValWithRepresentation v -> + + //dprintfn "Found use of %s" v.LogicalName + Some (localRep.MakeValueLookup thisValOpt thisTyInst safeStaticInitInfo v [] m) + + // Rewrite assignments to mutable values stored as fields + | Expr.Op (TOp.LValueOp (LSet, ValDeref v), [], [arg], m) + when localRep.IsValWithRepresentation v -> + let arg = rw arg + Some (localRep.MakeValueAssign thisValOpt thisTyInst safeStaticInitInfo v arg m) + + // Rewrite taking the address of mutable values stored as fields + | Expr.Op (TOp.LValueOp (LAddrOf readonly, ValDeref v), [], [], m) + when localRep.IsValWithRepresentation v -> + Some (localRep.MakeValueGetAddress readonly thisValOpt thisTyInst safeStaticInitInfo v m) + + | _ -> None + + RewriteExpr { PreIntercept = Some FixupExprNode + PostTransform = (fun _ -> None) + PreInterceptBinding = None + RewriteQuotations = true + StackGuard = StackGuard(TcClassRewriteStackGuardDepth) } expr + +type IncrClassConstructionBindingsPhase2C = + | Phase2CBindings of IncrClassBindingGroup list + | Phase2CCtorJustAfterSuperInit + | Phase2CCtorJustAfterLastLet + +/// +/// Given a set of 'let' bindings (static or not, recursive or not) that make up a class, +/// generate their initialization expression(s). +/// +/// +/// +/// The lhs information about the implicit constructor +/// The call to the super class constructor +/// Should we place a sequence point at the 'inheritedTys call? +/// The declarations +/// +/// Record any unconstrained type parameters generalized for the outer members as "free choices" in the let bindings +/// +let MakeCtorForIncrClassConstructionPhase2C( + cenv: cenv, + env: TcEnv, + ctorInfo: IncrClassCtorLhs, + inheritsExpr, + inheritsIsVisible, + decs: IncrClassConstructionBindingsPhase2C list, + memberBinds: Binding list, + generalizedTyparsForRecursiveBlock, + safeStaticInitInfo: SafeInitData +) = + + + let denv = env.DisplayEnv + let g = cenv.g + let thisVal = ctorInfo.InstanceCtorThisVal + + let m = thisVal.Range + let ctorDeclaredTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv m + + ctorDeclaredTypars |> List.iter (SetTyparRigid env.DisplayEnv m) + + // Reconstitute the type with the correct quantified type variables. + ctorInfo.InstanceCtorVal.SetType (mkForallTyIfNeeded ctorDeclaredTypars ctorInfo.InstanceCtorVal.TauType) + + let freeChoiceTypars = ListSet.subtract typarEq generalizedTyparsForRecursiveBlock ctorDeclaredTypars + + let thisTyInst = List.map mkTyparTy ctorDeclaredTypars + + let accFreeInExpr acc expr = + unionFreeVars acc (freeInExpr CollectLocalsNoCaching expr) + + let accFreeInBinding acc (bind: Binding) = + accFreeInExpr acc bind.Expr + + let accFreeInBindings acc (binds: Binding list) = + (acc, binds) ||> List.fold accFreeInBinding + + // Find all the variables used in any method. These become fields. + // staticForcedFieldVars: FreeLocals: the vars forced to be fields due to static member bindings, instance initialization expressions or instance member bindings + // instanceForcedFieldVars: FreeLocals: the vars forced to be fields due to instance member bindings + + let staticForcedFieldVars, instanceForcedFieldVars = + let staticForcedFieldVars, instanceForcedFieldVars = + ((emptyFreeVars, emptyFreeVars), decs) ||> List.fold (fun (staticForcedFieldVars, instanceForcedFieldVars) dec -> + match dec with + | Phase2CCtorJustAfterLastLet + | Phase2CCtorJustAfterSuperInit -> + (staticForcedFieldVars, instanceForcedFieldVars) + | Phase2CBindings decs -> + ((staticForcedFieldVars, instanceForcedFieldVars), decs) ||> List.fold (fun (staticForcedFieldVars, instanceForcedFieldVars) dec -> + match dec with + | IncrClassBindingGroup(binds, isStatic, _) -> + let methodBinds = binds |> List.filter (IncrClassReprInfo.IsMethodRepr cenv) + let staticForcedFieldVars = + if isStatic then + // Any references to static variables in any static method force the variable to be represented as a field + (staticForcedFieldVars, methodBinds) ||> accFreeInBindings + else + // Any references to static variables in any instance bindings force the variable to be represented as a field + (staticForcedFieldVars, binds) ||> accFreeInBindings + + let instanceForcedFieldVars = + // Any references to instance variables in any methods force the variable to be represented as a field + (instanceForcedFieldVars, methodBinds) ||> accFreeInBindings + + (staticForcedFieldVars, instanceForcedFieldVars) + | IncrClassDo (e, isStatic, _) -> + let staticForcedFieldVars = + if isStatic then + staticForcedFieldVars + else + unionFreeVars staticForcedFieldVars (freeInExpr CollectLocalsNoCaching e) + (staticForcedFieldVars, instanceForcedFieldVars))) + let staticForcedFieldVars = (staticForcedFieldVars, memberBinds) ||> accFreeInBindings + let instanceForcedFieldVars = (instanceForcedFieldVars, memberBinds) ||> accFreeInBindings + + // Any references to static variables in the 'inherits' expression force those static variables to be represented as fields + let staticForcedFieldVars = (staticForcedFieldVars, inheritsExpr) ||> accFreeInExpr + + (staticForcedFieldVars.FreeLocals, instanceForcedFieldVars.FreeLocals) + + + // Compute the implicit construction side effects of single + // 'let' or 'let rec' binding in the implicit class construction sequence + let TransBind (reps: IncrClassReprInfo) (TBind(v, rhsExpr, spBind)) = + if v.MustInline then + error(Error(FSComp.SR.tcLocalClassBindingsCannotBeInline(), v.Range)) + let rhsExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst rhsExpr + + // The initialization of the 'ref cell' variable for 'this' is the only binding which comes prior to the super init + let isPriorToSuperInit = + match ctorInfo.InstanceCtorSafeThisValOpt with + | None -> false + | Some v2 -> valEq v v2 + + match reps.LookupRepr v with + | InMethod(isStatic, methodVal, _) -> + let _, chooseTps, tauExpr, tauTy, m = + match rhsExpr with + | Expr.TyChoose (chooseTps, b, _) -> [], chooseTps, b, (tyOfExpr g b), m + | Expr.TyLambda (_, tps, Expr.TyChoose (chooseTps, b, _), m, returnTy) -> tps, chooseTps, b, returnTy, m + | Expr.TyLambda (_, tps, b, m, returnTy) -> tps, [], b, returnTy, m + | e -> [], [], e, (tyOfExpr g e), e.Range + + let chooseTps = chooseTps @ (ListSet.subtract typarEq freeChoiceTypars methodVal.Typars) + + // Add the 'this' variable as an argument + let tauExpr, tauTy = + if isStatic then + tauExpr, tauTy + else + let e = mkLambda m thisVal (tauExpr, tauTy) + e, tyOfExpr g e + + // Replace the type parameters that used to be on the rhs with + // the full set of type parameters including the type parameters of the enclosing class + let rhsExpr = mkTypeLambda m methodVal.Typars (mkTypeChoose m chooseTps tauExpr, tauTy) + (isPriorToSuperInit, id), [TBind (methodVal, rhsExpr, spBind)] + + // If it's represented as a non-escaping local variable then just bind it to its value + // If it's represented as a non-escaping local arg then no binding necessary (ctor args are already bound) + + | InVar isArg -> + (isPriorToSuperInit, (fun e -> if isArg then e else mkLetBind m (TBind(v, rhsExpr, spBind)) e)), [] + + | InField (isStatic, idx, _) -> + // Use spBind if it available as the span for the assignment into the field + let m = + match spBind, rhsExpr with + // Don't generate big sequence points for functions in classes + | _, (Expr.Lambda _ | Expr.TyLambda _) -> v.Range + | DebugPointAtBinding.Yes m, _ -> m + | _ -> v.Range + + let assignExpr = reps.MakeValueAssign (Some thisVal) thisTyInst NoSafeInitInfo v rhsExpr m + + let adjustSafeInitFieldExprOpt = + if isStatic then + match safeStaticInitInfo with + | SafeInitField (rfref, _) -> + let setExpr = mkStaticRecdFieldSet (rfref, thisTyInst, mkInt g m idx, m) + let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) NoSafeInitInfo thisTyInst setExpr + Some setExpr + | NoSafeInitInfo -> + None + else + None + + (isPriorToSuperInit, (fun e -> + let e = + match adjustSafeInitFieldExprOpt with + | None -> e + | Some adjustExpr -> mkCompGenSequential m adjustExpr e + + let assignExpr = + match spBind with + | DebugPointAtBinding.Yes _ -> mkDebugPoint m assignExpr + | _ -> assignExpr + + mkSequential m assignExpr e)), [] + + /// Work out the implicit construction side effects of a 'let', 'let rec' or 'do' + /// binding in the implicit class construction sequence + let TransTrueDec isCtorArg (reps: IncrClassReprInfo) dec = + match dec with + | IncrClassBindingGroup(binds, isStatic, isRec) -> + let actions, reps, methodBinds = + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ChooseAndAddRepresentation(cenv, env, isStatic, isCtorArg, ctorInfo, staticForcedFieldVars, instanceForcedFieldVars, bind)) // extend + if isRec then + // Note: the recursive calls are made via members on the object + // or via access to fields. This means the recursive loop is "broken", + // and we can collapse to sequential bindings + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // in scope before + let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip // since can occur in RHS of own defns + actions, reps, methodBinds + else + let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // in scope after + actions, reps, methodBinds + let methodBinds = List.concat methodBinds + if isStatic then + (actions, [], methodBinds), reps + else + ([], actions, methodBinds), reps + + | IncrClassDo (doExpr, isStatic, mFull) -> + let doExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst doExpr + // Extend the range of any immediate debug point to include the 'do' + let doExpr = + match doExpr with + | Expr.DebugPoint(_, innerExpr) -> Expr.DebugPoint(DebugPointAtLeafExpr.Yes mFull, innerExpr) + | e -> e + let binder = (fun e -> mkSequential mFull doExpr e) + let isPriorToSuperInit = false + if isStatic then + ([(isPriorToSuperInit, binder)], [], []), reps + else + ([], [(isPriorToSuperInit, binder)], []), reps + + + /// Work out the implicit construction side effects of each declaration + /// in the implicit class construction sequence + let TransDec (reps: IncrClassReprInfo) dec = + match dec with + // The call to the base class constructor is done so we can set the ref cell + | Phase2CCtorJustAfterSuperInit -> + let binders = + [ match ctorInfo.InstanceCtorSafeThisValOpt with + | None -> () + | Some v -> + let setExpr = mkRefCellSet g m ctorInfo.InstanceCtorThisVal.Type (exprForVal m v) (exprForVal m ctorInfo.InstanceCtorThisVal) + let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst setExpr + let binder = (fun e -> mkSequential setExpr.Range setExpr e) + let isPriorToSuperInit = false + yield (isPriorToSuperInit, binder) ] + + ([], binders, []), reps + + // The last 'let' binding is done so we can set the initialization condition for the collection of object fields + // which now allows members to be called. + | Phase2CCtorJustAfterLastLet -> + let binders = + [ match ctorInfo.InstanceCtorSafeInitInfo with + | SafeInitField (rfref, _) -> + let setExpr = mkRecdFieldSetViaExprAddr (exprForVal m thisVal, rfref, thisTyInst, mkOne g m, m) + let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst setExpr + let binder = (fun e -> mkSequential setExpr.Range setExpr e) + let isPriorToSuperInit = false + yield (isPriorToSuperInit, binder) + | NoSafeInitInfo -> + () ] + + ([], binders, []), reps + + | Phase2CBindings decs -> + let initActions, reps = List.mapFold (TransTrueDec false) reps decs + let cctorInitActions, ctorInitActions, methodBinds = List.unzip3 initActions + (List.concat cctorInitActions, List.concat ctorInitActions, List.concat methodBinds), reps + + let takenFieldNames = + [ for b in memberBinds do + b.Var.CompiledName g.CompilerGlobalState + b.Var.DisplayName + b.Var.DisplayNameCoreMangled + b.Var.LogicalName ] + + let reps = IncrClassReprInfo.Empty(g, takenFieldNames) + + // Bind the IsArg(true) representations of the object constructor arguments and assign them to fields + // if they escape to the members. We do this by running the instance bindings 'let x = x' through TransTrueDec + // for each constructor argument 'x', but with the special flag 'isCtorArg', which helps TransBind know that + // the value is already available as an argument, and that nothing special needs to be done unless the + // value is being stored into a field. + let (cctorInitActions1, ctorInitActions1, methodBinds1), reps = + let binds = ctorInfo.InstanceCtorArgs |> List.map (fun v -> mkInvisibleBind v (exprForVal v.Range v)) + TransTrueDec true reps (IncrClassBindingGroup(binds, false, false)) + + // We expect that only ctorInitActions1 will be non-empty here, and even then only if some elements are stored in the field + assert (isNil cctorInitActions1) + assert (isNil methodBinds1) + + // Now deal with all the 'let' and 'member' declarations + let initActions, reps = List.mapFold TransDec reps decs + let cctorInitActions2, ctorInitActions2, methodBinds2 = List.unzip3 initActions + let cctorInitActions = cctorInitActions1 @ List.concat cctorInitActions2 + let ctorInitActions = ctorInitActions1 @ List.concat ctorInitActions2 + let methodBinds = methodBinds1 @ List.concat methodBinds2 + + let ctorBody = + // Build the elements of the implicit constructor body, starting from the bottom + // + // + // + // return () + let ctorInitActionsPre, ctorInitActionsPost = ctorInitActions |> List.partition fst + + // This is the return result + let ctorBody = mkUnit g m + + // Add . + // That is, add any that come prior to the super init constructor call, + // This is only ever at most the init of the InstanceCtorSafeThisValOpt and InstanceCtorSafeInitInfo var/field + let ctorBody = List.foldBack (fun (_, binder) acc -> binder acc) ctorInitActionsPost ctorBody + + // Add the + let ctorBody = + // The inheritsExpr may refer to the this variable or to incoming arguments, e.g. in closure fields. + // References to the this variable go via the ref cell that gets created to help ensure coherent initialization. + // This ref cell itself may be stored in a field of the object and accessed via arg0. + // Likewise the incoming arguments will eventually be stored in fields and accessed via arg0. + // + // As a result, the most natural way to implement this would be to simply capture arg0 if needed + // and access all variables via that. This would be done by rewriting the inheritsExpr as follows: + // let inheritsExpr = reps.FixupIncrClassExprPhase2C (Some thisVal) thisTyInst inheritsExpr + // However, the rules of IL mean we are not actually allowed to capture arg0 + // and store it as a closure field before the base class constructor is called. + // + // As a result we do not rewrite the inheritsExpr and instead + // (a) wrap a let binding for the ref cell around the inheritsExpr if needed + // (b) rely on the fact that the input arguments are in scope and can be accessed from as argument variables + // (c) rely on the fact that there are no 'let' bindings prior to the inherits expr. + let inheritsExpr = + match ctorInfo.InstanceCtorSafeThisValOpt with + | Some v when not (reps.IsValRepresentedAsLocalVar v) -> + // Rewrite the expression to convert it to a load of a field if needed. + // We are allowed to load fields from our own object even though we haven't called + // the super class constructor yet. + let ldexpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst (exprForVal m v) + mkInvisibleLet m v ldexpr inheritsExpr + | _ -> + inheritsExpr + + // Add the debug point + let inheritsExpr = + if inheritsIsVisible then + Expr.DebugPoint(DebugPointAtLeafExpr.Yes inheritsExpr.Range, inheritsExpr) + else + inheritsExpr + + mkSequential m inheritsExpr ctorBody + + // Add the normal + let ctorBody = List.foldBack (fun (_, binder) acc -> binder acc) ctorInitActionsPre ctorBody + + // Add the final wrapping to make this into a method + let ctorBody = mkMemberLambdas g m [] (Some thisVal) ctorInfo.InstanceCtorBaseValOpt [ctorInfo.InstanceCtorArgs] (ctorBody, g.unit_ty) + + ctorBody + + let cctorBodyOpt = + // Omit the .cctor if it's empty + match cctorInitActions with + | [] -> None + | _ -> + let cctorInitAction = List.foldBack (fun (_, binder) acc -> binder acc) cctorInitActions (mkUnit g m) + let m = thisVal.Range + let cctorArgs, cctorVal, _ = ctorInfo.StaticCtorValInfo.Force() + // Reconstitute the type of the implicit class constructor with the correct quantified type variables. + cctorVal.SetType (mkForallTyIfNeeded ctorDeclaredTypars cctorVal.TauType) + let cctorBody = mkMemberLambdas g m [] None None [cctorArgs] (cctorInitAction, g.unit_ty) + Some cctorBody + + ctorBody, cctorBodyOpt, methodBinds, reps diff --git a/src/Compiler/Checking/CheckIncrementalClasses.fsi b/src/Compiler/Checking/CheckIncrementalClasses.fsi new file mode 100644 index 00000000000..c3f5b17a325 --- /dev/null +++ b/src/Compiler/Checking/CheckIncrementalClasses.fsi @@ -0,0 +1,159 @@ +module internal FSharp.Compiler.CheckIncrementalClasses + +open Internal.Utilities.Collections +open FSharp.Compiler.CheckExpressions +open FSharp.Compiler.CompilerGlobalState +open FSharp.Compiler.Syntax +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text +open FSharp.Compiler.TypedTree +open FSharp.Compiler.TypedTreeOps +open FSharp.Compiler.Xml + +exception ParameterlessStructCtor of range: range + +/// Typechecked info for implicit constructor and it's arguments +type IncrClassCtorLhs = + { + /// The TyconRef for the type being defined + TyconRef: TyconRef + + /// The type parameters allocated for the implicit instance constructor. + /// These may be equated with other (WillBeRigid) type parameters through equi-recursive inference, and so + /// should always be renormalized/canonicalized when used. + InstanceCtorDeclaredTypars: Typars + + /// The value representing the static implicit constructor. + /// Lazy to ensure the static ctor value is only published if needed. + StaticCtorValInfo: Lazy + + /// The value representing the implicit constructor. + InstanceCtorVal: Val + + /// The type of the implicit constructor, representing as a ValScheme. + InstanceCtorValScheme: ValScheme + + /// The values representing the arguments to the implicit constructor. + InstanceCtorArgs: Val list + + /// The reference cell holding the 'this' parameter within the implicit constructor so it can be referenced in the + /// arguments passed to the base constructor + InstanceCtorSafeThisValOpt: Val option + + /// Data indicating if safe-initialization checks need to be inserted for this type. + InstanceCtorSafeInitInfo: SafeInitData + + /// The value representing the 'base' variable within the implicit instance constructor. + InstanceCtorBaseValOpt: Val option + + /// The value representing the 'this' variable within the implicit instance constructor. + InstanceCtorThisVal: Val + + /// The name generator used to generate the names of fields etc. within the type. + NameGenerator: NiceNameGenerator + } + +/// Indicates how is a 'let' bound value in a class with implicit construction is represented in +/// the TAST ultimately produced by type checking. +type IncrClassValRepr = + + // e.g representation for 'let v = 3' if it is not used in anything given a method representation + | InVar of isArg: bool + + // e.g representation for 'let v = 3' + | InField of isStatic: bool * staticCountForSafeInit: int * fieldRef: RecdFieldRef + + // e.g representation for 'let f x = 3' + | InMethod of isStatic: bool * value: Val * valReprInfo: ValReprInfo + +/// IncrClassReprInfo represents the decisions we make about the representation of 'let' and 'do' bindings in a +/// type defined with implicit class construction. +type IncrClassReprInfo = + { + /// Indicates the set of field names taken within one incremental class + TakenFieldNames: Set + + RepInfoTcGlobals: TcGlobals + + /// vals mapped to representations + ValReprs: Zmap + + /// vals represented as fields or members from this point on + ValsWithRepresentation: Zset + } + + static member IsMethodRepr: cenv: TcFileState -> bind: Binding -> bool + + // Publish the fields of the representation to the type + member PublishIncrClassFields: + cenv: TcFileState * + denv: DisplayEnv * + cpath: CompilationPath * + ctorInfo: IncrClassCtorLhs * + safeStaticInitInfo: SafeInitData -> + unit + + /// Given localRep saying how locals have been represented, e.g. as fields. + /// Given an expr under a given thisVal context. + member FixupIncrClassExprPhase2C: + cenv: TcFileState -> + thisValOpt: Val option -> + safeStaticInitInfo: SafeInitData -> + thisTyInst: TypeInst -> + expr: Expr -> + Expr + +/// Represents a single group of bindings in a class with an implicit constructor +type IncrClassBindingGroup = + | IncrClassBindingGroup of bindings: Binding list * isStatic: bool * isRecursive: bool + | IncrClassDo of expr: Expr * isStatic: bool * range: Range + +type IncrClassConstructionBindingsPhase2C = + | Phase2CBindings of IncrClassBindingGroup list + | Phase2CCtorJustAfterSuperInit + | Phase2CCtorJustAfterLastLet + +/// Check and elaborate the "left hand side" of the implicit class construction +/// syntax. +val TcImplicitCtorLhs_Phase2A: + cenv: TcFileState * + env: TcEnv * + tpenv: UnscopedTyparEnv * + tcref: TyconRef * + vis: SynAccess option * + attrs: SynAttribute list * + spats: SynSimplePat list * + thisIdOpt: Ident option * + baseValOpt: Val option * + safeInitInfo: SafeInitData * + m: range * + copyOfTyconTypars: Typar list * + objTy: TType * + thisTy: TType * + xmlDoc: PreXmlDoc -> + IncrClassCtorLhs + +/// +/// Given a set of 'let' bindings (static or not, recursive or not) that make up a class, +/// generate their initialization expression(s). +/// +/// +/// +/// The lhs information about the implicit constructor +/// The call to the super class constructor +/// Should we place a sequence point at the 'inheritedTys call? +/// The declarations +/// +/// Record any unconstrained type parameters generalized for the outer members as "free choices" in the let bindings +/// +val MakeCtorForIncrClassConstructionPhase2C: + cenv: TcFileState * + env: TcEnv * + ctorInfo: IncrClassCtorLhs * + inheritsExpr: Expr * + inheritsIsVisible: bool * + decs: IncrClassConstructionBindingsPhase2C list * + memberBinds: Binding list * + generalizedTyparsForRecursiveBlock: Typar list * + safeStaticInitInfo: SafeInitData -> + Expr * Expr option * Binding list * IncrClassReprInfo diff --git a/src/Compiler/Checking/CheckPatterns.fs b/src/Compiler/Checking/CheckPatterns.fs index b39d6481517..7ced746b6a1 100644 --- a/src/Compiler/Checking/CheckPatterns.fs +++ b/src/Compiler/Checking/CheckPatterns.fs @@ -503,7 +503,7 @@ and TcPatLongIdent warnOnUpper cenv env ad valReprInfo vFlags (patEnv: TcPatLine | SynArgPats.Pats [] -> warnOnUpper | _ -> AllIdsOK - let lidRange = rangeOfLid longId + let mLongId = rangeOfLid longId match ResolvePatternLongIdent cenv.tcSink cenv.nameResolver warnOnUpperForId false m ad env.NameEnv TypeNameResolutionInfo.Default longId with | Item.NewDef id -> @@ -519,19 +519,19 @@ and TcPatLongIdent warnOnUpper cenv env ad valReprInfo vFlags (patEnv: TcPatLine let args = GetSynArgPatterns args - TcPatLongIdentActivePatternCase warnOnUpper cenv env vFlags patEnv ty (lidRange, item, apref, args, m) + TcPatLongIdentActivePatternCase warnOnUpper cenv env vFlags patEnv ty (mLongId, item, apref, args, m) | Item.UnionCase _ | Item.ExnCase _ as item -> - TcPatLongIdentUnionCaseOrExnCase warnOnUpper cenv env ad vFlags patEnv ty (lidRange, item, args, m) + TcPatLongIdentUnionCaseOrExnCase warnOnUpper cenv env ad vFlags patEnv ty (mLongId, item, args, m) | Item.ILField finfo -> - TcPatLongIdentILField warnOnUpper cenv env vFlags patEnv ty (lidRange, finfo, args, m) + TcPatLongIdentILField warnOnUpper cenv env vFlags patEnv ty (mLongId, finfo, args, m) | Item.RecdField rfinfo -> - TcPatLongIdentRecdField warnOnUpper cenv env vFlags patEnv ty (lidRange, rfinfo, args, m) + TcPatLongIdentRecdField warnOnUpper cenv env vFlags patEnv ty (mLongId, rfinfo, args, m) | Item.Value vref -> - TcPatLongIdentLiteral warnOnUpper cenv env vFlags patEnv ty (lidRange, vref, args, m) + TcPatLongIdentLiteral warnOnUpper cenv env vFlags patEnv ty (mLongId, vref, args, m) | _ -> error (Error(FSComp.SR.tcRequireVarConstRecogOrLiteral(), m)) @@ -577,9 +577,9 @@ and ApplyUnionCaseOrExn m (cenv: cenv) env overallTy item = let ucref = ucinfo.UnionCaseRef CheckUnionCaseAttributes g ucref m |> CommitOperationResult CheckUnionCaseAccessible cenv.amap m ad ucref |> ignore - let gtyp2 = actualResultTyOfUnionCase ucinfo.TypeInst ucref + let resTy = actualResultTyOfUnionCase ucinfo.TypeInst ucref let inst = mkTyparInst ucref.TyconRef.TyparsNoRange ucinfo.TypeInst - UnifyTypes cenv env m overallTy gtyp2 + UnifyTypes cenv env m overallTy resTy let mkf mArgs args = TPat_unioncase(ucref, ucinfo.TypeInst, args, unionRanges m mArgs) mkf, actualTysOfUnionCaseFields inst ucref, [ for f in ucref.AllFieldsAsList -> f.Id ] @@ -587,11 +587,11 @@ and ApplyUnionCaseOrExn m (cenv: cenv) env overallTy item = invalidArg "item" "not a union case or exception reference" /// Check a long identifier 'Case' or 'Case argsR that has been resolved to a union case or F# exception constructor -and TcPatLongIdentUnionCaseOrExnCase warnOnUpper cenv env ad vFlags patEnv ty (lidRange, item, args, m) = +and TcPatLongIdentUnionCaseOrExnCase warnOnUpper cenv env ad vFlags patEnv ty (mLongId, item, args, m) = let g = cenv.g // Report information about the case occurrence to IDE - CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.eAccessRights) + CallNameResolutionSink cenv.tcSink (mLongId, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.eAccessRights) let mkf, argTys, argNames = ApplyUnionCaseOrExn m cenv env ty item let numArgTys = argTys.Length @@ -693,38 +693,38 @@ and TcPatLongIdentUnionCaseOrExnCase warnOnUpper cenv env ad vFlags patEnv ty (l (fun values -> mkf m (List.map (fun f -> f values) argsR)), acc /// Check a long identifier that has been resolved to an IL field - valid if a literal -and TcPatLongIdentILField warnOnUpper (cenv: cenv) env vFlags patEnv ty (lidRange, finfo, args, m) = +and TcPatLongIdentILField warnOnUpper (cenv: cenv) env vFlags patEnv ty (mLongId, finfo, args, m) = let g = cenv.g - CheckILFieldInfoAccessible g cenv.amap lidRange env.AccessRights finfo + CheckILFieldInfoAccessible g cenv.amap mLongId env.AccessRights finfo if not finfo.IsStatic then - errorR (Error (FSComp.SR.tcFieldIsNotStatic finfo.FieldName, lidRange)) + errorR (Error (FSComp.SR.tcFieldIsNotStatic finfo.FieldName, mLongId)) CheckILFieldAttributes g finfo m match finfo.LiteralValue with | None -> - error (Error (FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern (), lidRange)) + error (Error (FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern (), mLongId)) | Some lit -> CheckNoArgsForLiteral args m let _, acc = TcArgPats warnOnUpper cenv env vFlags patEnv args UnifyTypes cenv env m ty (finfo.FieldType (cenv.amap, m)) - let c' = TcFieldInit lidRange lit + let c' = TcFieldInit mLongId lit let item = Item.ILField finfo - CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) + CallNameResolutionSink cenv.tcSink (mLongId, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) (fun _ -> TPat_const (c', m)), acc /// Check a long identifier that has been resolved to a record field -and TcPatLongIdentRecdField warnOnUpper cenv env vFlags patEnv ty (lidRange, rfinfo, args, m) = +and TcPatLongIdentRecdField warnOnUpper cenv env vFlags patEnv ty (mLongId, rfinfo, args, m) = let g = cenv.g - CheckRecdFieldInfoAccessible cenv.amap lidRange env.AccessRights rfinfo - if not rfinfo.IsStatic then errorR (Error (FSComp.SR.tcFieldIsNotStatic(rfinfo.DisplayName), lidRange)) - CheckRecdFieldInfoAttributes g rfinfo lidRange |> CommitOperationResult + CheckRecdFieldInfoAccessible cenv.amap mLongId env.AccessRights rfinfo + if not rfinfo.IsStatic then errorR (Error (FSComp.SR.tcFieldIsNotStatic(rfinfo.DisplayName), mLongId)) + CheckRecdFieldInfoAttributes g rfinfo mLongId |> CommitOperationResult match rfinfo.LiteralValue with - | None -> error (Error(FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern(), lidRange)) + | None -> error (Error(FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern(), mLongId)) | Some lit -> CheckNoArgsForLiteral args m let _, acc = TcArgPats warnOnUpper cenv env vFlags patEnv args @@ -733,26 +733,26 @@ and TcPatLongIdentRecdField warnOnUpper cenv env vFlags patEnv ty (lidRange, rfi let item = Item.RecdField rfinfo // FUTURE: can we do better than emptyTyparInst here, in order to display instantiations // of type variables in the quick info provided in the IDE. - CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) + CallNameResolutionSink cenv.tcSink (mLongId, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) (fun _ -> TPat_const (lit, m)), acc /// Check a long identifier that has been resolved to an F# value that is a literal -and TcPatLongIdentLiteral warnOnUpper (cenv: cenv) env vFlags patEnv ty (lidRange, vref, args, m) = +and TcPatLongIdentLiteral warnOnUpper (cenv: cenv) env vFlags patEnv ty (mLongId, vref, args, m) = let g = cenv.g let (TcPatLinearEnv(tpenv, _, _)) = patEnv match vref.LiteralValue with | None -> error (Error(FSComp.SR.tcNonLiteralCannotBeUsedInPattern(), m)) | Some lit -> - let _, _, _, vexpty, _, _ = TcVal true cenv env tpenv vref None None lidRange - CheckValAccessible lidRange env.AccessRights vref - CheckFSharpAttributes g vref.Attribs lidRange |> CommitOperationResult + let _, _, _, vexpty, _, _ = TcVal true cenv env tpenv vref None None mLongId + CheckValAccessible mLongId env.AccessRights vref + CheckFSharpAttributes g vref.Attribs mLongId |> CommitOperationResult CheckNoArgsForLiteral args m let _, acc = TcArgPats warnOnUpper cenv env vFlags patEnv args UnifyTypes cenv env m ty vexpty let item = Item.Value vref - CallNameResolutionSink cenv.tcSink (lidRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) + CallNameResolutionSink cenv.tcSink (mLongId, env.NameEnv, item, emptyTyparInst, ItemOccurence.Pattern, env.AccessRights) (fun _ -> TPat_const (lit, m)), acc and TcPatterns warnOnUpper cenv env vFlags s argTys args = diff --git a/src/Compiler/Checking/ConstraintSolver.fs b/src/Compiler/Checking/ConstraintSolver.fs index 7d7097dc25a..0119827bdf5 100644 --- a/src/Compiler/Checking/ConstraintSolver.fs +++ b/src/Compiler/Checking/ConstraintSolver.fs @@ -136,12 +136,12 @@ let FreshenTypars m tpsorig = match tpsorig with | [] -> [] | _ -> - let _, _, tptys = FreshenTypeInst m tpsorig - tptys + let _, _, tpTys = FreshenTypeInst m tpsorig + tpTys let FreshenMethInfo m (minfo: MethInfo) = - let _, _, tptys = FreshMethInst m (minfo.GetFormalTyparsOfDeclaringType m) minfo.DeclaringTypeInst minfo.FormalMethodTypars - tptys + let _, _, tpTys = FreshMethInst m (minfo.GetFormalTyparsOfDeclaringType m) minfo.DeclaringTypeInst minfo.FormalMethodTypars + tpTys //------------------------------------------------------------------------- // Unification of types: solve/record equality constraints @@ -362,7 +362,7 @@ let rec occursCheck g un ty = | TType_app (_, l, _) | TType_anon(_, l) | TType_tuple (_, l) -> List.exists (occursCheck g un) l - | TType_fun (d, r, _) -> occursCheck g un d || occursCheck g un r + | TType_fun (domainTy, rangeTy, _) -> occursCheck g un domainTy || occursCheck g un rangeTy | TType_var (r, _) -> typarEq un r | TType_forall (_, tau) -> occursCheck g un tau | _ -> false @@ -787,7 +787,7 @@ let UnifyMeasureWithOne (csenv: ConstraintSolverEnv) trace ms = match FindPreferredTypar nonRigidVars with | (v, e) :: vs -> let unexpandedCons = ListMeasureConOccsWithNonZeroExponents csenv.g false ms - let newms = ProdMeasures (List.map (fun (c, e') -> Measure.RationalPower (Measure.Con c, NegRational (DivRational e' e))) unexpandedCons + let newms = ProdMeasures (List.map (fun (c, e') -> Measure.RationalPower (Measure.Const c, NegRational (DivRational e' e))) unexpandedCons @ List.map (fun (v, e') -> Measure.RationalPower (Measure.Var v, NegRational (DivRational e' e))) (vs @ rigidVars)) SubstMeasureWarnIfRigid csenv trace v newms @@ -818,7 +818,7 @@ let SimplifyMeasure g vars ms = let newms = ProdMeasures [ for (c, e') in nonZeroCon do - Measure.RationalPower (Measure.Con c, NegRational (DivRational e' e)) + Measure.RationalPower (Measure.Const c, NegRational (DivRational e' e)) for (v', e') in nonZeroVar do if typarEq v v' then newvarExpr @@ -841,11 +841,11 @@ let rec SimplifyMeasuresInType g resultFirst (generalizable, generalized as para | TType_anon (_,l) | TType_tuple (_, l) -> SimplifyMeasuresInTypes g param l - | TType_fun (d, r, _) -> + | TType_fun (domainTy, rangeTy, _) -> if resultFirst then - SimplifyMeasuresInTypes g param [r;d] + SimplifyMeasuresInTypes g param [rangeTy;domainTy] else - SimplifyMeasuresInTypes g param [d;r] + SimplifyMeasuresInTypes g param [domainTy;rangeTy] | TType_var _ -> param @@ -886,7 +886,7 @@ let rec GetMeasureVarGcdInType v ty = | TType_anon (_,l) | TType_tuple (_, l) -> GetMeasureVarGcdInTypes v l - | TType_fun (d, r, _) -> GcdRational (GetMeasureVarGcdInType v d) (GetMeasureVarGcdInType v r) + | TType_fun (domainTy, rangeTy, _) -> GcdRational (GetMeasureVarGcdInType v domainTy) (GetMeasureVarGcdInType v rangeTy) | TType_var _ -> ZeroRational | TType_forall (_, tau) -> GetMeasureVarGcdInType v tau | TType_measure unt -> MeasureVarExponent v unt @@ -1027,7 +1027,7 @@ and solveTypMeetsTyparConstraints (csenv: ConstraintSolverEnv) ndeep m2 trace ty AddConstraint csenv ndeep m2 trace destTypar (TyparConstraint.DefaultsTo(priority, dty, m)) | TyparConstraint.SupportsNull m2 -> SolveTypeUseSupportsNull csenv ndeep m2 trace ty - | TyparConstraint.IsEnum(underlying, m2) -> SolveTypeIsEnum csenv ndeep m2 trace ty underlying + | TyparConstraint.IsEnum(underlyingTy, m2) -> SolveTypeIsEnum csenv ndeep m2 trace ty underlyingTy | TyparConstraint.SupportsComparison(m2) -> SolveTypeSupportsComparison csenv ndeep m2 trace ty | TyparConstraint.SupportsEquality(m2) -> SolveTypeSupportsEquality csenv ndeep m2 trace ty | TyparConstraint.IsDelegate(aty, bty, m2) -> SolveTypeIsDelegate csenv ndeep m2 trace ty aty bty @@ -1054,17 +1054,17 @@ and SolveTyparEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalT } // Like SolveTyparEqualsType but asserts all typar equalities simultaneously instead of one by one -and SolveTyparsEqualTypes (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) tptys tys = trackErrors { - do! (tptys, tys) ||> Iterate2D (fun tpty ty -> - match tpty with +and SolveTyparsEqualTypes (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) tpTys tys = trackErrors { + do! (tpTys, tys) ||> Iterate2D (fun tpTy ty -> + match tpTy with | TType_var (r, _) | TType_measure (Measure.Var r) -> - SolveTyparEqualsTypePart1 csenv m2 trace tpty r ty + SolveTyparEqualsTypePart1 csenv m2 trace tpTy r ty | _ -> failwith "SolveTyparsEqualTypes") - do! (tptys, tys) ||> Iterate2D (fun tpty ty -> - match tpty with + do! (tpTys, tys) ||> Iterate2D (fun tpTy ty -> + match tpTy with | TType_var (r, _) | TType_measure (Measure.Var r) -> SolveTyparEqualsTypePart2 csenv ndeep m2 trace r ty @@ -1135,7 +1135,7 @@ and SolveTypeEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTr match sty1, sty2 with // type vars inside forall-types may be alpha-equivalent - | TType_var (tp1, _), TType_var (tp2, _) when typarEq tp1 tp2 || (match aenv.EquivTypars.TryFind tp1 with | Some v when typeEquiv g v ty2 -> true | _ -> false) -> + | TType_var (tp1, _), TType_var (tp2, _) when typarEq tp1 tp2 || (match aenv.EquivTypars.TryFind tp1 with | Some tpTy1 when typeEquiv g tpTy1 ty2 -> true | _ -> false) -> CompleteD // 'v1 = 'v2 @@ -1173,18 +1173,18 @@ and SolveTypeEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTr SolveAnonInfoEqualsAnonInfo csenv m2 anonInfo1 anonInfo2 ++ (fun () -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2) - | TType_fun (d1, r1, _), TType_fun (d2, r2, _) -> - SolveFunTypeEqn csenv ndeep m2 trace None d1 d2 r1 r2 + | TType_fun (domainTy1, rangeTy1, _), TType_fun (domainTy2, rangeTy2, _) -> + SolveFunTypeEqn csenv ndeep m2 trace None domainTy1 domainTy2 rangeTy1 rangeTy2 | TType_measure ms1, TType_measure ms2 -> UnifyMeasures csenv trace ms1 ms2 - | TType_forall(tps1, rty1), TType_forall(tps2, rty2) -> + | TType_forall(tps1, bodyTy1), TType_forall(tps2, bodyTy2) -> if tps1.Length <> tps2.Length then localAbortD else let aenv = aenv.BindEquivTypars tps1 tps2 let csenv = {csenv with EquivEnv = aenv } if not (typarsAEquiv g aenv tps1 tps2) then localAbortD else - SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty1 rty2 + SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace bodyTy1 bodyTy2 | TType_ucase (uc1, l1), TType_ucase (uc2, l2) when g.unionCaseRefEq uc1 uc2 -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2 | _ -> localAbortD @@ -1214,9 +1214,9 @@ and SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln origl1 origl2 = ErrorD(ConstraintSolverTupleDiffLengths(csenv.DisplayEnv, origl1, origl2, csenv.m, m2)) loop origl1 origl2 -and SolveFunTypeEqn csenv ndeep m2 trace cxsln d1 d2 r1 r2 = trackErrors { - do! SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln d1 d2 - return! SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln r1 r2 +and SolveFunTypeEqn csenv ndeep m2 trace cxsln domainTy1 domainTy2 rangeTy1 rangeTy2 = trackErrors { + do! SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln domainTy1 domainTy2 + return! SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln rangeTy1 rangeTy2 } // ty1: expected @@ -1240,7 +1240,7 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional match sty1, sty2 with | TType_var (tp1, _), _ -> match aenv.EquivTypars.TryFind tp1 with - | Some v -> SolveTypeSubsumesType csenv ndeep m2 trace cxsln v ty2 + | Some tpTy1 -> SolveTypeSubsumesType csenv ndeep m2 trace cxsln tpTy1 ty2 | _ -> match sty2 with | TType_var (r2, _) when typarEq tp1 r2 -> CompleteD @@ -1258,8 +1258,8 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional SolveAnonInfoEqualsAnonInfo csenv m2 anonInfo1 anonInfo2 ++ (fun () -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2) (* nb. can unify since no variance *) - | TType_fun (d1, r1, _), TType_fun (d2, r2, _) -> - SolveFunTypeEqn csenv ndeep m2 trace cxsln d1 d2 r1 r2 (* nb. can unify since no variance *) + | TType_fun (domainTy1, rangeTy1, _), TType_fun (domainTy2, rangeTy2, _) -> + SolveFunTypeEqn csenv ndeep m2 trace cxsln domainTy1 domainTy2 rangeTy1 rangeTy2 (* nb. can unify since no variance *) | TType_measure ms1, TType_measure ms2 -> UnifyMeasures csenv trace ms1 ms2 @@ -1306,17 +1306,17 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional // Note we don't support co-variance on array types nor // the special .NET conversions for these types match ty1 with - | AppTy g (tcr1, tinst) when + | AppTy g (tcref1, tinst1) when isArray1DTy g ty2 && - (tyconRefEq g tcr1 g.tcref_System_Collections_Generic_IList || - tyconRefEq g tcr1 g.tcref_System_Collections_Generic_ICollection || - tyconRefEq g tcr1 g.tcref_System_Collections_Generic_IReadOnlyList || - tyconRefEq g tcr1 g.tcref_System_Collections_Generic_IReadOnlyCollection || - tyconRefEq g tcr1 g.tcref_System_Collections_Generic_IEnumerable) -> - match tinst with - | [ty1arg] -> - let ty2arg = destArrayTy g ty2 - SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln ty1arg ty2arg + (tyconRefEq g tcref1 g.tcref_System_Collections_Generic_IList || + tyconRefEq g tcref1 g.tcref_System_Collections_Generic_ICollection || + tyconRefEq g tcref1 g.tcref_System_Collections_Generic_IReadOnlyList || + tyconRefEq g tcref1 g.tcref_System_Collections_Generic_IReadOnlyCollection || + tyconRefEq g tcref1 g.tcref_System_Collections_Generic_IEnumerable) -> + match tinst1 with + | [elemTy1] -> + let elemTy2 = destArrayTy g ty2 + SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln elemTy1 elemTy2 | _ -> error(InternalError("destArrayTy", m)) | _ -> @@ -1525,13 +1525,13 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload if rankOfArrayTy g ty <> argTys.Length - 1 then do! ErrorD(ConstraintSolverError(FSComp.SR.csIndexArgumentMismatch((rankOfArrayTy g ty), (argTys.Length - 1)), m, m2)) - let argTys, ety = List.frontAndBack argTys + let argTys, lastTy = List.frontAndBack argTys for argTy in argTys do do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace argTy g.int_ty - let etys = destArrayTy g ty - do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace ety etys + let elemTy = destArrayTy g ty + do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace lastTy elemTy return TTraitBuiltIn | [], _, false, ("op_BitwiseAnd" | "op_BitwiseOr" | "op_ExclusiveOr"), [argTy1;argTy2] @@ -1845,10 +1845,10 @@ and MemberConstraintSolutionOfMethInfo css m minfo minst = match callMethInfoOpt, callExpr with | Some methInfo, Expr.Op (TOp.ILCall (_, _, _, _, NormalValUse, _, _, ilMethRef, _, methInst, _), [], args, m) when (args, (objArgVars@allArgVars)) ||> List.lengthsEqAndForall2 (fun a b -> match a with Expr.Val (v, _, _) -> valEq v.Deref b | _ -> false) -> - let declaringType = ImportProvidedType amap m (methInfo.PApply((fun x -> x.DeclaringType), m)) - if isILAppTy g declaringType then + let declaringTy = ImportProvidedType amap m (methInfo.PApply((fun x -> x.DeclaringType), m)) + if isILAppTy g declaringTy then let extOpt = None // EXTENSION METHODS FROM TYPE PROVIDERS: for extension methods coming from the type providers we would have something here. - ILMethSln(declaringType, extOpt, ilMethRef, methInst) + ILMethSln(declaringTy, extOpt, ilMethRef, methInst) else closedExprSln | _ -> @@ -2090,8 +2090,8 @@ and AddConstraint (csenv: ConstraintSolverEnv) ndeep m2 trace tp newConstraint | TyparConstraint.IsReferenceType _, TyparConstraint.IsReferenceType _ | TyparConstraint.RequiresDefaultConstructor _, TyparConstraint.RequiresDefaultConstructor _ -> true | TyparConstraint.SimpleChoice (tys1, _), TyparConstraint.SimpleChoice (tys2, _) -> ListSet.isSubsetOf (typeEquiv g) tys1 tys2 - | TyparConstraint.DefaultsTo (priority1, dty1, _), TyparConstraint.DefaultsTo (priority2, dty2, _) -> - (priority1 = priority2) && typeEquiv g dty1 dty2 + | TyparConstraint.DefaultsTo (priority1, defaultTy1, _), TyparConstraint.DefaultsTo (priority2, defaultTy2, _) -> + (priority1 = priority2) && typeEquiv g defaultTy1 defaultTy2 | _ -> false @@ -2565,14 +2565,12 @@ and SolveTypeSubsumesTypeWithWrappedContextualReport (csenv: ConstraintSolverEnv and SolveTypeSubsumesTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln ty1 ty2 = SolveTypeSubsumesTypeWithWrappedContextualReport csenv ndeep m trace cxsln ty1 ty2 id -// ty1: actual -// ty2: expected -and private SolveTypeEqualsTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln actual expected = +and SolveTypeEqualsTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln actualTy expectedTy = TryD - (fun () -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m trace cxsln actual expected) + (fun () -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m trace cxsln actualTy expectedTy) (function | AbortForFailedMemberConstraintResolution as err -> ErrorD err - | res -> ErrorD (ErrorFromAddingTypeEquation(csenv.g, csenv.DisplayEnv, actual, expected, res, m))) + | res -> ErrorD (ErrorFromAddingTypeEquation(csenv.g, csenv.DisplayEnv, actualTy, expectedTy, res, m))) and ArgsMustSubsumeOrConvert (csenv: ConstraintSolverEnv) diff --git a/src/Compiler/Checking/FindUnsolved.fs b/src/Compiler/Checking/FindUnsolved.fs index 76fb746ca4f..93f452abd7d 100644 --- a/src/Compiler/Checking/FindUnsolved.fs +++ b/src/Compiler/Checking/FindUnsolved.fs @@ -84,15 +84,15 @@ let rec accExpr (cenv: cenv) (env: env) expr = accExprs cenv env argsl | Expr.Lambda (_, _ctorThisValOpt, _baseValOpt, argvs, _body, m, bodyTy) -> - let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy cenv.g m argvs bodyTy - accLambdas cenv env topValInfo expr ty + accLambdas cenv env valReprInfo expr ty | Expr.TyLambda (_, tps, _body, _m, bodyTy) -> - let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) accTy cenv env bodyTy let ty = mkForallTyIfNeeded tps bodyTy - accLambdas cenv env topValInfo expr ty + accLambdas cenv env valReprInfo expr ty | Expr.TyChoose (_tps, e1, _m) -> accExpr cenv env e1 @@ -161,12 +161,12 @@ and accTraitInfo cenv env (TTrait(tys, _nm, _, argTys, retTy, _sln)) = retTy |> Option.iter (accTy cenv env) tys |> List.iter (accTy cenv env) -and accLambdas cenv env topValInfo expr exprTy = +and accLambdas cenv env valReprInfo expr exprTy = match stripDebugPoints expr with - | Expr.TyChoose (_tps, bodyExpr, _m) -> accLambdas cenv env topValInfo bodyExpr exprTy + | Expr.TyChoose (_tps, bodyExpr, _m) -> accLambdas cenv env valReprInfo bodyExpr exprTy | Expr.Lambda _ | Expr.TyLambda _ -> - let _tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = destTopLambda cenv.g cenv.amap topValInfo (expr, exprTy) + let _tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = destTopLambda cenv.g cenv.amap valReprInfo (expr, exprTy) accTy cenv env bodyTy vsl |> List.iterSquared (accVal cenv env) baseValOpt |> Option.iter (accVal cenv env) @@ -201,7 +201,7 @@ and accDiscrim cenv env d = | DecisionTreeTest.ArrayLength(_, ty) -> accTy cenv env ty | DecisionTreeTest.Const _ | DecisionTreeTest.IsNull -> () - | DecisionTreeTest.IsInst (srcty, tgty) -> accTy cenv env srcty; accTy cenv env tgty + | DecisionTreeTest.IsInst (srcTy, tgtTy) -> accTy cenv env srcTy; accTy cenv env tgtTy | DecisionTreeTest.ActivePatternCase (exp, tys, _, _, _, _) -> accExpr cenv env exp accTypeInst cenv env tys @@ -233,8 +233,8 @@ and accVal cenv env v = and accBind cenv env (bind: Binding) = accVal cenv env bind.Var - let topValInfo = match bind.Var.ValReprInfo with Some info -> info | _ -> ValReprInfo.emptyValData - accLambdas cenv env topValInfo bind.Expr bind.Var.Type + let valReprInfo = match bind.Var.ValReprInfo with Some info -> info | _ -> ValReprInfo.emptyValData + accLambdas cenv env valReprInfo bind.Expr bind.Var.Type and accBinds cenv env binds = binds |> List.iter (accBind cenv env) diff --git a/src/Compiler/Checking/InfoReader.fs b/src/Compiler/Checking/InfoReader.fs index 75a4e9aa897..581cb7d0353 100644 --- a/src/Compiler/Checking/InfoReader.fs +++ b/src/Compiler/Checking/InfoReader.fs @@ -628,10 +628,10 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) as this = keyComparer= { new System.Collections.Generic.IEqualityComparer<_> with - member _.Equals((flags1, _, typ1), (flags2, _, typ2)) = + member _.Equals((flags1, _, ty1), (flags2, _, ty2)) = // Ignoring the ranges - that's OK. flagsEq.Equals(flags1, flags2) && - match stripTyEqns g typ1, stripTyEqns g typ2 with + match stripTyEqns g ty1, stripTyEqns g ty2 with | TType_app(tcref1, [], _), TType_app(tcref2, [], _) -> tyconRefEq g tcref1 tcref2 | _ -> false member _.GetHashCode((flags, _, ty)) = @@ -910,11 +910,11 @@ type SigOfFunctionForDelegate = /// Given a delegate type work out the minfo, argument types, return type /// and F# function type by looking at the Invoke signature of the delegate. -let GetSigOfFunctionForDelegate (infoReader: InfoReader) delty m ad = +let GetSigOfFunctionForDelegate (infoReader: InfoReader) delTy m ad = let g = infoReader.g let amap = infoReader.amap let delInvokeMeth = - match GetIntrinsicMethInfosOfType infoReader (Some "Invoke") ad AllowMultiIntfInstantiations.Yes IgnoreOverrides m delty with + match GetIntrinsicMethInfosOfType infoReader (Some "Invoke") ad AllowMultiIntfInstantiations.Yes IgnoreOverrides m delTy with | [h] -> h | [] -> error(Error(FSComp.SR.noInvokeMethodsFound (), m)) | h :: _ -> warning(InternalError(FSComp.SR.moreThanOneInvokeMethodFound (), m)); h @@ -964,26 +964,26 @@ let TryDestStandardDelegateType (infoReader: InfoReader) m ad delTy = // already defined an appropriate delegate type: EventHandler. // (from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkEventsTutorial.asp) let IsStandardEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = - let dty = einfo.GetDelegateType(infoReader.amap, m) - match TryDestStandardDelegateType infoReader m ad dty with + let delTy = einfo.GetDelegateType(infoReader.amap, m) + match TryDestStandardDelegateType infoReader m ad delTy with | Some _ -> true | None -> false /// Get the (perhaps tupled) argument type accepted by an event -let ArgsTypOfEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = +let ArgsTypeOfEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = let amap = infoReader.amap - let dty = einfo.GetDelegateType(amap, m) - match TryDestStandardDelegateType infoReader m ad dty with + let delTy = einfo.GetDelegateType(amap, m) + match TryDestStandardDelegateType infoReader m ad delTy with | Some(argTys, _) -> argTys | None -> error(nonStandardEventError einfo.EventName m) /// Get the type of the event when looked at as if it is a property /// Used when displaying the property in Intellisense -let PropTypOfEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = +let PropTypeOfEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = let g = infoReader.g let amap = infoReader.amap let delTy = einfo.GetDelegateType(amap, m) - let argsTy = ArgsTypOfEventInfo infoReader m ad einfo + let argsTy = ArgsTypeOfEventInfo infoReader m ad einfo mkIEventType g delTy argsTy /// Try to find the name of the metadata file for this external definition diff --git a/src/Compiler/Checking/InfoReader.fsi b/src/Compiler/Checking/InfoReader.fsi index 5941702256a..c8cec7f82da 100644 --- a/src/Compiler/Checking/InfoReader.fsi +++ b/src/Compiler/Checking/InfoReader.fsi @@ -280,7 +280,7 @@ type SigOfFunctionForDelegate = /// Given a delegate type work out the minfo, argument types, return type /// and F# function type by looking at the Invoke signature of the delegate. val GetSigOfFunctionForDelegate: - infoReader: InfoReader -> delty: TType -> m: range -> ad: AccessorDomain -> SigOfFunctionForDelegate + infoReader: InfoReader -> delTy: TType -> m: range -> ad: AccessorDomain -> SigOfFunctionForDelegate /// Try and interpret a delegate type as a "standard" .NET delegate type associated with an event, with a "sender" parameter. val TryDestStandardDelegateType: @@ -290,9 +290,9 @@ val TryDestStandardDelegateType: /// with a sender parameter. val IsStandardEventInfo: infoReader: InfoReader -> m: range -> ad: AccessorDomain -> einfo: EventInfo -> bool -val ArgsTypOfEventInfo: infoReader: InfoReader -> m: range -> ad: AccessorDomain -> einfo: EventInfo -> TType +val ArgsTypeOfEventInfo: infoReader: InfoReader -> m: range -> ad: AccessorDomain -> einfo: EventInfo -> TType -val PropTypOfEventInfo: infoReader: InfoReader -> m: range -> ad: AccessorDomain -> einfo: EventInfo -> TType +val PropTypeOfEventInfo: infoReader: InfoReader -> m: range -> ad: AccessorDomain -> einfo: EventInfo -> TType /// Try to find the name of the metadata file for this external definition val TryFindMetadataInfoOfExternalEntityRef: diff --git a/src/Compiler/Checking/MethodCalls.fs b/src/Compiler/Checking/MethodCalls.fs index f4338d311df..7c8c07cb883 100644 --- a/src/Compiler/Checking/MethodCalls.fs +++ b/src/Compiler/Checking/MethodCalls.fs @@ -181,7 +181,7 @@ let TryFindRelevantImplicitConversion (infoReader: InfoReader) ad reqdTy actualT let reqdTy2 = if isTyparTy g reqdTy then let tp = destTyparTy g reqdTy - match tp.Constraints |> List.choose (function TyparConstraint.CoercesTo (c, _) -> Some c | _ -> None) with + match tp.Constraints |> List.choose (function TyparConstraint.CoercesTo (tgtTy, _) -> Some tgtTy | _ -> None) with | [reqdTy2] when tp.Rigidity = TyparRigidity.Flexible -> reqdTy2 | _ -> reqdTy else reqdTy @@ -363,8 +363,8 @@ let AdjustCalledArgTypeForOptionals (infoReader: InfoReader) ad enforceNullableO calledArgTy, TypeDirectedConversionUsed.No, None | _ -> let compgenId = mkSynId range0 unassignedTyparName - let tp = mkTyparTy (Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, SynTypar(compgenId, TyparStaticReq.None, true), false, TyparDynamicReq.No, [], false, false)) - tp, TypeDirectedConversionUsed.No, None + let tpTy = mkTyparTy (Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, SynTypar(compgenId, TyparStaticReq.None, true), false, TyparDynamicReq.No, [], false, false)) + tpTy, TypeDirectedConversionUsed.No, None else AdjustCalledArgTypeForTypeDirectedConversionsAndAutoQuote infoReader ad callerArgTy calledArgTy calledArg m @@ -456,7 +456,7 @@ type CalledMethArgSet<'T> = let MakeCalledArgs amap m (minfo: MethInfo) minst = // Mark up the arguments with their position, so we can sort them back into order later let paramDatas = minfo.GetParamDatas(amap, m, minst) - paramDatas |> List.mapiSquared (fun i j (ParamData(isParamArrayArg, isInArg, isOutArg, optArgInfo, callerInfoFlags, nmOpt, reflArgInfo, typeOfCalledArg)) -> + paramDatas |> List.mapiSquared (fun i j (ParamData(isParamArrayArg, isInArg, isOutArg, optArgInfo, callerInfoFlags, nmOpt, reflArgInfo, calledArgTy)) -> { Position=(i,j) IsParamArray=isParamArrayArg OptArgInfo=optArgInfo @@ -465,7 +465,7 @@ let MakeCalledArgs amap m (minfo: MethInfo) minst = IsOutArg=isOutArg ReflArgInfo=reflArgInfo NameOpt=nmOpt - CalledArgumentType=typeOfCalledArg }) + CalledArgumentType=calledArgTy }) /// /// Represents the syntactic matching between a caller of a method and the called method. @@ -969,11 +969,10 @@ let BuildILMethInfoCall g amap m isProp (minfo: ILMethInfo) valUseFlags minst di /// /// QUERY: this looks overly complex considering that we are doing a fundamentally simple /// thing here. -let BuildFSharpMethodApp g m (vref: ValRef) vexp vexprty (args: Exprs) = +let BuildFSharpMethodApp g m (vref: ValRef) vExpr vexprty (args: Exprs) = let arities = (arityOfVal vref.Deref).AritiesOfArgs let args3, (leftover, retTy) = - let exprL expr = exprL g expr ((args, vexprty), arities) ||> List.mapFold (fun (args, fty) arity -> match arity, args with | (0|1), [] when typeEquiv g (domainOfFunTy g fty) g.unit_ty -> mkUnit g m, (args, rangeOfFunTy g fty) @@ -991,17 +990,17 @@ let BuildFSharpMethodApp g m (vref: ValRef) vexp vexprty (args: Exprs) = (mkRefTupled g m tupargs tuptys), (argst, rangeOfFunTy g fty) ) if not leftover.IsEmpty then error(InternalError("Unexpected "+string(leftover.Length)+" remaining arguments in method application", m)) - mkApps g ((vexp, vexprty), [], args3, m), + mkApps g ((vExpr, vexprty), [], args3, m), retTy /// Build a call to an F# method. let BuildFSharpMethodCall g m (ty, vref: ValRef) valUseFlags minst args = - let vexp = Expr.Val (vref, valUseFlags, m) - let vexpty = vref.Type + let vExpr = Expr.Val (vref, valUseFlags, m) + let vExprTy = vref.Type let tpsorig, tau = vref.GeneralizedType let vtinst = argsOfAppTy g ty @ minst if tpsorig.Length <> vtinst.Length then error(InternalError("BuildFSharpMethodCall: unexpected List.length mismatch", m)) - let expr = mkTyAppExpr m (vexp, vexpty) vtinst + let expr = mkTyAppExpr m (vExpr, vExprTy) vtinst let exprTy = instType (mkTyparInst tpsorig vtinst) tau BuildFSharpMethodApp g m vref expr exprTy args @@ -1114,8 +1113,8 @@ let BuildMethodCall tcVal g amap isMutable m isProp minfo valUseFlags minst objA if valRefEq amap.g fsValRef amap.g.reraise_vref then mkReraise m exprTy, exprTy else - let vexp, vexpty = tcVal fsValRef valUseFlags (minfo.DeclaringTypeInst @ minst) m - BuildFSharpMethodApp g m fsValRef vexp vexpty allArgs + let vExpr, vExprTy = tcVal fsValRef valUseFlags (minfo.DeclaringTypeInst @ minst) m + BuildFSharpMethodApp g m fsValRef vExpr vExprTy allArgs | None -> let ilMethRef = Import.ImportProvidedMethodBaseAsILMethodRef amap m providedMeth let isNewObj = isCtor && (match valUseFlags with NormalValUse -> true | _ -> false) @@ -1140,8 +1139,8 @@ let BuildMethodCall tcVal g amap isMutable m isProp minfo valUseFlags minst objA // Go see if this is a use of a recursive definition... Note we know the value instantiation // we want to use so we pass that in order not to create a new one. - let vexp, vexpty = tcVal vref valUseFlags (minfo.DeclaringTypeInst @ minst) m - BuildFSharpMethodApp g m vref vexp vexpty allArgs + let vExpr, vExprTy = tcVal vref valUseFlags (minfo.DeclaringTypeInst @ minst) m + BuildFSharpMethodApp g m vref vExpr vExprTy allArgs // Build a 'call' to a struct default constructor | DefaultStructCtor (g, ty) -> @@ -1212,7 +1211,7 @@ let BuildObjCtorCall (g: TcGlobals) m = let BuildNewDelegateExpr (eventInfoOpt: EventInfo option, g, amap, delegateTy, delInvokeMeth: MethInfo, delArgTys, delFuncExpr, delFuncTy, m) = let slotsig = delInvokeMeth.GetSlotSig(amap, m) let delArgVals, expr = - let topValInfo = ValReprInfo([], List.replicate (max 1 (List.length delArgTys)) ValReprInfo.unnamedTopArg, ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo([], List.replicate (max 1 (List.length delArgTys)) ValReprInfo.unnamedTopArg, ValReprInfo.unnamedRetVal) // Try to pull apart an explicit lambda and use it directly // Don't do this in the case where we're adjusting the arguments of a function used to build a .NET-compatible event handler @@ -1220,7 +1219,7 @@ let BuildNewDelegateExpr (eventInfoOpt: EventInfo option, g, amap, delegateTy, d if Option.isSome eventInfoOpt then None else - tryDestTopLambda g amap topValInfo (delFuncExpr, delFuncTy) + tryDestTopLambda g amap valReprInfo (delFuncExpr, delFuncTy) match lambdaContents with | None -> @@ -1245,7 +1244,7 @@ let BuildNewDelegateExpr (eventInfoOpt: EventInfo option, g, amap, delegateTy, d delArgVals, expr | Some _ -> - let _, _, _, vsl, body, _ = IteratedAdjustArityOfLambda g amap topValInfo delFuncExpr + let _, _, _, vsl, body, _ = IteratedAdjustArityOfLambda g amap valReprInfo delFuncExpr List.concat vsl, body let meth = TObjExprMethod(slotsig, [], [], [delArgVals], expr, m) @@ -1794,6 +1793,7 @@ module ProvidedMethodCalls = for v, e in Seq.zip (paramVars |> Seq.map (fun x -> x.PUntaint(id, m))) (Option.toList thisArg @ allArgs) do dict.Add(v, (None, e)) dict + let rec exprToExprAndWitness top (ea: Tainted) = let fail() = error(Error(FSComp.SR.etUnsupportedProvidedExpression(ea.PUntaint((fun etree -> etree.UnderlyingExpressionString), m)), m)) match ea with @@ -1807,139 +1807,139 @@ module ProvidedMethodCalls = let srcExpr = exprToExpr expr let targetTy = Import.ImportProvidedType amap m (targetTy.PApply(id, m)) let sourceTy = Import.ImportProvidedType amap m (expr.PApply ((fun e -> e.Type), m)) - let te = mkCoerceIfNeeded g targetTy sourceTy srcExpr - None, (te, tyOfExpr g te) + let exprR = mkCoerceIfNeeded g targetTy sourceTy srcExpr + None, (exprR, tyOfExpr g exprR) | ProvidedTypeTestExpr (expr, targetTy) -> let expr, targetTy = exprType.PApply2((fun _ -> (expr, targetTy)), m) let srcExpr = exprToExpr expr let targetTy = Import.ImportProvidedType amap m (targetTy.PApply(id, m)) - let te = mkCallTypeTest g m targetTy srcExpr - None, (te, tyOfExpr g te) + let exprR = mkCallTypeTest g m targetTy srcExpr + None, (exprR, tyOfExpr g exprR) | ProvidedIfThenElseExpr (test, thenBranch, elseBranch) -> let test, thenBranch, elseBranch = exprType.PApply3((fun _ -> (test, thenBranch, elseBranch)), m) let testExpr = exprToExpr test let ifTrueExpr = exprToExpr thenBranch let ifFalseExpr = exprToExpr elseBranch - let te = mkCond DebugPointAtBinding.NoneAtSticky m (tyOfExpr g ifTrueExpr) testExpr ifTrueExpr ifFalseExpr - None, (te, tyOfExpr g te) + let exprR = mkCond DebugPointAtBinding.NoneAtSticky m (tyOfExpr g ifTrueExpr) testExpr ifTrueExpr ifFalseExpr + None, (exprR, tyOfExpr g exprR) | ProvidedVarExpr providedVar -> let _, vTe = varToExpr (exprType.PApply((fun _ -> providedVar), m)) None, (vTe, tyOfExpr g vTe) | ProvidedConstantExpr (obj, prType) -> - let ce = convertConstExpr g amap m (exprType.PApply((fun _ -> (obj, prType)), m)) - None, (ce, tyOfExpr g ce) + let exprR = convertConstExpr g amap m (exprType.PApply((fun _ -> (obj, prType)), m)) + None, (exprR, tyOfExpr g exprR) | ProvidedNewTupleExpr info -> let elems = exprType.PApplyArray((fun _ -> info), "GetInvokerExpression", m) - let elemsT = elems |> Array.map exprToExpr |> Array.toList - let exprT = mkRefTupledNoTypes g m elemsT - None, (exprT, tyOfExpr g exprT) + let elemsR = elems |> Array.map exprToExpr |> Array.toList + let exprR = mkRefTupledNoTypes g m elemsR + None, (exprR, tyOfExpr g exprR) | ProvidedNewArrayExpr (ty, elems) -> let ty, elems = exprType.PApply2((fun _ -> (ty, elems)), m) - let tyT = Import.ImportProvidedType amap m ty + let tyR = Import.ImportProvidedType amap m ty let elems = elems.PApplyArray(id, "GetInvokerExpression", m) - let elemsT = elems |> Array.map exprToExpr |> Array.toList - let exprT = Expr.Op (TOp.Array, [tyT], elemsT, m) - None, (exprT, tyOfExpr g exprT) + let elemsR = elems |> Array.map exprToExpr |> Array.toList + let exprR = Expr.Op (TOp.Array, [tyR], elemsR, m) + None, (exprR, tyOfExpr g exprR) | ProvidedTupleGetExpr (inp, n) -> let inp, n = exprType.PApply2((fun _ -> (inp, n)), m) - let inpT = inp |> exprToExpr + let inpR = inp |> exprToExpr // if type of expression is erased type then we need convert it to the underlying base type - let typeOfExpr = - let t = tyOfExpr g inpT + let exprTy = + let t = tyOfExpr g inpR stripTyEqnsWrtErasure EraseMeasures g t - let tupInfo, tysT = tryDestAnyTupleTy g typeOfExpr - let exprT = mkTupleFieldGet g (tupInfo, inpT, tysT, n.PUntaint(id, m), m) - None, (exprT, tyOfExpr g exprT) + let tupInfo, tysT = tryDestAnyTupleTy g exprTy + let exprR = mkTupleFieldGet g (tupInfo, inpR, tysT, n.PUntaint(id, m), m) + None, (exprR, tyOfExpr g exprR) | ProvidedLambdaExpr (v, b) -> let v, b = exprType.PApply2((fun _ -> (v, b)), m) - let vT = addVar v - let bT = exprToExpr b + let vR = addVar v + let bR = exprToExpr b removeVar v - let exprT = mkLambda m vT (bT, tyOfExpr g bT) - None, (exprT, tyOfExpr g exprT) + let exprR = mkLambda m vR (bR, tyOfExpr g bR) + None, (exprR, tyOfExpr g exprR) | ProvidedLetExpr (v, e, b) -> let v, e, b = exprType.PApply3((fun _ -> (v, e, b)), m) - let eT = exprToExpr e - let vT = addVar v - let bT = exprToExpr b + let eR = exprToExpr e + let vR = addVar v + let bR = exprToExpr b removeVar v - let exprT = mkCompGenLet m vT eT bT - None, (exprT, tyOfExpr g exprT) + let exprR = mkCompGenLet m vR eR bR + None, (exprR, tyOfExpr g exprR) | ProvidedVarSetExpr (v, e) -> let v, e = exprType.PApply2((fun _ -> (v, e)), m) - let eT = exprToExpr e - let vTopt, _ = varToExpr v - match vTopt with + let eR = exprToExpr e + let vOptR, _ = varToExpr v + match vOptR with | None -> fail() - | Some vT -> - let exprT = mkValSet m (mkLocalValRef vT) eT - None, (exprT, tyOfExpr g exprT) + | Some vR -> + let exprR = mkValSet m (mkLocalValRef vR) eR + None, (exprR, tyOfExpr g exprR) | ProvidedWhileLoopExpr (guardExpr, bodyExpr) -> let guardExpr, bodyExpr = (exprType.PApply2((fun _ -> (guardExpr, bodyExpr)), m)) - let guardExprT = exprToExpr guardExpr - let bodyExprT = exprToExpr bodyExpr - let exprT = mkWhile g (DebugPointAtWhile.No, SpecialWhileLoopMarker.NoSpecialWhileLoopMarker, guardExprT, bodyExprT, m) - None, (exprT, tyOfExpr g exprT) + let guardExprR = exprToExpr guardExpr + let bodyExprR = exprToExpr bodyExpr + let exprR = mkWhile g (DebugPointAtWhile.No, SpecialWhileLoopMarker.NoSpecialWhileLoopMarker, guardExprR, bodyExprR, m) + None, (exprR, tyOfExpr g exprR) | ProvidedForIntegerRangeLoopExpr (v, e1, e2, e3) -> let v, e1, e2, e3 = exprType.PApply4((fun _ -> (v, e1, e2, e3)), m) - let e1T = exprToExpr e1 - let e2T = exprToExpr e2 - let vT = addVar v - let e3T = exprToExpr e3 + let e1R = exprToExpr e1 + let e2R = exprToExpr e2 + let vR = addVar v + let e3R = exprToExpr e3 removeVar v - let exprT = mkFastForLoop g (DebugPointAtFor.No, DebugPointAtInOrTo.No, m, vT, e1T, true, e2T, e3T) - None, (exprT, tyOfExpr g exprT) + let exprR = mkFastForLoop g (DebugPointAtFor.No, DebugPointAtInOrTo.No, m, vR, e1R, true, e2R, e3R) + None, (exprR, tyOfExpr g exprR) | ProvidedNewDelegateExpr (delegateTy, boundVars, delegateBodyExpr) -> let delegateTy, boundVars, delegateBodyExpr = exprType.PApply3((fun _ -> (delegateTy, boundVars, delegateBodyExpr)), m) - let delegateTyT = Import.ImportProvidedType amap m delegateTy + let delegateTyR = Import.ImportProvidedType amap m delegateTy let vs = boundVars.PApplyArray(id, "GetInvokerExpression", m) |> Array.toList let vsT = List.map addVar vs - let delegateBodyExprT = exprToExpr delegateBodyExpr + let delegateBodyExprR = exprToExpr delegateBodyExpr List.iter removeVar vs - let lambdaExpr = mkLambdas g m [] vsT (delegateBodyExprT, tyOfExpr g delegateBodyExprT) + let lambdaExpr = mkLambdas g m [] vsT (delegateBodyExprR, tyOfExpr g delegateBodyExprR) let lambdaExprTy = tyOfExpr g lambdaExpr let infoReader = InfoReader(g, amap) - let exprT = CoerceFromFSharpFuncToDelegate g amap infoReader AccessorDomain.AccessibleFromSomewhere lambdaExprTy m lambdaExpr delegateTyT - None, (exprT, tyOfExpr g exprT) + let exprR = CoerceFromFSharpFuncToDelegate g amap infoReader AccessorDomain.AccessibleFromSomewhere lambdaExprTy m lambdaExpr delegateTyR + None, (exprR, tyOfExpr g exprR) #if PROVIDED_ADDRESS_OF | ProvidedAddressOfExpr e -> - let eT = exprToExpr (exprType.PApply((fun _ -> e), m)) - let wrap,ce, _readonly, _writeonly = mkExprAddrOfExpr g true false DefinitelyMutates eT None m - let ce = wrap ce - None, (ce, tyOfExpr g ce) + let eR = exprToExpr (exprType.PApply((fun _ -> e), m)) + let wrap,exprR, _readonly, _writeonly = mkExprAddrOfExpr g true false DefinitelyMutates eR None m + let exprR = wrap exprR + None, (exprR, tyOfExpr g exprR) #endif | ProvidedDefaultExpr pty -> let ty = Import.ImportProvidedType amap m (exprType.PApply((fun _ -> pty), m)) - let ce = mkDefault (m, ty) - None, (ce, tyOfExpr g ce) + let exprR = mkDefault (m, ty) + None, (exprR, tyOfExpr g exprR) | ProvidedCallExpr (e1, e2, e3) -> methodCallToExpr top ea (exprType.PApply((fun _ -> (e1, e2, e3)), m)) | ProvidedSequentialExpr (e1, e2) -> let e1, e2 = exprType.PApply2((fun _ -> (e1, e2)), m) - let e1T = exprToExpr e1 - let e2T = exprToExpr e2 - let ce = mkCompGenSequential m e1T e2T - None, (ce, tyOfExpr g ce) + let e1R = exprToExpr e1 + let e2R = exprToExpr e2 + let exprR = mkCompGenSequential m e1R e2R + None, (exprR, tyOfExpr g exprR) | ProvidedTryFinallyExpr (e1, e2) -> let e1, e2 = exprType.PApply2((fun _ -> (e1, e2)), m) - let e1T = exprToExpr e1 - let e2T = exprToExpr e2 - let ce = mkTryFinally g (e1T, e2T, m, tyOfExpr g e1T, DebugPointAtTry.No, DebugPointAtFinally.No) - None, (ce, tyOfExpr g ce) + let e1R = exprToExpr e1 + let e2R = exprToExpr e2 + let exprR = mkTryFinally g (e1R, e2R, m, tyOfExpr g e1R, DebugPointAtTry.No, DebugPointAtFinally.No) + None, (exprR, tyOfExpr g exprR) | ProvidedTryWithExpr (e1, e2, e3, e4, e5) -> let info = exprType.PApply((fun _ -> (e1, e2, e3, e4, e5)), m) - let bT = exprToExpr (info.PApply((fun (x, _, _, _, _) -> x), m)) + let bR = exprToExpr (info.PApply((fun (x, _, _, _, _) -> x), m)) let v1 = info.PApply((fun (_, x, _, _, _) -> x), m) - let v1T = addVar v1 - let e1T = exprToExpr (info.PApply((fun (_, _, x, _, _) -> x), m)) + let v1R = addVar v1 + let e1R = exprToExpr (info.PApply((fun (_, _, x, _, _) -> x), m)) removeVar v1 let v2 = info.PApply((fun (_, _, _, x, _) -> x), m) - let v2T = addVar v2 - let e2T = exprToExpr (info.PApply((fun (_, _, _, _, x) -> x), m)) + let v2R = addVar v2 + let e2R = exprToExpr (info.PApply((fun (_, _, _, _, x) -> x), m)) removeVar v2 - let ce = mkTryWith g (bT, v1T, e1T, v2T, e2T, m, tyOfExpr g bT, DebugPointAtTry.No, DebugPointAtWith.No) - None, (ce, tyOfExpr g ce) + let exprR = mkTryWith g (bR, v1R, e1R, v2R, e2R, m, tyOfExpr g bR, DebugPointAtTry.No, DebugPointAtWith.No) + None, (exprR, tyOfExpr g exprR) | ProvidedNewObjectExpr (e1, e2) -> None, ctorCallToExpr (exprType.PApply((fun _ -> (e1, e2)), m)) @@ -1956,10 +1956,10 @@ module ProvidedMethodCalls = let nm = v.PUntaint ((fun v -> v.Name), m) let mut = v.PUntaint ((fun v -> v.IsMutable), m) let vRaw = v.PUntaint (id, m) - let tyT = Import.ImportProvidedType amap m (v.PApply ((fun v -> v.Type), m)) - let vT, vTe = if mut then mkMutableCompGenLocal m nm tyT else mkCompGenLocal m nm tyT - varConv[vRaw] <- (Some vT, vTe) - vT + let tyR = Import.ImportProvidedType amap m (v.PApply ((fun v -> v.Type), m)) + let vR, vTe = if mut then mkMutableCompGenLocal m nm tyR else mkCompGenLocal m nm tyR + varConv[vRaw] <- (Some vR, vTe) + vR and removeVar (v: Tainted) = let vRaw = v.PUntaint (id, m) diff --git a/src/Compiler/Checking/MethodOverrides.fs b/src/Compiler/Checking/MethodOverrides.fs index 9d3e6c50153..7c5e9934a77 100644 --- a/src/Compiler/Checking/MethodOverrides.fs +++ b/src/Compiler/Checking/MethodOverrides.fs @@ -160,7 +160,7 @@ module DispatchSlotChecking = let belongsToReqdTy = match overrideBy.MemberInfo.Value.ImplementedSlotSigs with | [] -> false - | ss :: _ -> isInterfaceTy g ss.ImplementedType && typeEquiv g reqdTy ss.ImplementedType + | ss :: _ -> isInterfaceTy g ss.DeclaringType && typeEquiv g reqdTy ss.DeclaringType if belongsToReqdTy then CanImplementAnyInterfaceSlot else @@ -178,7 +178,7 @@ module DispatchSlotChecking = Override(implKind, overrideBy.MemberApparentEntity, mkSynId overrideBy.Range nm, memberMethodTypars, memberToParentInst, argTys, retTy, isFakeEventProperty, overrideBy.IsCompilerGenerated) /// Get the override information for an object expression method being used to implement dispatch slots - let GetObjectExprOverrideInfo g amap (implty, id: Ident, memberFlags, ty, arityInfo, bindingAttribs, rhsExpr) = + let GetObjectExprOverrideInfo g amap (implTy, id: Ident, memberFlags, ty, arityInfo, bindingAttribs, rhsExpr) = // Dissect the type. The '0' indicates there are no enclosing generic class type parameters relevant here. let tps, _, argInfos, retTy, _ = GetMemberTypeInMemberForm g memberFlags arityInfo 0 ty id.idRange let argTys = argInfos |> List.mapSquared fst @@ -192,13 +192,13 @@ module DispatchSlotChecking = // Check for empty variable list from a () arg let vs = if List.isSingleton vs && argInfos.IsEmpty then [] else vs let implKind = - if isInterfaceTy g implty then + if isInterfaceTy g implTy then CanImplementAnyInterfaceSlot else CanImplementAnyClassHierarchySlot //CanImplementAnySlot <<----- Change to this to enable implicit interface implementation let isFakeEventProperty = CompileAsEvent g bindingAttribs - let overrideByInfo = Override(implKind, tcrefOfAppTy g implty, id, tps, [], argTys, retTy, isFakeEventProperty, false) + let overrideByInfo = Override(implKind, tcrefOfAppTy g implTy, id, tps, [], argTys, retTy, isFakeEventProperty, false) overrideByInfo, (baseValOpt, thisv, vs, bindingAttribs, rhsExpr) | _ -> error(InternalError("Unexpected shape for object expression override", id.idRange)) @@ -749,7 +749,7 @@ module DispatchSlotChecking = let amap = infoReader.amap let tcaug = tycon.TypeContents - let interfaces = tycon.ImmediateInterfacesOfFSharpTycon |> List.map (fun (ity, _compgen, m) -> (ity, m)) + let interfaces = tycon.ImmediateInterfacesOfFSharpTycon |> List.map (fun (intfTy, _compgen, m) -> (intfTy, m)) let overallTy = generalizedTyconRef g (mkLocalTyconRef tycon) @@ -780,9 +780,9 @@ module DispatchSlotChecking = | [] -> // Are we looking at the implementation of the class hierarchy? If so include all the override members not (isInterfaceTy g reqdTy) - | ss -> - ss |> List.forall (fun ss -> - let ty = ss.ImplementedType + | slotSigs -> + slotSigs |> List.forall (fun slotSig -> + let ty = slotSig.DeclaringType if isInterfaceTy g ty then // Is this a method impl listed under the reqdTy? typeEquiv g ty reqdTy diff --git a/src/Compiler/Checking/MethodOverrides.fsi b/src/Compiler/Checking/MethodOverrides.fsi index e6091626469..b93b290f5d3 100644 --- a/src/Compiler/Checking/MethodOverrides.fsi +++ b/src/Compiler/Checking/MethodOverrides.fsi @@ -89,7 +89,7 @@ module DispatchSlotChecking = val GetObjectExprOverrideInfo: g: TcGlobals -> amap: ImportMap -> - implty: TType * + implTy: TType * id: Ident * memberFlags: SynMemberFlags * ty: TType * diff --git a/src/Compiler/Checking/NameResolution.fs b/src/Compiler/Checking/NameResolution.fs index d4825fb9e9a..0f3daba1d0f 100644 --- a/src/Compiler/Checking/NameResolution.fs +++ b/src/Compiler/Checking/NameResolution.fs @@ -1420,10 +1420,10 @@ and AddModuleOrNamespaceContentsToNameEnv (g: TcGlobals) amap (ad: AccessorDomai and AddModuleOrNamespaceRefsContentsToNameEnv g amap ad m root nenv modrefs = (modrefs, nenv) ||> List.foldBack (fun modref acc -> AddModuleOrNamespaceRefContentsToNameEnv g amap ad m root acc modref) -and AddTypeContentsToNameEnv g amap ad m nenv (typ: TType) = - assert (isAppTy g typ) - assert not (tcrefOfAppTy g typ).IsModuleOrNamespace - AddStaticContentOfTypeToNameEnv g amap ad m nenv typ +and AddTypeContentsToNameEnv g amap ad m nenv (ty: TType) = + assert (isAppTy g ty) + assert not (tcrefOfAppTy g ty).IsModuleOrNamespace + AddStaticContentOfTypeToNameEnv g amap ad m nenv ty and AddModuleOrNamespaceRefContentsToNameEnv g amap ad m root nenv (modref: EntityRef) = assert modref.IsModuleOrNamespace @@ -2167,7 +2167,7 @@ let CheckAllTyparsInferrable amap m item = /// ultimately calls ResolutionInfo.Method to record it for /// later use by Visual Studio. type ResolutionInfo = - | ResolutionInfo of (*entityPath, reversed*)(range * EntityRef) list * (*warnings/errors*)(ResultTyparChecker -> unit) * tinstEnclosing: EnclosingTypeInst + | ResolutionInfo of revEntityPath: (range * EntityRef) list * reportResult: (ResultTyparChecker -> unit) * tinstEnclosing: EnclosingTypeInst static member SendEntityPathToSink(sink, ncenv: NameResolver, nenv, occ, ad, ResolutionInfo(entityPath, warnings, _), typarChecker) = entityPath |> List.iter (fun (m, eref: EntityRef) -> @@ -2426,8 +2426,8 @@ let TryFindUnionCaseOfType g ty nm = ValueNone /// Try to find a union case of a type, with the given name -let TryFindAnonRecdFieldOfType g typ nm = - match tryDestAnonRecdTy g typ with +let TryFindAnonRecdFieldOfType g ty nm = + match tryDestAnonRecdTy g ty with | ValueSome (anonInfo, tys) -> match anonInfo.SortedIds |> Array.tryFindIndex (fun x -> x.idText = nm) with | Some i -> Some (Item.AnonRecdField(anonInfo, tys, i, anonInfo.SortedIds[i].idRange)) @@ -4113,7 +4113,7 @@ let rec ResolvePartialLongIdentInType (ncenv: NameResolver) nenv isApplicableMet // e.g. .. for einfo in ncenv.InfoReader.GetEventInfosOfType(Some id, ad, m, ty) do - let einfoTy = PropTypOfEventInfo ncenv.InfoReader m ad einfo + let einfoTy = PropTypeOfEventInfo ncenv.InfoReader m ad einfo yield! ResolvePartialLongIdentInType ncenv nenv isApplicableMeth m ad false rest einfoTy // nested types @@ -4811,7 +4811,7 @@ let rec ResolvePartialLongIdentInTypeForItem (ncenv: NameResolver) nenv m ad sta // e.g. .. for einfo in ncenv.InfoReader.GetEventInfosOfType(Some id, ad, m, ty) do - let tyinfo = PropTypOfEventInfo ncenv.InfoReader m ad einfo + let tyinfo = PropTypeOfEventInfo ncenv.InfoReader m ad einfo yield! ResolvePartialLongIdentInTypeForItem ncenv nenv m ad false rest item tyinfo // nested types! diff --git a/src/Compiler/Checking/NicePrint.fs b/src/Compiler/Checking/NicePrint.fs index 49063183b01..a07f000c7a7 100644 --- a/src/Compiler/Checking/NicePrint.fs +++ b/src/Compiler/Checking/NicePrint.fs @@ -72,46 +72,61 @@ module internal PrintUtilities = // // val SampleFunctionTupledAllBreakA: // longLongLongArgName1: string * longLongLongArgName2: TType * - // longLongLongArgName3: TType * longLongLongArgName4: TType - // -> TType list + // longLongLongArgName3: TType * longLongLongArgName4: TType -> + // TType list // // val SampleFunctionTupledAllBreakA: // longLongLongArgName1: string * // longLongLongArgName2: TType * // longLongLongArgName3: TType * - // longLongLongArgName4: TType - // -> TType list + // longLongLongArgName4: TType -> + // TType list // // val SampleFunctionCurriedOneBreakA: - // arg1: string -> arg2: TType -> arg3: TType - // -> arg4: TType -> TType list + // arg1: string -> arg2: TType -> arg3: TType -> + // arg4: TType -> TType list // // val SampleFunctionCurriedAllBreaksA: - // longLongLongArgName1: string - // -> longLongLongArgName2: TType - // -> longLongLongArgName3: TType - // -> longLongLongArgName4: TType - // -> TType list + // longLongLongArgName1: string -> + // longLongLongArgName2: TType -> + // longLongLongArgName3: TType -> + // longLongLongArgName4: TType -> + // TType list // // val SampleFunctionMixedA: // longLongLongArgName1: string * - // longLongLongArgName2: string - // -> longLongLongArgName3: string * - // longLongLongArgName4: string * - // longLongLongArgName5: TType - // -> longLongLongArgName6: TType * - // longLongLongArgName7: TType * - // -> longLongLongArgName8: TType * - // longLongLongArgName9: TType * - // longLongLongArgName10: TType - // -> TType list + // longLongLongArgName2: string -> + // longLongLongArgName3: string * + // longLongLongArgName4: string * + // longLongLongArgName5: TType -> + // longLongLongArgName6: TType * + // longLongLongArgName7: TType -> + // longLongLongArgName8: TType * + // longLongLongArgName9: TType * + // longLongLongArgName10: TType -> + // TType list let curriedLayoutsL retTyDelim (argTysL: Layout list) (retTyL: Layout) = - let arrowAndRetyL = wordL (tagPunctuation retTyDelim) ^^ retTyL - let argTysL = - argTysL - |> List.mapi (fun i argTyL -> if i = 0 then argTyL else wordL (tagPunctuation "->") ^^ argTyL) - |> List.reduce (++) - argTysL --- arrowAndRetyL + let lastIndex = List.length argTysL - 1 + + argTysL + |> List.mapi (fun idx argTyL -> + let isTupled = + idx = 0 || + match argTyL with + | Node(leftLayout = Node(rightLayout = Leaf (text = starText))) -> starText.Text = "*" + | _ -> false + + let layout = + argTyL + ^^ (if idx = lastIndex then + wordL (tagPunctuation retTyDelim) + else + wordL (tagPunctuation "->")) + + isTupled, layout) + |> List.rev + |> fun reversedArgs -> (true, retTyL) :: reversedArgs + |> List.fold (fun acc (shouldBreak, layout) -> (if shouldBreak then (---) else (++)) layout acc) emptyL let tagNavArbValRef (valRefOpt: ValRef option) tag = match valRefOpt with @@ -482,7 +497,7 @@ module PrintTypes = | _ -> itemL /// Layout a reference to a type - let layoutTyconRef denv tycon = layoutTyconRefImpl false denv tycon + let layoutTyconRef denv tcref = layoutTyconRefImpl false denv tcref /// Layout the flags of a member let layoutMemberFlags (memFlags: SynMemberFlags) = @@ -531,8 +546,8 @@ module PrintTypes = | TypeDefOfExpr denv.g ty -> LeftL.keywordTypedefof ^^ wordL (tagPunctuation "<") ^^ layoutType denv ty ^^ rightL (tagPunctuation ">") - | Expr.Op (TOp.Coerce, [tgTy;_], [arg2], _) -> - leftL (tagPunctuation "(") ^^ layoutAttribArg denv arg2 ^^ wordL (tagPunctuation ":>") ^^ layoutType denv tgTy ^^ rightL (tagPunctuation ")") + | Expr.Op (TOp.Coerce, [tgtTy;_], [arg2], _) -> + leftL (tagPunctuation "(") ^^ layoutAttribArg denv arg2 ^^ wordL (tagPunctuation ":>") ^^ layoutType denv tgtTy ^^ rightL (tagPunctuation ")") | AttribBitwiseOrExpr denv.g (arg1, arg2) -> layoutAttribArg denv arg1 ^^ wordL (tagPunctuation "|||") ^^ layoutAttribArg denv arg2 @@ -711,8 +726,8 @@ module PrintTypes = and layoutConstraintWithInfo denv env (tp, tpc) = let longConstraintPrefix l = (layoutTyparRefWithInfo denv env tp |> addColonL) ^^ l match tpc with - | TyparConstraint.CoercesTo(tpct, _) -> - [layoutTyparRefWithInfo denv env tp ^^ wordL (tagOperator ":>") --- layoutTypeWithInfo denv env tpct] + | TyparConstraint.CoercesTo(tgtTy, _) -> + [layoutTyparRefWithInfo denv env tp ^^ wordL (tagOperator ":>") --- layoutTypeWithInfo denv env tgtTy] | TyparConstraint.MayResolveMember(traitInfo, _) -> [layoutTraitWithInfo denv env traitInfo] @@ -800,8 +815,8 @@ module PrintTypes = /// Layout a unit of measure expression and layoutMeasure denv unt = - let sortVars vs = vs |> List.sortBy (fun (v: Typar, _) -> v.DisplayName) - let sortCons cs = cs |> List.sortBy (fun (c: TyconRef, _) -> c.DisplayName) + let sortVars vs = vs |> List.sortBy (fun (tp: Typar, _) -> tp.DisplayName) + let sortCons cs = cs |> List.sortBy (fun (tcref: TyconRef, _) -> tcref.DisplayName) let negvs, posvs = ListMeasureVarOccsWithNonZeroExponents unt |> sortVars |> List.partition (fun (_, e) -> SignRational e < 0) let negcs, poscs = ListMeasureConOccsWithNonZeroExponents denv.g false unt |> sortCons |> List.partition (fun (_, e) -> SignRational e < 0) let unparL uv = layoutTyparRef denv uv @@ -817,14 +832,14 @@ module PrintTypes = | _ -> prefix ^^ sepL (tagPunctuation "/") ^^ (if List.length negvs + List.length negcs > 1 then sepL (tagPunctuation "(") ^^ postfix ^^ sepL (tagPunctuation ")") else postfix) /// Layout type arguments, either NAME or (ty, ..., ty) NAME *) - and layoutTypeAppWithInfoAndPrec denv env tcL prec prefix args = + and layoutTypeAppWithInfoAndPrec denv env tcL prec prefix argTys = if prefix then - match args with + match argTys with | [] -> tcL - | [arg] -> tcL ^^ sepL (tagPunctuation "<") ^^ (layoutTypeWithInfoAndPrec denv env 4 arg) ^^ rightL (tagPunctuation">") - | args -> bracketIfL (prec <= 1) (tcL ^^ angleL (layoutTypesWithInfoAndPrec denv env 2 (sepL (tagPunctuation ",")) args)) + | [argTy] -> tcL ^^ sepL (tagPunctuation "<") ^^ (layoutTypeWithInfoAndPrec denv env 4 argTy) ^^ rightL (tagPunctuation">") + | _ -> bracketIfL (prec <= 1) (tcL ^^ angleL (layoutTypesWithInfoAndPrec denv env 2 (sepL (tagPunctuation ",")) argTys)) else - match args with + match argTys with | [] -> tcL | [arg] -> layoutTypeWithInfoAndPrec denv env 2 arg ^^ tcL | args -> bracketIfL (prec <= 1) (bracketL (layoutTypesWithInfoAndPrec denv env 2 (sepL (tagPunctuation ",")) args) --- tcL) @@ -957,7 +972,6 @@ module PrintTypes = /// Layout a single type used as the type of a member or value let layoutTopType denv env argInfos retTy cxs = - // Parenthesize the return type to match the topValInfo let retTyL = layoutReturnType denv env retTy let cxsL = layoutConstraintsWithInfo denv env cxs match argInfos with @@ -1036,8 +1050,8 @@ module PrintTypes = prettyTyparInst, niceMethodTypars, layout - let prettyLayoutOfMemberType denv v typarInst argInfos retTy = - match PartitionValRefTypars denv.g v with + let prettyLayoutOfMemberType denv vref typarInst argInfos retTy = + match PartitionValRefTypars denv.g vref with | Some(_, _, memberMethodTypars, memberToParentInst, _) -> prettyLayoutOfMemberSigCore denv memberToParentInst (typarInst, memberMethodTypars, argInfos, retTy) | None -> @@ -1109,14 +1123,14 @@ module PrintTypes = let ty, _cxs = PrettyTypes.PrettifyType denv.g ty layoutTypeWithInfoAndPrec denv SimplifyTypes.typeSimplificationInfo0 5 ty - let layoutOfValReturnType denv (v: ValRef) = - match v.ValReprInfo with + let layoutOfValReturnType denv (vref: ValRef) = + match vref.ValReprInfo with | None -> - let tau = v.TauType + let tau = vref.TauType let _argTysl, retTy = stripFunTy denv.g tau layoutReturnType denv SimplifyTypes.typeSimplificationInfo0 retTy | Some (ValReprInfo(_typars, argInfos, _retInfo)) -> - let tau = v.TauType + let tau = vref.TauType let _c, retTy = GetTopTauTypeInFSharpForm denv.g argInfos tau Range.range0 layoutReturnType denv SimplifyTypes.typeSimplificationInfo0 retTy @@ -1133,22 +1147,22 @@ module PrintTastMemberOrVals = else nameL - let layoutMemberName (denv: DisplayEnv) (v: ValRef) niceMethodTypars tagFunction name = - let nameL = ConvertValNameToDisplayLayout v.IsBaseVal (tagFunction >> mkNav v.DefinitionRange >> wordL) name + let layoutMemberName (denv: DisplayEnv) (vref: ValRef) niceMethodTypars tagFunction name = + let nameL = ConvertValNameToDisplayLayout vref.IsBaseVal (tagFunction >> mkNav vref.DefinitionRange >> wordL) name let nameL = if denv.showMemberContainers then - layoutTyconRef denv v.MemberApparentEntity ^^ SepL.dot ^^ nameL + layoutTyconRef denv vref.MemberApparentEntity ^^ SepL.dot ^^ nameL else nameL let nameL = if denv.showTyparBinding then layoutTyparDecls denv nameL true niceMethodTypars else nameL - let nameL = layoutAccessibility denv v.Accessibility nameL + let nameL = layoutAccessibility denv vref.Accessibility nameL nameL let prettyLayoutOfMemberShortOption denv typarInst (v: Val) short = - let v = mkLocalValRef v - let membInfo = Option.get v.MemberInfo + let vref = mkLocalValRef v + let membInfo = Option.get vref.MemberInfo let stat = layoutMemberFlags membInfo.MemberFlags - let _tps, argInfos, retTy, _ = GetTypeOfMemberInFSharpForm denv.g v + let _tps, argInfos, retTy, _ = GetTypeOfMemberInFSharpForm denv.g vref if short then for argInfo in argInfos do @@ -1159,22 +1173,22 @@ module PrintTastMemberOrVals = let prettyTyparInst, memberL = match membInfo.MemberFlags.MemberKind with | SynMemberKind.Member -> - let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos retTy + let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv vref typarInst argInfos retTy let resL = if short then tauL else - let nameL = layoutMemberName denv v niceMethodTypars tagMember v.DisplayNameCoreMangled - let nameL = if short then nameL else mkInlineL denv v.Deref nameL + let nameL = layoutMemberName denv vref niceMethodTypars tagMember vref.DisplayNameCoreMangled + let nameL = if short then nameL else mkInlineL denv vref.Deref nameL stat --- ((nameL |> addColonL) ^^ tauL) prettyTyparInst, resL | SynMemberKind.ClassConstructor | SynMemberKind.Constructor -> - let prettyTyparInst, _, tauL = prettyLayoutOfMemberType denv v typarInst argInfos retTy + let prettyTyparInst, _, tauL = prettyLayoutOfMemberType denv vref typarInst argInfos retTy let resL = if short then tauL else - let newL = layoutAccessibility denv v.Accessibility WordL.keywordNew + let newL = layoutAccessibility denv vref.Accessibility WordL.keywordNew stat ++ (newL |> addColonL) ^^ tauL prettyTyparInst, resL @@ -1184,8 +1198,8 @@ module PrintTastMemberOrVals = | SynMemberKind.PropertyGet -> if isNil argInfos then // use error recovery because intellisense on an incomplete file will show this - errorR(Error(FSComp.SR.tastInvalidFormForPropertyGetter(), v.Id.idRange)) - let nameL = layoutMemberName denv v [] tagProperty v.DisplayNameCoreMangled + errorR(Error(FSComp.SR.tastInvalidFormForPropertyGetter(), vref.Id.idRange)) + let nameL = layoutMemberName denv vref [] tagProperty vref.DisplayNameCoreMangled let resL = if short then nameL --- (WordL.keywordWith ^^ WordL.keywordGet) else stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordGet) @@ -1195,31 +1209,31 @@ module PrintTastMemberOrVals = match argInfos with | [[(ty, _)]] when isUnitTy denv.g ty -> [] | _ -> argInfos - let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos retTy + let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv vref typarInst argInfos retTy let resL = if short then if isNil argInfos then tauL else tauL --- (WordL.keywordWith ^^ WordL.keywordGet) else - let nameL = layoutMemberName denv v niceMethodTypars tagProperty v.DisplayNameCoreMangled + let nameL = layoutMemberName denv vref niceMethodTypars tagProperty vref.DisplayNameCoreMangled stat --- ((nameL |> addColonL) ^^ (if isNil argInfos then tauL else tauL --- (WordL.keywordWith ^^ WordL.keywordGet))) prettyTyparInst, resL | SynMemberKind.PropertySet -> if argInfos.Length <> 1 || isNil argInfos.Head then // use error recovery because intellisense on an incomplete file will show this - errorR(Error(FSComp.SR.tastInvalidFormForPropertySetter(), v.Id.idRange)) - let nameL = layoutMemberName denv v [] tagProperty v.DisplayNameCoreMangled + errorR(Error(FSComp.SR.tastInvalidFormForPropertySetter(), vref.Id.idRange)) + let nameL = layoutMemberName denv vref [] tagProperty vref.DisplayNameCoreMangled let resL = stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordSet) emptyTyparInst, resL else let argInfos, valueInfo = List.frontAndBack argInfos.Head - let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst (if isNil argInfos then [] else [argInfos]) (fst valueInfo) + let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv vref typarInst (if isNil argInfos then [] else [argInfos]) (fst valueInfo) let resL = if short then (tauL --- (WordL.keywordWith ^^ WordL.keywordSet)) else - let nameL = layoutMemberName denv v niceMethodTypars tagProperty v.DisplayNameCoreMangled + let nameL = layoutMemberName denv vref niceMethodTypars tagProperty vref.DisplayNameCoreMangled stat --- ((nameL |> addColonL) ^^ (tauL --- (WordL.keywordWith ^^ WordL.keywordSet))) prettyTyparInst, resL @@ -1256,7 +1270,8 @@ module PrintTastMemberOrVals = let layoutNonMemberVal denv (tps, v: Val, tau, cxs) = let env = SimplifyTypes.CollectInfo true [tau] cxs let cxs = env.postfixConstraints - let argInfos, retTy = GetTopTauTypeInFSharpForm denv.g (arityOfVal v).ArgInfos tau v.Range + let valReprInfo = arityOfValForDisplay v + let argInfos, retTy = GetTopTauTypeInFSharpForm denv.g valReprInfo.ArgInfos tau v.Range let nameL = let tagF = @@ -1555,7 +1570,7 @@ module TastDefinitionPrinting = let layoutExtensionMember denv infoReader (vref: ValRef) = let (@@*) = if denv.printVerboseSignatures then (@@----) else (@@--) let tycon = vref.MemberApparentEntity.Deref - let nameL = ConvertNameToDisplayLayout (tagMethod >> mkNav vref.DefinitionRange >> wordL) tycon.DisplayNameCore + let nameL = layoutTyconRefImpl false denv vref.MemberApparentEntity let nameL = layoutAccessibility denv tycon.Accessibility nameL // "type-accessibility" let tps = match PartitionValTyparsForApparentEnclosingType denv.g vref.Deref with @@ -1572,7 +1587,13 @@ module TastDefinitionPrinting = let lhs = ConvertNameToDisplayLayout (tagRecordField >> mkNav fld.DefinitionRange >> wordL) fld.DisplayNameCore let lhs = (if isClassDecl then layoutAccessibility denv fld.Accessibility lhs else lhs) let lhs = if fld.IsMutable then wordL (tagKeyword "mutable") --- lhs else lhs - let fieldL = (lhs |> addColonL) --- layoutType denv fld.FormalType + let fieldL = + let rhs = + match stripTyparEqns fld.FormalType with + | TType_fun _ -> LeftL.leftParen ^^ layoutType denv fld.FormalType ^^ RightL.rightParen + | _ -> layoutType denv fld.FormalType + + (lhs |> addColonL) --- rhs let fieldL = prefix fieldL let fieldL = fieldL |> layoutAttribs denv None false TyparKind.Type (fld.FieldAttribs @ fld.PropertyAttribs) @@ -1680,7 +1701,7 @@ module TastDefinitionPrinting = let ty = generalizedTyconRef g tcref let start, tagger = - if isStructTy g ty then + if isStructTy g ty && not tycon.TypeAbbrev.IsSome then // Always show [] whether verbose or not Some "struct", tagStruct elif isInterfaceTy g ty then @@ -1709,23 +1730,23 @@ module TastDefinitionPrinting = typewordL ^^ tpsL - let sortKey (v: MethInfo) = - (not v.IsConstructor, - not v.IsInstance, // instance first - v.DisplayNameCore, // sort by name - List.sum v.NumArgs, // sort by #curried - v.NumArgs.Length) // sort by arity + let sortKey (minfo: MethInfo) = + (not minfo.IsConstructor, + not minfo.IsInstance, // instance first + minfo.DisplayNameCore, // sort by name + List.sum minfo.NumArgs, // sort by #curried + minfo.NumArgs.Length) // sort by arity - let shouldShow (valRef: ValRef option) = - match valRef with + let shouldShow (vrefOpt: ValRef option) = + match vrefOpt with | None -> true - | Some(vr) -> - (denv.showObsoleteMembers || not (CheckFSharpAttributesForObsolete denv.g vr.Attribs)) && - (denv.showHiddenMembers || not (CheckFSharpAttributesForHidden denv.g vr.Attribs)) + | Some vref -> + (denv.showObsoleteMembers || not (CheckFSharpAttributesForObsolete denv.g vref.Attribs)) && + (denv.showHiddenMembers || not (CheckFSharpAttributesForHidden denv.g vref.Attribs)) let ctors = GetIntrinsicConstructorInfosOfType infoReader m ty - |> List.filter (fun v -> IsMethInfoAccessible amap m ad v && not v.IsClassConstructor && shouldShow v.ArbitraryValRef) + |> List.filter (fun minfo -> IsMethInfoAccessible amap m ad minfo && not minfo.IsClassConstructor && shouldShow minfo.ArbitraryValRef) let iimpls = if suppressInheritanceAndInterfacesForTyInSimplifiedDisplays g amap m ty then @@ -1739,15 +1760,15 @@ module TastDefinitionPrinting = let iimplsLs = iimpls - |> List.map (fun ity -> wordL (tagKeyword (if isInterfaceTy g ty then "inherit" else "interface")) -* layoutType denv ity) + |> List.map (fun intfTy -> wordL (tagKeyword (if isInterfaceTy g ty then "inherit" else "interface")) -* layoutType denv intfTy) let props = GetImmediateIntrinsicPropInfosOfType (None, ad) g amap m ty - |> List.filter (fun v -> shouldShow v.ArbitraryValRef) + |> List.filter (fun pinfo -> shouldShow pinfo.ArbitraryValRef) let events = infoReader.GetEventInfosOfType(None, ad, m, ty) - |> List.filter (fun v -> shouldShow v.ArbitraryValRef && typeEquiv g ty v.ApparentEnclosingType) + |> List.filter (fun einfo -> shouldShow einfo.ArbitraryValRef && typeEquiv g ty einfo.ApparentEnclosingType) let impliedNames = try @@ -1862,8 +1883,8 @@ module TastDefinitionPrinting = let inherits = [ if not (suppressInheritanceAndInterfacesForTyInSimplifiedDisplays g amap m ty) then match GetSuperTypeOfType g amap m ty with - | Some super when not (isObjTy g super) && not (isValueTypeTy g super) -> - super + | Some superTy when not (isObjTy g superTy) && not (isValueTypeTy g superTy) -> + superTy | _ -> () ] @@ -1988,8 +2009,18 @@ module TastDefinitionPrinting = |> aboveListL |> addLhs - | TFSharpObjectRepr _ when isNil allDecls -> - lhsL + | TFSharpObjectRepr objRepr when isNil allDecls -> + match objRepr.fsobjmodel_kind with + | TFSharpClass -> + WordL.keywordClass ^^ WordL.keywordEnd + |> addLhs + | TFSharpInterface -> + WordL.keywordInterface ^^ WordL.keywordEnd + |> addLhs + | TFSharpStruct -> + WordL.keywordStruct ^^ WordL.keywordEnd + |> addLhs + | _ -> lhsL | TFSharpObjectRepr _ -> allDecls @@ -2021,8 +2052,8 @@ module TastDefinitionPrinting = |> addLhs | TNoRepr when tycon.TypeAbbrev.IsSome -> - let abbreviatedType = tycon.TypeAbbrev.Value - (lhsL ^^ WordL.equals) -* (layoutType { denv with shortTypeNames = false } abbreviatedType) + let abbreviatedTy = tycon.TypeAbbrev.Value + (lhsL ^^ WordL.equals) -* (layoutType { denv with shortTypeNames = false } abbreviatedTy) | _ when isNil allDecls -> lhsL @@ -2116,7 +2147,8 @@ module TastDefinitionPrinting = mspec.ModuleOrNamespaceType.AllValsAndMembers |> Seq.isEmpty // Check if its an outer module or a nested module - if (outerPath |> List.forall (fun (_, istype) -> istype = Namespace)) && isNil outerPath then + let isNamespace = function | Namespace _ -> true | _ -> false + if (outerPath |> List.forall (fun (_, istype) -> isNamespace istype)) && isNil outerPath then // If so print a "module" declaration modNameL elif modIsEmpty then @@ -2245,8 +2277,42 @@ module InferredSigPrinting = let innerPath = (fullCompPathOfModuleOrNamespace mspec).AccessPath let outerPath = mspec.CompilationPath.AccessPath - let denv = denv.AddOpenPath (List.map fst innerPath) - if mspec.IsNamespace then + let denv = + innerPath + |> List.choose (fun (path, kind) -> + match kind with + | ModuleOrNamespaceKind.Namespace false -> None + | _ -> Some path) + |> denv.AddOpenPath + + if mspec.IsImplicitNamespace then + // The current mspec is a namespace that belongs to the `def` child (nested) module(s). + let fullModuleName, def, denv = + let rec (|NestedModule|_|) (currentContents:ModuleOrNamespaceContents) = + match currentContents with + | ModuleOrNamespaceContents.TMDefRec (bindings = [ ModuleOrNamespaceBinding.Module(mn, NestedModule(path, contents)) ]) -> + Some ([ yield mn.DisplayNameCore; yield! path ], contents) + | ModuleOrNamespaceContents.TMDefs [ ModuleOrNamespaceContents.TMDefRec (bindings = [ ModuleOrNamespaceBinding.Module(mn, NestedModule(path, contents)) ]) ] -> + Some ([ yield mn.DisplayNameCore; yield! path ], contents) + | ModuleOrNamespaceContents.TMDefs [ ModuleOrNamespaceContents.TMDefRec (bindings = [ ModuleOrNamespaceBinding.Module(mn, nestedModuleContents) ]) ] -> + Some ([ mn.DisplayNameCore ], nestedModuleContents) + | _ -> + None + + match def with + | NestedModule(path, nestedModuleContents) -> + let fullPath = mspec.DisplayNameCore :: path + fullPath, nestedModuleContents, denv.AddOpenPath(fullPath) + | _ -> [ mspec.DisplayNameCore ], def, denv + + let nmL = List.map (tagModule >> wordL) fullModuleName |> sepListL SepL.dot + let nmL = layoutAccessibility denv mspec.Accessibility nmL + let denv = denv.AddAccessibility mspec.Accessibility + let basic = imdefL denv def + let modNameL = wordL (tagKeyword "module") ^^ nmL + let basicL = modNameL @@ basic + layoutXmlDoc denv true mspec.XmlDoc basicL + elif mspec.IsNamespace then let basic = imdefL denv def let basicL = // Check if this namespace contains anything interesting @@ -2271,7 +2337,8 @@ module InferredSigPrinting = let basic = imdefL denv def let modNameL = wordL (tagKeyword "module") ^^ nmL let modNameEqualsL = modNameL ^^ WordL.equals - let modIsOuter = (outerPath |> List.forall (fun (_, istype) -> istype = Namespace) ) + let isNamespace = function | Namespace _ -> true | _ -> false + let modIsOuter = (outerPath |> List.forall (fun (_, istype) -> isNamespace istype) ) let basicL = // Check if its an outer module or a nested module if modIsOuter then @@ -2319,8 +2386,8 @@ module PrintData = else layoutConst denv.g ty c - | Expr.Val (v, _, _) -> - wordL (tagLocal v.DisplayName) + | Expr.Val (vref, _, _) -> + wordL (tagLocal vref.DisplayName) | Expr.Link rX -> dataExprWrapL denv isAtomic rX.Value @@ -2368,21 +2435,28 @@ let outputValOrMember denv infoReader os x = x |> PrintTastMemberOrVals.prettyLa let stringValOrMember denv infoReader x = x |> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv infoReader |> showL /// Print members with a qualification showing the type they are contained in -let layoutQualifiedValOrMember denv infoReader typarInst v = PrintTastMemberOrVals.prettyLayoutOfValOrMember { denv with showMemberContainers=true; } infoReader typarInst v +let layoutQualifiedValOrMember denv infoReader typarInst vref = + PrintTastMemberOrVals.prettyLayoutOfValOrMember { denv with showMemberContainers=true; } infoReader typarInst vref -let outputQualifiedValOrMember denv infoReader os v = outputValOrMember { denv with showMemberContainers=true; } infoReader os v +let outputQualifiedValOrMember denv infoReader os vref = + outputValOrMember { denv with showMemberContainers=true; } infoReader os vref -let outputQualifiedValSpec denv infoReader os v = outputQualifiedValOrMember denv infoReader os v +let outputQualifiedValSpec denv infoReader os vref = + outputQualifiedValOrMember denv infoReader os vref -let stringOfQualifiedValOrMember denv infoReader v = PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst { denv with showMemberContainers=true; } infoReader v |> showL +let stringOfQualifiedValOrMember denv infoReader vref = + PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst { denv with showMemberContainers=true; } infoReader vref |> showL /// Convert a MethInfo to a string -let formatMethInfoToBufferFreeStyle infoReader m denv buf d = InfoMemberPrinting.formatMethInfoToBufferFreeStyle infoReader m denv buf d +let formatMethInfoToBufferFreeStyle infoReader m denv buf d = + InfoMemberPrinting.formatMethInfoToBufferFreeStyle infoReader m denv buf d -let prettyLayoutOfMethInfoFreeStyle infoReader m denv typarInst minfo = InfoMemberPrinting.prettyLayoutOfMethInfoFreeStyle infoReader m denv typarInst minfo +let prettyLayoutOfMethInfoFreeStyle infoReader m denv typarInst minfo = + InfoMemberPrinting.prettyLayoutOfMethInfoFreeStyle infoReader m denv typarInst minfo /// Convert a PropInfo to a string -let prettyLayoutOfPropInfoFreeStyle g amap m denv d = InfoMemberPrinting.prettyLayoutOfPropInfoFreeStyle g amap m denv d +let prettyLayoutOfPropInfoFreeStyle g amap m denv d = + InfoMemberPrinting.prettyLayoutOfPropInfoFreeStyle g amap m denv d /// Convert a MethInfo to a string let stringOfMethInfo infoReader m denv minfo = @@ -2442,13 +2516,15 @@ let stringOfILAttrib denv x = x |> PrintTypes.layoutILAttrib denv |> squareAngle let layoutImpliedSignatureOfModuleOrNamespace showHeader denv infoReader ad m contents = InferredSigPrinting.layoutImpliedSignatureOfModuleOrNamespace showHeader denv infoReader ad m contents -let prettyLayoutOfValOrMember denv infoReader typarInst v = PrintTastMemberOrVals.prettyLayoutOfValOrMember denv infoReader typarInst v +let prettyLayoutOfValOrMember denv infoReader typarInst vref = + PrintTastMemberOrVals.prettyLayoutOfValOrMember denv infoReader typarInst vref -let prettyLayoutOfValOrMemberNoInst denv infoReader v = PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv infoReader v +let prettyLayoutOfValOrMemberNoInst denv infoReader vref = + PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv infoReader vref let prettyLayoutOfMemberNoInstShort denv v = PrintTastMemberOrVals.prettyLayoutOfMemberNoInstShort denv v -let layoutOfValReturnType denv v = v |> PrintTypes.layoutOfValReturnType denv +let layoutOfValReturnType denv vref = vref |> PrintTypes.layoutOfValReturnType denv let prettyLayoutOfInstAndSig denv x = PrintTypes.prettyLayoutOfInstAndSig denv x @@ -2456,14 +2532,14 @@ let prettyLayoutOfInstAndSig denv x = PrintTypes.prettyLayoutOfInstAndSig denv x /// /// If the output text is different without showing constraints and/or imperative type variable /// annotations and/or fully qualifying paths then don't show them! -let minimalStringsOfTwoTypes denv t1 t2= - let (t1, t2), tpcs = PrettyTypes.PrettifyTypePair denv.g (t1, t2) +let minimalStringsOfTwoTypes denv ty1 ty2 = + let (ty1, ty2), tpcs = PrettyTypes.PrettifyTypePair denv.g (ty1, ty2) // try denv + no type annotations let attempt1 = let denv = { denv with showInferenceTyparAnnotations=false; showStaticallyResolvedTyparAnnotations=false } - let min1 = stringOfTy denv t1 - let min2 = stringOfTy denv t2 + let min1 = stringOfTy denv ty1 + let min2 = stringOfTy denv ty2 if min1 <> min2 then Some (min1, min2, "") else None match attempt1 with @@ -2473,8 +2549,8 @@ let minimalStringsOfTwoTypes denv t1 t2= // try denv + no type annotations + show full paths let attempt2 = let denv = { denv with showInferenceTyparAnnotations=false; showStaticallyResolvedTyparAnnotations=false }.SetOpenPaths [] - let min1 = stringOfTy denv t1 - let min2 = stringOfTy denv t2 + let min1 = stringOfTy denv ty1 + let min2 = stringOfTy denv ty2 if min1 <> min2 then Some (min1, min2, "") else None match attempt2 with @@ -2482,8 +2558,8 @@ let minimalStringsOfTwoTypes denv t1 t2= | None -> let attempt3 = - let min1 = stringOfTy denv t1 - let min2 = stringOfTy denv t2 + let min1 = stringOfTy denv ty1 + let min2 = stringOfTy denv ty2 if min1 <> min2 then Some (min1, min2, stringOfTyparConstraints denv tpcs) else None match attempt3 with @@ -2494,8 +2570,8 @@ let minimalStringsOfTwoTypes denv t1 t2= // try denv + show full paths + static parameters let denv = denv.SetOpenPaths [] let denv = { denv with includeStaticParametersInTypeNames=true } - let min1 = stringOfTy denv t1 - let min2 = stringOfTy denv t2 + let min1 = stringOfTy denv ty1 + let min2 = stringOfTy denv ty2 if min1 <> min2 then Some (min1, min2, stringOfTyparConstraints denv tpcs) else None match attempt4 with @@ -2509,19 +2585,19 @@ let minimalStringsOfTwoTypes denv t1 t2= let assemblyName = PrintTypes.layoutAssemblyName denv t |> function | null | "" -> "" | name -> sprintf " (%s)" name sprintf "%s%s" (stringOfTy denv t) assemblyName - (makeName t1, makeName t2, stringOfTyparConstraints denv tpcs) + (makeName ty1, makeName ty2, stringOfTyparConstraints denv tpcs) // Note: Always show imperative annotations when comparing value signatures -let minimalStringsOfTwoValues denv infoReader v1 v2= +let minimalStringsOfTwoValues denv infoReader vref1 vref2 = let denvMin = { denv with showInferenceTyparAnnotations=true; showStaticallyResolvedTyparAnnotations=false } - let min1 = buildString (fun buf -> outputQualifiedValOrMember denvMin infoReader buf v1) - let min2 = buildString (fun buf -> outputQualifiedValOrMember denvMin infoReader buf v2) + let min1 = buildString (fun buf -> outputQualifiedValOrMember denvMin infoReader buf vref1) + let min2 = buildString (fun buf -> outputQualifiedValOrMember denvMin infoReader buf vref2) if min1 <> min2 then (min1, min2) else let denvMax = { denv with showInferenceTyparAnnotations=true; showStaticallyResolvedTyparAnnotations=true } - let max1 = buildString (fun buf -> outputQualifiedValOrMember denvMax infoReader buf v1) - let max2 = buildString (fun buf -> outputQualifiedValOrMember denvMax infoReader buf v2) + let max1 = buildString (fun buf -> outputQualifiedValOrMember denvMax infoReader buf vref1) + let max2 = buildString (fun buf -> outputQualifiedValOrMember denvMax infoReader buf vref2) max1, max2 let minimalStringOfType denv ty = diff --git a/src/Compiler/Checking/NicePrint.fsi b/src/Compiler/Checking/NicePrint.fsi index c9df76a87a7..523202af9b9 100644 --- a/src/Compiler/Checking/NicePrint.fsi +++ b/src/Compiler/Checking/NicePrint.fsi @@ -54,14 +54,14 @@ val layoutQualifiedValOrMember: denv: DisplayEnv -> infoReader: InfoReader -> typarInst: TyparInstantiation -> - v: ValRef -> + vref: ValRef -> TyparInstantiation * Layout -val outputQualifiedValOrMember: denv: DisplayEnv -> infoReader: InfoReader -> os: StringBuilder -> v: ValRef -> unit +val outputQualifiedValOrMember: denv: DisplayEnv -> infoReader: InfoReader -> os: StringBuilder -> vref: ValRef -> unit -val outputQualifiedValSpec: denv: DisplayEnv -> infoReader: InfoReader -> os: StringBuilder -> v: ValRef -> unit +val outputQualifiedValSpec: denv: DisplayEnv -> infoReader: InfoReader -> os: StringBuilder -> vref: ValRef -> unit -val stringOfQualifiedValOrMember: denv: DisplayEnv -> infoReader: InfoReader -> v: ValRef -> string +val stringOfQualifiedValOrMember: denv: DisplayEnv -> infoReader: InfoReader -> vref: ValRef -> string val formatMethInfoToBufferFreeStyle: infoReader: InfoReader -> m: range -> denv: DisplayEnv -> buf: StringBuilder -> d: MethInfo -> unit @@ -139,22 +139,23 @@ val prettyLayoutOfValOrMember: denv: DisplayEnv -> infoReader: InfoReader -> typarInst: TyparInstantiation -> - v: ValRef -> + vref: ValRef -> TyparInstantiation * Layout -val prettyLayoutOfValOrMemberNoInst: denv: DisplayEnv -> infoReader: InfoReader -> v: ValRef -> Layout +val prettyLayoutOfValOrMemberNoInst: denv: DisplayEnv -> infoReader: InfoReader -> vref: ValRef -> Layout val prettyLayoutOfMemberNoInstShort: denv: DisplayEnv -> v: Val -> Layout -val layoutOfValReturnType: denv: DisplayEnv -> v: ValRef -> Layout +val layoutOfValReturnType: denv: DisplayEnv -> vref: ValRef -> Layout val prettyLayoutOfInstAndSig: denv: DisplayEnv -> TyparInstantiation * TTypes * TType -> TyparInstantiation * (TTypes * TType) * (Layout list * Layout) * Layout -val minimalStringsOfTwoTypes: denv: DisplayEnv -> t1: TType -> t2: TType -> string * string * string +val minimalStringsOfTwoTypes: denv: DisplayEnv -> ty1: TType -> ty2: TType -> string * string * string -val minimalStringsOfTwoValues: denv: DisplayEnv -> infoReader: InfoReader -> v1: ValRef -> v2: ValRef -> string * string +val minimalStringsOfTwoValues: + denv: DisplayEnv -> infoReader: InfoReader -> vref1: ValRef -> vref2: ValRef -> string * string val minimalStringOfType: denv: DisplayEnv -> ty: TType -> string diff --git a/src/Compiler/Checking/PatternMatchCompilation.fs b/src/Compiler/Checking/PatternMatchCompilation.fs index 90bd293deac..ec5c5488f81 100644 --- a/src/Compiler/Checking/PatternMatchCompilation.fs +++ b/src/Compiler/Checking/PatternMatchCompilation.fs @@ -312,8 +312,8 @@ let RefuteDiscrimSet g m path discrims = raise CannotRefute go path tm -let rec CombineRefutations g r1 r2 = - match r1, r2 with +let rec CombineRefutations g refutation1 refutation2 = + match refutation1, refutation2 with | Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = "_" -> other | Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = notNullText -> other | Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = otherSubtypeText -> other @@ -326,9 +326,9 @@ let rec CombineRefutations g r1 r2 = Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) (* Choose the greater of the two ucrefs based on name ordering *) elif ucref1.CaseName < ucref2.CaseName then - r2 + refutation2 else - r1 + refutation1 | Expr.Op (op1, tinst1, flds1, m1), Expr.Op (_, _, flds2, _) -> Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1) @@ -352,19 +352,17 @@ let rec CombineRefutations g r1 r2 = Expr.Const (c12, m1, ty1) - | _ -> r1 + | _ -> refutation1 let ShowCounterExample g denv m refuted = try - let exprL expr = exprL g expr let refutations = refuted |> List.collect (function RefutedWhenClause -> [] | RefutedInvestigation(path, discrim) -> [RefuteDiscrimSet g m path discrim]) let counterExample, enumCoversKnown = match refutations with | [] -> raise CannotRefute | (r, eck) :: t -> - if verbose then dprintf "r = %s (enumCoversKnownValue = %b)\n" (LayoutRender.showL (exprL r)) eck - List.fold (fun (rAcc, eckAcc) (r, eck) -> - CombineRefutations g rAcc r, eckAcc || eck) (r, eck) t + ((r, eck), t) ||> List.fold (fun (rAcc, eckAcc) (r, eck) -> + CombineRefutations g rAcc r, eckAcc || eck) let text = LayoutRender.showL (NicePrint.dataExprL denv counterExample) let failingWhenClause = refuted |> List.exists (function RefutedWhenClause -> true | _ -> false) Some(text, failingWhenClause, enumCoversKnown) @@ -594,8 +592,8 @@ let getDiscrimOfPattern (g: TcGlobals) tpinst t = match t with | TPat_null _m -> Some(DecisionTreeTest.IsNull) - | TPat_isinst (srcty, tgty, _, _m) -> - Some(DecisionTreeTest.IsInst (instType tpinst srcty, instType tpinst tgty)) + | TPat_isinst (srcTy, tgtTy, _, _m) -> + Some(DecisionTreeTest.IsInst (instType tpinst srcTy, instType tpinst tgtTy)) | TPat_exnconstr(tcref, _, _m) -> Some(DecisionTreeTest.IsInst (g.exn_ty, mkAppTy tcref [])) | TPat_const (c, _m) -> @@ -626,7 +624,7 @@ let discrimsEq (g: TcGlobals) d1 d2 = | DecisionTreeTest.ArrayLength (n1, _), DecisionTreeTest.ArrayLength(n2, _) -> (n1=n2) | DecisionTreeTest.Const c1, DecisionTreeTest.Const c2 -> (c1=c2) | DecisionTreeTest.IsNull, DecisionTreeTest.IsNull -> true - | DecisionTreeTest.IsInst (srcty1, tgty1), DecisionTreeTest.IsInst (srcty2, tgty2) -> typeEquiv g srcty1 srcty2 && typeEquiv g tgty1 tgty2 + | DecisionTreeTest.IsInst (srcTy1, tgtTy1), DecisionTreeTest.IsInst (srcTy2, tgtTy2) -> typeEquiv g srcTy1 srcTy2 && typeEquiv g tgtTy1 tgtTy2 | DecisionTreeTest.ActivePatternCase (_, _, _, vrefOpt1, n1, _), DecisionTreeTest.ActivePatternCase (_, _, _, vrefOpt2, n2, _) -> match vrefOpt1, vrefOpt2 with | Some (vref1, tinst1), Some (vref2, tinst2) -> valRefEq g vref1 vref2 && n1 = n2 && not (doesActivePatternHaveFreeTypars g vref1) && List.lengthsEqAndForall2 (typeEquiv g) tinst1 tinst2 @@ -1215,15 +1213,15 @@ let CompilePatternBasic // This is really an optimization that could be done more effectively in opt.fs // if we flowed a bit of information through - | [EdgeDiscrim(_i', DecisionTreeTest.IsInst (_srcty, tgty), m)] + | [EdgeDiscrim(_i', DecisionTreeTest.IsInst (_srcTy, tgtTy), m)] // check we can use a simple 'isinst' instruction - when isRefTy g tgty && canUseTypeTestFast g tgty && isNil origInputValTypars -> + when isRefTy g tgtTy && canUseTypeTestFast g tgtTy && isNil origInputValTypars -> - let v, vExpr = mkCompGenLocal m "typeTestResult" tgty + let v, vExpr = mkCompGenLocal m "typeTestResult" tgtTy if origInputVal.IsMemberOrModuleBinding then AdjustValToTopVal v origInputVal.DeclaringEntity ValReprInfo.emptyValData let argExpr = GetSubExprOfInput subexpr - let appExpr = mkIsInst tgty argExpr mMatch + let appExpr = mkIsInst tgtTy argExpr mMatch Some vExpr, Some(mkInvisibleBind v appExpr) // Any match on a struct union must take the address of its input. diff --git a/src/Compiler/Checking/PostInferenceChecks.fs b/src/Compiler/Checking/PostInferenceChecks.fs index 87eb68c7d80..d8bca9c223c 100644 --- a/src/Compiler/Checking/PostInferenceChecks.fs +++ b/src/Compiler/Checking/PostInferenceChecks.fs @@ -416,8 +416,8 @@ and CheckTypeConstraintDeep cenv f g env x = | TyparConstraint.MayResolveMember(traitInfo, _) -> CheckTraitInfoDeep cenv f g env traitInfo | TyparConstraint.DefaultsTo(_, ty, _) -> CheckTypeDeep cenv f g env true ty | TyparConstraint.SimpleChoice(tys, _) -> CheckTypesDeep cenv f g env tys - | TyparConstraint.IsEnum(uty, _) -> CheckTypeDeep cenv f g env true uty - | TyparConstraint.IsDelegate(aty, bty, _) -> CheckTypeDeep cenv f g env true aty; CheckTypeDeep cenv f g env true bty + | TyparConstraint.IsEnum(underlyingTy, _) -> CheckTypeDeep cenv f g env true underlyingTy + | TyparConstraint.IsDelegate(argTys, retTy, _) -> CheckTypeDeep cenv f g env true argTys; CheckTypeDeep cenv f g env true retTy | TyparConstraint.SupportsComparison _ | TyparConstraint.SupportsEquality _ | TyparConstraint.SupportsNull _ @@ -591,8 +591,8 @@ let mkArgsPermit n = /// Work out what byref-values are allowed at input positions to named F# functions or members let mkArgsForAppliedVal isBaseCall (vref: ValRef) argsl = match vref.ValReprInfo with - | Some topValInfo -> - let argArities = topValInfo.AritiesOfArgs + | Some valReprInfo -> + let argArities = valReprInfo.AritiesOfArgs let argArities = if isBaseCall && argArities.Length >= 1 then List.tail argArities else argArities // Check for partial applications: arguments to partial applications don't get to use byrefs if List.length argsl >= argArities.Length then @@ -717,39 +717,42 @@ type TTypeEquality = | FeasiblyEqual | NotEqual -let compareTypesWithRegardToTypeVariablesAndMeasures g amap m typ1 typ2 = +let compareTypesWithRegardToTypeVariablesAndMeasures g amap m ty1 ty2 = - if (typeEquiv g typ1 typ2) then + if (typeEquiv g ty1 ty2) then ExactlyEqual else - if (typeEquiv g typ1 typ2 || TypesFeasiblyEquivStripMeasures g amap m typ1 typ2) then + if (typeEquiv g ty1 ty2 || TypesFeasiblyEquivStripMeasures g amap m ty1 ty2) then FeasiblyEqual else NotEqual -let CheckMultipleInterfaceInstantiations cenv (typ:TType) (interfaces:TType list) isObjectExpression m = - let keyf ty = assert isAppTy cenv.g ty; (tcrefOfAppTy cenv.g ty).Stamp - let groups = interfaces |> List.groupBy keyf +let keyTyByStamp g ty = + assert isAppTy g ty + (tcrefOfAppTy g ty).Stamp + +let CheckMultipleInterfaceInstantiations cenv (ty:TType) (interfaces:TType list) isObjectExpression m = + let groups = interfaces |> List.groupBy (keyTyByStamp cenv.g) let errors = seq { for _, items in groups do for i1 in 0 .. items.Length - 1 do for i2 in i1 + 1 .. items.Length - 1 do - let typ1 = items[i1] - let typ2 = items[i2] - let tcRef1 = tcrefOfAppTy cenv.g typ1 - match compareTypesWithRegardToTypeVariablesAndMeasures cenv.g cenv.amap m typ1 typ2 with + let ty1 = items[i1] + let ty2 = items[i2] + let tcRef1 = tcrefOfAppTy cenv.g ty1 + match compareTypesWithRegardToTypeVariablesAndMeasures cenv.g cenv.amap m ty1 ty2 with | ExactlyEqual -> () | FeasiblyEqual -> match tryLanguageFeatureErrorOption cenv.g.langVersion LanguageFeature.InterfacesWithMultipleGenericInstantiation m with | None -> () | Some exn -> exn - let typ1Str = NicePrint.minimalStringOfType cenv.denv typ1 - let typ2Str = NicePrint.minimalStringOfType cenv.denv typ2 + let typ1Str = NicePrint.minimalStringOfType cenv.denv ty1 + let typ2Str = NicePrint.minimalStringOfType cenv.denv ty2 if isObjectExpression then Error(FSComp.SR.typrelInterfaceWithConcreteAndVariableObjectExpression(tcRef1.DisplayNameWithStaticParametersAndUnderscoreTypars, typ1Str, typ2Str),m) else - let typStr = NicePrint.minimalStringOfType cenv.denv typ + let typStr = NicePrint.minimalStringOfType cenv.denv ty Error(FSComp.SR.typrelInterfaceWithConcreteAndVariable(typStr, tcRef1.DisplayNameWithStaticParametersAndUnderscoreTypars, typ1Str, typ2Str),m) | NotEqual -> @@ -1352,14 +1355,14 @@ and CheckApplication cenv env expr (f, tyargs, argsl, m) ctxt = CheckCall cenv env m returnTy argsl ctxts ctxt and CheckLambda cenv env expr (argvs, m, bodyTy) = - let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy cenv.g m argvs bodyTy in - CheckLambdas false None cenv env false topValInfo false expr m ty PermitByRefExpr.Yes + CheckLambdas false None cenv env false valReprInfo false expr m ty PermitByRefExpr.Yes and CheckTyLambda cenv env expr (tps, m, bodyTy) = - let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) let ty = mkForallTyIfNeeded tps bodyTy in - CheckLambdas false None cenv env false topValInfo false expr m ty PermitByRefExpr.Yes + CheckLambdas false None cenv env false valReprInfo false expr m ty PermitByRefExpr.Yes and CheckMatch cenv env ctxt (dtree, targets, m, ty) = CheckTypeNoInnerByrefs cenv env m ty // computed byrefs allowed at each branch @@ -1575,8 +1578,8 @@ and CheckExprOp cenv env (op, tyargs, args, m) ctxt expr = errorR(Error(FSComp.SR.chkNoWriteToLimitedSpan(rf.FieldName), m)) NoLimit - | TOp.Coerce, [tgty;srcty], [x] -> - if TypeDefinitelySubsumesTypeNoCoercion 0 g cenv.amap m tgty srcty then + | TOp.Coerce, [tgtTy;srcTy], [x] -> + if TypeDefinitelySubsumesTypeNoCoercion 0 g cenv.amap m tgtTy srcTy then CheckExpr cenv env x ctxt else CheckTypeInstNoByrefs cenv env m tyargs @@ -1699,20 +1702,20 @@ and CheckExprOp cenv env (op, tyargs, args, m) ctxt expr = CheckTypeInstNoByrefs cenv env m tyargs CheckExprsNoByRefLike cenv env args -and CheckLambdas isTop (memberVal: Val option) cenv env inlined topValInfo alwaysCheckNoReraise expr mOrig ety ctxt = +and CheckLambdas isTop (memberVal: Val option) cenv env inlined valReprInfo alwaysCheckNoReraise expr mOrig ety ctxt = let g = cenv.g let memInfo = memberVal |> Option.bind (fun v -> v.MemberInfo) - // The topValInfo here says we are _guaranteeing_ to compile a function value + // The valReprInfo here says we are _guaranteeing_ to compile a function value // as a .NET method with precisely the corresponding argument counts. match stripDebugPoints expr with | Expr.TyChoose (tps, e1, m) -> let env = BindTypars g env tps - CheckLambdas isTop memberVal cenv env inlined topValInfo alwaysCheckNoReraise e1 m ety ctxt + CheckLambdas isTop memberVal cenv env inlined valReprInfo alwaysCheckNoReraise e1 m ety ctxt | Expr.Lambda (_, _, _, _, _, m, _) | Expr.TyLambda (_, _, _, m, _) -> - let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = destTopLambda g cenv.amap topValInfo (expr, ety) + let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = destTopLambda g cenv.amap valReprInfo (expr, ety) let env = BindTypars g env tps let thisAndBase = Option.toList ctorThisValOpt @ Option.toList baseValOpt let restArgs = List.concat vsl @@ -2071,7 +2074,7 @@ and CheckBinding cenv env alwaysCheckNoReraise ctxt (TBind(v, bindRhs, _) as bin | _ -> () - let topValInfo = match bind.Var.ValReprInfo with Some info -> info | _ -> ValReprInfo.emptyValData + let valReprInfo = match bind.Var.ValReprInfo with Some info -> info | _ -> ValReprInfo.emptyValData // If the method has ResumableCode argument or return type it must be inline // unless warning is suppressed (user must know what they're doing). @@ -2089,7 +2092,7 @@ and CheckBinding cenv env alwaysCheckNoReraise ctxt (TBind(v, bindRhs, _) as bin else env - CheckLambdas isTop (Some v) cenv env v.MustInline topValInfo alwaysCheckNoReraise bindRhs v.Range v.Type ctxt + CheckLambdas isTop (Some v) cenv env v.MustInline valReprInfo alwaysCheckNoReraise bindRhs v.Range v.Type ctxt and CheckBindings cenv env binds = for bind in binds do @@ -2279,8 +2282,8 @@ let CheckEntityDefn cenv env (tycon: Entity) = let allVirtualMethsInParent = match GetSuperTypeOfType g cenv.amap m ty with - | Some super -> - GetIntrinsicMethInfosOfType cenv.infoReader None AccessibleFromSomewhere AllowMultiIntfInstantiations.Yes IgnoreOverrides m super + | Some superTy -> + GetIntrinsicMethInfosOfType cenv.infoReader None AccessibleFromSomewhere AllowMultiIntfInstantiations.Yes IgnoreOverrides m superTy |> List.filter (fun minfo -> minfo.IsVirtual) | None -> [] @@ -2479,8 +2482,8 @@ let CheckEntityDefn cenv env (tycon: Entity) = // Abstract slots can have byref arguments and returns for vref in abstractSlotValsOfTycons [tycon] do match vref.ValReprInfo with - | Some topValInfo -> - let tps, argTysl, retTy, _ = GetTopValTypeInFSharpForm g topValInfo vref.Type m + | Some valReprInfo -> + let tps, argTysl, retTy, _ = GetTopValTypeInFSharpForm g valReprInfo vref.Type m let env = BindTypars g env tps for argTys in argTysl do for argTy, _ in argTys do diff --git a/src/Compiler/Checking/QuotationTranslator.fs b/src/Compiler/Checking/QuotationTranslator.fs index fe05b73ac0a..089de7b4a7f 100644 --- a/src/Compiler/Checking/QuotationTranslator.fs +++ b/src/Compiler/Checking/QuotationTranslator.fs @@ -172,7 +172,7 @@ let (|ModuleValueOrMemberUse|_|) g expr = match stripExpr expr with | Expr.App (InnerExprPat(Expr.Val (vref, vFlags, _) as f), fty, tyargs, actualArgs, _m) when vref.IsMemberOrModuleBinding -> Some(vref, vFlags, f, fty, tyargs, actualArgs @ args) - | Expr.App (f, _fty, [], actualArgs, _) -> + | Expr.App (f, _fTy, [], actualArgs, _) -> loop f (actualArgs @ args) | Expr.Val (vref, vFlags, _m) as f when (match vref.DeclaringEntity with ParentNone -> false | _ -> true) -> let fty = tyOfExpr g f @@ -292,8 +292,8 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. // Recognize applications of module functions. match expr with // Detect expression tree exprSplices - | Expr.App (InnerExprPat(Expr.Val (vf, _, _)), _, _, x0 :: rest, m) - when isSplice g vf -> + | Expr.App (InnerExprPat(Expr.Val (vref, _, _)), _, _, x0 :: rest, m) + when isSplice g vref -> let idx = cenv.exprSplices.Count let ty = tyOfExpr g expr @@ -305,7 +305,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. let hole = QP.mkHole(ConvType cenv env m ty, idx) (hole, rest) ||> List.fold (fun fR arg -> QP.mkApp (fR, ConvExpr cenv env arg)) - | ModuleValueOrMemberUse g (vref, vFlags, _f, _fty, tyargs, curriedArgs) + | ModuleValueOrMemberUse g (vref, vFlags, _f, _fTy, tyargs, curriedArgs) when not (isSplice g vref) -> let m = expr.Range @@ -348,12 +348,12 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. dprintfn "vref.DisplayName = %A was under applied" vref.DisplayName // Too few arguments or incorrect tupling? Convert to a lambda and beta-reduce the // partially applied arguments to 'let' bindings - let topValInfo = + let valReprInfo = match vref.ValReprInfo with | None -> error(InternalError("no arity information found for F# value " + vref.LogicalName, vref.Range)) | Some a -> a - let expr, exprTy = AdjustValForExpectedArity g m vref vFlags topValInfo + let expr, exprTy = AdjustValForExpectedArity g m vref vFlags valReprInfo ConvExpr cenv env (MakeApplicationAndBetaReduce g (expr, exprTy, [tyargs], curriedArgs, m)) else // Too many arguments? Chop @@ -419,16 +419,16 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. List.fold (fun fR arg -> QP.mkApp (fR, ConvExpr cenv env arg)) callR laterArgs // Blast type application nodes and expression application nodes apart so values are left with just their type arguments - | Expr.App (f, fty, (_ :: _ as tyargs), (_ :: _ as args), m) -> - let rfty = applyForallTy g fty tyargs - ConvExpr cenv env (primMkApp (primMkApp (f, fty) tyargs [] m, rfty) [] args m) + | Expr.App (f, fTy, (_ :: _ as tyargs), (_ :: _ as args), m) -> + let reducedTy = applyForallTy g fTy tyargs + ConvExpr cenv env (primMkApp (primMkApp (f, fTy) tyargs [] m, reducedTy) [] args m) // Uses of possibly-polymorphic values - | Expr.App (InnerExprPat(Expr.Val (vref, _vFlags, m)), _fty, tyargs, [], _) -> + | Expr.App (InnerExprPat(Expr.Val (vref, _vFlags, m)), _fTy, tyargs, [], _) -> ConvValRef true cenv env m vref tyargs // Simple applications - | Expr.App (f, _fty, tyargs, args, m) -> + | Expr.App (f, _fTy, tyargs, args, m) -> if not (List.isEmpty tyargs) then wfail(Error(FSComp.SR.crefQuotationsCantContainGenericExprs(), m)) List.fold (fun fR arg -> QP.mkApp (fR, ConvExpr cenv env arg)) (ConvExpr cenv env f) args @@ -828,12 +828,12 @@ and ConvLValueExprCore cenv env expr = | TOp.UnionCaseFieldGetAddr (ucref, n, _), [e], _ -> ConvUnionFieldGet cenv env m ucref n tyargs e | TOp.ILAsm ([ I_ldflda(fspec) ], _), _, _ -> ConvLdfld cenv env m fspec tyargs args | TOp.ILAsm ([ I_ldsflda(fspec) ], _), _, _ -> ConvLdfld cenv env m fspec tyargs args - | TOp.ILAsm ([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ], _), arr :: idxs, [elemty] -> + | TOp.ILAsm ([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ], _), arr :: idxs, [elemTy] -> match shape.Rank, idxs with - | 1, [idx1] -> ConvExpr cenv env (mkCallArrayGet cenv.g m elemty arr idx1) - | 2, [idx1; idx2] -> ConvExpr cenv env (mkCallArray2DGet cenv.g m elemty arr idx1 idx2) - | 3, [idx1; idx2; idx3] -> ConvExpr cenv env (mkCallArray3DGet cenv.g m elemty arr idx1 idx2 idx3) - | 4, [idx1; idx2; idx3; idx4] -> ConvExpr cenv env (mkCallArray4DGet cenv.g m elemty arr idx1 idx2 idx3 idx4) + | 1, [idx1] -> ConvExpr cenv env (mkCallArrayGet cenv.g m elemTy arr idx1) + | 2, [idx1; idx2] -> ConvExpr cenv env (mkCallArray2DGet cenv.g m elemTy arr idx1 idx2) + | 3, [idx1; idx2; idx3] -> ConvExpr cenv env (mkCallArray3DGet cenv.g m elemTy arr idx1 idx2 idx3) + | 4, [idx1; idx2; idx3; idx4] -> ConvExpr cenv env (mkCallArray4DGet cenv.g m elemTy arr idx1 idx2 idx3 idx4) | _ -> ConvExpr cenv env expr | _ -> ConvExpr cenv env expr | _ -> ConvExpr cenv env expr @@ -937,15 +937,15 @@ and private ConvValRefCore holeOk cenv env m (vref: ValRef) tyargs = elif v.IsCtorThisVal && cenv.isReflectedDefinition = IsReflectedDefinition.Yes then QP.mkThisVar(ConvType cenv env m v.Type) else - let vty = v.Type + let vTy = v.Type match v.DeclaringEntity with | ParentNone -> // References to local values are embedded by value if not holeOk then wfail(Error(FSComp.SR.crefNoSetOfHole(), m)) let idx = cenv.exprSplices.Count - let liftExpr = mkCallLiftValueWithName cenv.g m vty v.LogicalName (exprForValRef m vref) + let liftExpr = mkCallLiftValueWithName cenv.g m vTy v.LogicalName (exprForValRef m vref) cenv.exprSplices.Add((liftExpr, m)) - QP.mkHole(ConvType cenv env m vty, idx) + QP.mkHole(ConvType cenv env m vTy, idx) | Parent _ -> // First-class use or use of type function @@ -1106,9 +1106,9 @@ and ConvDecisionTree cenv env tgs typR x = let eqR = ConvExpr cenv env eq QP.mkCond (eqR, ConvDecisionTree cenv env tgs typR dtree, acc) - | DecisionTreeTest.IsInst (_srcty, tgty) -> + | DecisionTreeTest.IsInst (_srcTy, tgtTy) -> let e1R = ConvExpr cenv env e1 - QP.mkCond (QP.mkTypeTest (ConvType cenv env m tgty, e1R), ConvDecisionTree cenv env tgs typR dtree, acc) + QP.mkCond (QP.mkTypeTest (ConvType cenv env m tgtTy, e1R), ConvDecisionTree cenv env tgs typR dtree, acc) | DecisionTreeTest.ActivePatternCase _ -> wfail(InternalError( "DecisionTreeTest.ActivePatternCase test in quoted expression", m)) diff --git a/src/Compiler/Checking/SignatureConformance.fs b/src/Compiler/Checking/SignatureConformance.fs index f9d9b41b871..4a689f48a0c 100644 --- a/src/Compiler/Checking/SignatureConformance.fs +++ b/src/Compiler/Checking/SignatureConformance.fs @@ -187,26 +187,26 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = else let aenv = aenv.BindEquivTypars implTypars sigTypars - let aintfs = implTycon.ImmediateInterfaceTypesOfFSharpTycon - let fintfs = sigTycon.ImmediateInterfaceTypesOfFSharpTycon - let aintfsUser = implTycon.TypeContents.tcaug_interfaces |> List.filter (fun (_, compgen, _) -> not compgen) |> List.map p13 + let implIntfTys = implTycon.ImmediateInterfaceTypesOfFSharpTycon + let sigIntfTys = sigTycon.ImmediateInterfaceTypesOfFSharpTycon + let implUserIntfTys = implTycon.TypeContents.tcaug_interfaces |> List.filter (fun (_, compgen, _) -> not compgen) |> List.map p13 let flatten tys = tys |> List.collect (AllSuperTypesOfType g amap m AllowMultiIntfInstantiations.Yes) |> ListSet.setify (typeEquiv g) |> List.filter (isInterfaceTy g) - let aintfs = flatten aintfs - let fintfs = flatten fintfs + let implIntfTys = flatten implIntfTys + let sigIntfTys = flatten sigIntfTys - let unimpl = ListSet.subtract (fun fity aity -> typeAEquiv g aenv aity fity) fintfs aintfs - (unimpl + let unimplIntfTys = ListSet.subtract (fun sigIntfTy implIntfTy -> typeAEquiv g aenv implIntfTy sigIntfTy) sigIntfTys implIntfTys + (unimplIntfTys |> List.forall (fun ity -> let errorMessage = FSComp.SR.DefinitionsInSigAndImplNotCompatibleMissingInterface(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName, NicePrint.minimalStringOfType denv ity) errorR (Error(errorMessage, m)); false)) && - let aintfsUser = flatten aintfsUser + let implUserIntfTys = flatten implUserIntfTys - let hidden = ListSet.subtract (typeAEquiv g aenv) aintfsUser fintfs + let hidden = ListSet.subtract (typeAEquiv g aenv) implUserIntfTys sigIntfTys let continueChecks, warningOrError = if implTycon.IsFSharpInterfaceTycon then false, errorR else true, warning (hidden |> List.forall (fun ity -> warningOrError (InterfaceNotRevealed(denv, ity, implTycon.Range)); continueChecks)) && @@ -328,12 +328,12 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = elif implVal.LiteralValue <> sigVal.LiteralValue then (err denv FSComp.SR.ValueNotContainedMutabilityLiteralConstantValuesDiffer) elif implVal.IsTypeFunction <> sigVal.IsTypeFunction then (err denv FSComp.SR.ValueNotContainedMutabilityOneIsTypeFunction) else - let implTypars, atau = implVal.GeneralizedType - let sigTypars, ftau = sigVal.GeneralizedType + let implTypars, implValTy = implVal.GeneralizedType + let sigTypars, sigValTy = sigVal.GeneralizedType if implTypars.Length <> sigTypars.Length then (err {denv with showTyparBinding=true} FSComp.SR.ValueNotContainedMutabilityParameterCountsDiffer) else let aenv = aenv.BindEquivTypars implTypars sigTypars checkTypars m aenv implTypars sigTypars && - if not (typeAEquiv g aenv atau ftau) then err denv FSComp.SR.ValueNotContainedMutabilityTypesDiffer + if not (typeAEquiv g aenv implValTy sigValTy) then err denv FSComp.SR.ValueNotContainedMutabilityTypesDiffer elif not (checkValInfo aenv (err denv) implVal sigVal) then false elif not (implVal.IsExtensionMember = sigVal.IsExtensionMember) then err denv FSComp.SR.ValueNotContainedMutabilityExtensionsDiffer elif not (checkMemberDatasConform (err denv) (implVal.Attribs, implVal, implVal.MemberInfo) (sigVal.Attribs, sigVal, sigVal.MemberInfo)) then false diff --git a/src/Compiler/Checking/TypeHierarchy.fs b/src/Compiler/Checking/TypeHierarchy.fs index 12572e87d10..fe44b9cf874 100644 --- a/src/Compiler/Checking/TypeHierarchy.fs +++ b/src/Compiler/Checking/TypeHierarchy.fs @@ -92,8 +92,8 @@ let GetImmediateInterfacesOfMetadataType g amap m skipUnref ty (tcref: TyconRef) match metadataOfTy g ty with #if !NO_TYPEPROVIDERS | ProvidedTypeMetadata info -> - for ity in info.ProvidedType.PApplyArray((fun st -> st.GetInterfaces()), "GetInterfaces", m) do - ImportProvidedType amap m ity + for intfTy in info.ProvidedType.PApplyArray((fun st -> st.GetInterfaces()), "GetInterfaces", m) do + ImportProvidedType amap m intfTy #endif | ILTypeMetadata (TILObjectReprData(scoref, _, tdef)) -> // ImportILType may fail for an interface if the assembly load set is incomplete and the interface @@ -103,12 +103,12 @@ let GetImmediateInterfacesOfMetadataType g amap m skipUnref ty (tcref: TyconRef) // succeeded with more reported. There are pathological corner cases where this // doesn't apply: e.g. for mscorlib interfaces like IComparable, but we can always // assume those are present. - for ity in tdef.Implements do - if skipUnref = SkipUnrefInterfaces.No || CanRescopeAndImportILType scoref amap m ity then - RescopeAndImportILType scoref amap m tinst ity + for intfTy in tdef.Implements do + if skipUnref = SkipUnrefInterfaces.No || CanRescopeAndImportILType scoref amap m intfTy then + RescopeAndImportILType scoref amap m tinst intfTy | FSharpOrArrayOrByrefOrTupleOrExnTypeMetadata -> - for ity in tcref.ImmediateInterfaceTypesOfFSharpTycon do - instType (mkInstForAppTy g ty) ity ] + for intfTy in tcref.ImmediateInterfaceTypesOfFSharpTycon do + instType (mkInstForAppTy g ty) intfTy ] /// Collect the set of immediate declared interface types for an F# type, but do not /// traverse the type hierarchy to collect further interfaces. @@ -163,10 +163,10 @@ let rec GetImmediateInterfacesOfType skipUnref g amap m ty = and GetImmediateInterfacesOfMeasureAnnotatedType skipUnref g amap m ty reprTy = [ // Report any interfaces that don't derive from IComparable<_> or IEquatable<_> - for ity in GetImmediateInterfacesOfType skipUnref g amap m reprTy do - if not (ExistsHeadTypeInInterfaceHierarchy g.system_GenericIComparable_tcref skipUnref g amap m ity) && - not (ExistsHeadTypeInInterfaceHierarchy g.system_GenericIEquatable_tcref skipUnref g amap m ity) then - ity + for intfTy in GetImmediateInterfacesOfType skipUnref g amap m reprTy do + if not (ExistsHeadTypeInInterfaceHierarchy g.system_GenericIComparable_tcref skipUnref g amap m intfTy) && + not (ExistsHeadTypeInInterfaceHierarchy g.system_GenericIEquatable_tcref skipUnref g amap m intfTy) then + intfTy // NOTE: we should really only report the IComparable> interface for measure-annotated types // if the original type supports IComparable somewhere in the hierarchy, likeiwse IEquatable>. @@ -181,15 +181,15 @@ and GetImmediateInterfacesOfMeasureAnnotatedType skipUnref g amap m ty reprTy = ] // Check for IComparable, IEquatable and interfaces that derive from these -and ExistsHeadTypeInInterfaceHierarchy target skipUnref g amap m ity = - ExistsInInterfaceHierarchy (function AppTy g (tcref,_) -> tyconRefEq g tcref target | _ -> false) skipUnref g amap m ity +and ExistsHeadTypeInInterfaceHierarchy target skipUnref g amap m intfTy = + ExistsInInterfaceHierarchy (function AppTy g (tcref,_) -> tyconRefEq g tcref target | _ -> false) skipUnref g amap m intfTy // Check for IComparable, IEquatable and interfaces that derive from these -and ExistsInInterfaceHierarchy p skipUnref g amap m ity = - match ity with +and ExistsInInterfaceHierarchy p skipUnref g amap m intfTy = + match intfTy with | AppTy g (tcref, tinst) -> - p ity || - (GetImmediateInterfacesOfMetadataType g amap m skipUnref ity tcref tinst + p intfTy || + (GetImmediateInterfacesOfMetadataType g amap m skipUnref intfTy tcref tinst |> List.exists (ExistsInInterfaceHierarchy p skipUnref g amap m)) | _ -> false @@ -369,14 +369,14 @@ let CopyTyparConstraints m tprefInst (tporig: Typar) = TyparConstraint.DefaultsTo (priority, instType tprefInst ty, m) | TyparConstraint.SupportsNull _ -> TyparConstraint.SupportsNull m - | TyparConstraint.IsEnum (uty, _) -> - TyparConstraint.IsEnum (instType tprefInst uty, m) + | TyparConstraint.IsEnum (underlyingTy, _) -> + TyparConstraint.IsEnum (instType tprefInst underlyingTy, m) | TyparConstraint.SupportsComparison _ -> TyparConstraint.SupportsComparison m | TyparConstraint.SupportsEquality _ -> TyparConstraint.SupportsEquality m - | TyparConstraint.IsDelegate(aty, bty, _) -> - TyparConstraint.IsDelegate (instType tprefInst aty, instType tprefInst bty, m) + | TyparConstraint.IsDelegate(argTys, retTy, _) -> + TyparConstraint.IsDelegate (instType tprefInst argTys, instType tprefInst retTy, m) | TyparConstraint.IsNonNullableStruct _ -> TyparConstraint.IsNonNullableStruct m | TyparConstraint.IsUnmanaged _ -> diff --git a/src/Compiler/Checking/TypeRelations.fs b/src/Compiler/Checking/TypeRelations.fs index 6cbb7547f30..d714e1b1a60 100644 --- a/src/Compiler/Checking/TypeRelations.fs +++ b/src/Compiler/Checking/TypeRelations.fs @@ -46,24 +46,25 @@ let rec TypeDefinitelySubsumesTypeNoCoercion ndeep g amap m ty1 ty2 = type CanCoerce = CanCoerce | NoCoerce +let stripAll stripMeasures g ty = + if stripMeasures then + ty |> stripTyEqnsWrtErasure EraseAll g |> stripMeasuresFromTy g + else + ty |> stripTyEqns g + /// The feasible equivalence relation. Part of the language spec. let rec TypesFeasiblyEquivalent stripMeasures ndeep g amap m ty1 ty2 = if ndeep > 100 then error(InternalError("recursive class hierarchy (detected in TypeFeasiblySubsumesType), ty1 = " + (DebugPrint.showType ty1), m)); - let stripAll ty = - if stripMeasures then - ty |> stripTyEqnsWrtErasure EraseAll g |> stripMeasuresFromTType g - else - ty |> stripTyEqns g - let ty1str = stripAll ty1 - let ty2str = stripAll ty2 + let ty1 = stripAll stripMeasures g ty1 + let ty2 = stripAll stripMeasures g ty2 - match ty1str, ty2str with + match ty1, ty2 with | TType_var _, _ | _, TType_var _ -> true - | TType_app (tc1, l1, _), TType_app (tc2, l2, _) when tyconRefEq g tc1 tc2 -> + | TType_app (tcref1, l1, _), TType_app (tcref2, l2, _) when tyconRefEq g tcref1 tcref2 -> List.lengthsEqAndForall2 (TypesFeasiblyEquivalent stripMeasures ndeep g amap m) l1 l2 | TType_anon (anonInfo1, l1),TType_anon (anonInfo2, l2) -> @@ -76,9 +77,9 @@ let rec TypesFeasiblyEquivalent stripMeasures ndeep g amap m ty1 ty2 = evalTupInfoIsStruct tupInfo1 = evalTupInfoIsStruct tupInfo2 && List.lengthsEqAndForall2 (TypesFeasiblyEquivalent stripMeasures ndeep g amap m) l1 l2 - | TType_fun (d1, r1, _), TType_fun (d2, r2, _) -> - TypesFeasiblyEquivalent stripMeasures ndeep g amap m d1 d2 && - TypesFeasiblyEquivalent stripMeasures ndeep g amap m r1 r2 + | TType_fun (domainTy1, rangeTy1, _), TType_fun (domainTy2, rangeTy2, _) -> + TypesFeasiblyEquivalent stripMeasures ndeep g amap m domainTy1 domainTy2 && + TypesFeasiblyEquivalent stripMeasures ndeep g amap m rangeTy1 rangeTy2 | TType_measure _, TType_measure _ -> true @@ -133,51 +134,51 @@ let rec TypeFeasiblySubsumesType ndeep g amap m ty1 canCoerce ty2 = /// Here x gets a generalized type "list<'T>". let ChooseTyparSolutionAndRange (g: TcGlobals) amap (tp:Typar) = let m = tp.Range - let max, m = - let initial = + let maxTy, m = + let initialTy = match tp.Kind with | TyparKind.Type -> g.obj_ty | TyparKind.Measure -> TType_measure Measure.One // Loop through the constraints computing the lub - ((initial, m), tp.Constraints) ||> List.fold (fun (maxSoFar, _) tpc -> + ((initialTy, m), tp.Constraints) ||> List.fold (fun (maxTy, _) tpc -> let join m x = - if TypeFeasiblySubsumesType 0 g amap m x CanCoerce maxSoFar then maxSoFar - elif TypeFeasiblySubsumesType 0 g amap m maxSoFar CanCoerce x then x - else errorR(Error(FSComp.SR.typrelCannotResolveImplicitGenericInstantiation((DebugPrint.showType x), (DebugPrint.showType maxSoFar)), m)); maxSoFar + if TypeFeasiblySubsumesType 0 g amap m x CanCoerce maxTy then maxTy + elif TypeFeasiblySubsumesType 0 g amap m maxTy CanCoerce x then x + else errorR(Error(FSComp.SR.typrelCannotResolveImplicitGenericInstantiation((DebugPrint.showType x), (DebugPrint.showType maxTy)), m)); maxTy // Don't continue if an error occurred and we set the value eagerly - if tp.IsSolved then maxSoFar, m else + if tp.IsSolved then maxTy, m else match tpc with | TyparConstraint.CoercesTo(x, m) -> join m x, m | TyparConstraint.MayResolveMember(_traitInfo, m) -> - maxSoFar, m + maxTy, m | TyparConstraint.SimpleChoice(_, m) -> errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInPrintf(), m)) - maxSoFar, m + maxTy, m | TyparConstraint.SupportsNull m -> - maxSoFar, m + maxTy, m | TyparConstraint.SupportsComparison m -> join m g.mk_IComparable_ty, m | TyparConstraint.SupportsEquality m -> - maxSoFar, m + maxTy, m | TyparConstraint.IsEnum(_, m) -> errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInEnum(), m)) - maxSoFar, m + maxTy, m | TyparConstraint.IsDelegate(_, _, m) -> errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInDelegate(), m)) - maxSoFar, m + maxTy, m | TyparConstraint.IsNonNullableStruct m -> join m g.int_ty, m | TyparConstraint.IsUnmanaged m -> errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInUnmanaged(), m)) - maxSoFar, m + maxTy, m | TyparConstraint.RequiresDefaultConstructor m -> - maxSoFar, m + maxTy, m | TyparConstraint.IsReferenceType m -> - maxSoFar, m + maxTy, m | TyparConstraint.DefaultsTo(_priority, _ty, m) -> - maxSoFar, m) - max, m + maxTy, m) + maxTy, m let ChooseTyparSolution g amap tp = let ty, _m = ChooseTyparSolutionAndRange g amap tp @@ -249,18 +250,18 @@ let tryDestTopLambda g amap (ValReprInfo (tpNames, _, _) as tvd) (e, ty) = (None, None, [], e, ty) let n = tvd.NumCurriedArgs - let tps, taue, tauty = + let tps, bodyExpr, bodyTy = match stripDebugPoints e with | Expr.TyLambda (_, tps, b, _, retTy) when not (isNil tpNames) -> tps, b, retTy | _ -> [], e, ty - let ctorThisValOpt, baseValOpt, vsl, body, retTy = startStripLambdaUpto n (taue, tauty) + let ctorThisValOpt, baseValOpt, vsl, body, retTy = startStripLambdaUpto n (bodyExpr, bodyTy) if vsl.Length <> n then None else Some (tps, ctorThisValOpt, baseValOpt, vsl, body, retTy) -let destTopLambda g amap topValInfo (e, ty) = - match tryDestTopLambda g amap topValInfo (e, ty) with +let destTopLambda g amap valReprInfo (e, ty) = + match tryDestTopLambda g amap valReprInfo (e, ty) with | None -> error(Error(FSComp.SR.typrelInvalidValue(), e.Range)) | Some res -> res @@ -271,11 +272,11 @@ let IteratedAdjustArityOfLambdaBody g arities vsl body = /// Do AdjustArityOfLambdaBody for a series of /// iterated lambdas, producing one method. -/// The required iterated function arity (List.length topValInfo) must be identical +/// The required iterated function arity (List.length valReprInfo) must be identical /// to the iterated function arity of the input lambda (List.length vsl) -let IteratedAdjustArityOfLambda g amap topValInfo e = - let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = destTopLambda g amap topValInfo (e, tyOfExpr g e) - let arities = topValInfo.AritiesOfArgs +let IteratedAdjustArityOfLambda g amap valReprInfo e = + let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = destTopLambda g amap valReprInfo (e, tyOfExpr g e) + let arities = valReprInfo.AritiesOfArgs if arities.Length <> vsl.Length then errorR(InternalError(sprintf "IteratedAdjustArityOfLambda, List.length arities = %d, List.length vsl = %d" arities.Length vsl.Length, body.Range)) let vsl, body = IteratedAdjustArityOfLambdaBody g arities vsl body diff --git a/src/Compiler/Checking/TypeRelations.fsi b/src/Compiler/Checking/TypeRelations.fsi index a33eb284c35..cdaa7aab8a6 100644 --- a/src/Compiler/Checking/TypeRelations.fsi +++ b/src/Compiler/Checking/TypeRelations.fsi @@ -63,17 +63,17 @@ val tryDestTopLambda: val destTopLambda: g: TcGlobals -> amap: ImportMap -> - topValInfo: ValReprInfo -> + valReprInfo: ValReprInfo -> e: Expr * ty: TType -> Typars * Val option * Val option * Val list list * Expr * TType /// Do AdjustArityOfLambdaBody for a series of iterated lambdas, producing one method. -/// The required iterated function arity (List.length topValInfo) must be identical +/// The required iterated function arity (List.length valReprInfo) must be identical /// to the iterated function arity of the input lambda (List.length vsl) val IteratedAdjustArityOfLambda: g: TcGlobals -> amap: ImportMap -> - topValInfo: ValReprInfo -> + valReprInfo: ValReprInfo -> e: Expr -> Typars * Val option * Val option * Val list list * Expr * TType diff --git a/src/Compiler/Checking/import.fs b/src/Compiler/Checking/import.fs index 0208d8bf432..cca134f4d38 100644 --- a/src/Compiler/Checking/import.fs +++ b/src/Compiler/Checking/import.fs @@ -174,8 +174,8 @@ let rec ImportILType (env: ImportMap) m tinst ty = | ILType.Array(bounds, ty) -> let n = bounds.Rank - let elementType = ImportILType env m tinst ty - mkArrayTy env.g n elementType m + let elemTy = ImportILType env m tinst ty + mkArrayTy env.g n elemTy m | ILType.Boxed tspec | ILType.Value tspec -> let tcref = ImportILTypeRef env m tspec.TypeRef @@ -335,10 +335,10 @@ let rec ImportProvidedType (env: ImportMap) (m: range) (* (tinst: TypeInst) *) ( if tp.Kind = TyparKind.Measure then let rec conv ty = match ty with - | TType_app (tcref, [t1;t2], _) when tyconRefEq g tcref g.measureproduct_tcr -> Measure.Prod (conv t1, conv t2) - | TType_app (tcref, [t1], _) when tyconRefEq g tcref g.measureinverse_tcr -> Measure.Inv (conv t1) + | TType_app (tcref, [ty1;ty2], _) when tyconRefEq g tcref g.measureproduct_tcr -> Measure.Prod (conv ty1, conv ty2) + | TType_app (tcref, [ty1], _) when tyconRefEq g tcref g.measureinverse_tcr -> Measure.Inv (conv ty1) | TType_app (tcref, [], _) when tyconRefEq g tcref g.measureone_tcr -> Measure.One - | TType_app (tcref, [], _) when tcref.TypeOrMeasureKind = TyparKind.Measure -> Measure.Con tcref + | TType_app (tcref, [], _) when tcref.TypeOrMeasureKind = TyparKind.Measure -> Measure.Const tcref | TType_app (tcref, _, _) -> errorR(Error(FSComp.SR.impInvalidMeasureArgument1(tcref.CompiledName, tp.Name), m)) Measure.One @@ -525,13 +525,13 @@ and ImportILTypeDefList amap m (cpath: CompilationPath) enc items = items |> multisetDiscriminateAndMap (fun n tgs -> - let modty = lazy (ImportILTypeDefList amap m (cpath.NestedCompPath n Namespace) enc tgs) + let modty = lazy (ImportILTypeDefList amap m (cpath.NestedCompPath n (Namespace true)) enc tgs) Construct.NewModuleOrNamespace (Some cpath) taccessPublic (mkSynId m n) XmlDoc.Empty [] (MaybeLazy.Lazy modty)) (fun (n, info: Lazy<_>) -> let (scoref2, lazyTypeDef: ILPreTypeDef) = info.Force() ImportILTypeDef amap m scoref2 cpath enc n (lazyTypeDef.GetTypeDef())) - let kind = match enc with [] -> Namespace | _ -> ModuleOrType + let kind = match enc with [] -> Namespace true | _ -> ModuleOrType Construct.NewModuleOrNamespaceType kind entities [] /// Import a table of IL types as a ModuleOrNamespaceType. diff --git a/src/Compiler/Checking/infos.fs b/src/Compiler/Checking/infos.fs index 28c4382f918..c5d45e95e3f 100644 --- a/src/Compiler/Checking/infos.fs +++ b/src/Compiler/Checking/infos.fs @@ -55,7 +55,7 @@ type ValRef with | Some membInfo -> not membInfo.MemberFlags.IsDispatchSlot && (match membInfo.ImplementedSlotSigs with - | TSlotSig(_, oty, _, _, _, _) :: _ -> isInterfaceTy g oty + | slotSig :: _ -> isInterfaceTy g slotSig.DeclaringType | [] -> false) member vref.ImplementedSlotSignatures = @@ -312,8 +312,8 @@ let OptionalArgInfoOfProvidedParameter (amap: ImportMap) m (provParam : Tainted< elif isObjTy g ty then MissingValue else DefaultValue - let pty = ImportProvidedType amap m (provParam.PApply((fun p -> p.ParameterType), m)) - CallerSide (analyze pty) + let paramTy = ImportProvidedType amap m (provParam.PApply((fun p -> p.ParameterType), m)) + CallerSide (analyze paramTy) | _ -> let v = provParam.PUntaint((fun p -> p.RawDefaultValue), m) CallerSide (Constant (ILFieldInit.FromProvidedObj m v)) @@ -1217,8 +1217,8 @@ type MethInfo = let formalRetTy = ImportReturnTypeFromMetadata amap m ilminfo.RawMetadata.Return.Type (fun _ -> ilminfo.RawMetadata.Return.CustomAttrs) ftinfo.ILScopeRef ftinfo.TypeInstOfRawMetadata formalMethTyparTys let formalParams = [ [ for p in ilminfo.RawMetadata.Parameters do - let paramType = ImportILTypeFromMetadataWithAttributes amap m ftinfo.ILScopeRef ftinfo.TypeInstOfRawMetadata formalMethTyparTys p.Type (fun _ -> p.CustomAttrs) - yield TSlotParam(p.Name, paramType, p.IsIn, p.IsOut, p.IsOptional, []) ] ] + let paramTy = ImportILTypeFromMetadataWithAttributes amap m ftinfo.ILScopeRef ftinfo.TypeInstOfRawMetadata formalMethTyparTys p.Type (fun _ -> p.CustomAttrs) + yield TSlotParam(p.Name, paramTy, p.IsIn, p.IsOut, p.IsOptional, []) ] ] formalRetTy, formalParams #if !NO_TYPEPROVIDERS | ProvidedMeth (_, mi, _, _) -> @@ -1230,9 +1230,9 @@ type MethInfo = let formalParams = [ [ for p in mi.PApplyArray((fun mi -> mi.GetParameters()), "GetParameters", m) do let paramName = p.PUntaint((fun p -> match p.Name with null -> None | s -> Some s), m) - let paramType = ImportProvidedType amap m (p.PApply((fun p -> p.ParameterType), m)) + let paramTy = ImportProvidedType amap m (p.PApply((fun p -> p.ParameterType), m)) let isIn, isOut, isOptional = p.PUntaint((fun p -> p.IsIn, p.IsOut, p.IsOptional), m) - yield TSlotParam(paramName, paramType, isIn, isOut, isOptional, []) ] ] + yield TSlotParam(paramName, paramTy, isIn, isOut, isOptional, []) ] ] formalRetTy, formalParams #endif | _ -> failwith "unreachable" @@ -1256,15 +1256,15 @@ type MethInfo = | ProvidedMeth(amap, mi, _, _) -> // A single set of tupled parameters [ [for p in mi.PApplyArray((fun mi -> mi.GetParameters()), "GetParameters", m) do - let pname = + let paramName = match p.PUntaint((fun p -> p.Name), m) with | null -> None | name -> Some (mkSynId m name) - let pty = + let paramTy = match p.PApply((fun p -> p.ParameterType), m) with | Tainted.Null -> amap.g.unit_ty | parameterType -> ImportProvidedType amap m parameterType - yield ParamNameAndType(pname, pty) ] ] + yield ParamNameAndType(paramName, paramTy) ] ] #endif @@ -1866,14 +1866,14 @@ type PropInfo = | ProvidedProp (_, pi, m) -> [ for p in pi.PApplyArray((fun pi -> pi.GetIndexParameters()), "GetIndexParameters", m) do let paramName = p.PUntaint((fun p -> match p.Name with null -> None | s -> Some (mkSynId m s)), m) - let paramType = ImportProvidedType amap m (p.PApply((fun p -> p.ParameterType), m)) - yield ParamNameAndType(paramName, paramType) ] + let paramTy = ImportProvidedType amap m (p.PApply((fun p -> p.ParameterType), m)) + yield ParamNameAndType(paramName, paramTy) ] #endif /// Get the details of the indexer parameters associated with the property member x.GetParamDatas(amap, m) = x.GetParamNamesAndTypes(amap, m) - |> List.map (fun (ParamNameAndType(nmOpt, pty)) -> ParamData(false, false, false, NotOptional, NoCallerInfo, nmOpt, ReflectedArgInfo.None, pty)) + |> List.map (fun (ParamNameAndType(nmOpt, paramTy)) -> ParamData(false, false, false, NotOptional, NoCallerInfo, nmOpt, ReflectedArgInfo.None, paramTy)) /// Get the types of the indexer parameters associated with the property member x.GetParamTypes(amap, m) = @@ -1908,14 +1908,16 @@ type PropInfo = /// Uses the same techniques as 'MethInfosUseIdenticalDefinitions'. /// Must be compatible with ItemsAreEffectivelyEqual relation. static member PropInfosUseIdenticalDefinitions x1 x2 = + let optVrefEq g = function - | Some v1, Some v2 -> valRefEq g v1 v2 + | Some vref1, Some vref2 -> valRefEq g vref1 vref2 | None, None -> true | _ -> false + match x1, x2 with | ILProp ilpinfo1, ILProp ilpinfo2 -> (ilpinfo1.RawMetadata === ilpinfo2.RawMetadata) | FSProp(g, _, vrefa1, vrefb1), FSProp(_, _, vrefa2, vrefb2) -> - (optVrefEq g (vrefa1, vrefa2)) && (optVrefEq g (vrefb1, vrefb2)) + optVrefEq g (vrefa1, vrefa2) && optVrefEq g (vrefb1, vrefb2) #if !NO_TYPEPROVIDERS | ProvidedProp(_, pi1, _), ProvidedProp(_, pi2, _) -> ProvidedPropertyInfo.TaintedEquals (pi1, pi2) #endif @@ -1927,7 +1929,7 @@ type PropInfo = | ILProp ilpinfo -> hash ilpinfo.RawMetadata.Name | FSProp(_, _, vrefOpt1, vrefOpt2) -> // Hash on string option * string option - let vth = (vrefOpt1 |> Option.map (fun vr -> vr.LogicalName), (vrefOpt2 |> Option.map (fun vr -> vr.LogicalName))) + let vth = (vrefOpt1 |> Option.map (fun vr -> vr.LogicalName), (vrefOpt2 |> Option.map (fun vref -> vref.LogicalName))) hash vth #if !NO_TYPEPROVIDERS | ProvidedProp(_, pi, _) -> ProvidedPropertyInfo.TaintedGetHashCode pi diff --git a/src/Compiler/CodeGen/EraseClosures.fs b/src/Compiler/CodeGen/EraseClosures.fs index ec05d1fc7e2..5ba6c4b50a0 100644 --- a/src/Compiler/CodeGen/EraseClosures.fs +++ b/src/Compiler/CodeGen/EraseClosures.fs @@ -2,653 +2,813 @@ module internal FSharp.Compiler.AbstractIL.ILX.EraseClosures -open Internal.Utilities.Library -open FSharp.Compiler.AbstractIL.ILX.Types -open FSharp.Compiler.AbstractIL.Morphs -open FSharp.Compiler.AbstractIL.IL +open Internal.Utilities.Library +open FSharp.Compiler.AbstractIL.ILX.Types +open FSharp.Compiler.AbstractIL.Morphs +open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.Syntax.PrettyNaming -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Erase closures and function types // by compiling down to code pointers, classes etc. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- let notlazy v = Lazy.CreateFromValue v let rec stripUpTo n test dest x = - if n = 0 then ([], x) else - if test x then + if n = 0 then + ([], x) + else if test x then let l, r = dest x - let ls, res = stripUpTo (n-1) test dest r + let ls, res = stripUpTo (n - 1) test dest r (l :: ls), res - else ([], x) + else + ([], x) -// -------------------------------------------------------------------- -// Flags. These need to match the various classes etc. in the -// ILX standard library, and the parts +// -------------------------------------------------------------------- +// Flags. These need to match the various classes etc. in the +// ILX standard library, and the parts // of the makefile that select the right standard library for a given // combination of flags. // -// Beyond this, the translation inserts classes or value classes for -// the closure environment. -// -------------------------------------------------------------------- +// Beyond this, the translation inserts classes or value classes for +// the closure environment. +// -------------------------------------------------------------------- + +let destTyLambda = + function + | Lambdas_forall (l, r) -> (l, r) + | _ -> failwith "no" + +let isTyLambda = + function + | Lambdas_forall _ -> true + | _ -> false -let destTyLambda = function Lambdas_forall(l, r) -> (l, r) | _ -> failwith "no" -let isTyLambda = function Lambdas_forall _ -> true | _ -> false -let isTyApp = function Apps_tyapp _ -> true | _ -> false +let isTyApp = + function + | Apps_tyapp _ -> true + | _ -> false -let stripTyLambdasUpTo n lambdas = stripUpTo n isTyLambda destTyLambda lambdas +let stripTyLambdasUpTo n lambdas = + stripUpTo n isTyLambda destTyLambda lambdas -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Three tables related to indirect calling // -------------------------------------------------------------------- *) -// Supported indirect calling conventions: -// 1 -// 1_1 -// 1_1_1 -// 1_1_1_1 -// 1_1_1_1_1 -// plus type applications - up to 7 in one step -// Nb. later code currently takes advantage of the fact that term -// and type applications are never mixed in a single step. +// Supported indirect calling conventions: +// 1 +// 1_1 +// 1_1_1 +// 1_1_1_1 +// 1_1_1_1_1 +// plus type applications - up to 7 in one step +// Nb. later code currently takes advantage of the fact that term +// and type applications are never mixed in a single step. let stripSupportedIndirectCall apps = - match apps with - | Apps_app(x, Apps_app(y, Apps_app(z, Apps_app(w, Apps_app(v, rest))))) -> [], [x;y;z;w;v], rest - | Apps_app(x, Apps_app(y, Apps_app(z, Apps_app(w, rest)))) -> [], [x;y;z;w], rest - | Apps_app(x, Apps_app(y, Apps_app(z, rest))) -> [], [x;y;z], rest - | Apps_app(x, Apps_app(y, rest)) -> [], [x;y], rest - | Apps_app(x, rest) -> [], [x], rest - | Apps_tyapp _ -> - let maxTyApps = 1 - let tys, rest = stripUpTo maxTyApps isTyApp destTyFuncApp apps + match apps with + | Apps_app (x, Apps_app (y, Apps_app (z, Apps_app (w, Apps_app (v, rest))))) -> [], [ x; y; z; w; v ], rest + | Apps_app (x, Apps_app (y, Apps_app (z, Apps_app (w, rest)))) -> [], [ x; y; z; w ], rest + | Apps_app (x, Apps_app (y, Apps_app (z, rest))) -> [], [ x; y; z ], rest + | Apps_app (x, Apps_app (y, rest)) -> [], [ x; y ], rest + | Apps_app (x, rest) -> [], [ x ], rest + | Apps_tyapp _ -> + let maxTyApps = 1 + let tys, rest = stripUpTo maxTyApps isTyApp destTyFuncApp apps tys, [], rest | rest -> [], [], rest -// Supported conventions for baking closures: -// 0 -// 1 -// 1_1 -// 1_1_1 -// 1_1_1_1 -// 1_1_1_1_1 -// plus type applications - up to 7 in one step -// Nb. later code currently takes advantage of the fact that term -// and type applications are never mixed in a single step. +// Supported conventions for baking closures: +// 0 +// 1 +// 1_1 +// 1_1_1 +// 1_1_1_1 +// 1_1_1_1_1 +// plus type applications - up to 7 in one step +// Nb. later code currently takes advantage of the fact that term +// and type applications are never mixed in a single step. let stripSupportedAbstraction lambdas = - match lambdas with - | Lambdas_lambda(x, Lambdas_lambda(y, Lambdas_lambda(z, Lambdas_lambda(w, Lambdas_lambda(v, rest))))) -> [], [ x;y;z;w;v ], rest - | Lambdas_lambda(x, Lambdas_lambda(y, Lambdas_lambda(z, Lambdas_lambda(w, rest)))) -> [], [ x;y;z;w ], rest - | Lambdas_lambda(x, Lambdas_lambda(y, Lambdas_lambda(z, rest))) -> [], [ x;y;z ], rest - | Lambdas_lambda(x, Lambdas_lambda(y, rest)) -> [], [ x;y ], rest - | Lambdas_lambda(x, rest) -> [], [ x ], rest - | Lambdas_forall _ -> - let maxTyApps = 1 + match lambdas with + | Lambdas_lambda (x, Lambdas_lambda (y, Lambdas_lambda (z, Lambdas_lambda (w, Lambdas_lambda (v, rest))))) -> + [], [ x; y; z; w; v ], rest + | Lambdas_lambda (x, Lambdas_lambda (y, Lambdas_lambda (z, Lambdas_lambda (w, rest)))) -> [], [ x; y; z; w ], rest + | Lambdas_lambda (x, Lambdas_lambda (y, Lambdas_lambda (z, rest))) -> [], [ x; y; z ], rest + | Lambdas_lambda (x, Lambdas_lambda (y, rest)) -> [], [ x; y ], rest + | Lambdas_lambda (x, rest) -> [], [ x ], rest + | Lambdas_forall _ -> + let maxTyApps = 1 let tys, rest = stripTyLambdasUpTo maxTyApps lambdas - tys, [ ], rest - | rest -> [], [ ], rest + tys, [], rest + | rest -> [], [], rest // This must correspond to stripSupportedAbstraction -let isSupportedDirectCall apps = - match apps with - | Apps_app (_, Apps_done _) -> true - | Apps_app (_, Apps_app (_, Apps_done _)) -> true - | Apps_app (_, Apps_app (_, Apps_app (_, Apps_done _))) -> true +let isSupportedDirectCall apps = + match apps with + | Apps_app (_, Apps_done _) -> true + | Apps_app (_, Apps_app (_, Apps_done _)) -> true + | Apps_app (_, Apps_app (_, Apps_app (_, Apps_done _))) -> true | Apps_app (_, Apps_app (_, Apps_app (_, Apps_app (_, Apps_done _)))) -> true | Apps_tyapp _ -> false | _ -> false -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Prelude for function types. Only use System.Func for now, prepare // for more refined types later. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- [] let fsharpCoreNamespace = "Microsoft.FSharp.Core" -let mkFuncTypeRef fsharpCoreAssemblyScopeRef n = - if n = 1 then mkILTyRef (fsharpCoreAssemblyScopeRef, fsharpCoreNamespace + ".FSharpFunc`2") - else mkILNestedTyRef (fsharpCoreAssemblyScopeRef, - [fsharpCoreNamespace + ".OptimizedClosures"], - "FSharpFunc`"+ string (n + 1)) -type cenv = +let mkFuncTypeRef fsharpCoreAssemblyScopeRef n = + if n = 1 then + mkILTyRef (fsharpCoreAssemblyScopeRef, fsharpCoreNamespace + ".FSharpFunc`2") + else + mkILNestedTyRef (fsharpCoreAssemblyScopeRef, [ fsharpCoreNamespace + ".OptimizedClosures" ], "FSharpFunc`" + string (n + 1)) + +type cenv = { - ilg:ILGlobals + ilg: ILGlobals - tref_Func: ILTypeRef[] + tref_Func: ILTypeRef[] - mkILTyFuncTy: ILType + mkILTyFuncTy: ILType - addFieldGeneratedAttrs: ILFieldDef -> ILFieldDef + addFieldGeneratedAttrs: ILFieldDef -> ILFieldDef - addFieldNeverAttrs: ILFieldDef -> ILFieldDef + addFieldNeverAttrs: ILFieldDef -> ILFieldDef - addMethodGeneratedAttrs: ILMethodDef -> ILMethodDef + addMethodGeneratedAttrs: ILMethodDef -> ILMethodDef } override _.ToString() = "" - -let addMethodGeneratedAttrsToTypeDef cenv (tdef: ILTypeDef) = - tdef.With(methods = (tdef.Methods.AsList() |> List.map (fun md -> md |> cenv.addMethodGeneratedAttrs) |> mkILMethods)) +let addMethodGeneratedAttrsToTypeDef cenv (tdef: ILTypeDef) = + tdef.With( + methods = + (tdef.Methods.AsList() + |> List.map (fun md -> md |> cenv.addMethodGeneratedAttrs) + |> mkILMethods) + ) -let newIlxPubCloEnv(ilg, addMethodGeneratedAttrs, addFieldGeneratedAttrs, addFieldNeverAttrs) = - { ilg = ilg - tref_Func = Array.init 10 (fun i -> mkFuncTypeRef ilg.fsharpCoreAssemblyScopeRef (i+1)) - mkILTyFuncTy = ILType.Boxed (mkILNonGenericTySpec (mkILTyRef (ilg.fsharpCoreAssemblyScopeRef, fsharpCoreNamespace + ".FSharpTypeFunc"))) - addMethodGeneratedAttrs = addMethodGeneratedAttrs - addFieldGeneratedAttrs = addFieldGeneratedAttrs - addFieldNeverAttrs = addFieldNeverAttrs } +let newIlxPubCloEnv (ilg, addMethodGeneratedAttrs, addFieldGeneratedAttrs, addFieldNeverAttrs) = + { + ilg = ilg + tref_Func = Array.init 10 (fun i -> mkFuncTypeRef ilg.fsharpCoreAssemblyScopeRef (i + 1)) + mkILTyFuncTy = + ILType.Boxed(mkILNonGenericTySpec (mkILTyRef (ilg.fsharpCoreAssemblyScopeRef, fsharpCoreNamespace + ".FSharpTypeFunc"))) + addMethodGeneratedAttrs = addMethodGeneratedAttrs + addFieldGeneratedAttrs = addFieldGeneratedAttrs + addFieldNeverAttrs = addFieldNeverAttrs + } let mkILTyFuncTy cenv = cenv.mkILTyFuncTy -let mkILFuncTy cenv dty rty = mkILBoxedTy cenv.tref_Func[0] [dty;rty] +let mkILFuncTy cenv dty rty = + mkILBoxedTy cenv.tref_Func[0] [ dty; rty ] -let mkILCurriedFuncTy cenv dtys rty = List.foldBack (mkILFuncTy cenv) dtys rty +let mkILCurriedFuncTy cenv dtys rty = + List.foldBack (mkILFuncTy cenv) dtys rty -let typ_Func cenv (dtys: ILType list) rty = +let typ_Func cenv (dtys: ILType list) rty = let n = dtys.Length - let tref = if n <= 10 then cenv.tref_Func[n-1] else mkFuncTypeRef cenv.ilg.fsharpCoreAssemblyScopeRef n - mkILBoxedTy tref (dtys @ [rty]) + + let tref = + if n <= 10 then + cenv.tref_Func[n - 1] + else + mkFuncTypeRef cenv.ilg.fsharpCoreAssemblyScopeRef n + + mkILBoxedTy tref (dtys @ [ rty ]) let rec mkTyOfApps cenv apps = - match apps with + match apps with | Apps_tyapp _ -> cenv.mkILTyFuncTy | Apps_app (dty, rest) -> mkILFuncTy cenv dty (mkTyOfApps cenv rest) | Apps_done rty -> rty -let rec mkTyOfLambdas cenv lam = - match lam with +let rec mkTyOfLambdas cenv lam = + match lam with | Lambdas_return rty -> rty | Lambdas_lambda (d, r) -> mkILFuncTy cenv d.Type (mkTyOfLambdas cenv r) | Lambdas_forall _ -> cenv.mkILTyFuncTy -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Method to call for a particular multi-application -// -------------------------------------------------------------------- - -let mkMethSpecForMultiApp cenv (argTys: ILType list, retTy) = +// -------------------------------------------------------------------- + +let mkMethSpecForMultiApp cenv (argTys: ILType list, retTy) = let n = argTys.Length - let formalArgTys = List.mapi (fun i _ -> ILType.TypeVar (uint16 i)) argTys - let formalRetTy = ILType.TypeVar (uint16 n) - let inst = argTys@[retTy] - if n = 1 then - true, - (mkILNonGenericInstanceMethSpecInTy (mkILBoxedTy cenv.tref_Func[0] inst, "Invoke", formalArgTys, formalRetTy)) - else - false, - (mkILStaticMethSpecInTy - (mkILFuncTy cenv inst[0] inst[1], - "InvokeFast", - [mkILCurriedFuncTy cenv formalArgTys formalRetTy]@formalArgTys, - formalRetTy, - inst.Tail.Tail)) + let formalArgTys = List.mapi (fun i _ -> ILType.TypeVar(uint16 i)) argTys + let formalRetTy = ILType.TypeVar(uint16 n) + let inst = argTys @ [ retTy ] + + if n = 1 then + true, (mkILNonGenericInstanceMethSpecInTy (mkILBoxedTy cenv.tref_Func[0] inst, "Invoke", formalArgTys, formalRetTy)) + else + false, + (mkILStaticMethSpecInTy ( + mkILFuncTy cenv inst[0] inst[1], + "InvokeFast", + [ mkILCurriedFuncTy cenv formalArgTys formalRetTy ] @ formalArgTys, + formalRetTy, + inst.Tail.Tail + )) let mkCallBlockForMultiValueApp cenv doTailCall (argTys, retTy) = let callvirt, mr = mkMethSpecForMultiApp cenv (argTys, retTy) - [ ( if callvirt then I_callvirt (doTailCall, mr, None) else I_call (doTailCall, mr, None) ) ] -let mkMethSpecForClosureCall cenv (clospec: IlxClosureSpec) = + [ + (if callvirt then + I_callvirt(doTailCall, mr, None) + else + I_call(doTailCall, mr, None)) + ] + +let mkMethSpecForClosureCall cenv (clospec: IlxClosureSpec) = let tyargsl, argTys, rstruct = stripSupportedAbstraction clospec.FormalLambdas - if not (isNil tyargsl) then failwith "mkMethSpecForClosureCall: internal error" + + if not (isNil tyargsl) then + failwith "mkMethSpecForClosureCall: internal error" + let retTyR = mkTyOfLambdas cenv rstruct let argTysR = typesOfILParams argTys let minstR = clospec.GenericArgs - mkILInstanceMethSpecInTy(clospec.ILType, "Invoke", argTysR, retTyR, minstR) + mkILInstanceMethSpecInTy (clospec.ILType, "Invoke", argTysR, retTyR, minstR) -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Translate instructions.... -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkLdFreeVar (clospec: IlxClosureSpec) (fv: IlxClosureFreeVar) = - [ mkLdarg0; mkNormalLdfld (mkILFieldSpecInTy (clospec.ILType, fv.fvName, fv.fvType) ) ] +let mkLdFreeVar (clospec: IlxClosureSpec) (fv: IlxClosureFreeVar) = + [ + mkLdarg0 + mkNormalLdfld (mkILFieldSpecInTy (clospec.ILType, fv.fvName, fv.fvType)) + ] -let mkCallFunc cenv allocLocal numThisGenParams tailness apps = +let mkCallFunc cenv allocLocal numThisGenParams tailness apps = - // "callfunc" and "callclo" instructions become a series of indirect - // calls or a single direct call. + // "callfunc" and "callclo" instructions become a series of indirect + // calls or a single direct call. let varCount = numThisGenParams - // Unwind the stack until the arguments given in the apps have - // all been popped off. The apps given to this function is - // what remains after the first "strip" of suitable arguments for the - // first call. - // Loaders and storers are returned in groups. Storers are used to pop - // the arguments off the stack that correspond to all the arguments in - // the apps, and the loaders are used to load them back on. - let rec unwind apps = - match apps with - | Apps_tyapp (actual, rest) -> + // Unwind the stack until the arguments given in the apps have + // all been popped off. The apps given to this function is + // what remains after the first "strip" of suitable arguments for the + // first call. + // Loaders and storers are returned in groups. Storers are used to pop + // the arguments off the stack that correspond to all the arguments in + // the apps, and the loaders are used to load them back on. + let rec unwind apps = + match apps with + | Apps_tyapp (actual, rest) -> let rest = instAppsAux varCount [ actual ] rest let storers, loaders = unwind rest - [] :: storers, [] :: loaders - | Apps_app (arg, rest) -> + [] :: storers, [] :: loaders + | Apps_app (arg, rest) -> let storers, loaders = unwind rest - let argStorers, argLoaders = - let locn = allocLocal arg - [mkStloc locn], [mkLdloc locn] - argStorers :: storers, argLoaders :: loaders - | Apps_done _ -> - [], [] - - let rec computePreCall fst n rest (loaders: ILInstr list) = - if fst then - let storers, (loaders2 : ILInstr list list) = unwind rest - (List.rev (List.concat storers) : ILInstr list) , List.concat loaders2 - else - stripUpTo n (function _x :: _y -> true | _ -> false) (function x :: y -> (x, y) | _ -> failwith "no!") loaders - + + let argStorers, argLoaders = + let locn = allocLocal arg + [ mkStloc locn ], [ mkLdloc locn ] + + argStorers :: storers, argLoaders :: loaders + | Apps_done _ -> [], [] + + let rec computePreCall fst n rest (loaders: ILInstr list) = + if fst then + let storers, (loaders2: ILInstr list list) = unwind rest + (List.rev (List.concat storers): ILInstr list), List.concat loaders2 + else + stripUpTo + n + (function + | _x :: _y -> true + | _ -> false) + (function + | x :: y -> (x, y) + | _ -> failwith "no!") + loaders + let rec buildApp fst loaders apps = - // Strip off one valid indirect call. [fst] indicates if this is the - // first indirect call we're making. The code below makes use of the - // fact that term and type applications are never currently mixed for - // direct calls. - match stripSupportedIndirectCall apps with - // Type applications: REVIEW: get rid of curried tyapps - just tuple them + // Strip off one valid indirect call. [fst] indicates if this is the + // first indirect call we're making. The code below makes use of the + // fact that term and type applications are never currently mixed for + // direct calls. + match stripSupportedIndirectCall apps with + // Type applications: REVIEW: get rid of curried tyapps - just tuple them | tyargs, [], _ when not (isNil tyargs) -> - // strip again, instantiating as we go. we could do this while we count. - let revInstTyArgs, rest' = - (([], apps), tyargs) ||> List.fold (fun (revArgsSoFar, cs) _ -> - let actual, rest' = destTyFuncApp cs - let rest'' = instAppsAux varCount [ actual ] rest' - ((actual :: revArgsSoFar), rest'')) + // strip again, instantiating as we go. we could do this while we count. + let revInstTyArgs, rest' = + (([], apps), tyargs) + ||> List.fold (fun (revArgsSoFar, cs) _ -> + let actual, rest' = destTyFuncApp cs + let rest'' = instAppsAux varCount [ actual ] rest' + ((actual :: revArgsSoFar), rest'')) + let instTyargs = List.rev revInstTyArgs let precall, loaders' = computePreCall fst 0 rest' loaders let doTailCall = andTailness tailness false - let instrs1 = - precall @ - [ I_callvirt (doTailCall, (mkILInstanceMethSpecInTy (cenv.mkILTyFuncTy, "Specialize", [], cenv.ilg.typ_Object, instTyargs)), None) ] - let instrs1 = - // TyFunc are represented as Specialize<_> methods returning an object. + + let instrs1 = + precall + @ [ + I_callvirt( + doTailCall, + (mkILInstanceMethSpecInTy (cenv.mkILTyFuncTy, "Specialize", [], cenv.ilg.typ_Object, instTyargs)), + None + ) + ] + + let instrs1 = + // TyFunc are represented as Specialize<_> methods returning an object. // For value types, recover result via unbox and load. // For reference types, recover via cast. let rtnTy = mkTyOfApps cenv rest' - instrs1 @ [ I_unbox_any rtnTy] - if doTailCall = Tailcall then instrs1 - else instrs1 @ buildApp false loaders' rest' + instrs1 @ [ I_unbox_any rtnTy ] - // Term applications - | [], args, rest when not (isNil args) -> + if doTailCall = Tailcall then + instrs1 + else + instrs1 @ buildApp false loaders' rest' + + // Term applications + | [], args, rest when not (isNil args) -> let precall, loaders' = computePreCall fst args.Length rest loaders - let isLast = (match rest with Apps_done _ -> true | _ -> false) - let rty = mkTyOfApps cenv rest + + let isLast = + (match rest with + | Apps_done _ -> true + | _ -> false) + + let rty = mkTyOfApps cenv rest let doTailCall = andTailness tailness isLast - let preCallBlock = precall + let preCallBlock = precall - if doTailCall = Tailcall then - let callBlock = mkCallBlockForMultiValueApp cenv doTailCall (args, rty) - preCallBlock @ callBlock + if doTailCall = Tailcall then + let callBlock = mkCallBlockForMultiValueApp cenv doTailCall (args, rty) + preCallBlock @ callBlock else - let callBlock = mkCallBlockForMultiValueApp cenv doTailCall (args, rty) - let restBlock = buildApp false loaders' rest - preCallBlock @ callBlock @ restBlock + let callBlock = mkCallBlockForMultiValueApp cenv doTailCall (args, rty) + let restBlock = buildApp false loaders' rest + preCallBlock @ callBlock @ restBlock - | [], [], Apps_done _rty -> [ ] + | [], [], Apps_done _rty -> [] | _ -> failwith "*** Error: internal error: unknown indirect calling convention returned by stripSupportedIndirectCall" - - buildApp true [] apps + + buildApp true [] apps // Fix up I_ret instruction. Generalise to selected instr. Remove tailcalls. -let convReturnInstr ty instr = - match instr with - | I_ret -> [I_box ty;I_ret] - | I_call (_, mspec, varargs) -> [I_call (Normalcall, mspec, varargs)] - | I_callvirt (_, mspec, varargs) -> [I_callvirt (Normalcall, mspec, varargs)] - | I_callconstraint (_, ty, mspec, varargs) -> [I_callconstraint (Normalcall, ty, mspec, varargs)] - | I_calli (_, csig, varargs) -> [I_calli (Normalcall, csig, varargs)] - | _ -> [instr] - -let convILMethodBody (thisClo, boxReturnTy) (il: ILMethodBody) = - // This increase in maxstack is historical, though it's harmless - let newMax = - match thisClo with - | Some _ -> il.MaxStack+2 +let convReturnInstr ty instr = + match instr with + | I_ret -> [ I_box ty; I_ret ] + | I_call (_, mspec, varargs) -> [ I_call(Normalcall, mspec, varargs) ] + | I_callvirt (_, mspec, varargs) -> [ I_callvirt(Normalcall, mspec, varargs) ] + | I_callconstraint (_, ty, mspec, varargs) -> [ I_callconstraint(Normalcall, ty, mspec, varargs) ] + | I_calli (_, csig, varargs) -> [ I_calli(Normalcall, csig, varargs) ] + | _ -> [ instr ] + +let convILMethodBody (thisClo, boxReturnTy) (il: ILMethodBody) = + // This increase in maxstack is historical, though it's harmless + let newMax = + match thisClo with + | Some _ -> il.MaxStack + 2 | None -> il.MaxStack + let code = il.Code - // Box before returning? e.g. in the case of a TyFunc returning a struct, which - // compiles to a Specialise<_> method returning an object - let code = + // Box before returning? e.g. in the case of a TyFunc returning a struct, which + // compiles to a Specialise<_> method returning an object + let code = match boxReturnTy with - | None -> code + | None -> code | Some ty -> morphILInstrsInILCode (convReturnInstr ty) code - { il with MaxStack = newMax; Code = code } -let convMethodBody thisClo = function - | MethodBody.IL il -> + { il with + MaxStack = newMax + Code = code + } + +let convMethodBody thisClo = + function + | MethodBody.IL il -> let convil = convILMethodBody (thisClo, None) il.Value - MethodBody.IL (notlazy convil) + MethodBody.IL(notlazy convil) | x -> x -let convMethodDef thisClo (md: ILMethodDef) = +let convMethodDef thisClo (md: ILMethodDef) = let b' = convMethodBody thisClo md.Body - md.With(body=notlazy b') + md.With(body = notlazy b') -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Make fields for free variables of a type abstraction. // REVIEW: change type abstractions to use other closure mechanisms. -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let mkILFreeVarForParam (p : ILParameter) = - let nm = (match p.Name with Some x -> x | None -> failwith "closure parameters must be given names") - mkILFreeVar(nm, false, p.Type) +let mkILFreeVarForParam (p: ILParameter) = + let nm = + (match p.Name with + | Some x -> x + | None -> failwith "closure parameters must be given names") + + mkILFreeVar (nm, false, p.Type) let mkILLocalForFreeVar (p: IlxClosureFreeVar) = mkILLocal p.fvType None -let mkILCloFldSpecs _cenv flds = +let mkILCloFldSpecs _cenv flds = flds |> Array.map (fun fv -> (fv.fvName, fv.fvType)) |> Array.toList -let mkILCloFldDefs cenv flds = - flds +let mkILCloFldDefs cenv flds = + flds |> Array.toList - |> List.map (fun fv -> - let fdef = mkILInstanceField (fv.fvName, fv.fvType, None, ILMemberAccess.Public) - if fv.fvCompilerGenerated then - fdef |> cenv.addFieldNeverAttrs - |> cenv.addFieldGeneratedAttrs - else - fdef) + |> List.map (fun fv -> + let fdef = mkILInstanceField (fv.fvName, fv.fvType, None, ILMemberAccess.Public) -// -------------------------------------------------------------------- -// Convert a closure. Split and chop if there are too many arguments, + if fv.fvCompilerGenerated then + fdef |> cenv.addFieldNeverAttrs |> cenv.addFieldGeneratedAttrs + else + fdef) + +// -------------------------------------------------------------------- +// Convert a closure. Split and chop if there are too many arguments, // otherwise build the appropriate kind of thing depending on whether // it's a type abstraction or a term abstraction. -// -------------------------------------------------------------------- - -let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = - let newTypeDefs = - - // the following are shared between cases 1 && 2 - let nowFields = clo.cloFreeVars - let nowTypeRef = mkILNestedTyRef (ILScopeRef.Local, encl, td.Name) - let nowTy = mkILFormalBoxedTy nowTypeRef td.GenericParams - let nowCloRef = IlxClosureRef(nowTypeRef, clo.cloStructure, nowFields) - let nowCloSpec = mkILFormalCloRef td.GenericParams nowCloRef clo.cloUseStaticField - let nowMethods = List.map (convMethodDef (Some nowCloSpec)) (td.Methods.AsList()) - let ilCloCode = Lazy.force clo.cloCode - let cloDebugRange = ilCloCode.DebugRange - let cloImports = ilCloCode.DebugImports - - let tyargsl, tmargsl, laterStruct = stripSupportedAbstraction clo.cloStructure - - // Adjust all the argument and environment accesses - let rewriteCodeToAccessArgsFromEnv laterCloSpec (argToFreeVarMap: (int * IlxClosureFreeVar) list) = - let il = Lazy.force clo.cloCode - let numLocals = il.Locals.Length - let rewriteInstrToAccessArgsFromEnv instr = - let fixupArg mkEnv mkArg n = - let rec findMatchingArg l c = - match l with - | (m, _) :: t -> - if n = m then mkEnv c - else findMatchingArg t (c+1) - | [] -> mkArg (n - argToFreeVarMap.Length + 1) - findMatchingArg argToFreeVarMap 0 - match instr with - | I_ldarg n -> - fixupArg - (fun x -> [ mkLdloc (uint16 (x+numLocals)) ]) - (fun x -> [ mkLdarg (uint16 x )]) - (int n) - | I_starg n -> - fixupArg - (fun x -> [ mkStloc (uint16 (x+numLocals)) ]) - (fun x -> [ I_starg (uint16 x) ]) - (int n) - | I_ldarga n -> - fixupArg - (fun x -> [ I_ldloca (uint16 (x+numLocals)) ]) - (fun x -> [ I_ldarga (uint16 x) ]) - (int n) - | i -> [i] - let mainCode = morphILInstrsInILCode rewriteInstrToAccessArgsFromEnv il.Code - let ldenvCode = argToFreeVarMap |> List.mapi (fun n (_, fv) -> mkLdFreeVar laterCloSpec fv @ [mkStloc (uint16 (n+numLocals)) ]) |> List.concat - let code = prependInstrsToCode ldenvCode mainCode - - {il with - Code=code - Locals= il.Locals @ (List.map (snd >> mkILLocalForFreeVar) argToFreeVarMap) - // maxstack may increase by 1 due to environment loads - MaxStack=il.MaxStack+1 } - - match tyargsl, tmargsl, laterStruct with - // CASE 1 - Type abstraction - | _ :: _, [], _ -> - let addedGenParams = tyargsl - let nowReturnTy = (mkTyOfLambdas cenv laterStruct) - - // CASE 1a. Split a type abstraction. - // Adjust all the argument and environment accesses - // Actually that special to do here in the type abstraction case - // nb. should combine the term and type abstraction cases for - // to allow for term and type variables to be mixed in a single - // application. - if (match laterStruct with Lambdas_return _ -> false | _ -> true) then - - let nowStruct = List.foldBack (fun x y -> Lambdas_forall(x, y)) tyargsl (Lambdas_return nowReturnTy) - let laterTypeName = td.Name+"T" - let laterTypeRef = mkILNestedTyRef (ILScopeRef.Local, encl, laterTypeName) - let laterGenericParams = td.GenericParams @ addedGenParams - let selfFreeVar = mkILFreeVar(CompilerGeneratedName ("self"+string nowFields.Length), true, nowCloSpec.ILType) - let laterFields = Array.append nowFields [| selfFreeVar |] - let laterCloRef = IlxClosureRef(laterTypeRef, laterStruct, laterFields) - let laterCloSpec = mkILFormalCloRef laterGenericParams laterCloRef false - - let laterCode = rewriteCodeToAccessArgsFromEnv laterCloSpec [(0, selfFreeVar)] - let laterTypeDefs = - convIlxClosureDef cenv encl - (td.With(genericParams=laterGenericParams, name=laterTypeName, methods=emptyILMethods, fields=emptyILFields)) - {clo with cloStructure=laterStruct - cloFreeVars=laterFields - cloCode=notlazy laterCode} - - // This is the code which will get called when then "now" - // arguments get applied. Convert it with the information - // that it is the code for a closure... - let nowInstrs = - // Load up the environment, including self... - [ for fld in nowFields do - yield! mkLdFreeVar nowCloSpec fld - mkLdarg0 - // Make the instance of the delegated closure && return it. - // This passes the method type params. as class type params. - I_newobj (laterCloSpec.Constructor, None) ] - - let nowCode = mkILMethodBody (false, [], nowFields.Length + 1, nonBranchingInstrsToCode nowInstrs, cloDebugRange, cloImports) - - let nowTypeDefs = - convIlxClosureDef cenv encl td - {clo with cloStructure=nowStruct - cloCode=notlazy nowCode} - - let nowTypeDefs = nowTypeDefs |> List.map (addMethodGeneratedAttrsToTypeDef cenv) - - nowTypeDefs @ laterTypeDefs - else - // CASE 1b. Build a type application. - let boxReturnTy = Some nowReturnTy (* box prior to all I_ret *) - let convil = convILMethodBody (Some nowCloSpec, boxReturnTy) (Lazy.force clo.cloCode) - let nowApplyMethDef = - mkILGenericVirtualMethod - ("Specialize", - ILMemberAccess.Public, - addedGenParams, (* method is generic over added ILGenericParameterDefs *) - [], - mkILReturn(cenv.ilg.typ_Object), - MethodBody.IL (notlazy convil)) - - let ctorMethodDef = - mkILStorageCtor - ([ mkLdarg0; mkNormalCall (mkILCtorMethSpecForTy (cenv.mkILTyFuncTy, [])) ], - nowTy, - mkILCloFldSpecs cenv nowFields, - ILMemberAccess.Assembly, - None, - None) - |> cenv.addMethodGeneratedAttrs - - let cloTypeDef = - ILTypeDef(name = td.Name, - genericParams= td.GenericParams, - attributes = td.Attributes, - implements = [], - nestedTypes = emptyILTypeDefs, - layout=ILTypeDefLayout.Auto, - extends= Some cenv.mkILTyFuncTy, - methods= mkILMethods (ctorMethodDef :: nowApplyMethDef :: nowMethods) , - fields= mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList()), - customAttrs=emptyILCustomAttrs, - methodImpls=emptyILMethodImpls, - properties=emptyILProperties, - events=emptyILEvents, - isKnownToBeAttribute=false, - securityDecls=emptyILSecurityDecls) - .WithSpecialName(false) - .WithImport(false) - .WithHasSecurity(false) - .WithAbstract(false) - .WithSealed(true) - .WithInitSemantics(ILTypeInit.BeforeField) - .WithEncoding(ILDefaultPInvokeEncoding.Ansi) - [ cloTypeDef] - - // CASE 2 - Term abstraction - | [], (_ :: _ as nowParams), _ -> - let nowReturnTy = mkTyOfLambdas cenv laterStruct - - // CASE 2a - Too Many Term Arguments or Remaining Type arguments - Split the Closure Class in Two - if (match laterStruct with Lambdas_return _ -> false | _ -> true) then - let nowStruct = List.foldBack (fun l r -> Lambdas_lambda(l, r)) nowParams (Lambdas_return nowReturnTy) - let laterTypeName = td.Name+"D" - let laterTypeRef = mkILNestedTyRef (ILScopeRef.Local, encl, laterTypeName) - let laterGenericParams = td.GenericParams - // Number each argument left-to-right, adding one to account for the "this" pointer - let selfFreeVar = mkILFreeVar(CompilerGeneratedName "self", true, nowCloSpec.ILType) - let argToFreeVarMap = (0, selfFreeVar) :: (nowParams |> List.mapi (fun i p -> i+1, mkILFreeVarForParam p)) - let laterFreeVars = argToFreeVarMap |> List.map snd |> List.toArray - let laterFields = Array.append nowFields laterFreeVars - let laterCloRef = IlxClosureRef(laterTypeRef, laterStruct, laterFields) - let laterCloSpec = mkILFormalCloRef laterGenericParams laterCloRef false - - let nowInstrs = - [ // Load up the environment - for nowField in nowFields do - yield! mkLdFreeVar nowCloSpec nowField - // Load up all the arguments (including self), which become free variables in the delegated closure - for (n, _) in argToFreeVarMap do - mkLdarg (uint16 n) - // Make the instance of the delegated closure && return it. - I_newobj (laterCloSpec.Constructor, None) ] - - // This is the code which will first get called. - let nowCode = mkILMethodBody (false, [], argToFreeVarMap.Length + nowFields.Length, nonBranchingInstrsToCode nowInstrs, cloDebugRange, cloImports) - - let nowTypeDefs = - convIlxClosureDef cenv encl td - {clo with cloStructure=nowStruct - cloCode=notlazy nowCode} - - let laterCode = rewriteCodeToAccessArgsFromEnv laterCloSpec argToFreeVarMap - - let laterTypeDefs = - convIlxClosureDef cenv encl - (td.With(genericParams=laterGenericParams, name=laterTypeName, methods=emptyILMethods, fields=emptyILFields)) - {clo with cloStructure=laterStruct - cloFreeVars=laterFields - cloCode=notlazy laterCode} - - // add 'compiler generated' to all the methods in the 'now' classes - let nowTypeDefs = nowTypeDefs |> List.map (addMethodGeneratedAttrsToTypeDef cenv) - - nowTypeDefs @ laterTypeDefs - - else - // CASE 2b - Build an Invoke method - - let nowEnvParentClass = typ_Func cenv (typesOfILParams nowParams) nowReturnTy - - let cloTypeDef = - let convil = convILMethodBody (Some nowCloSpec, None) (Lazy.force clo.cloCode) +// -------------------------------------------------------------------- + +let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = + let newTypeDefs = + + // the following are shared between cases 1 && 2 + let nowFields = clo.cloFreeVars + let nowTypeRef = mkILNestedTyRef (ILScopeRef.Local, encl, td.Name) + let nowTy = mkILFormalBoxedTy nowTypeRef td.GenericParams + let nowCloRef = IlxClosureRef(nowTypeRef, clo.cloStructure, nowFields) + let nowCloSpec = mkILFormalCloRef td.GenericParams nowCloRef clo.cloUseStaticField + let nowMethods = List.map (convMethodDef (Some nowCloSpec)) (td.Methods.AsList()) + let ilCloCode = Lazy.force clo.cloCode + let cloDebugRange = ilCloCode.DebugRange + let cloImports = ilCloCode.DebugImports + + let tyargsl, tmargsl, laterStruct = stripSupportedAbstraction clo.cloStructure + + // Adjust all the argument and environment accesses + let rewriteCodeToAccessArgsFromEnv laterCloSpec (argToFreeVarMap: (int * IlxClosureFreeVar) list) = + let il = Lazy.force clo.cloCode + let numLocals = il.Locals.Length + + let rewriteInstrToAccessArgsFromEnv instr = + let fixupArg mkEnv mkArg n = + let rec findMatchingArg l c = + match l with + | (m, _) :: t -> if n = m then mkEnv c else findMatchingArg t (c + 1) + | [] -> mkArg (n - argToFreeVarMap.Length + 1) + + findMatchingArg argToFreeVarMap 0 + + match instr with + | I_ldarg n -> fixupArg (fun x -> [ mkLdloc (uint16 (x + numLocals)) ]) (fun x -> [ mkLdarg (uint16 x) ]) (int n) + | I_starg n -> fixupArg (fun x -> [ mkStloc (uint16 (x + numLocals)) ]) (fun x -> [ I_starg(uint16 x) ]) (int n) + | I_ldarga n -> fixupArg (fun x -> [ I_ldloca(uint16 (x + numLocals)) ]) (fun x -> [ I_ldarga(uint16 x) ]) (int n) + | i -> [ i ] + + let mainCode = morphILInstrsInILCode rewriteInstrToAccessArgsFromEnv il.Code + + let ldenvCode = + argToFreeVarMap + |> List.mapi (fun n (_, fv) -> mkLdFreeVar laterCloSpec fv @ [ mkStloc (uint16 (n + numLocals)) ]) + |> List.concat + + let code = prependInstrsToCode ldenvCode mainCode + + { il with + Code = code + Locals = il.Locals @ (List.map (snd >> mkILLocalForFreeVar) argToFreeVarMap) + // maxstack may increase by 1 due to environment loads + MaxStack = il.MaxStack + 1 + } + + match tyargsl, tmargsl, laterStruct with + // CASE 1 - Type abstraction + | _ :: _, [], _ -> + let addedGenParams = tyargsl + let nowReturnTy = (mkTyOfLambdas cenv laterStruct) + + // CASE 1a. Split a type abstraction. + // Adjust all the argument and environment accesses + // Actually that special to do here in the type abstraction case + // nb. should combine the term and type abstraction cases for + // to allow for term and type variables to be mixed in a single + // application. + if + (match laterStruct with + | Lambdas_return _ -> false + | _ -> true) + then + + let nowStruct = + List.foldBack (fun x y -> Lambdas_forall(x, y)) tyargsl (Lambdas_return nowReturnTy) + + let laterTypeName = td.Name + "T" + let laterTypeRef = mkILNestedTyRef (ILScopeRef.Local, encl, laterTypeName) + let laterGenericParams = td.GenericParams @ addedGenParams + + let selfFreeVar = + mkILFreeVar (CompilerGeneratedName("self" + string nowFields.Length), true, nowCloSpec.ILType) + + let laterFields = Array.append nowFields [| selfFreeVar |] + let laterCloRef = IlxClosureRef(laterTypeRef, laterStruct, laterFields) + let laterCloSpec = mkILFormalCloRef laterGenericParams laterCloRef false + + let laterCode = rewriteCodeToAccessArgsFromEnv laterCloSpec [ (0, selfFreeVar) ] + + let laterTypeDefs = + convIlxClosureDef + cenv + encl + (td.With(genericParams = laterGenericParams, name = laterTypeName, methods = emptyILMethods, fields = emptyILFields)) + { clo with + cloStructure = laterStruct + cloFreeVars = laterFields + cloCode = notlazy laterCode + } + + // This is the code which will get called when then "now" + // arguments get applied. Convert it with the information + // that it is the code for a closure... + let nowInstrs = + // Load up the environment, including self... + [ + for fld in nowFields do + yield! mkLdFreeVar nowCloSpec fld + mkLdarg0 + // Make the instance of the delegated closure && return it. + // This passes the method type params. as class type params. + I_newobj(laterCloSpec.Constructor, None) + ] + + let nowCode = + mkILMethodBody (false, [], nowFields.Length + 1, nonBranchingInstrsToCode nowInstrs, cloDebugRange, cloImports) + + let nowTypeDefs = + convIlxClosureDef + cenv + encl + td + { clo with + cloStructure = nowStruct + cloCode = notlazy nowCode + } + + let nowTypeDefs = nowTypeDefs |> List.map (addMethodGeneratedAttrsToTypeDef cenv) + + nowTypeDefs @ laterTypeDefs + else + // CASE 1b. Build a type application. + let boxReturnTy = Some nowReturnTy (* box prior to all I_ret *) + + let convil = + convILMethodBody (Some nowCloSpec, boxReturnTy) (Lazy.force clo.cloCode) + + let nowApplyMethDef = + mkILGenericVirtualMethod ( + "Specialize", + ILMemberAccess.Public, + addedGenParams (* method is generic over added ILGenericParameterDefs *) , + [], + mkILReturn (cenv.ilg.typ_Object), + MethodBody.IL(notlazy convil) + ) + + let ctorMethodDef = + mkILStorageCtor ( + [ mkLdarg0; mkNormalCall (mkILCtorMethSpecForTy (cenv.mkILTyFuncTy, [])) ], + nowTy, + mkILCloFldSpecs cenv nowFields, + ILMemberAccess.Assembly, + None, + None + ) + |> cenv.addMethodGeneratedAttrs + + let cloTypeDef = + ILTypeDef( + name = td.Name, + genericParams = td.GenericParams, + attributes = td.Attributes, + implements = [], + nestedTypes = emptyILTypeDefs, + layout = ILTypeDefLayout.Auto, + extends = Some cenv.mkILTyFuncTy, + methods = mkILMethods (ctorMethodDef :: nowApplyMethDef :: nowMethods), + fields = mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList()), + customAttrs = emptyILCustomAttrs, + methodImpls = emptyILMethodImpls, + properties = emptyILProperties, + events = emptyILEvents, + isKnownToBeAttribute = false, + securityDecls = emptyILSecurityDecls + ) + .WithSpecialName(false) + .WithImport(false) + .WithHasSecurity(false) + .WithAbstract(false) + .WithSealed(true) + .WithInitSemantics(ILTypeInit.BeforeField) + .WithEncoding(ILDefaultPInvokeEncoding.Ansi) + + [ cloTypeDef ] + + // CASE 2 - Term abstraction + | [], (_ :: _ as nowParams), _ -> + let nowReturnTy = mkTyOfLambdas cenv laterStruct + + // CASE 2a - Too Many Term Arguments or Remaining Type arguments - Split the Closure Class in Two + if + (match laterStruct with + | Lambdas_return _ -> false + | _ -> true) + then + let nowStruct = + List.foldBack (fun l r -> Lambdas_lambda(l, r)) nowParams (Lambdas_return nowReturnTy) + + let laterTypeName = td.Name + "D" + let laterTypeRef = mkILNestedTyRef (ILScopeRef.Local, encl, laterTypeName) + let laterGenericParams = td.GenericParams + // Number each argument left-to-right, adding one to account for the "this" pointer + let selfFreeVar = + mkILFreeVar (CompilerGeneratedName "self", true, nowCloSpec.ILType) + + let argToFreeVarMap = + (0, selfFreeVar) + :: (nowParams |> List.mapi (fun i p -> i + 1, mkILFreeVarForParam p)) + + let laterFreeVars = argToFreeVarMap |> List.map snd |> List.toArray + let laterFields = Array.append nowFields laterFreeVars + let laterCloRef = IlxClosureRef(laterTypeRef, laterStruct, laterFields) + let laterCloSpec = mkILFormalCloRef laterGenericParams laterCloRef false + + let nowInstrs = + [ // Load up the environment + for nowField in nowFields do + yield! mkLdFreeVar nowCloSpec nowField + // Load up all the arguments (including self), which become free variables in the delegated closure + for (n, _) in argToFreeVarMap do + mkLdarg (uint16 n) + // Make the instance of the delegated closure && return it. + I_newobj(laterCloSpec.Constructor, None) + ] + + // This is the code which will first get called. + let nowCode = + mkILMethodBody ( + false, + [], + argToFreeVarMap.Length + nowFields.Length, + nonBranchingInstrsToCode nowInstrs, + cloDebugRange, + cloImports + ) + + let nowTypeDefs = + convIlxClosureDef + cenv + encl + td + { clo with + cloStructure = nowStruct + cloCode = notlazy nowCode + } + + let laterCode = rewriteCodeToAccessArgsFromEnv laterCloSpec argToFreeVarMap + + let laterTypeDefs = + convIlxClosureDef + cenv + encl + (td.With(genericParams = laterGenericParams, name = laterTypeName, methods = emptyILMethods, fields = emptyILFields)) + { clo with + cloStructure = laterStruct + cloFreeVars = laterFields + cloCode = notlazy laterCode + } + + // add 'compiler generated' to all the methods in the 'now' classes + let nowTypeDefs = nowTypeDefs |> List.map (addMethodGeneratedAttrsToTypeDef cenv) + + nowTypeDefs @ laterTypeDefs + + else + // CASE 2b - Build an Invoke method + + let nowEnvParentClass = typ_Func cenv (typesOfILParams nowParams) nowReturnTy + + let cloTypeDef = + let convil = convILMethodBody (Some nowCloSpec, None) (Lazy.force clo.cloCode) + let nowApplyMethDef = - mkILNonGenericVirtualMethod - ("Invoke", ILMemberAccess.Public, - nowParams, - mkILReturn nowReturnTy, - MethodBody.IL (notlazy convil)) - - let ctorMethodDef = - mkILStorageCtor - ([ mkLdarg0; mkNormalCall (mkILCtorMethSpecForTy (nowEnvParentClass, [])) ], - nowTy, - mkILCloFldSpecs cenv nowFields, + mkILNonGenericVirtualMethod ( + "Invoke", + ILMemberAccess.Public, + nowParams, + mkILReturn nowReturnTy, + MethodBody.IL(notlazy convil) + ) + + let ctorMethodDef = + mkILStorageCtor ( + [ mkLdarg0; mkNormalCall (mkILCtorMethSpecForTy (nowEnvParentClass, [])) ], + nowTy, + mkILCloFldSpecs cenv nowFields, ILMemberAccess.Assembly, - None, cloImports) - |> cenv.addMethodGeneratedAttrs - - ILTypeDef(name = td.Name, - genericParams= td.GenericParams, - attributes = td.Attributes, - implements = [], - layout=ILTypeDefLayout.Auto, - nestedTypes = emptyILTypeDefs, - extends= Some nowEnvParentClass, - methods= mkILMethods (ctorMethodDef :: nowApplyMethDef :: nowMethods), - fields= mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList()), - customAttrs=emptyILCustomAttrs, - methodImpls=emptyILMethodImpls, - properties=emptyILProperties, - events=emptyILEvents, - isKnownToBeAttribute=false, - securityDecls=emptyILSecurityDecls) - .WithHasSecurity(false) - .WithSpecialName(false) - .WithAbstract(false) - .WithImport(false) - .WithEncoding(ILDefaultPInvokeEncoding.Ansi) - .WithSealed(true) - .WithInitSemantics(ILTypeInit.BeforeField) - - [cloTypeDef] - - | [], [], Lambdas_return _ -> - - // No code is being declared: just bake a (mutable) environment - let cloCodeR = - match td.Extends with - | None -> (mkILNonGenericEmptyCtor (cenv.ilg.typ_Object, None, cloImports)).MethodBody - | Some _ -> convILMethodBody (Some nowCloSpec, None) (Lazy.force clo.cloCode) - - let ctorMethodDef = - let flds = (mkILCloFldSpecs cenv nowFields) - mkILCtor( - ILMemberAccess.Public, - List.map mkILParamNamed flds, - mkMethodBody - (cloCodeR.IsZeroInit, - cloCodeR.Locals, - cloCodeR.MaxStack, - prependInstrsToCode - (List.concat (List.mapi (fun n (nm, ty) -> - [ mkLdarg0 - mkLdarg (uint16 (n+1)) - mkNormalStfld (mkILFieldSpecInTy (nowTy, nm, ty)) - ]) flds)) - cloCodeR.Code, - None, - None)) - - let cloTypeDef = - td.With(implements= td.Implements, - extends= (match td.Extends with None -> Some cenv.ilg.typ_Object | Some x -> Some(x)), + None, + cloImports + ) + |> cenv.addMethodGeneratedAttrs + + ILTypeDef( + name = td.Name, + genericParams = td.GenericParams, + attributes = td.Attributes, + implements = [], + layout = ILTypeDefLayout.Auto, + nestedTypes = emptyILTypeDefs, + extends = Some nowEnvParentClass, + methods = mkILMethods (ctorMethodDef :: nowApplyMethDef :: nowMethods), + fields = mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList()), + customAttrs = emptyILCustomAttrs, + methodImpls = emptyILMethodImpls, + properties = emptyILProperties, + events = emptyILEvents, + isKnownToBeAttribute = false, + securityDecls = emptyILSecurityDecls + ) + .WithHasSecurity(false) + .WithSpecialName(false) + .WithAbstract(false) + .WithImport(false) + .WithEncoding(ILDefaultPInvokeEncoding.Ansi) + .WithSealed(true) + .WithInitSemantics(ILTypeInit.BeforeField) + + [ cloTypeDef ] + + | [], [], Lambdas_return _ -> + + // No code is being declared: just bake a (mutable) environment + let cloCodeR = + match td.Extends with + | None -> (mkILNonGenericEmptyCtor (cenv.ilg.typ_Object, None, cloImports)).MethodBody + | Some _ -> convILMethodBody (Some nowCloSpec, None) (Lazy.force clo.cloCode) + + let ctorMethodDef = + let flds = (mkILCloFldSpecs cenv nowFields) + + mkILCtor ( + ILMemberAccess.Public, + List.map mkILParamNamed flds, + mkMethodBody ( + cloCodeR.IsZeroInit, + cloCodeR.Locals, + cloCodeR.MaxStack, + prependInstrsToCode + (List.concat ( + List.mapi + (fun n (nm, ty) -> + [ + mkLdarg0 + mkLdarg (uint16 (n + 1)) + mkNormalStfld (mkILFieldSpecInTy (nowTy, nm, ty)) + ]) + flds + )) + cloCodeR.Code, + None, + None + ) + ) + + let cloTypeDef = + td.With( + implements = td.Implements, + extends = + (match td.Extends with + | None -> Some cenv.ilg.typ_Object + | Some x -> Some(x)), name = td.Name, - genericParams= td.GenericParams, - methods= mkILMethods (ctorMethodDef :: nowMethods), - fields= mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList())) + genericParams = td.GenericParams, + methods = mkILMethods (ctorMethodDef :: nowMethods), + fields = mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList()) + ) - [cloTypeDef] + [ cloTypeDef ] - | a, b, _ -> - failwith ("Unexpected unsupported abstraction sequence, #tyabs = "+string a.Length + ", #tmabs = "+string b.Length) - - newTypeDefs + | a, b, _ -> + failwith ( + "Unexpected unsupported abstraction sequence, #tyabs = " + + string a.Length + + ", #tmabs = " + + string b.Length + ) + newTypeDefs diff --git a/src/Compiler/CodeGen/EraseUnions.fs b/src/Compiler/CodeGen/EraseUnions.fs index 05049eae208..626ddd49758 100644 --- a/src/Compiler/CodeGen/EraseUnions.fs +++ b/src/Compiler/CodeGen/EraseUnions.fs @@ -5,8 +5,8 @@ module internal FSharp.Compiler.AbstractIL.ILX.EraseUnions open System.Collections.Generic open System.Reflection -open Internal.Utilities.Library -open FSharp.Compiler.AbstractIL.IL +open Internal.Utilities.Library +open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILX.Types [] @@ -19,21 +19,21 @@ let TagCons = 1 let ALT_NAME_CONS = "Cons" type DiscriminationTechnique = - /// Indicates a special representation for the F# list type where the "empty" value has a tail field of value null - | TailOrNull + /// Indicates a special representation for the F# list type where the "empty" value has a tail field of value null + | TailOrNull - /// Indicates a type with either number of cases < 4, and not a single-class type with an integer tag (IntegerTag) - | RuntimeTypes + /// Indicates a type with either number of cases < 4, and not a single-class type with an integer tag (IntegerTag) + | RuntimeTypes - /// Indicates a type with a single case, e.g. ``type X = ABC of string * int`` - | SingleCase + /// Indicates a type with a single case, e.g. ``type X = ABC of string * int`` + | SingleCase - /// Indicates a type with either cases >= 4, or a type like - // type X = A | B | C - // or type X = A | B | C of string - // where at most one case is non-nullary. These can be represented using a single - // class (no subclasses), but an integer tag is stored to discriminate between the objects. - | IntegerTag + /// Indicates a type with either cases >= 4, or a type like + // type X = A | B | C + // or type X = A | B | C of string + // where at most one case is non-nullary. These can be represented using a single + // class (no subclasses), but an integer tag is stored to discriminate between the objects. + | IntegerTag // A potentially useful additional representation trades an extra integer tag in the root type // for faster discrimination, and in the important single-non-nullary constructor case @@ -41,174 +41,193 @@ type DiscriminationTechnique = // type Tree = Tip | Node of int * Tree * Tree // // it also flattens so the fields for "Node" are stored in the base class, meaning that no type casts -// are needed to access the data. +// are needed to access the data. // -// However, it can't be enabled because it suppresses the generation +// However, it can't be enabled because it suppresses the generation // of C#-facing nested types for the non-nullary case. This could be enabled -// in a binary compatible way by ensuring we continue to generate the C# facing types and use +// in a binary compatible way by ensuring we continue to generate the C# facing types and use // them as the instance types, but still store all field elements in the base type. Additional // accessors would be needed to access these fields directly, akin to HeadOrDefault and TailOrNull. // This functor helps us make representation decisions for F# union type compilation -type UnionReprDecisions<'Union,'Alt,'Type> - (getAlternatives: 'Union->'Alt[], - nullPermitted:'Union->bool, - isNullary:'Alt->bool, - isList:'Union->bool, - isStruct:'Union->bool, - nameOfAlt : 'Alt -> string, - makeRootType: 'Union -> 'Type, - makeNestedType: 'Union * string -> 'Type) = +type UnionReprDecisions<'Union, 'Alt, 'Type> + ( + getAlternatives: 'Union -> 'Alt[], + nullPermitted: 'Union -> bool, + isNullary: 'Alt -> bool, + isList: 'Union -> bool, + isStruct: 'Union -> bool, + nameOfAlt: 'Alt -> string, + makeRootType: 'Union -> 'Type, + makeNestedType: 'Union * string -> 'Type + ) = static let TaggingThresholdFixedConstant = 4 - member repr.RepresentAllAlternativesAsConstantFieldsInRootClass cu = + member repr.RepresentAllAlternativesAsConstantFieldsInRootClass cu = cu |> getAlternatives |> Array.forall isNullary - member repr.DiscriminationTechnique cu = - if isList cu then + member repr.DiscriminationTechnique cu = + if isList cu then TailOrNull else let alts = getAlternatives cu - if alts.Length = 1 then + + if alts.Length = 1 then SingleCase - elif - not (isStruct cu) && - alts.Length < TaggingThresholdFixedConstant && - not (repr.RepresentAllAlternativesAsConstantFieldsInRootClass cu) then + elif + not (isStruct cu) + && alts.Length < TaggingThresholdFixedConstant + && not (repr.RepresentAllAlternativesAsConstantFieldsInRootClass cu) + then RuntimeTypes else IntegerTag - // WARNING: this must match IsUnionTypeWithNullAsTrueValue in the F# compiler - member repr.RepresentAlternativeAsNull (cu,alt) = + // WARNING: this must match IsUnionTypeWithNullAsTrueValue in the F# compiler + member repr.RepresentAlternativeAsNull(cu, alt) = let alts = getAlternatives cu - nullPermitted cu && - (repr.DiscriminationTechnique cu = RuntimeTypes) && (* don't use null for tags, lists or single-case *) - Array.existsOne isNullary alts && - Array.exists (isNullary >> not) alts && - isNullary alt (* is this the one? *) - member repr.RepresentOneAlternativeAsNull cu = + nullPermitted cu + && (repr.DiscriminationTechnique cu = RuntimeTypes) + && (* don't use null for tags, lists or single-case *) Array.existsOne isNullary alts + && Array.exists (isNullary >> not) alts + && isNullary alt (* is this the one? *) + + member repr.RepresentOneAlternativeAsNull cu = let alts = getAlternatives cu - nullPermitted cu && - alts |> Array.existsOne (fun alt -> repr.RepresentAlternativeAsNull (cu,alt)) - member repr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull (cu,alt) = - // Check all nullary constructors are being represented without using sub-classes + nullPermitted cu + && alts |> Array.existsOne (fun alt -> repr.RepresentAlternativeAsNull(cu, alt)) + + member repr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull(cu, alt) = + // Check all nullary constructors are being represented without using sub-classes let alts = getAlternatives cu - not (isStruct cu) && - not (isNullary alt) && - (alts |> Array.forall (fun alt2 -> not (isNullary alt2) || repr.RepresentAlternativeAsNull (cu,alt2))) && - // Check this is the one and only non-nullary constructor + + not (isStruct cu) + && not (isNullary alt) + && (alts + |> Array.forall (fun alt2 -> not (isNullary alt2) || repr.RepresentAlternativeAsNull(cu, alt2))) + && + // Check this is the one and only non-nullary constructor Array.existsOne (isNullary >> not) alts - member repr.RepresentAlternativeAsStructValue cu = - isStruct cu + member repr.RepresentAlternativeAsStructValue cu = isStruct cu - member repr.RepresentAlternativeAsFreshInstancesOfRootClass (cu,alt) = - not (isStruct cu) && - (// Check all nullary constructors are being represented without using sub-classes - (isList cu && nameOfAlt alt = ALT_NAME_CONS) || - repr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull (cu, alt) ) + member repr.RepresentAlternativeAsFreshInstancesOfRootClass(cu, alt) = + not (isStruct cu) + && ((isList // Check all nullary constructors are being represented without using sub-classes + cu + && nameOfAlt alt = ALT_NAME_CONS) + || repr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull(cu, alt)) - member repr.RepresentAlternativeAsConstantFieldInTaggedRootClass (cu,alt) = - not (isStruct cu) && - isNullary alt && - not (repr.RepresentAlternativeAsNull (cu,alt)) && - (repr.DiscriminationTechnique cu <> RuntimeTypes) + member repr.RepresentAlternativeAsConstantFieldInTaggedRootClass(cu, alt) = + not (isStruct cu) + && isNullary alt + && not (repr.RepresentAlternativeAsNull(cu, alt)) + && (repr.DiscriminationTechnique cu <> RuntimeTypes) - member repr.Flatten cu = - isStruct cu + member repr.Flatten cu = isStruct cu - member repr.OptimizeAlternativeToRootClass (cu,alt) = - // The list type always collapses to the root class - isList cu || + member repr.OptimizeAlternativeToRootClass(cu, alt) = + // The list type always collapses to the root class + isList cu + || // Structs are always flattened - repr.Flatten cu || - repr.RepresentAllAlternativesAsConstantFieldsInRootClass cu || - repr.RepresentAlternativeAsConstantFieldInTaggedRootClass (cu,alt) || - repr.RepresentAlternativeAsStructValue(cu) || - repr.RepresentAlternativeAsFreshInstancesOfRootClass(cu,alt) - - member repr.MaintainPossiblyUniqueConstantFieldForAlternative(cu,alt) = - not (isStruct cu) && - not (repr.RepresentAlternativeAsNull (cu,alt)) && - isNullary alt - - member repr.TypeForAlternative (cuspec,alt) = - if repr.OptimizeAlternativeToRootClass (cuspec,alt) || repr.RepresentAlternativeAsNull (cuspec,alt) then + repr.Flatten cu + || repr.RepresentAllAlternativesAsConstantFieldsInRootClass cu + || repr.RepresentAlternativeAsConstantFieldInTaggedRootClass(cu, alt) + || repr.RepresentAlternativeAsStructValue(cu) + || repr.RepresentAlternativeAsFreshInstancesOfRootClass(cu, alt) + + member repr.MaintainPossiblyUniqueConstantFieldForAlternative(cu, alt) = + not (isStruct cu) + && not (repr.RepresentAlternativeAsNull(cu, alt)) + && isNullary alt + + member repr.TypeForAlternative(cuspec, alt) = + if + repr.OptimizeAlternativeToRootClass(cuspec, alt) + || repr.RepresentAlternativeAsNull(cuspec, alt) + then makeRootType cuspec - else - let altName = nameOfAlt alt + else + let altName = nameOfAlt alt // Add "_" if the thing is nullary or if it is 'List._Cons', which is special because it clashes with the name of the static method "Cons" - let nm = if isNullary alt || isList cuspec then "_"+altName else altName - makeNestedType (cuspec, nm) + let nm = + if isNullary alt || isList cuspec then + "_" + altName + else + altName + makeNestedType (cuspec, nm) -let baseTyOfUnionSpec (cuspec : IlxUnionSpec) = +let baseTyOfUnionSpec (cuspec: IlxUnionSpec) = mkILNamedTy cuspec.Boxity cuspec.TypeRef cuspec.GenericArgs -let mkMakerName (cuspec: IlxUnionSpec) nm = +let mkMakerName (cuspec: IlxUnionSpec) nm = match cuspec.HasHelpers with - | SpecialFSharpListHelpers - | SpecialFSharpOptionHelpers -> nm // Leave 'Some', 'None', 'Cons', 'Empty' as is - | AllHelpers + | SpecialFSharpListHelpers + | SpecialFSharpOptionHelpers -> nm // Leave 'Some', 'None', 'Cons', 'Empty' as is + | AllHelpers | NoHelpers -> "New" + nm let mkCasesTypeRef (cuspec: IlxUnionSpec) = cuspec.TypeRef -let cuspecRepr = - UnionReprDecisions - ((fun (cuspec:IlxUnionSpec) -> cuspec.AlternativesArray), - (fun (cuspec:IlxUnionSpec) -> cuspec.IsNullPermitted), - (fun (alt:IlxUnionCase) -> alt.IsNullary), - (fun cuspec -> cuspec.HasHelpers = IlxUnionHasHelpers.SpecialFSharpListHelpers), - (fun cuspec -> cuspec.Boxity = ILBoxity.AsValue), - (fun (alt:IlxUnionCase) -> alt.Name), - (fun cuspec -> cuspec.DeclaringType), - (fun (cuspec,nm) -> mkILNamedTy cuspec.Boxity (mkILTyRefInTyRef (mkCasesTypeRef cuspec, nm)) cuspec.GenericArgs)) +let cuspecRepr = + UnionReprDecisions( + (fun (cuspec: IlxUnionSpec) -> cuspec.AlternativesArray), + (fun (cuspec: IlxUnionSpec) -> cuspec.IsNullPermitted), + (fun (alt: IlxUnionCase) -> alt.IsNullary), + (fun cuspec -> cuspec.HasHelpers = IlxUnionHasHelpers.SpecialFSharpListHelpers), + (fun cuspec -> cuspec.Boxity = ILBoxity.AsValue), + (fun (alt: IlxUnionCase) -> alt.Name), + (fun cuspec -> cuspec.DeclaringType), + (fun (cuspec, nm) -> mkILNamedTy cuspec.Boxity (mkILTyRefInTyRef (mkCasesTypeRef cuspec, nm)) cuspec.GenericArgs) + ) type NoTypesGeneratedViaThisReprDecider = NoTypesGeneratedViaThisReprDecider -let cudefRepr = - UnionReprDecisions - ((fun (_td,cud) -> cud.UnionCases), - (fun (_td,cud) -> cud.IsNullPermitted), - (fun (alt:IlxUnionCase) -> alt.IsNullary), - (fun (_td,cud) -> cud.HasHelpers = IlxUnionHasHelpers.SpecialFSharpListHelpers), - (fun (td:ILTypeDef,_cud) -> td.IsStruct), - (fun (alt:IlxUnionCase) -> alt.Name), - (fun (_td,_cud) -> NoTypesGeneratedViaThisReprDecider), - (fun ((_td,_cud),_nm) -> NoTypesGeneratedViaThisReprDecider)) - +let cudefRepr = + UnionReprDecisions( + (fun (_td, cud) -> cud.UnionCases), + (fun (_td, cud) -> cud.IsNullPermitted), + (fun (alt: IlxUnionCase) -> alt.IsNullary), + (fun (_td, cud) -> cud.HasHelpers = IlxUnionHasHelpers.SpecialFSharpListHelpers), + (fun (td: ILTypeDef, _cud) -> td.IsStruct), + (fun (alt: IlxUnionCase) -> alt.Name), + (fun (_td, _cud) -> NoTypesGeneratedViaThisReprDecider), + (fun ((_td, _cud), _nm) -> NoTypesGeneratedViaThisReprDecider) + ) let mkTesterName nm = "Is" + nm let tagPropertyName = "Tag" -let mkUnionCaseFieldId (fdef: IlxUnionCaseField) = +let mkUnionCaseFieldId (fdef: IlxUnionCaseField) = // Use the lower case name of a field or constructor as the field/parameter name if it differs from the uppercase name fdef.LowerName, fdef.Type let refToFieldInTy ty (nm, fldTy) = mkILFieldSpecInTy (ty, nm, fldTy) -let formalTypeArgs (baseTy:ILType) = List.mapi (fun i _ -> mkILTyvarTy (uint16 i)) baseTy.GenericArgs +let formalTypeArgs (baseTy: ILType) = + List.mapi (fun i _ -> mkILTyvarTy (uint16 i)) baseTy.GenericArgs -let constFieldName nm = "_unique_" + nm +let constFieldName nm = "_unique_" + nm -let constFormalFieldTy (baseTy:ILType) = +let constFormalFieldTy (baseTy: ILType) = mkILNamedTy baseTy.Boxity baseTy.TypeRef (formalTypeArgs baseTy) -let mkConstFieldSpecFromId (baseTy:ILType) constFieldId = - refToFieldInTy baseTy constFieldId +let mkConstFieldSpecFromId (baseTy: ILType) constFieldId = refToFieldInTy baseTy constFieldId -let mkConstFieldSpec nm (baseTy:ILType) = - mkConstFieldSpecFromId baseTy (constFieldName nm, constFormalFieldTy baseTy) +let mkConstFieldSpec nm (baseTy: ILType) = + mkConstFieldSpecFromId baseTy (constFieldName nm, constFormalFieldTy baseTy) -let tyForAlt cuspec alt = cuspecRepr.TypeForAlternative(cuspec,alt) +let tyForAlt cuspec alt = + cuspecRepr.TypeForAlternative(cuspec, alt) -let GetILTypeForAlternative cuspec alt = cuspecRepr.TypeForAlternative(cuspec,cuspec.Alternative alt) +let GetILTypeForAlternative cuspec alt = + cuspecRepr.TypeForAlternative(cuspec, cuspec.Alternative alt) let mkTagFieldType (ilg: ILGlobals) _cuspec = ilg.typ_Int32 @@ -218,93 +237,105 @@ let mkTagFieldId ilg cuspec = "_tag", mkTagFieldType ilg cuspec let mkTailOrNullId baseTy = "tail", constFormalFieldTy baseTy -let altOfUnionSpec (cuspec:IlxUnionSpec) cidx = - try cuspec.Alternative cidx - with _ -> failwith ("alternative " + string cidx + " not found") +let altOfUnionSpec (cuspec: IlxUnionSpec) cidx = + try + cuspec.Alternative cidx + with _ -> + failwith ("alternative " + string cidx + " not found") -// Nullary cases on types with helpers do not reveal their underlying type even when -// using runtime type discrimination, because the underlying type is never needed from -// C# code and pollutes the visible API surface. In this case we must discriminate by -// calling the IsFoo helper. This only applies to discriminations outside the +// Nullary cases on types with helpers do not reveal their underlying type even when +// using runtime type discrimination, because the underlying type is never needed from +// C# code and pollutes the visible API surface. In this case we must discriminate by +// calling the IsFoo helper. This only applies to discriminations outside the // assembly where the type is defined (indicated by 'avoidHelpers' flag - if this is true // then the reference is intra-assembly). -let doesRuntimeTypeDiscriminateUseHelper avoidHelpers (cuspec: IlxUnionSpec) (alt: IlxUnionCase) = - not avoidHelpers && alt.IsNullary && cuspec.HasHelpers = IlxUnionHasHelpers.AllHelpers +let doesRuntimeTypeDiscriminateUseHelper avoidHelpers (cuspec: IlxUnionSpec) (alt: IlxUnionCase) = + not avoidHelpers + && alt.IsNullary + && cuspec.HasHelpers = IlxUnionHasHelpers.AllHelpers -let mkRuntimeTypeDiscriminate (ilg: ILGlobals) avoidHelpers cuspec alt altName altTy = +let mkRuntimeTypeDiscriminate (ilg: ILGlobals) avoidHelpers cuspec alt altName altTy = let useHelper = doesRuntimeTypeDiscriminateUseHelper avoidHelpers cuspec alt - if useHelper then + + if useHelper then let baseTy = baseTyOfUnionSpec cuspec - [ mkNormalCall (mkILNonGenericInstanceMethSpecInTy (baseTy, "get_" + mkTesterName altName, [], ilg.typ_Bool)) ] + + [ + mkNormalCall (mkILNonGenericInstanceMethSpecInTy (baseTy, "get_" + mkTesterName altName, [], ilg.typ_Bool)) + ] else [ I_isinst altTy; AI_ldnull; AI_cgt_un ] -let mkRuntimeTypeDiscriminateThen ilg avoidHelpers cuspec alt altName altTy after = +let mkRuntimeTypeDiscriminateThen ilg avoidHelpers cuspec alt altName altTy after = let useHelper = doesRuntimeTypeDiscriminateUseHelper avoidHelpers cuspec alt - match after with - | I_brcmp (BI_brfalse,_) - | I_brcmp (BI_brtrue,_) when not useHelper -> - [ I_isinst altTy; after ] - | _ -> - mkRuntimeTypeDiscriminate ilg avoidHelpers cuspec alt altName altTy @ [ after ] - -let mkGetTagFromField ilg cuspec baseTy = + + match after with + | I_brcmp (BI_brfalse, _) + | I_brcmp (BI_brtrue, _) when not useHelper -> [ I_isinst altTy; after ] + | _ -> mkRuntimeTypeDiscriminate ilg avoidHelpers cuspec alt altName altTy @ [ after ] + +let mkGetTagFromField ilg cuspec baseTy = mkNormalLdfld (refToFieldInTy baseTy (mkTagFieldId ilg cuspec)) -let adjustFieldName hasHelpers nm = - match hasHelpers, nm with - | SpecialFSharpListHelpers, "Head" -> "HeadOrDefault" - | SpecialFSharpListHelpers, "Tail" -> "TailOrNull" +let adjustFieldName hasHelpers nm = + match hasHelpers, nm with + | SpecialFSharpListHelpers, "Head" -> "HeadOrDefault" + | SpecialFSharpListHelpers, "Tail" -> "TailOrNull" | _ -> nm -let mkLdData (avoidHelpers, cuspec, cidx, fidx) = +let mkLdData (avoidHelpers, cuspec, cidx, fidx) = let alt = altOfUnionSpec cuspec cidx let altTy = tyForAlt cuspec alt let fieldDef = alt.FieldDef fidx - if avoidHelpers then + + if avoidHelpers then mkNormalLdfld (mkILFieldSpecInTy (altTy, fieldDef.LowerName, fieldDef.Type)) else - mkNormalCall (mkILNonGenericInstanceMethSpecInTy (altTy, "get_" + adjustFieldName cuspec.HasHelpers fieldDef.Name, [], fieldDef.Type)) + mkNormalCall ( + mkILNonGenericInstanceMethSpecInTy (altTy, "get_" + adjustFieldName cuspec.HasHelpers fieldDef.Name, [], fieldDef.Type) + ) -let mkLdDataAddr (avoidHelpers, cuspec, cidx, fidx) = +let mkLdDataAddr (avoidHelpers, cuspec, cidx, fidx) = let alt = altOfUnionSpec cuspec cidx let altTy = tyForAlt cuspec alt let fieldDef = alt.FieldDef fidx - if avoidHelpers then - mkNormalLdflda (mkILFieldSpecInTy(altTy,fieldDef.LowerName, fieldDef.Type)) + + if avoidHelpers then + mkNormalLdflda (mkILFieldSpecInTy (altTy, fieldDef.LowerName, fieldDef.Type)) else failwith (sprintf "can't load address using helpers, for fieldDef %s" fieldDef.LowerName) -let mkGetTailOrNull avoidHelpers cuspec = +let mkGetTailOrNull avoidHelpers cuspec = mkLdData (avoidHelpers, cuspec, 1, 1) (* tail is in alternative 1, field number 1 *) - -let mkGetTagFromHelpers ilg (cuspec: IlxUnionSpec) = + +let mkGetTagFromHelpers ilg (cuspec: IlxUnionSpec) = let baseTy = baseTyOfUnionSpec cuspec + if cuspecRepr.RepresentOneAlternativeAsNull cuspec then - mkNormalCall (mkILNonGenericStaticMethSpecInTy (baseTy, "Get" + tagPropertyName, [baseTy], mkTagFieldFormalType ilg cuspec)) + mkNormalCall (mkILNonGenericStaticMethSpecInTy (baseTy, "Get" + tagPropertyName, [ baseTy ], mkTagFieldFormalType ilg cuspec)) else - mkNormalCall (mkILNonGenericInstanceMethSpecInTy(baseTy, "get_" + tagPropertyName, [], mkTagFieldFormalType ilg cuspec)) + mkNormalCall (mkILNonGenericInstanceMethSpecInTy (baseTy, "get_" + tagPropertyName, [], mkTagFieldFormalType ilg cuspec)) -let mkGetTag ilg (cuspec: IlxUnionSpec) = +let mkGetTag ilg (cuspec: IlxUnionSpec) = match cuspec.HasHelpers with | AllHelpers -> mkGetTagFromHelpers ilg cuspec | _hasHelpers -> mkGetTagFromField ilg cuspec (baseTyOfUnionSpec cuspec) -let mkCeqThen after = - match after with - | I_brcmp (BI_brfalse,a) -> [I_brcmp (BI_bne_un,a)] - | I_brcmp (BI_brtrue,a) -> [I_brcmp (BI_beq,a)] - | _ -> [AI_ceq; after] +let mkCeqThen after = + match after with + | I_brcmp (BI_brfalse, a) -> [ I_brcmp(BI_bne_un, a) ] + | I_brcmp (BI_brtrue, a) -> [ I_brcmp(BI_beq, a) ] + | _ -> [ AI_ceq; after ] -let mkTagDiscriminate ilg cuspec _baseTy cidx = +let mkTagDiscriminate ilg cuspec _baseTy cidx = [ mkGetTag ilg cuspec; mkLdcInt32 cidx; AI_ceq ] -let mkTagDiscriminateThen ilg cuspec cidx after = +let mkTagDiscriminateThen ilg cuspec cidx after = [ mkGetTag ilg cuspec; mkLdcInt32 cidx ] @ mkCeqThen after /// The compilation for struct unions relies on generating a set of constructors. /// If necessary some fake types are added to the constructor parameters to distinguish the signature. -let rec extraTysAndInstrsForStructCtor (ilg: ILGlobals) cidx = +let rec extraTysAndInstrsForStructCtor (ilg: ILGlobals) cidx = match cidx with | 0 -> [ ilg.typ_Bool ], [ mkLdcInt32 0 ] | 1 -> [ ilg.typ_Byte ], [ mkLdcInt32 0 ] @@ -313,52 +344,66 @@ let rec extraTysAndInstrsForStructCtor (ilg: ILGlobals) cidx = | 4 -> [ ilg.typ_Int16 ], [ mkLdcInt32 0 ] | 5 -> [ ilg.typ_Int32 ], [ mkLdcInt32 0 ] | 6 -> [ ilg.typ_UInt16 ], [ mkLdcInt32 0 ] - | _ -> + | _ -> let tys, instrs = extraTysAndInstrsForStructCtor ilg (cidx - 7) (ilg.typ_UInt32 :: tys, mkLdcInt32 0 :: instrs) -let takesExtraParams (alts: IlxUnionCase[]) = - alts.Length > 1 && - (alts |> Array.exists (fun d -> d.FieldDefs.Length > 0) || - // Check if not all lengths are distinct - alts |> Array.countBy (fun d -> d.FieldDefs.Length) |> Array.length <> alts.Length) +let takesExtraParams (alts: IlxUnionCase[]) = + alts.Length > 1 + && (alts |> Array.exists (fun d -> d.FieldDefs.Length > 0) + || + // Check if not all lengths are distinct + alts |> Array.countBy (fun d -> d.FieldDefs.Length) |> Array.length + <> alts.Length) -let convNewDataInstrInternal ilg cuspec cidx = +let convNewDataInstrInternal ilg cuspec cidx = let alt = altOfUnionSpec cuspec cidx let altTy = tyForAlt cuspec alt let altName = alt.Name - if cuspecRepr.RepresentAlternativeAsNull (cuspec,alt) then - [ AI_ldnull ] - elif cuspecRepr.MaintainPossiblyUniqueConstantFieldForAlternative (cuspec,alt) then + if cuspecRepr.RepresentAlternativeAsNull(cuspec, alt) then + [ AI_ldnull ] + elif cuspecRepr.MaintainPossiblyUniqueConstantFieldForAlternative(cuspec, alt) then let baseTy = baseTyOfUnionSpec cuspec - [ I_ldsfld (Nonvolatile,mkConstFieldSpec altName baseTy) ] - elif cuspecRepr.RepresentAlternativeAsFreshInstancesOfRootClass (cuspec,alt) then + [ I_ldsfld(Nonvolatile, mkConstFieldSpec altName baseTy) ] + elif cuspecRepr.RepresentAlternativeAsFreshInstancesOfRootClass(cuspec, alt) then let baseTy = baseTyOfUnionSpec cuspec - let instrs, tagfields = + + let instrs, tagfields = match cuspecRepr.DiscriminationTechnique cuspec with - | IntegerTag -> [ mkLdcInt32 cidx ], [mkTagFieldType ilg cuspec] + | IntegerTag -> [ mkLdcInt32 cidx ], [ mkTagFieldType ilg cuspec ] | _ -> [], [] + let ctorFieldTys = alt.FieldTypes |> Array.toList - instrs @ [ mkNormalNewobj(mkILCtorMethSpecForTy (baseTy,(ctorFieldTys @ tagfields))) ] - elif cuspecRepr.RepresentAlternativeAsStructValue cuspec then + + instrs + @ [ mkNormalNewobj (mkILCtorMethSpecForTy (baseTy, (ctorFieldTys @ tagfields))) ] + elif cuspecRepr.RepresentAlternativeAsStructValue cuspec then let baseTy = baseTyOfUnionSpec cuspec - let instrs, tagfields = + + let instrs, tagfields = match cuspecRepr.DiscriminationTechnique cuspec with - | IntegerTag -> [ mkLdcInt32 cidx ], [mkTagFieldType ilg cuspec] + | IntegerTag -> [ mkLdcInt32 cidx ], [ mkTagFieldType ilg cuspec ] | _ -> [], [] + let ctorFieldTys = alt.FieldTypes |> Array.toList - let extraTys, extraInstrs = + + let extraTys, extraInstrs = if takesExtraParams cuspec.AlternativesArray then extraTysAndInstrsForStructCtor ilg cidx - else + else [], [] - instrs @ extraInstrs @ [ mkNormalNewobj (mkILCtorMethSpecForTy (baseTy, (ctorFieldTys @ tagfields @ extraTys))) ] - else - [ mkNormalNewobj(mkILCtorMethSpecForTy (altTy,Array.toList alt.FieldTypes)) ] + + instrs + @ extraInstrs + @ [ + mkNormalNewobj (mkILCtorMethSpecForTy (baseTy, (ctorFieldTys @ tagfields @ extraTys))) + ] + else + [ mkNormalNewobj (mkILCtorMethSpecForTy (altTy, Array.toList alt.FieldTypes)) ] // The stdata 'instruction' is only ever used for the F# "List" type within FSharp.Core.dll -let mkStData (cuspec, cidx, fidx) = +let mkStData (cuspec, cidx, fidx) = let alt = altOfUnionSpec cuspec cidx let altTy = tyForAlt cuspec alt let fieldDef = alt.FieldDef fidx @@ -370,742 +415,1053 @@ let mkNewData ilg (cuspec, cidx) = let baseTy = baseTyOfUnionSpec cuspec // If helpers exist, use them match cuspec.HasHelpers with - | AllHelpers - | SpecialFSharpListHelpers - | SpecialFSharpOptionHelpers -> - if cuspecRepr.RepresentAlternativeAsNull (cuspec,alt) then - [ AI_ldnull ] - elif alt.IsNullary then - [ mkNormalCall (mkILNonGenericStaticMethSpecInTy (baseTy, "get_" + altName, [], constFormalFieldTy baseTy)) ] + | AllHelpers + | SpecialFSharpListHelpers + | SpecialFSharpOptionHelpers -> + if cuspecRepr.RepresentAlternativeAsNull(cuspec, alt) then + [ AI_ldnull ] + elif alt.IsNullary then + [ + mkNormalCall (mkILNonGenericStaticMethSpecInTy (baseTy, "get_" + altName, [], constFormalFieldTy baseTy)) + ] else - [ mkNormalCall (mkILNonGenericStaticMethSpecInTy (baseTy, mkMakerName cuspec altName, Array.toList alt.FieldTypes, constFormalFieldTy baseTy)) ] - - | NoHelpers -> - if cuspecRepr.MaintainPossiblyUniqueConstantFieldForAlternative (cuspec,alt) then + [ + mkNormalCall ( + mkILNonGenericStaticMethSpecInTy ( + baseTy, + mkMakerName cuspec altName, + Array.toList alt.FieldTypes, + constFormalFieldTy baseTy + ) + ) + ] + + | NoHelpers -> + if cuspecRepr.MaintainPossiblyUniqueConstantFieldForAlternative(cuspec, alt) then // This method is only available if not AllHelpers. It fetches the unique object for the alternative // without exposing direct access to the underlying field - [ mkNormalCall (mkILNonGenericStaticMethSpecInTy(baseTy, "get_" + altName, [], constFormalFieldTy baseTy)) ] + [ + mkNormalCall (mkILNonGenericStaticMethSpecInTy (baseTy, "get_" + altName, [], constFormalFieldTy baseTy)) + ] else - convNewDataInstrInternal ilg cuspec cidx + convNewDataInstrInternal ilg cuspec cidx -let mkIsData ilg (avoidHelpers, cuspec, cidx) = +let mkIsData ilg (avoidHelpers, cuspec, cidx) = let alt = altOfUnionSpec cuspec cidx let altTy = tyForAlt cuspec alt let altName = alt.Name - if cuspecRepr.RepresentAlternativeAsNull (cuspec,alt) then - [ AI_ldnull; AI_ceq ] - elif cuspecRepr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull (cuspec,alt) then + + if cuspecRepr.RepresentAlternativeAsNull(cuspec, alt) then + [ AI_ldnull; AI_ceq ] + elif cuspecRepr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull(cuspec, alt) then // in this case we can use a null test - [ AI_ldnull; AI_cgt_un ] - else - match cuspecRepr.DiscriminationTechnique cuspec with - | SingleCase -> [ mkLdcInt32 1 ] - | RuntimeTypes -> mkRuntimeTypeDiscriminate ilg avoidHelpers cuspec alt altName altTy + [ AI_ldnull; AI_cgt_un ] + else + match cuspecRepr.DiscriminationTechnique cuspec with + | SingleCase -> [ mkLdcInt32 1 ] + | RuntimeTypes -> mkRuntimeTypeDiscriminate ilg avoidHelpers cuspec alt altName altTy | IntegerTag -> mkTagDiscriminate ilg cuspec (baseTyOfUnionSpec cuspec) cidx - | TailOrNull -> - match cidx with + | TailOrNull -> + match cidx with | TagNil -> [ mkGetTailOrNull avoidHelpers cuspec; AI_ldnull; AI_ceq ] | TagCons -> [ mkGetTailOrNull avoidHelpers cuspec; AI_ldnull; AI_cgt_un ] | _ -> failwith "mkIsData - unexpected" -type ICodeGen<'Mark> = +type ICodeGen<'Mark> = abstract CodeLabel: 'Mark -> ILCodeLabel abstract GenerateDelayMark: unit -> 'Mark abstract GenLocal: ILType -> uint16 - abstract SetMarkToHere: 'Mark -> unit + abstract SetMarkToHere: 'Mark -> unit abstract EmitInstr: ILInstr -> unit abstract EmitInstrs: ILInstr list -> unit abstract MkInvalidCastExnNewobj: unit -> ILInstr -let genWith g : ILCode = - let instrs = ResizeArray() - let lab2pc = Dictionary() - g { new ICodeGen with +let genWith g : ILCode = + let instrs = ResizeArray() + let lab2pc = Dictionary() + + g + { new ICodeGen with member _.CodeLabel(m) = m - member _.GenerateDelayMark() = generateCodeLabel() + member _.GenerateDelayMark() = generateCodeLabel () member _.GenLocal(ilTy) = failwith "not needed" member _.SetMarkToHere(m) = lab2pc[m] <- instrs.Count member _.EmitInstr x = instrs.Add x - member cg.EmitInstrs xs = for i in xs do cg.EmitInstr i - member _.MkInvalidCastExnNewobj () = failwith "not needed" } - { Labels = lab2pc - Instrs = instrs.ToArray() - Exceptions = [] - Locals = [] } + member cg.EmitInstrs xs = + for i in xs do + cg.EmitInstr i -let mkBrIsData ilg sense (avoidHelpers, cuspec,cidx,tg) = + member _.MkInvalidCastExnNewobj() = failwith "not needed" + } + + { + Labels = lab2pc + Instrs = instrs.ToArray() + Exceptions = [] + Locals = [] + } + +let mkBrIsData ilg sense (avoidHelpers, cuspec, cidx, tg) = let neg = (if sense then BI_brfalse else BI_brtrue) let pos = (if sense then BI_brtrue else BI_brfalse) let alt = altOfUnionSpec cuspec cidx let altTy = tyForAlt cuspec alt let altName = alt.Name - if cuspecRepr.RepresentAlternativeAsNull (cuspec,alt) then - [ I_brcmp (neg,tg) ] - elif cuspecRepr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull (cuspec,alt) then + + if cuspecRepr.RepresentAlternativeAsNull(cuspec, alt) then + [ I_brcmp(neg, tg) ] + elif cuspecRepr.RepresentSingleNonNullaryAlternativeAsInstancesOfRootClassAndAnyOtherAlternativesAsNull(cuspec, alt) then // in this case we can use a null test - [ I_brcmp (pos,tg) ] + [ I_brcmp(pos, tg) ] else - match cuspecRepr.DiscriminationTechnique cuspec with - | SingleCase -> [ ] - | RuntimeTypes -> mkRuntimeTypeDiscriminateThen ilg avoidHelpers cuspec alt altName altTy (I_brcmp (pos,tg)) - | IntegerTag -> mkTagDiscriminateThen ilg cuspec cidx (I_brcmp (pos,tg)) - | TailOrNull -> - match cidx with - | TagNil -> [ mkGetTailOrNull avoidHelpers cuspec; I_brcmp (neg,tg) ] - | TagCons -> [ mkGetTailOrNull avoidHelpers cuspec; I_brcmp (pos,tg) ] + match cuspecRepr.DiscriminationTechnique cuspec with + | SingleCase -> [] + | RuntimeTypes -> mkRuntimeTypeDiscriminateThen ilg avoidHelpers cuspec alt altName altTy (I_brcmp(pos, tg)) + | IntegerTag -> mkTagDiscriminateThen ilg cuspec cidx (I_brcmp(pos, tg)) + | TailOrNull -> + match cidx with + | TagNil -> [ mkGetTailOrNull avoidHelpers cuspec; I_brcmp(neg, tg) ] + | TagCons -> [ mkGetTailOrNull avoidHelpers cuspec; I_brcmp(pos, tg) ] | _ -> failwith "mkBrIsData - unexpected" - -let emitLdDataTagPrim ilg ldOpt (cg: ICodeGen<'Mark>) (avoidHelpers,cuspec: IlxUnionSpec) = - // If helpers exist, use them +let emitLdDataTagPrim ilg ldOpt (cg: ICodeGen<'Mark>) (avoidHelpers, cuspec: IlxUnionSpec) = + // If helpers exist, use them match cuspec.HasHelpers with - | SpecialFSharpListHelpers | AllHelpers when not avoidHelpers -> - ldOpt |> Option.iter cg.EmitInstr - cg.EmitInstr (mkGetTagFromHelpers ilg cuspec) - | _ -> - + | SpecialFSharpListHelpers + | AllHelpers when not avoidHelpers -> + ldOpt |> Option.iter cg.EmitInstr + cg.EmitInstr(mkGetTagFromHelpers ilg cuspec) + | _ -> + let alts = cuspec.Alternatives + match cuspecRepr.DiscriminationTechnique cuspec with | TailOrNull -> // leaves 1 if cons, 0 if not - ldOpt |> Option.iter cg.EmitInstr + ldOpt |> Option.iter cg.EmitInstr cg.EmitInstrs [ mkGetTailOrNull avoidHelpers cuspec; AI_ldnull; AI_cgt_un ] - | IntegerTag -> + | IntegerTag -> let baseTy = baseTyOfUnionSpec cuspec - ldOpt |> Option.iter cg.EmitInstr - cg.EmitInstr (mkGetTagFromField ilg cuspec baseTy) - | SingleCase -> - ldOpt |> Option.iter cg.EmitInstr - cg.EmitInstrs [ AI_pop; mkLdcInt32 0 ] - | RuntimeTypes -> + ldOpt |> Option.iter cg.EmitInstr + cg.EmitInstr(mkGetTagFromField ilg cuspec baseTy) + | SingleCase -> + ldOpt |> Option.iter cg.EmitInstr + cg.EmitInstrs [ AI_pop; mkLdcInt32 0 ] + | RuntimeTypes -> let baseTy = baseTyOfUnionSpec cuspec - let ld = - match ldOpt with - | None -> - let locn = cg.GenLocal baseTy - // Add on a branch to the first input label. This gets optimized away by the printer/emitter. - cg.EmitInstr (mkStloc locn) - mkLdloc locn + + let ld = + match ldOpt with + | None -> + let locn = cg.GenLocal baseTy + // Add on a branch to the first input label. This gets optimized away by the printer/emitter. + cg.EmitInstr(mkStloc locn) + mkLdloc locn | Some i -> i let outlab = cg.GenerateDelayMark() - let emitCase cidx = + let emitCase cidx = let alt = altOfUnionSpec cuspec cidx let internalLab = cg.GenerateDelayMark() - let failLab = cg.GenerateDelayMark () - let cmpNull = cuspecRepr.RepresentAlternativeAsNull (cuspec, alt) - let test = I_brcmp ((if cmpNull then BI_brtrue else BI_brfalse),cg.CodeLabel failLab) - let testBlock = - if cmpNull || cuspecRepr.RepresentAlternativeAsFreshInstancesOfRootClass (cuspec,alt) then + let failLab = cg.GenerateDelayMark() + let cmpNull = cuspecRepr.RepresentAlternativeAsNull(cuspec, alt) + + let test = + I_brcmp((if cmpNull then BI_brtrue else BI_brfalse), cg.CodeLabel failLab) + + let testBlock = + if + cmpNull + || cuspecRepr.RepresentAlternativeAsFreshInstancesOfRootClass(cuspec, alt) + then [ test ] else let altName = alt.Name let altTy = tyForAlt cuspec alt mkRuntimeTypeDiscriminateThen ilg avoidHelpers cuspec alt altName altTy test - cg.EmitInstrs (ld :: testBlock) + + cg.EmitInstrs(ld :: testBlock) cg.SetMarkToHere internalLab - cg.EmitInstrs [mkLdcInt32 cidx; I_br (cg.CodeLabel outlab) ] + cg.EmitInstrs [ mkLdcInt32 cidx; I_br(cg.CodeLabel outlab) ] cg.SetMarkToHere failLab - // Make the blocks for the remaining tests. - for n in alts.Length-1 .. -1 .. 1 do - emitCase n + // Make the blocks for the remaining tests. + for n in alts.Length - 1 .. -1 .. 1 do + emitCase n - // Make the block for the last test. - cg.EmitInstr (mkLdcInt32 0) + // Make the block for the last test. + cg.EmitInstr(mkLdcInt32 0) cg.SetMarkToHere outlab -let emitLdDataTag ilg (cg: ICodeGen<'Mark>) (avoidHelpers,cuspec: IlxUnionSpec) = - emitLdDataTagPrim ilg None cg (avoidHelpers,cuspec) +let emitLdDataTag ilg (cg: ICodeGen<'Mark>) (avoidHelpers, cuspec: IlxUnionSpec) = + emitLdDataTagPrim ilg None cg (avoidHelpers, cuspec) -let emitCastData ilg (cg: ICodeGen<'Mark>) (canfail, avoidHelpers, cuspec, cidx) = +let emitCastData ilg (cg: ICodeGen<'Mark>) (canfail, avoidHelpers, cuspec, cidx) = let alt = altOfUnionSpec cuspec cidx - if cuspecRepr.RepresentAlternativeAsNull (cuspec,alt) then - if canfail then - let outlab = cg.GenerateDelayMark () - let internal1 = cg.GenerateDelayMark () - cg.EmitInstrs [AI_dup; I_brcmp (BI_brfalse, cg.CodeLabel outlab) ] + + if cuspecRepr.RepresentAlternativeAsNull(cuspec, alt) then + if canfail then + let outlab = cg.GenerateDelayMark() + let internal1 = cg.GenerateDelayMark() + cg.EmitInstrs [ AI_dup; I_brcmp(BI_brfalse, cg.CodeLabel outlab) ] cg.SetMarkToHere internal1 - cg.EmitInstrs [cg.MkInvalidCastExnNewobj (); I_throw ] + cg.EmitInstrs [ cg.MkInvalidCastExnNewobj(); I_throw ] cg.SetMarkToHere outlab else - // If it can't fail, it's still verifiable just to leave the value on the stack unchecked + // If it can't fail, it's still verifiable just to leave the value on the stack unchecked () elif cuspecRepr.Flatten cuspec then if canfail then - let outlab = cg.GenerateDelayMark () - let internal1 = cg.GenerateDelayMark () + let outlab = cg.GenerateDelayMark() + let internal1 = cg.GenerateDelayMark() cg.EmitInstr AI_dup - emitLdDataTagPrim ilg None cg (avoidHelpers,cuspec) - cg.EmitInstrs [ mkLdcInt32 cidx; I_brcmp (BI_beq, cg.CodeLabel outlab) ] + emitLdDataTagPrim ilg None cg (avoidHelpers, cuspec) + cg.EmitInstrs [ mkLdcInt32 cidx; I_brcmp(BI_beq, cg.CodeLabel outlab) ] cg.SetMarkToHere internal1 - cg.EmitInstrs [cg.MkInvalidCastExnNewobj (); I_throw ] + cg.EmitInstrs [ cg.MkInvalidCastExnNewobj(); I_throw ] cg.SetMarkToHere outlab else - // If it can't fail, it's still verifiable just to leave the value on the stack unchecked + // If it can't fail, it's still verifiable just to leave the value on the stack unchecked () - elif cuspecRepr.OptimizeAlternativeToRootClass (cuspec,alt) then + elif cuspecRepr.OptimizeAlternativeToRootClass(cuspec, alt) then () - else + else let altTy = tyForAlt cuspec alt - cg.EmitInstr (I_castclass altTy) - + cg.EmitInstr(I_castclass altTy) + let emitDataSwitch ilg (cg: ICodeGen<'Mark>) (avoidHelpers, cuspec, cases) = let baseTy = baseTyOfUnionSpec cuspec - - match cuspecRepr.DiscriminationTechnique cuspec with - | RuntimeTypes -> - let locn = cg.GenLocal baseTy - cg.EmitInstr (mkStloc locn) + match cuspecRepr.DiscriminationTechnique cuspec with + | RuntimeTypes -> + let locn = cg.GenLocal baseTy - for cidx,tg in cases do + cg.EmitInstr(mkStloc locn) + + for cidx, tg in cases do let alt = altOfUnionSpec cuspec cidx let altTy = tyForAlt cuspec alt let altName = alt.Name - let failLab = cg.GenerateDelayMark () - let cmpNull = cuspecRepr.RepresentAlternativeAsNull (cuspec,alt) - - cg.EmitInstr (mkLdloc locn) - let testInstr = I_brcmp ((if cmpNull then BI_brfalse else BI_brtrue),tg) - if cmpNull || cuspecRepr.RepresentAlternativeAsFreshInstancesOfRootClass (cuspec,alt) then - cg.EmitInstr testInstr - else - cg.EmitInstrs (mkRuntimeTypeDiscriminateThen ilg avoidHelpers cuspec alt altName altTy testInstr) + let failLab = cg.GenerateDelayMark() + let cmpNull = cuspecRepr.RepresentAlternativeAsNull(cuspec, alt) + + cg.EmitInstr(mkLdloc locn) + let testInstr = I_brcmp((if cmpNull then BI_brfalse else BI_brtrue), tg) + + if + cmpNull + || cuspecRepr.RepresentAlternativeAsFreshInstancesOfRootClass(cuspec, alt) + then + cg.EmitInstr testInstr + else + cg.EmitInstrs(mkRuntimeTypeDiscriminateThen ilg avoidHelpers cuspec alt altName altTy testInstr) + cg.SetMarkToHere failLab - - | IntegerTag -> - match cases with + | IntegerTag -> + match cases with | [] -> cg.EmitInstr AI_pop | _ -> - // Use a dictionary to avoid quadratic lookup in case list - let dict = Dictionary() - for i,case in cases do dict[i] <- case - let failLab = cg.GenerateDelayMark () - let emitCase i _ = - match dict.TryGetValue i with - | true, res -> res - | _ -> cg.CodeLabel failLab - - let dests = Array.mapi emitCase cuspec.AlternativesArray - cg.EmitInstr (mkGetTag ilg cuspec) - cg.EmitInstr (I_switch (Array.toList dests)) - cg.SetMarkToHere failLab + // Use a dictionary to avoid quadratic lookup in case list + let dict = Dictionary() + + for i, case in cases do + dict[i] <- case + + let failLab = cg.GenerateDelayMark() + + let emitCase i _ = + match dict.TryGetValue i with + | true, res -> res + | _ -> cg.CodeLabel failLab + + let dests = Array.mapi emitCase cuspec.AlternativesArray + cg.EmitInstr(mkGetTag ilg cuspec) + cg.EmitInstr(I_switch(Array.toList dests)) + cg.SetMarkToHere failLab | SingleCase -> - match cases with - | [(0,tg)] -> cg.EmitInstrs [ AI_pop; I_br tg ] + match cases with + | [ (0, tg) ] -> cg.EmitInstrs [ AI_pop; I_br tg ] | [] -> cg.EmitInstr AI_pop | _ -> failwith "unexpected: strange switch on single-case unions should not be present" - | TailOrNull -> - failwith "unexpected: switches on lists should have been eliminated to brisdata tests" - + | TailOrNull -> failwith "unexpected: switches on lists should have been eliminated to brisdata tests" + //--------------------------------------------------- // Generate the union classes -let mkMethodsAndPropertiesForFields (addMethodGeneratedAttrs, addPropertyGeneratedAttrs) access attr imports hasHelpers (ilTy: ILType) (fields: IlxUnionCaseField[]) = - let basicProps = - fields - |> Array.map (fun field -> - ILPropertyDef(name = adjustFieldName hasHelpers field.Name, - attributes = PropertyAttributes.None, - setMethod = None, - getMethod = Some (mkILMethRef (ilTy.TypeRef, ILCallingConv.Instance, "get_" + adjustFieldName hasHelpers field.Name, 0, [], field.Type)), - callingConv = ILThisConvention.Instance, - propertyType = field.Type, - init = None, - args = [], - customAttrs = field.ILField.CustomAttrs) - |> addPropertyGeneratedAttrs - ) +let mkMethodsAndPropertiesForFields + (addMethodGeneratedAttrs, addPropertyGeneratedAttrs) + access + attr + imports + hasHelpers + (ilTy: ILType) + (fields: IlxUnionCaseField[]) + = + let basicProps = + fields + |> Array.map (fun field -> + ILPropertyDef( + name = adjustFieldName hasHelpers field.Name, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = + Some( + mkILMethRef ( + ilTy.TypeRef, + ILCallingConv.Instance, + "get_" + adjustFieldName hasHelpers field.Name, + 0, + [], + field.Type + ) + ), + callingConv = ILThisConvention.Instance, + propertyType = field.Type, + init = None, + args = [], + customAttrs = field.ILField.CustomAttrs + ) + |> addPropertyGeneratedAttrs) |> Array.toList - let basicMethods = - [ for field in fields do - let fspec = mkILFieldSpecInTy(ilTy,field.LowerName,field.Type) - yield - mkILNonGenericInstanceMethod - ("get_" + adjustFieldName hasHelpers field.Name, - access, [], mkILReturn field.Type, - mkMethodBody(true,[],2,nonBranchingInstrsToCode [ mkLdarg 0us; mkNormalLdfld fspec ], attr, imports)) - |> addMethodGeneratedAttrs ] - + let basicMethods = + [ + for field in fields do + let fspec = mkILFieldSpecInTy (ilTy, field.LowerName, field.Type) + + yield + mkILNonGenericInstanceMethod ( + "get_" + adjustFieldName hasHelpers field.Name, + access, + [], + mkILReturn field.Type, + mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkLdarg 0us; mkNormalLdfld fspec ], attr, imports) + ) + |> addMethodGeneratedAttrs + ] + basicProps, basicMethods -let convAlternativeDef - (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addPropertyNeverAttrs, addFieldGeneratedAttrs, addFieldNeverAttrs, mkDebuggerTypeProxyAttribute) - (ilg: ILGlobals) num (td:ILTypeDef) (cud : IlxUnionInfo) info cuspec (baseTy:ILType) (alt:IlxUnionCase) = +let convAlternativeDef + (addMethodGeneratedAttrs, + addPropertyGeneratedAttrs, + addPropertyNeverAttrs, + addFieldGeneratedAttrs, + addFieldNeverAttrs, + mkDebuggerTypeProxyAttribute) + (ilg: ILGlobals) + num + (td: ILTypeDef) + (cud: IlxUnionInfo) + info + cuspec + (baseTy: ILType) + (alt: IlxUnionCase) + = let imports = cud.DebugImports let attr = cud.DebugPoint let altName = alt.Name let fields = alt.FieldDefs let altTy = tyForAlt cuspec alt - let repr = cudefRepr + let repr = cudefRepr // Attributes on unions get attached to the construction methods in the helpers - let addAltAttribs (mdef: ILMethodDef) = mdef.With(customAttrs=alt.altCustomAttrs) + let addAltAttribs (mdef: ILMethodDef) = + mdef.With(customAttrs = alt.altCustomAttrs) // The stdata instruction is only ever used for the F# "List" type // // Microsoft.FSharp.Collections.List`1 is indeed logically immutable, but we use mutation on this type internally // within FSharp.Core.dll on fresh unpublished cons cells. let isTotallyImmutable = (cud.HasHelpers <> SpecialFSharpListHelpers) - - let altUniqObjMeths = - - // This method is only generated if helpers are not available. It fetches the unique object for the alternative - // without exposing direct access to the underlying field - match cud.HasHelpers with - | AllHelpers - | SpecialFSharpOptionHelpers - | SpecialFSharpListHelpers -> [] - | _ -> - if alt.IsNullary && repr.MaintainPossiblyUniqueConstantFieldForAlternative (info,alt) then - let methName = "get_" + altName - let meth = - mkILNonGenericStaticMethod - (methName, - cud.UnionCasesAccessibility,[],mkILReturn(baseTy), - mkMethodBody(true,[],fields.Length, nonBranchingInstrsToCode [ I_ldsfld (Nonvolatile,mkConstFieldSpec altName baseTy) ], attr, imports)) - |> addMethodGeneratedAttrs - [meth] - - else - [] - let baseMakerMeths, baseMakerProps = + let altUniqObjMeths = - match cud.HasHelpers with + // This method is only generated if helpers are not available. It fetches the unique object for the alternative + // without exposing direct access to the underlying field + match cud.HasHelpers with | AllHelpers - | SpecialFSharpOptionHelpers - | SpecialFSharpListHelpers -> + | SpecialFSharpOptionHelpers + | SpecialFSharpListHelpers -> [] + | _ -> + if + alt.IsNullary + && repr.MaintainPossiblyUniqueConstantFieldForAlternative(info, alt) + then + let methName = "get_" + altName + + let meth = + mkILNonGenericStaticMethod ( + methName, + cud.UnionCasesAccessibility, + [], + mkILReturn (baseTy), + mkMethodBody ( + true, + [], + fields.Length, + nonBranchingInstrsToCode [ I_ldsfld(Nonvolatile, mkConstFieldSpec altName baseTy) ], + attr, + imports + ) + ) + |> addMethodGeneratedAttrs + + [ meth ] - let baseTesterMeths, baseTesterProps = - if cud.UnionCases.Length <= 1 then [], [] - elif repr.RepresentOneAlternativeAsNull info then [], [] + else + [] + + let baseMakerMeths, baseMakerProps = + + match cud.HasHelpers with + | AllHelpers + | SpecialFSharpOptionHelpers + | SpecialFSharpListHelpers -> + + let baseTesterMeths, baseTesterProps = + if cud.UnionCases.Length <= 1 then + [], [] + elif repr.RepresentOneAlternativeAsNull info then + [], [] else - [ mkILNonGenericInstanceMethod - ("get_" + mkTesterName altName, - cud.HelpersAccessibility,[], - mkILReturn ilg.typ_Bool, - mkMethodBody(true,[],2,nonBranchingInstrsToCode ([ mkLdarg0 ] @ mkIsData ilg (true, cuspec, num)), attr, imports)) - |> addMethodGeneratedAttrs ], - [ ILPropertyDef(name = mkTesterName altName, - attributes = PropertyAttributes.None, - setMethod = None, - getMethod = Some (mkILMethRef (baseTy.TypeRef, ILCallingConv.Instance, "get_" + mkTesterName altName, 0, [], ilg.typ_Bool)), - callingConv = ILThisConvention.Instance, - propertyType = ilg.typ_Bool, - init = None, - args = [], - customAttrs = emptyILCustomAttrs) - |> addPropertyGeneratedAttrs - |> addPropertyNeverAttrs ] - - - - let baseMakerMeths, baseMakerProps = - - if alt.IsNullary then - - let nullaryMeth = - mkILNonGenericStaticMethod - ("get_" + altName, - cud.HelpersAccessibility, [], mkILReturn baseTy, - mkMethodBody(true,[],fields.Length, nonBranchingInstrsToCode (convNewDataInstrInternal ilg cuspec num), attr, imports)) - |> addMethodGeneratedAttrs + [ + mkILNonGenericInstanceMethod ( + "get_" + mkTesterName altName, + cud.HelpersAccessibility, + [], + mkILReturn ilg.typ_Bool, + mkMethodBody ( + true, + [], + 2, + nonBranchingInstrsToCode ([ mkLdarg0 ] @ mkIsData ilg (true, cuspec, num)), + attr, + imports + ) + ) + |> addMethodGeneratedAttrs + ], + [ + ILPropertyDef( + name = mkTesterName altName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = + Some( + mkILMethRef (baseTy.TypeRef, ILCallingConv.Instance, "get_" + mkTesterName altName, 0, [], ilg.typ_Bool) + ), + callingConv = ILThisConvention.Instance, + propertyType = ilg.typ_Bool, + init = None, + args = [], + customAttrs = emptyILCustomAttrs + ) + |> addPropertyGeneratedAttrs + |> addPropertyNeverAttrs + ] + + let baseMakerMeths, baseMakerProps = + + if alt.IsNullary then + + let nullaryMeth = + mkILNonGenericStaticMethod ( + "get_" + altName, + cud.HelpersAccessibility, + [], + mkILReturn baseTy, + mkMethodBody ( + true, + [], + fields.Length, + nonBranchingInstrsToCode (convNewDataInstrInternal ilg cuspec num), + attr, + imports + ) + ) + |> addMethodGeneratedAttrs |> addAltAttribs - let nullaryProp = - - ILPropertyDef(name = altName, - attributes = PropertyAttributes.None, - setMethod = None, - getMethod = Some (mkILMethRef (baseTy.TypeRef, ILCallingConv.Static, "get_" + altName, 0, [], baseTy)), - callingConv = ILThisConvention.Static, - propertyType = baseTy, - init = None, - args = [], - customAttrs = emptyILCustomAttrs) - |> addPropertyGeneratedAttrs + let nullaryProp = + + ILPropertyDef( + name = altName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some(mkILMethRef (baseTy.TypeRef, ILCallingConv.Static, "get_" + altName, 0, [], baseTy)), + callingConv = ILThisConvention.Static, + propertyType = baseTy, + init = None, + args = [], + customAttrs = emptyILCustomAttrs + ) + |> addPropertyGeneratedAttrs |> addPropertyNeverAttrs - [nullaryMeth],[nullaryProp] - + [ nullaryMeth ], [ nullaryProp ] + else let ilInstrs = - [ for i in 0..fields.Length-1 do - mkLdarg (uint16 i) - yield! convNewDataInstrInternal ilg cuspec num ] + [ + for i in 0 .. fields.Length - 1 do + mkLdarg (uint16 i) + yield! convNewDataInstrInternal ilg cuspec num + ] |> nonBranchingInstrsToCode - let mdef = - mkILNonGenericStaticMethod - (mkMakerName cuspec altName, + let mdef = + mkILNonGenericStaticMethod ( + mkMakerName cuspec altName, cud.HelpersAccessibility, - fields |> Array.map (fun fd -> mkILParamNamed (fd.LowerName, fd.Type)) |> Array.toList, + fields + |> Array.map (fun fd -> mkILParamNamed (fd.LowerName, fd.Type)) + |> Array.toList, mkILReturn baseTy, - mkMethodBody(true, [], fields.Length, ilInstrs, attr, imports)) - |> addMethodGeneratedAttrs - |> addAltAttribs + mkMethodBody (true, [], fields.Length, ilInstrs, attr, imports) + ) + |> addMethodGeneratedAttrs + |> addAltAttribs - [mdef],[] + [ mdef ], [] - (baseMakerMeths@baseTesterMeths), (baseMakerProps@baseTesterProps) + (baseMakerMeths @ baseTesterMeths), (baseMakerProps @ baseTesterProps) - | NoHelpers -> - [], [] + | NoHelpers -> [], [] - let typeDefs, altDebugTypeDefs, altNullaryFields = - if repr.RepresentAlternativeAsNull (info,alt) then [], [], [] - elif repr.RepresentAlternativeAsFreshInstancesOfRootClass (info,alt) then [], [], [] - elif repr.RepresentAlternativeAsStructValue info then [], [], [] + let typeDefs, altDebugTypeDefs, altNullaryFields = + if repr.RepresentAlternativeAsNull(info, alt) then + [], [], [] + elif repr.RepresentAlternativeAsFreshInstancesOfRootClass(info, alt) then + [], [], [] + elif repr.RepresentAlternativeAsStructValue info then + [], [], [] else - let altNullaryFields = - if repr.MaintainPossiblyUniqueConstantFieldForAlternative(info,alt) then - let basic : ILFieldDef = - mkILStaticField (constFieldName altName, baseTy, None, None, ILMemberAccess.Assembly) - |> addFieldNeverAttrs - |> addFieldGeneratedAttrs - - let uniqObjField = basic.WithInitOnly(true) - let inRootClass = cuspecRepr.OptimizeAlternativeToRootClass (cuspec,alt) - [ (info,alt, altTy,num,uniqObjField,inRootClass) ] - else - [] - - let typeDefs, altDebugTypeDefs = - if repr.OptimizeAlternativeToRootClass (info,alt) then [], [] else - - let altDebugTypeDefs, debugAttrs = - if not cud.GenerateDebugProxies then [], [] - else - - let debugProxyTypeName = altTy.TypeSpec.Name + "@DebugTypeProxy" - let debugProxyTy = mkILBoxedTy (mkILNestedTyRef(altTy.TypeSpec.Scope,altTy.TypeSpec.Enclosing, debugProxyTypeName)) altTy.GenericArgs - let debugProxyFieldName = "_obj" - - let debugProxyFields = - [ mkILInstanceField (debugProxyFieldName,altTy, None, ILMemberAccess.Assembly) |> addFieldNeverAttrs |> addFieldGeneratedAttrs] - - let debugProxyCode = - [ mkLdarg0 - mkNormalCall (mkILCtorMethSpecForTy (ilg.typ_Object,[])) - mkLdarg0 - mkLdarg 1us - mkNormalStfld (mkILFieldSpecInTy (debugProxyTy,debugProxyFieldName,altTy)) ] - |> nonBranchingInstrsToCode + let altNullaryFields = + if repr.MaintainPossiblyUniqueConstantFieldForAlternative(info, alt) then + let basic: ILFieldDef = + mkILStaticField (constFieldName altName, baseTy, None, None, ILMemberAccess.Assembly) + |> addFieldNeverAttrs + |> addFieldGeneratedAttrs + + let uniqObjField = basic.WithInitOnly(true) + let inRootClass = cuspecRepr.OptimizeAlternativeToRootClass(cuspec, alt) + [ (info, alt, altTy, num, uniqObjField, inRootClass) ] + else + [] - let debugProxyCtor = - mkILCtor(ILMemberAccess.Public (* must always be public - see jared parson blog entry on implementing debugger type proxy *), - [ mkILParamNamed ("obj",altTy) ], - mkMethodBody (false, [], 3, debugProxyCode, None, imports)) - - |> addMethodGeneratedAttrs - - let debugProxyGetterMeths = - fields - |> Array.map (fun field -> - let fldName,fldTy = mkUnionCaseFieldId field - let instrs = - [ mkLdarg0 - (if td.IsStruct then mkNormalLdflda else mkNormalLdfld) (mkILFieldSpecInTy (debugProxyTy,debugProxyFieldName,altTy)) - mkNormalLdfld (mkILFieldSpecInTy(altTy,fldName,fldTy))] + let typeDefs, altDebugTypeDefs = + if repr.OptimizeAlternativeToRootClass(info, alt) then + [], [] + else + + let altDebugTypeDefs, debugAttrs = + if not cud.GenerateDebugProxies then + [], [] + else + + let debugProxyTypeName = altTy.TypeSpec.Name + "@DebugTypeProxy" + + let debugProxyTy = + mkILBoxedTy + (mkILNestedTyRef (altTy.TypeSpec.Scope, altTy.TypeSpec.Enclosing, debugProxyTypeName)) + altTy.GenericArgs + + let debugProxyFieldName = "_obj" + + let debugProxyFields = + [ + mkILInstanceField (debugProxyFieldName, altTy, None, ILMemberAccess.Assembly) + |> addFieldNeverAttrs + |> addFieldGeneratedAttrs + ] + + let debugProxyCode = + [ + mkLdarg0 + mkNormalCall (mkILCtorMethSpecForTy (ilg.typ_Object, [])) + mkLdarg0 + mkLdarg 1us + mkNormalStfld (mkILFieldSpecInTy (debugProxyTy, debugProxyFieldName, altTy)) + ] |> nonBranchingInstrsToCode - let mbody = mkMethodBody(true,[],2, instrs, None, imports) - - mkILNonGenericInstanceMethod ("get_" + field.Name, ILMemberAccess.Public, [], mkILReturn field.Type, mbody) - |> addMethodGeneratedAttrs ) - |> Array.toList - - let debugProxyGetterProps = - fields - |> Array.map (fun fdef -> - ILPropertyDef(name = fdef.Name, - attributes = PropertyAttributes.None, - setMethod = None, - getMethod = Some(mkILMethRef(debugProxyTy.TypeRef,ILCallingConv.Instance,"get_" + fdef.Name,0,[],fdef.Type)), - callingConv = ILThisConvention.Instance, - propertyType = fdef.Type, - init = None, - args = [], - customAttrs = fdef.ILField.CustomAttrs) - |> addPropertyGeneratedAttrs) - |> Array.toList - - let debugProxyTypeDef = - mkILGenericClass (debugProxyTypeName, - ILTypeDefAccess.Nested ILMemberAccess.Assembly, - td.GenericParams, - ilg.typ_Object, [], - mkILMethods ([debugProxyCtor] @ debugProxyGetterMeths), - mkILFields debugProxyFields, - emptyILTypeDefs, - mkILProperties debugProxyGetterProps, - emptyILEvents, - emptyILCustomAttrs, - ILTypeInit.BeforeField) - - [ debugProxyTypeDef.WithSpecialName(true) ], - ( [mkDebuggerTypeProxyAttribute debugProxyTy] @ cud.DebugDisplayAttributes) - - let altTypeDef = - let basicFields = - fields - |> Array.map (fun field -> - let fldName,fldTy = mkUnionCaseFieldId field - let fdef = mkILInstanceField (fldName,fldTy, None, ILMemberAccess.Assembly) |> addFieldNeverAttrs |> addFieldGeneratedAttrs - fdef.WithInitOnly(isTotallyImmutable)) - |> Array.toList - - - let basicProps, basicMethods = mkMethodsAndPropertiesForFields (addMethodGeneratedAttrs, addPropertyGeneratedAttrs) cud.UnionCasesAccessibility attr imports cud.HasHelpers altTy fields - - let basicCtorInstrs = - [ yield mkLdarg0 - match repr.DiscriminationTechnique info with - | IntegerTag -> - yield mkLdcInt32 num - yield mkNormalCall (mkILCtorMethSpecForTy (baseTy,[mkTagFieldType ilg cuspec])) - | SingleCase - | RuntimeTypes -> - yield mkNormalCall (mkILCtorMethSpecForTy (baseTy,[])) - | TailOrNull -> - failwith "unreachable" ] - - let basicCtorAccess = (if cuspec.HasHelpers = AllHelpers then ILMemberAccess.Assembly else cud.UnionCasesAccessibility) - - let basicCtorFields = basicFields |> List.map (fun fdef -> fdef.Name, fdef.FieldType) - - let basicCtorMeth = - mkILStorageCtor (basicCtorInstrs, altTy, basicCtorFields, basicCtorAccess, attr, imports) - |> addMethodGeneratedAttrs - - let altTypeDef = - mkILGenericClass (altTy.TypeSpec.Name, - // Types for nullary's become private, they also have names like _Empty - ILTypeDefAccess.Nested (if alt.IsNullary && cud.HasHelpers = IlxUnionHasHelpers.AllHelpers then ILMemberAccess.Assembly else cud.UnionCasesAccessibility), - td.GenericParams, - baseTy, [], - mkILMethods ([basicCtorMeth] @ basicMethods), - mkILFields basicFields, - emptyILTypeDefs, - mkILProperties basicProps, - emptyILEvents, - mkILCustomAttrs debugAttrs, - ILTypeInit.BeforeField) - - altTypeDef.WithSpecialName(true).WithSerializable(td.IsSerializable) - - [ altTypeDef ], altDebugTypeDefs - - - typeDefs,altDebugTypeDefs,altNullaryFields + let debugProxyCtor = + mkILCtor ( + ILMemberAccess.Public (* must always be public - see jared parson blog entry on implementing debugger type proxy *) , + [ mkILParamNamed ("obj", altTy) ], + mkMethodBody (false, [], 3, debugProxyCode, None, imports) + ) + + |> addMethodGeneratedAttrs + + let debugProxyGetterMeths = + fields + |> Array.map (fun field -> + let fldName, fldTy = mkUnionCaseFieldId field + + let instrs = + [ + mkLdarg0 + (if td.IsStruct then mkNormalLdflda else mkNormalLdfld) + (mkILFieldSpecInTy (debugProxyTy, debugProxyFieldName, altTy)) + mkNormalLdfld (mkILFieldSpecInTy (altTy, fldName, fldTy)) + ] + |> nonBranchingInstrsToCode + + let mbody = mkMethodBody (true, [], 2, instrs, None, imports) + + mkILNonGenericInstanceMethod ( + "get_" + field.Name, + ILMemberAccess.Public, + [], + mkILReturn field.Type, + mbody + ) + |> addMethodGeneratedAttrs) + |> Array.toList + + let debugProxyGetterProps = + fields + |> Array.map (fun fdef -> + ILPropertyDef( + name = fdef.Name, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = + Some( + mkILMethRef ( + debugProxyTy.TypeRef, + ILCallingConv.Instance, + "get_" + fdef.Name, + 0, + [], + fdef.Type + ) + ), + callingConv = ILThisConvention.Instance, + propertyType = fdef.Type, + init = None, + args = [], + customAttrs = fdef.ILField.CustomAttrs + ) + |> addPropertyGeneratedAttrs) + |> Array.toList + + let debugProxyTypeDef = + mkILGenericClass ( + debugProxyTypeName, + ILTypeDefAccess.Nested ILMemberAccess.Assembly, + td.GenericParams, + ilg.typ_Object, + [], + mkILMethods ([ debugProxyCtor ] @ debugProxyGetterMeths), + mkILFields debugProxyFields, + emptyILTypeDefs, + mkILProperties debugProxyGetterProps, + emptyILEvents, + emptyILCustomAttrs, + ILTypeInit.BeforeField + ) + + [ debugProxyTypeDef.WithSpecialName(true) ], + ([ mkDebuggerTypeProxyAttribute debugProxyTy ] @ cud.DebugDisplayAttributes) + + let altTypeDef = + let basicFields = + fields + |> Array.map (fun field -> + let fldName, fldTy = mkUnionCaseFieldId field + + let fdef = + mkILInstanceField (fldName, fldTy, None, ILMemberAccess.Assembly) + |> addFieldNeverAttrs + |> addFieldGeneratedAttrs + + fdef.WithInitOnly(isTotallyImmutable)) + |> Array.toList + + let basicProps, basicMethods = + mkMethodsAndPropertiesForFields + (addMethodGeneratedAttrs, addPropertyGeneratedAttrs) + cud.UnionCasesAccessibility + attr + imports + cud.HasHelpers + altTy + fields + + let basicCtorInstrs = + [ + yield mkLdarg0 + match repr.DiscriminationTechnique info with + | IntegerTag -> + yield mkLdcInt32 num + yield mkNormalCall (mkILCtorMethSpecForTy (baseTy, [ mkTagFieldType ilg cuspec ])) + | SingleCase + | RuntimeTypes -> yield mkNormalCall (mkILCtorMethSpecForTy (baseTy, [])) + | TailOrNull -> failwith "unreachable" + ] + + let basicCtorAccess = + (if cuspec.HasHelpers = AllHelpers then + ILMemberAccess.Assembly + else + cud.UnionCasesAccessibility) + + let basicCtorFields = + basicFields |> List.map (fun fdef -> fdef.Name, fdef.FieldType) + + let basicCtorMeth = + mkILStorageCtor (basicCtorInstrs, altTy, basicCtorFields, basicCtorAccess, attr, imports) + |> addMethodGeneratedAttrs + + let altTypeDef = + mkILGenericClass ( + altTy.TypeSpec.Name, + // Types for nullary's become private, they also have names like _Empty + ILTypeDefAccess.Nested( + if alt.IsNullary && cud.HasHelpers = IlxUnionHasHelpers.AllHelpers then + ILMemberAccess.Assembly + else + cud.UnionCasesAccessibility + ), + td.GenericParams, + baseTy, + [], + mkILMethods ([ basicCtorMeth ] @ basicMethods), + mkILFields basicFields, + emptyILTypeDefs, + mkILProperties basicProps, + emptyILEvents, + mkILCustomAttrs debugAttrs, + ILTypeInit.BeforeField + ) + + altTypeDef.WithSpecialName(true).WithSerializable(td.IsSerializable) + + [ altTypeDef ], altDebugTypeDefs + + typeDefs, altDebugTypeDefs, altNullaryFields baseMakerMeths, baseMakerProps, altUniqObjMeths, typeDefs, altDebugTypeDefs, altNullaryFields - - -let mkClassUnionDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addPropertyNeverAttrs, addFieldGeneratedAttrs: ILFieldDef -> ILFieldDef, addFieldNeverAttrs: ILFieldDef -> ILFieldDef, mkDebuggerTypeProxyAttribute) ilg tref (td:ILTypeDef) cud = + +let mkClassUnionDef + (addMethodGeneratedAttrs, + addPropertyGeneratedAttrs, + addPropertyNeverAttrs, + addFieldGeneratedAttrs: ILFieldDef -> ILFieldDef, + addFieldNeverAttrs: ILFieldDef -> ILFieldDef, + mkDebuggerTypeProxyAttribute) + ilg + tref + (td: ILTypeDef) + cud + = let boxity = if td.IsStruct then ILBoxity.AsValue else ILBoxity.AsObject let baseTy = mkILFormalNamedTy boxity tref td.GenericParams - let cuspec = IlxUnionSpec(IlxUnionRef(boxity,baseTy.TypeRef, cud.UnionCases, cud.IsNullPermitted, cud.HasHelpers), baseTy.GenericArgs) - let info = (td,cud) - let repr = cudefRepr - let isTotallyImmutable = (cud.HasHelpers <> SpecialFSharpListHelpers) - let results = - cud.UnionCases - |> List.ofArray - |> List.mapi (fun i alt -> convAlternativeDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addPropertyNeverAttrs, addFieldGeneratedAttrs, addFieldNeverAttrs, mkDebuggerTypeProxyAttribute) ilg i td cud info cuspec baseTy alt) - - let baseMethsFromAlt = results |> List.collect (fun (a,_,_,_,_,_) -> a) - let basePropsFromAlt = results |> List.collect (fun (_,a,_,_,_,_) -> a) - let altUniqObjMeths = results |> List.collect (fun (_,_,a,_,_,_) -> a) - let altTypeDefs = results |> List.collect (fun (_,_,_,a,_,_) -> a) - let altDebugTypeDefs = results |> List.collect (fun (_,_,_,_,a,_) -> a) - let altNullaryFields = results |> List.collect (fun (_,_,_,_,_,a) -> a) - - let tagFieldsInObject = - match repr.DiscriminationTechnique info with - | SingleCase | RuntimeTypes | TailOrNull -> [] - | IntegerTag -> [ mkTagFieldId ilg cuspec ] + let cuspec = + IlxUnionSpec(IlxUnionRef(boxity, baseTy.TypeRef, cud.UnionCases, cud.IsNullPermitted, cud.HasHelpers), baseTy.GenericArgs) - let isStruct = td.IsStruct - - let selfFields, selfMeths, selfProps = - - [ for cidx, alt in Array.indexed cud.UnionCases do - if repr.RepresentAlternativeAsFreshInstancesOfRootClass (info,alt) || - repr.RepresentAlternativeAsStructValue info then - // TODO - let fields = alt.FieldDefs |> Array.map mkUnionCaseFieldId |> Array.toList - let baseInit = - if isStruct then None else - match td.Extends with - | None -> Some ilg.typ_Object.TypeSpec - | Some ilTy -> Some ilTy.TypeSpec - - let extraParamsForCtor = - if isStruct && takesExtraParams cud.UnionCases then - let extraTys, _extraInstrs = extraTysAndInstrsForStructCtor ilg cidx - List.map mkILParamAnon extraTys - else - [] + let info = (td, cud) + let repr = cudefRepr + let isTotallyImmutable = (cud.HasHelpers <> SpecialFSharpListHelpers) - let ctorAccess = (if cuspec.HasHelpers = AllHelpers then ILMemberAccess.Assembly else cud.UnionCasesAccessibility) - - let ctor = - mkILSimpleStorageCtor - (baseInit, - baseTy, - extraParamsForCtor, - (fields @ tagFieldsInObject), - ctorAccess, - cud.DebugPoint, - cud.DebugImports) - |> addMethodGeneratedAttrs + let results = + cud.UnionCases + |> List.ofArray + |> List.mapi (fun i alt -> + convAlternativeDef + (addMethodGeneratedAttrs, + addPropertyGeneratedAttrs, + addPropertyNeverAttrs, + addFieldGeneratedAttrs, + addFieldNeverAttrs, + mkDebuggerTypeProxyAttribute) + ilg + i + td + cud + info + cuspec + baseTy + alt) + + let baseMethsFromAlt = results |> List.collect (fun (a, _, _, _, _, _) -> a) + let basePropsFromAlt = results |> List.collect (fun (_, a, _, _, _, _) -> a) + let altUniqObjMeths = results |> List.collect (fun (_, _, a, _, _, _) -> a) + let altTypeDefs = results |> List.collect (fun (_, _, _, a, _, _) -> a) + let altDebugTypeDefs = results |> List.collect (fun (_, _, _, _, a, _) -> a) + let altNullaryFields = results |> List.collect (fun (_, _, _, _, _, a) -> a) + + let tagFieldsInObject = + match repr.DiscriminationTechnique info with + | SingleCase + | RuntimeTypes + | TailOrNull -> [] + | IntegerTag -> [ mkTagFieldId ilg cuspec ] - let props, meths = mkMethodsAndPropertiesForFields (addMethodGeneratedAttrs, addPropertyGeneratedAttrs) cud.UnionCasesAccessibility cud.DebugPoint cud.DebugImports cud.HasHelpers baseTy alt.FieldDefs - yield (fields,([ctor] @ meths),props) ] - |> List.unzip3 - |> (fun (a,b,c) -> List.concat a, List.concat b, List.concat c) + let isStruct = td.IsStruct - let selfAndTagFields = - [ for fldName,fldTy in (selfFields @ tagFieldsInObject) do - let fdef = mkILInstanceField (fldName,fldTy, None, ILMemberAccess.Assembly) |> addFieldNeverAttrs |> addFieldGeneratedAttrs - yield fdef.WithInitOnly(not isStruct && isTotallyImmutable) ] + let selfFields, selfMeths, selfProps = + + [ + for cidx, alt in Array.indexed cud.UnionCases do + if + repr.RepresentAlternativeAsFreshInstancesOfRootClass(info, alt) + || repr.RepresentAlternativeAsStructValue info + then + // TODO + let fields = alt.FieldDefs |> Array.map mkUnionCaseFieldId |> Array.toList + + let baseInit = + if isStruct then + None + else + match td.Extends with + | None -> Some ilg.typ_Object.TypeSpec + | Some ilTy -> Some ilTy.TypeSpec + + let extraParamsForCtor = + if isStruct && takesExtraParams cud.UnionCases then + let extraTys, _extraInstrs = extraTysAndInstrsForStructCtor ilg cidx + List.map mkILParamAnon extraTys + else + [] + + let ctorAccess = + (if cuspec.HasHelpers = AllHelpers then + ILMemberAccess.Assembly + else + cud.UnionCasesAccessibility) + + let ctor = + mkILSimpleStorageCtor ( + baseInit, + baseTy, + extraParamsForCtor, + (fields @ tagFieldsInObject), + ctorAccess, + cud.DebugPoint, + cud.DebugImports + ) + |> addMethodGeneratedAttrs + + let props, meths = + mkMethodsAndPropertiesForFields + (addMethodGeneratedAttrs, addPropertyGeneratedAttrs) + cud.UnionCasesAccessibility + cud.DebugPoint + cud.DebugImports + cud.HasHelpers + baseTy + alt.FieldDefs + + yield (fields, ([ ctor ] @ meths), props) + ] + |> List.unzip3 + |> (fun (a, b, c) -> List.concat a, List.concat b, List.concat c) + + let selfAndTagFields = + [ + for fldName, fldTy in (selfFields @ tagFieldsInObject) do + let fdef = + mkILInstanceField (fldName, fldTy, None, ILMemberAccess.Assembly) + |> addFieldNeverAttrs + |> addFieldGeneratedAttrs + + yield fdef.WithInitOnly(not isStruct && isTotallyImmutable) + ] let ctorMeths = - if (List.isEmpty selfFields && List.isEmpty tagFieldsInObject && not (List.isEmpty selfMeths)) + if + (List.isEmpty selfFields + && List.isEmpty tagFieldsInObject + && not (List.isEmpty selfMeths)) || isStruct - || cud.UnionCases |> Array.forall (fun alt -> repr.RepresentAlternativeAsFreshInstancesOfRootClass (info,alt)) then + || cud.UnionCases + |> Array.forall (fun alt -> repr.RepresentAlternativeAsFreshInstancesOfRootClass(info, alt)) + then [] (* no need for a second ctor in these cases *) - else - let baseTySpec = (match td.Extends with None -> ilg.typ_Object | Some ilTy -> ilTy).TypeSpec - [ mkILSimpleStorageCtor - (Some baseTySpec, - baseTy, - [], - tagFieldsInObject, - ILMemberAccess.Assembly, - cud.DebugPoint, - cud.DebugImports) - |> addMethodGeneratedAttrs ] - - // Now initialize the constant fields wherever they are stored... - let addConstFieldInit cd = - if List.isEmpty altNullaryFields then - cd - else - prependInstrsToClassCtor - [ for info,_alt,altTy,fidx,fd,inRootClass in altNullaryFields do - let constFieldId = (fd.Name,baseTy) - let constFieldSpec = mkConstFieldSpecFromId baseTy constFieldId - match repr.DiscriminationTechnique info with - | SingleCase - | RuntimeTypes - | TailOrNull -> - yield mkNormalNewobj (mkILCtorMethSpecForTy (altTy,[])) - | IntegerTag -> - if inRootClass then - yield mkLdcInt32 fidx - yield mkNormalNewobj (mkILCtorMethSpecForTy (altTy,[mkTagFieldType ilg cuspec] )) - else - yield mkNormalNewobj (mkILCtorMethSpecForTy (altTy,[])) - yield mkNormalStsfld constFieldSpec ] - cud.DebugPoint - cud.DebugImports - cd - - let tagMeths, tagProps, tagEnumFields = + else + let baseTySpec = + (match td.Extends with + | None -> ilg.typ_Object + | Some ilTy -> ilTy) + .TypeSpec + + [ + mkILSimpleStorageCtor ( + Some baseTySpec, + baseTy, + [], + tagFieldsInObject, + ILMemberAccess.Assembly, + cud.DebugPoint, + cud.DebugImports + ) + |> addMethodGeneratedAttrs + ] + + // Now initialize the constant fields wherever they are stored... + let addConstFieldInit cd = + if List.isEmpty altNullaryFields then + cd + else + prependInstrsToClassCtor + [ + for info, _alt, altTy, fidx, fd, inRootClass in altNullaryFields do + let constFieldId = (fd.Name, baseTy) + let constFieldSpec = mkConstFieldSpecFromId baseTy constFieldId + + match repr.DiscriminationTechnique info with + | SingleCase + | RuntimeTypes + | TailOrNull -> yield mkNormalNewobj (mkILCtorMethSpecForTy (altTy, [])) + | IntegerTag -> + if inRootClass then + yield mkLdcInt32 fidx + yield mkNormalNewobj (mkILCtorMethSpecForTy (altTy, [ mkTagFieldType ilg cuspec ])) + else + yield mkNormalNewobj (mkILCtorMethSpecForTy (altTy, [])) + + yield mkNormalStsfld constFieldSpec + ] + cud.DebugPoint + cud.DebugImports + cd + + let tagMeths, tagProps, tagEnumFields = let tagFieldType = mkTagFieldType ilg cuspec - let tagEnumFields = - cud.UnionCases + + let tagEnumFields = + cud.UnionCases |> Array.mapi (fun num alt -> mkILLiteralField (alt.Name, tagFieldType, ILFieldInit.Int32 num, None, ILMemberAccess.Public)) |> Array.toList - - let tagMeths,tagProps = - - let code = genWith (fun cg -> emitLdDataTagPrim ilg (Some mkLdarg0) cg (true, cuspec); cg.EmitInstr I_ret) - let body = mkMethodBody(true, [], 2, code, cud.DebugPoint, cud.DebugImports) - // // If we are using NULL as a representation for an element of this type then we cannot - // // use an instance method - if (repr.RepresentOneAlternativeAsNull info) then - [ mkILNonGenericStaticMethod("Get" + tagPropertyName,cud.HelpersAccessibility,[mkILParamAnon baseTy],mkILReturn tagFieldType,body) - |> addMethodGeneratedAttrs ], - [] - - else - [ mkILNonGenericInstanceMethod("get_" + tagPropertyName,cud.HelpersAccessibility,[],mkILReturn tagFieldType,body) - |> addMethodGeneratedAttrs ], - - [ ILPropertyDef(name = tagPropertyName, - attributes = PropertyAttributes.None, - setMethod = None, - getMethod = Some(mkILMethRef(baseTy.TypeRef,ILCallingConv.Instance,"get_" + tagPropertyName,0,[], tagFieldType)), - callingConv = ILThisConvention.Instance, - propertyType = tagFieldType, - init = None, - args = [], - customAttrs = emptyILCustomAttrs) - |> addPropertyGeneratedAttrs - |> addPropertyNeverAttrs ] + let tagMeths, tagProps = + + let code = + genWith (fun cg -> + emitLdDataTagPrim ilg (Some mkLdarg0) cg (true, cuspec) + cg.EmitInstr I_ret) + + let body = mkMethodBody (true, [], 2, code, cud.DebugPoint, cud.DebugImports) + // // If we are using NULL as a representation for an element of this type then we cannot + // // use an instance method + if (repr.RepresentOneAlternativeAsNull info) then + [ + mkILNonGenericStaticMethod ( + "Get" + tagPropertyName, + cud.HelpersAccessibility, + [ mkILParamAnon baseTy ], + mkILReturn tagFieldType, + body + ) + |> addMethodGeneratedAttrs + ], + [] + + else + [ + mkILNonGenericInstanceMethod ("get_" + tagPropertyName, cud.HelpersAccessibility, [], mkILReturn tagFieldType, body) + |> addMethodGeneratedAttrs + ], + + [ + ILPropertyDef( + name = tagPropertyName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = + Some(mkILMethRef (baseTy.TypeRef, ILCallingConv.Instance, "get_" + tagPropertyName, 0, [], tagFieldType)), + callingConv = ILThisConvention.Instance, + propertyType = tagFieldType, + init = None, + args = [], + customAttrs = emptyILCustomAttrs + ) + |> addPropertyGeneratedAttrs + |> addPropertyNeverAttrs + ] tagMeths, tagProps, tagEnumFields // The class can be abstract if each alternative is represented by a derived type - let isAbstract = (altTypeDefs.Length = cud.UnionCases.Length) + let isAbstract = (altTypeDefs.Length = cud.UnionCases.Length) let existingMeths = td.Methods.AsList() let existingProps = td.Properties.AsList() - let enumTypeDef = + let enumTypeDef = // The nested Tags type is elided if there is only one tag // The Tag property is NOT elided if there is only one tag - if tagEnumFields.Length <= 1 then + if tagEnumFields.Length <= 1 then None else - let tdef = - ILTypeDef(name = "Tags", - nestedTypes = emptyILTypeDefs, - genericParams= td.GenericParams, - attributes = enum 0, - layout=ILTypeDefLayout.Auto, - implements = [], - extends= Some ilg.typ_Object, - methods= emptyILMethods, - securityDecls=emptyILSecurityDecls, - fields=mkILFields tagEnumFields, - methodImpls=emptyILMethodImpls, - events=emptyILEvents, - properties=emptyILProperties, - isKnownToBeAttribute=false, - customAttrs= emptyILCustomAttrs) - .WithNestedAccess(cud.UnionCasesAccessibility) - .WithAbstract(true) - .WithSealed(true) - .WithImport(false) - .WithEncoding(ILDefaultPInvokeEncoding.Ansi) - .WithHasSecurity(false) + let tdef = + ILTypeDef( + name = "Tags", + nestedTypes = emptyILTypeDefs, + genericParams = td.GenericParams, + attributes = enum 0, + layout = ILTypeDefLayout.Auto, + implements = [], + extends = Some ilg.typ_Object, + methods = emptyILMethods, + securityDecls = emptyILSecurityDecls, + fields = mkILFields tagEnumFields, + methodImpls = emptyILMethodImpls, + events = emptyILEvents, + properties = emptyILProperties, + isKnownToBeAttribute = false, + customAttrs = emptyILCustomAttrs + ) + .WithNestedAccess(cud.UnionCasesAccessibility) + .WithAbstract(true) + .WithSealed(true) + .WithImport(false) + .WithEncoding(ILDefaultPInvokeEncoding.Ansi) + .WithHasSecurity(false) + Some tdef - let baseTypeDef = - td.WithInitSemantics(ILTypeInit.BeforeField) - .With(nestedTypes = mkILTypeDefs (Option.toList enumTypeDef @ altTypeDefs @ altDebugTypeDefs @ td.NestedTypes.AsList()), - extends= (match td.Extends with None -> Some ilg.typ_Object | _ -> td.Extends), - methods= mkILMethods (ctorMeths @ baseMethsFromAlt @ selfMeths @ tagMeths @ altUniqObjMeths @ existingMeths), - fields=mkILFields (selfAndTagFields @ List.map (fun (_,_,_,_,fdef,_) -> fdef) altNullaryFields @ td.Fields.AsList()), - properties=mkILProperties (tagProps @ basePropsFromAlt @ selfProps @ existingProps)) - // The .cctor goes on the Cases type since that's where the constant fields for nullary constructors live - |> addConstFieldInit + let baseTypeDef = + td + .WithInitSemantics(ILTypeInit.BeforeField) + .With( + nestedTypes = + mkILTypeDefs ( + Option.toList enumTypeDef + @ altTypeDefs @ altDebugTypeDefs @ td.NestedTypes.AsList() + ), + extends = + (match td.Extends with + | None -> Some ilg.typ_Object + | _ -> td.Extends), + methods = + mkILMethods ( + ctorMeths + @ baseMethsFromAlt @ selfMeths @ tagMeths @ altUniqObjMeths @ existingMeths + ), + fields = + mkILFields ( + selfAndTagFields + @ List.map (fun (_, _, _, _, fdef, _) -> fdef) altNullaryFields + @ td.Fields.AsList() + ), + properties = mkILProperties (tagProps @ basePropsFromAlt @ selfProps @ existingProps) + ) + // The .cctor goes on the Cases type since that's where the constant fields for nullary constructors live + |> addConstFieldInit baseTypeDef.WithAbstract(isAbstract).WithSealed(altTypeDefs.IsEmpty) diff --git a/src/Compiler/CodeGen/IlxGen.fs b/src/Compiler/CodeGen/IlxGen.fs index ddb2e8f7f83..17eecfc2639 100644 --- a/src/Compiler/CodeGen/IlxGen.fs +++ b/src/Compiler/CodeGen/IlxGen.fs @@ -42,42 +42,49 @@ open FSharp.Compiler.TypeRelations let IlxGenStackGuardDepth = StackGuard.GetDepthOption "IlxGen" -let IsNonErasedTypar (tp: Typar) = - not tp.IsErased +let IsNonErasedTypar (tp: Typar) = not tp.IsErased -let DropErasedTypars (tps: Typar list) = - tps |> List.filter IsNonErasedTypar +let DropErasedTypars (tps: Typar list) = tps |> List.filter IsNonErasedTypar let DropErasedTyargs tys = - tys |> List.filter (fun ty -> match ty with TType_measure _ -> false | _ -> true) + tys + |> List.filter (fun ty -> + match ty with + | TType_measure _ -> false + | _ -> true) -let AddNonUserCompilerGeneratedAttribs (g: TcGlobals) (mdef: ILMethodDef) = - g.AddMethodGeneratedAttributes mdef +let AddNonUserCompilerGeneratedAttribs (g: TcGlobals) (mdef: ILMethodDef) = g.AddMethodGeneratedAttributes mdef let debugDisplayMethodName = "__DebugDisplay" let useHiddenInitCode = true -let iLdcZero = AI_ldc (DT_I4, ILConst.I4 0) +let iLdcZero = AI_ldc(DT_I4, ILConst.I4 0) -let iLdcInt64 i = AI_ldc (DT_I8, ILConst.I8 i) +let iLdcInt64 i = AI_ldc(DT_I8, ILConst.I8 i) -let iLdcDouble i = AI_ldc (DT_R8, ILConst.R8 i) +let iLdcDouble i = AI_ldc(DT_R8, ILConst.R8 i) -let iLdcSingle i = AI_ldc (DT_R4, ILConst.R4 i) +let iLdcSingle i = AI_ldc(DT_R4, ILConst.R4 i) /// Make a method that simply loads a field -let mkLdfldMethodDef (ilMethName, reprAccess, isStatic, ilTy, ilFieldName, ilPropType) = - let ilFieldSpec = mkILFieldSpecInTy(ilTy, ilFieldName, ilPropType) - let ilReturn = mkILReturn ilPropType - let ilMethodDef = - if isStatic then - let body = mkMethodBody(true, [], 2, nonBranchingInstrsToCode [mkNormalLdsfld ilFieldSpec], None, None) - mkILNonGenericStaticMethod (ilMethName, reprAccess, [], ilReturn, body) - else - let body = mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkLdarg0; mkNormalLdfld ilFieldSpec], None, None) - mkILNonGenericInstanceMethod (ilMethName, reprAccess, [], ilReturn, body) - ilMethodDef.WithSpecialName +let mkLdfldMethodDef (ilMethName, reprAccess, isStatic, ilTy, ilFieldName, ilPropType, customAttrs) = + let ilFieldSpec = mkILFieldSpecInTy (ilTy, ilFieldName, ilPropType) + let ilReturn = mkILReturn ilPropType + + let ilMethodDef = + if isStatic then + let body = + mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkNormalLdsfld ilFieldSpec ], None, None) + + mkILNonGenericStaticMethod (ilMethName, reprAccess, [], ilReturn, body) + else + let body = + mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkLdarg0; mkNormalLdfld ilFieldSpec ], None, None) + + mkILNonGenericInstanceMethod (ilMethName, reprAccess, [], ilReturn, body) + + ilMethodDef.With(customAttrs = mkILCustomAttrs customAttrs).WithSpecialName /// Choose the constructor parameter names for fields let ChooseParamNames fieldNamesAndTypes = @@ -86,23 +93,48 @@ let ChooseParamNames fieldNamesAndTypes = fieldNamesAndTypes |> List.map (fun (ilPropName, ilFieldName, ilPropType) -> let lowerPropName = String.uncapitalize ilPropName - let ilParamName = if takenFieldNames.Contains lowerPropName then ilPropName else lowerPropName + + let ilParamName = + if takenFieldNames.Contains lowerPropName then + ilPropName + else + lowerPropName + ilParamName, ilFieldName, ilPropType) /// Approximation for purposes of optimization and giving a warning when compiling definition-only files as EXEs let rec CheckCodeDoesSomething (code: ILCode) = - code.Instrs |> Array.exists (function AI_ldnull | AI_nop | AI_pop | I_ret | I_seqpoint _ -> false | _ -> true) + code.Instrs + |> Array.exists (function + | AI_ldnull + | AI_nop + | AI_pop + | I_ret + | I_seqpoint _ -> false + | _ -> true) /// Choose the field names for variables captured by closures let ChooseFreeVarNames takenNames ts = let tns = List.map (fun t -> (t, None)) ts + let rec chooseName names (t, nOpt) = - let tn = match nOpt with None -> t | Some n -> t + string n + let tn = + match nOpt with + | None -> t + | Some n -> t + string n + if Zset.contains tn names then - chooseName names (t, Some(match nOpt with None -> 0 | Some n -> (n+1))) + chooseName + names + (t, + Some( + match nOpt with + | None -> 0 + | Some n -> (n + 1) + )) else - let names = Zset.add tn names - tn, names + let names = Zset.add tn names + tn, names let names = Zset.empty String.order |> Zset.addList takenNames let ts, _names = List.mapFold chooseName names tns @@ -110,9 +142,9 @@ let ChooseFreeVarNames takenNames ts = /// We can't tailcall to methods taking byrefs. This helper helps search for them let rec IsILTypeByref inp = - match inp with + match inp with | ILType.Byref _ -> true - | ILType.Modified(_, _, nestedTy) -> IsILTypeByref nestedTy + | ILType.Modified (_, _, nestedTy) -> IsILTypeByref nestedTy | _ -> false let mainMethName = CompilerGeneratedName "main" @@ -120,27 +152,45 @@ let mainMethName = CompilerGeneratedName "main" /// Used to query custom attributes when emitting COM interop code. type AttributeDecoder(namedArgs) = - let nameMap = namedArgs |> List.map (fun (AttribNamedArg(s, _, _, c)) -> s, c) |> NameMap.ofList + let nameMap = + namedArgs + |> List.map (fun (AttribNamedArg (s, _, _, c)) -> s, c) + |> NameMap.ofList let findConst x = match NameMap.tryFind x nameMap with - | Some(AttribExpr(_, Expr.Const (c, _, _))) -> Some c + | Some (AttribExpr (_, Expr.Const (c, _, _))) -> Some c | _ -> None let findTyconRef x = match NameMap.tryFind x nameMap with - | Some(AttribExpr(_, Expr.App (_, _, [TType_app(tr, _, _)], _, _))) -> Some tr + | Some (AttribExpr (_, Expr.App (_, _, [ TType_app (tcref, _, _) ], _, _))) -> Some tcref | _ -> None - member _.FindInt16 x dflt = match findConst x with | Some(Const.Int16 x) -> x | _ -> dflt + member _.FindInt16 x dflt = + match findConst x with + | Some (Const.Int16 x) -> x + | _ -> dflt - member _.FindInt32 x dflt = match findConst x with | Some(Const.Int32 x) -> x | _ -> dflt + member _.FindInt32 x dflt = + match findConst x with + | Some (Const.Int32 x) -> x + | _ -> dflt - member _.FindBool x dflt = match findConst x with | Some(Const.Bool x) -> x | _ -> dflt + member _.FindBool x dflt = + match findConst x with + | Some (Const.Bool x) -> x + | _ -> dflt - member _.FindString x dflt = match findConst x with | Some(Const.String x) -> x | _ -> dflt + member _.FindString x dflt = + match findConst x with + | Some (Const.String x) -> x + | _ -> dflt - member _.FindTypeName x dflt = match findTyconRef x with | Some tr -> tr.DisplayName | _ -> dflt + member _.FindTypeName x dflt = + match findTyconRef x with + | Some tr -> tr.DisplayName + | _ -> dflt //-------------------------------------------------------------------------- // Statistics @@ -150,14 +200,21 @@ let mutable reports = (fun _ -> ()) let AddReport f = let old = reports - reports <- (fun oc -> old oc; f oc) -let ReportStatistics (oc: TextWriter) = - reports oc + reports <- + (fun oc -> + old oc + f oc) + +let ReportStatistics (oc: TextWriter) = reports oc let NewCounter nm = let mutable count = 0 - AddReport (fun oc -> if count <> 0 then oc.WriteLine (string count + " " + nm)) + + AddReport(fun oc -> + if count <> 0 then + oc.WriteLine(string count + " " + nm)) + (fun () -> count <- count + 1) let CountClosure = NewCounter "closures" @@ -171,12 +228,12 @@ let CountCallFuncInstructions = NewCounter "callfunc instructions (indirect call /// Non-local information related to internals of code generation within an assembly type IlxGenIntraAssemblyInfo = { - /// A table recording the generated name of the static backing fields for each mutable top level value where - /// we may need to take the address of that value, e.g. static mutable module-bound values which are structs. These are - /// only accessible intra-assembly. Across assemblies, taking the address of static mutable module-bound values is not permitted. - /// The key to the table is the method ref for the property getter for the value, which is a stable name for the Val's - /// that come from both the signature and the implementation. - StaticFieldInfo: Dictionary + /// A table recording the generated name of the static backing fields for each mutable top level value where + /// we may need to take the address of that value, e.g. static mutable module-bound values which are structs. These are + /// only accessible intra-assembly. Across assemblies, taking the address of static mutable module-bound values is not permitted. + /// The key to the table is the method ref for the property getter for the value, which is a stable name for the Val's + /// that come from both the signature and the implementation. + StaticFieldInfo: Dictionary } /// Helper to make sure we take tailcalls in some situations @@ -193,91 +250,91 @@ type IlxGenBackend = [] type IlxGenOptions = { - /// Indicates the "fragment name" for the part of the assembly we are emitting, particularly for incremental - /// emit using Reflection.Emit in F# Interactive. - fragName: string + /// Indicates the "fragment name" for the part of the assembly we are emitting, particularly for incremental + /// emit using Reflection.Emit in F# Interactive. + fragName: string - /// Indicates if we are generating filter blocks - generateFilterBlocks: bool + /// Indicates if we are generating filter blocks + generateFilterBlocks: bool - /// Indicates if we are working around historical Reflection.Emit bugs - workAroundReflectionEmitBugs: bool + /// Indicates if we are working around historical Reflection.Emit bugs + workAroundReflectionEmitBugs: bool - /// Indicates if we should/shouldn't emit constant arrays as static data blobs - emitConstantArraysUsingStaticDataBlobs: bool + /// Indicates if we should/shouldn't emit constant arrays as static data blobs + emitConstantArraysUsingStaticDataBlobs: bool - /// If this is set, then the last module becomes the "main" module and its toplevel bindings are executed at startup - mainMethodInfo: Attribs option + /// If this is set, then the last module becomes the "main" module and its toplevel bindings are executed at startup + mainMethodInfo: Attribs option - /// Indicates if local optimizations are on - localOptimizationsEnabled: bool + /// Indicates if local optimizations are on + localOptimizationsEnabled: bool - /// Indicates if we are generating debug symbols - generateDebugSymbols: bool + /// Indicates if we are generating debug symbols + generateDebugSymbols: bool - /// Indicates that FeeFee debug values should be emitted as value 100001 for - /// easier detection in debug output - testFlagEmitFeeFeeAs100001: bool + /// Indicates that FeeFee debug values should be emitted as value 100001 for + /// easier detection in debug output + testFlagEmitFeeFeeAs100001: bool - ilxBackend: IlxGenBackend + ilxBackend: IlxGenBackend - fsiMultiAssemblyEmit: bool + fsiMultiAssemblyEmit: bool - /// Indicates the code is being generated in FSI.EXE and is executed immediately after code generation - /// This includes all interactively compiled code, including #load, definitions, and expressions - isInteractive: bool + /// Indicates the code is being generated in FSI.EXE and is executed immediately after code generation + /// This includes all interactively compiled code, including #load, definitions, and expressions + isInteractive: bool - /// Indicates the code generated is an interactive 'it' expression. We generate a setter to allow clearing of the underlying - /// storage, even though 'it' is not logically mutable - isInteractiveItExpr: bool + /// Indicates the code generated is an interactive 'it' expression. We generate a setter to allow clearing of the underlying + /// storage, even though 'it' is not logically mutable + isInteractiveItExpr: bool - /// Suppress ToString emit - useReflectionFreeCodeGen: bool + /// Suppress ToString emit + useReflectionFreeCodeGen: bool - /// Whenever possible, use callvirt instead of call - alwaysCallVirt: bool + /// Whenever possible, use callvirt instead of call + alwaysCallVirt: bool } /// Compilation environment for compiling a fragment of an assembly [] type cenv = { - /// The TcGlobals for the compilation - g: TcGlobals + /// The TcGlobals for the compilation + g: TcGlobals - /// The ImportMap for reading IL - amap: ImportMap + /// The ImportMap for reading IL + amap: ImportMap - /// Environment for EraseClosures functionality - ilxPubCloEnv: EraseClosures.cenv + /// Environment for EraseClosures functionality + ilxPubCloEnv: EraseClosures.cenv - /// A callback for TcVal in the typechecker. Used to generalize values when finding witnesses. - /// It is unfortunate this is needed but it is until we supply witnesses through the compilation. - tcVal: ConstraintSolver.TcValF + /// A callback for TcVal in the typechecker. Used to generalize values when finding witnesses. + /// It is unfortunate this is needed but it is until we supply witnesses through the compilation. + tcVal: ConstraintSolver.TcValF - /// The TAST for the assembly being emitted - viewCcu: CcuThunk + /// The TAST for the assembly being emitted + viewCcu: CcuThunk - /// Collection of all debug points available for inlined code - namedDebugPointsForInlinedCode: Map + /// Collection of all debug points available for inlined code + namedDebugPointsForInlinedCode: Map - /// The options for ILX code generation. Only available when generating in implementation code. - optionsOpt: IlxGenOptions option + /// The options for ILX code generation. Only available when generating in implementation code. + optionsOpt: IlxGenOptions option - /// Cache the generation of the "unit" type - mutable ilUnitTy: ILType option + /// Cache the generation of the "unit" type + mutable ilUnitTy: ILType option - /// Other information from the emit of this assembly - intraAssemblyInfo: IlxGenIntraAssemblyInfo + /// Other information from the emit of this assembly + intraAssemblyInfo: IlxGenIntraAssemblyInfo - /// Cache methods with SecurityAttribute applied to them, to prevent unnecessary calls to ExistsInEntireHierarchyOfType - casApplied: Dictionary + /// Cache methods with SecurityAttribute applied to them, to prevent unnecessary calls to ExistsInEntireHierarchyOfType + casApplied: Dictionary - /// Used to apply forced inlining optimizations to witnesses generated late during codegen - mutable optimizeDuringCodeGen: bool -> Expr -> Expr + /// Used to apply forced inlining optimizations to witnesses generated late during codegen + mutable optimizeDuringCodeGen: bool -> Expr -> Expr - /// Guard the stack and move to a new one if necessary - mutable stackGuard: StackGuard + /// Guard the stack and move to a new one if necessary + mutable stackGuard: StackGuard } @@ -288,130 +345,182 @@ type cenv = override _.ToString() = "" - let mkTypeOfExpr cenv m ilTy = let g = cenv.g - mkAsmExpr ([ mkNormalCall (mspec_Type_GetTypeFromHandle g) ], [], - [mkAsmExpr ([ I_ldtoken (ILToken.ILType ilTy) ], [], [], [g.system_RuntimeTypeHandle_ty], m)], - [g.system_Type_ty], m) + + mkAsmExpr ( + [ mkNormalCall (mspec_Type_GetTypeFromHandle g) ], + [], + [ + mkAsmExpr ([ I_ldtoken(ILToken.ILType ilTy) ], [], [], [ g.system_RuntimeTypeHandle_ty ], m) + ], + [ g.system_Type_ty ], + m + ) let mkGetNameExpr cenv (ilt: ILType) m = - mkAsmExpr ([I_ldstr ilt.BasicQualifiedName], [], [], [cenv.g.string_ty], m) + mkAsmExpr ([ I_ldstr ilt.BasicQualifiedName ], [], [], [ cenv.g.string_ty ], m) let useCallVirt (cenv: cenv) boxity (mspec: ILMethodSpec) isBaseCall = - cenv.options.alwaysCallVirt && - (boxity = AsObject) && - not mspec.CallingConv.IsStatic && - not isBaseCall + cenv.options.alwaysCallVirt + && (boxity = AsObject) + && not mspec.CallingConv.IsStatic + && not isBaseCall /// Describes where items are to be placed within the generated IL namespace/typespace. /// This should be cleaned up. type CompileLocation = - { Scope: ILScopeRef + { + Scope: ILScopeRef - TopImplQualifiedName: string + TopImplQualifiedName: string - Namespace: string option + Namespace: string option - Enclosing: string list + Enclosing: string list - QualifiedNameOfFile: string + QualifiedNameOfFile: string } //-------------------------------------------------------------------------- // Access this and other assemblies //-------------------------------------------------------------------------- -let mkTopName ns n = String.concat "." (match ns with Some x -> [x;n] | None -> [n]) +let mkTopName ns n = + String.concat + "." + (match ns with + | Some x -> [ x; n ] + | None -> [ n ]) let CompLocForFragment fragName (ccu: CcuThunk) = - { QualifiedNameOfFile = fragName - TopImplQualifiedName = fragName - Scope = ccu.ILScopeRef - Namespace = None - Enclosing = []} + { + QualifiedNameOfFile = fragName + TopImplQualifiedName = fragName + Scope = ccu.ILScopeRef + Namespace = None + Enclosing = [] + } let CompLocForCcu (ccu: CcuThunk) = CompLocForFragment ccu.AssemblyName ccu let CompLocForSubModuleOrNamespace cloc (submod: ModuleOrNamespace) = let n = submod.CompiledName + match submod.ModuleOrNamespaceType.ModuleOrNamespaceKind with - | FSharpModuleWithSuffix | ModuleOrType -> { cloc with Enclosing= cloc.Enclosing @ [n]} - | Namespace -> {cloc with Namespace=Some (mkTopName cloc.Namespace n)} + | FSharpModuleWithSuffix + | ModuleOrType -> + { cloc with + Enclosing = cloc.Enclosing @ [ n ] + } + | Namespace _ -> + { cloc with + Namespace = Some(mkTopName cloc.Namespace n) + } + +let CompLocForFixedPath fragName qname (CompPath (sref, cpath)) = + let ns, t = + cpath + |> List.takeUntil (fun (_, mkind) -> + match mkind with + | Namespace _ -> false + | _ -> true) -let CompLocForFixedPath fragName qname (CompPath(sref, cpath)) = - let ns, t = List.takeUntil (fun (_, mkind) -> mkind <> Namespace) cpath let ns = List.map fst ns let ns = textOfPath ns - let encl = t |> List.map (fun (s, _)-> s) + let encl = t |> List.map (fun (s, _) -> s) let ns = if ns = "" then None else Some ns - { QualifiedNameOfFile = fragName - TopImplQualifiedName = qname - Scope = sref - Namespace = ns - Enclosing = encl } + + { + QualifiedNameOfFile = fragName + TopImplQualifiedName = qname + Scope = sref + Namespace = ns + Enclosing = encl + } let CompLocForFixedModule fragName qname (mspec: ModuleOrNamespace) = - let cloc = CompLocForFixedPath fragName qname mspec.CompilationPath - let cloc = CompLocForSubModuleOrNamespace cloc mspec - cloc + let cloc = CompLocForFixedPath fragName qname mspec.CompilationPath + let cloc = CompLocForSubModuleOrNamespace cloc mspec + cloc let NestedTypeRefForCompLoc cloc n = match cloc.Enclosing with | [] -> let tyname = mkTopName cloc.Namespace n - mkILTyRef(cloc.Scope, tyname) - | h :: t -> mkILNestedTyRef(cloc.Scope, mkTopName cloc.Namespace h :: t, n) + mkILTyRef (cloc.Scope, tyname) + | h :: t -> mkILNestedTyRef (cloc.Scope, mkTopName cloc.Namespace h :: t, n) let CleanUpGeneratedTypeName (nm: string) = if nm.IndexOfAny IllegalCharactersInTypeAndNamespaceNames = -1 then nm else - (nm, IllegalCharactersInTypeAndNamespaceNames) ||> Array.fold (fun nm c -> nm.Replace(string c, "-")) + (nm, IllegalCharactersInTypeAndNamespaceNames) + ||> Array.fold (fun nm c -> nm.Replace(string c, "-")) let TypeNameForInitClass cloc = - ".$" + cloc.TopImplQualifiedName + ".$" + + cloc.TopImplQualifiedName -let TypeNameForImplicitMainMethod cloc = - TypeNameForInitClass cloc + "$Main" +let TypeNameForImplicitMainMethod cloc = TypeNameForInitClass cloc + "$Main" let TypeNameForPrivateImplementationDetails cloc = - "" + "" let CompLocForInitClass cloc = - {cloc with Enclosing=[TypeNameForInitClass cloc]; Namespace=None} + { cloc with + Enclosing = [ TypeNameForInitClass cloc ] + Namespace = None + } let CompLocForImplicitMainMethod cloc = - {cloc with Enclosing=[TypeNameForImplicitMainMethod cloc]; Namespace=None} + { cloc with + Enclosing = [ TypeNameForImplicitMainMethod cloc ] + Namespace = None + } let CompLocForPrivateImplementationDetails cloc = - {cloc with - Enclosing=[TypeNameForPrivateImplementationDetails cloc]; Namespace=None} + { cloc with + Enclosing = [ TypeNameForPrivateImplementationDetails cloc ] + Namespace = None + } /// Compute an ILTypeRef for a CompilationLocation let rec TypeRefForCompLoc cloc = match cloc.Enclosing with - | [] -> - mkILTyRef(cloc.Scope, TypeNameForPrivateImplementationDetails cloc) - | [h] -> - let tyname = mkTopName cloc.Namespace h - mkILTyRef(cloc.Scope, tyname) + | [] -> mkILTyRef (cloc.Scope, TypeNameForPrivateImplementationDetails cloc) + | [ h ] -> + let tyname = mkTopName cloc.Namespace h + mkILTyRef (cloc.Scope, tyname) | _ -> - let encl, n = List.frontAndBack cloc.Enclosing - NestedTypeRefForCompLoc {cloc with Enclosing=encl} n + let encl, n = List.frontAndBack cloc.Enclosing + NestedTypeRefForCompLoc { cloc with Enclosing = encl } n /// Compute an ILType for a CompilationLocation for a non-generic type -let mkILTyForCompLoc cloc = mkILNonGenericBoxedTy (TypeRefForCompLoc cloc) +let mkILTyForCompLoc cloc = + mkILNonGenericBoxedTy (TypeRefForCompLoc cloc) -let ComputeMemberAccess hidden = if hidden then ILMemberAccess.Assembly else ILMemberAccess.Public +let ComputeMemberAccess hidden = + if hidden then + ILMemberAccess.Assembly + else + ILMemberAccess.Public // Under --publicasinternal change types from Public to Private (internal for types) -let ComputePublicTypeAccess() = ILTypeDefAccess.Public +let ComputePublicTypeAccess () = ILTypeDefAccess.Public let ComputeTypeAccess (tref: ILTypeRef) hidden = match tref.Enclosing with - | [] -> if hidden then ILTypeDefAccess.Private else ComputePublicTypeAccess() - | _ -> ILTypeDefAccess.Nested (ComputeMemberAccess hidden) + | [] -> + if hidden then + ILTypeDefAccess.Private + else + ComputePublicTypeAccess() + | _ -> ILTypeDefAccess.Nested(ComputeMemberAccess hidden) //-------------------------------------------------------------------------- // TypeReprEnv @@ -427,21 +536,24 @@ type TypeReprEnv(reprs: Map, count: int, templateReplacement: (Ty member _.TemplateReplacement = templateReplacement member _.WithTemplateReplacement(tcref, ilCloTyRef, cloFreeTyvars, templateTypeInst) = - TypeReprEnv(reprs, count, Some (tcref, ilCloTyRef, cloFreeTyvars, templateTypeInst)) + TypeReprEnv(reprs, count, Some(tcref, ilCloTyRef, cloFreeTyvars, templateTypeInst)) + + member _.WithoutTemplateReplacement() = TypeReprEnv(reprs, count, None) /// Lookup a type parameter - member _.Item (tp: Typar, m: range) = - try reprs[tp.Stamp] + member _.Item(tp: Typar, m: range) = + try + reprs[tp.Stamp] with :? KeyNotFoundException -> - errorR(InternalError("Undefined or unsolved type variable: " + showL(typarL tp), m)) - // Random value for post-hoc diagnostic analysis on generated tree * - uint16 666 + errorR (InternalError("Undefined or unsolved type variable: " + showL (typarL tp), m)) + // Random value for post-hoc diagnostic analysis on generated tree * + uint16 666 /// Add an additional type parameter to the environment. If the parameter is a units-of-measure parameter /// then it is ignored, since it doesn't correspond to a .NET type parameter. - member tyenv.AddOne (tp: Typar) = + member tyenv.AddOne(tp: Typar) = if IsNonErasedTypar tp then - TypeReprEnv(reprs.Add (tp.Stamp, uint16 count), count + 1, templateReplacement) + TypeReprEnv(reprs.Add(tp.Stamp, uint16 count), count + 1, templateReplacement) else tyenv @@ -460,16 +572,13 @@ type TypeReprEnv(reprs: Map, count: int, templateReplacement: (Ty TypeReprEnv(count = 0, reprs = Map.empty, templateReplacement = eenv.TemplateReplacement) /// Get the environment for a fixed set of type parameters - member eenv.ForTypars tps = - eenv.ResetTypars().Add tps + member eenv.ForTypars tps = eenv.ResetTypars().Add tps /// Get the environment for within a type definition - member eenv.ForTycon (tycon: Tycon) = - eenv.ForTypars tycon.TyparsNoRange + member eenv.ForTycon(tycon: Tycon) = eenv.ForTypars tycon.TyparsNoRange /// Get the environment for generating a reference to items within a type definition - member eenv.ForTyconRef (tycon: TyconRef) = - eenv.ForTycon tycon.Deref + member eenv.ForTyconRef(tcref: TyconRef) = eenv.ForTycon tcref.Deref //-------------------------------------------------------------------------- // Generate type references @@ -477,7 +586,7 @@ type TypeReprEnv(reprs: Map, count: int, templateReplacement: (Ty /// Get the ILTypeRef or other representation information for a type let GenTyconRef (tcref: TyconRef) = - assert(not tcref.IsTypeAbbrev) + assert (not tcref.IsTypeAbbrev) tcref.CompiledRepresentation type VoidNotOK = @@ -486,8 +595,8 @@ type VoidNotOK = #if DEBUG let voidCheck m g permits ty = - if permits=VoidNotOK && isVoidTy g ty then - error(InternalError("System.Void unexpectedly detected in IL code generation. This should not occur.", m)) + if permits = VoidNotOK && isVoidTy g ty then + error (InternalError("System.Void unexpectedly detected in IL code generation. This should not occur.", m)) #endif /// When generating parameter and return types generate precise .NET IL pointer types. @@ -498,10 +607,14 @@ type PtrsOK = | PtrTypesOK | PtrTypesNotOK +let GenReadOnlyAttribute (g: TcGlobals) = + mkILCustomAttribute (g.attrib_IsReadOnlyAttribute.TypeRef, [], [], []) + let GenReadOnlyAttributeIfNecessary (g: TcGlobals) ty = let add = isInByrefTy g ty && g.attrib_IsReadOnlyAttribute.TyconRef.CanDeref + if add then - let attr = mkILCustomAttribute (g.attrib_IsReadOnlyAttribute.TypeRef, [], [], []) + let attr = GenReadOnlyAttribute g Some attr else None @@ -509,6 +622,7 @@ let GenReadOnlyAttributeIfNecessary (g: TcGlobals) ty = /// Generate "modreq([mscorlib]System.Runtime.InteropServices.InAttribute)" on inref types. let GenReadOnlyModReqIfNecessary (g: TcGlobals) ty ilTy = let add = isInByrefTy g ty && g.attrib_InAttribute.TyconRef.CanDeref + if add then ILType.Modified(true, g.attrib_InAttribute.TypeRef, ilTy) else @@ -526,36 +640,38 @@ and GenTyAppAux cenv m tyenv repr tinst = let ilTypeInst = GenTypeArgsAux cenv m tyenv tinst let ty = instILType ilTypeInst ty ty - | CompiledTypeRepr.ILAsmNamed (tref, boxity, ilTypeOpt) -> - GenILTyAppAux cenv m tyenv (tref, boxity, ilTypeOpt) tinst + | CompiledTypeRepr.ILAsmNamed (tref, boxity, ilTypeOpt) -> GenILTyAppAux cenv m tyenv (tref, boxity, ilTypeOpt) tinst and GenILTyAppAux cenv m tyenv (tref, boxity, ilTypeOpt) tinst = match ilTypeOpt with | None -> let ilTypeInst = GenTypeArgsAux cenv m tyenv tinst mkILTy boxity (mkILTySpec (tref, ilTypeInst)) - | Some ilType -> - ilType // monomorphic types include a cached ilType to avoid reallocation of an ILType node + | Some ilType -> ilType // monomorphic types include a cached ilType to avoid reallocation of an ILType node and GenNamedTyAppAux (cenv: cenv) m (tyenv: TypeReprEnv) ptrsOK tcref tinst = let g = cenv.g + match tyenv.TemplateReplacement with - | Some (tcref2, ilCloTyRef, cloFreeTyvars, _) when tyconRefEq g tcref tcref2 -> + | Some (tcref2, ilCloTyRef, cloFreeTyvars, _) when tyconRefEq g tcref tcref2 -> let cloInst = List.map mkTyparTy cloFreeTyvars let ilTypeInst = GenTypeArgsAux cenv m tyenv cloInst mkILValueTy ilCloTyRef ilTypeInst | _ -> - let tinst = DropErasedTyargs tinst - // See above note on ptrsOK - if ptrsOK = PtrTypesOK && tyconRefEq g tcref g.nativeptr_tcr && (freeInTypes CollectTypars tinst).FreeTypars.IsEmpty then - GenNamedTyAppAux cenv m tyenv ptrsOK g.ilsigptr_tcr tinst - else + let tinst = DropErasedTyargs tinst + // See above note on ptrsOK + if + ptrsOK = PtrTypesOK + && tyconRefEq g tcref g.nativeptr_tcr + && (freeInTypes CollectTypars tinst).FreeTypars.IsEmpty + then + GenNamedTyAppAux cenv m tyenv ptrsOK g.ilsigptr_tcr tinst + else #if !NO_TYPEPROVIDERS - match tcref.TypeReprInfo with - // Generate the base type, because that is always the representation of the erased type, unless the assembly is being injected - | TProvidedTypeRepr info when info.IsErased -> - GenTypeAux cenv m tyenv VoidNotOK ptrsOK (info.BaseTypeForErased (m, g.obj_ty)) - | _ -> + match tcref.TypeReprInfo with + // Generate the base type, because that is always the representation of the erased type, unless the assembly is being injected + | TProvidedTypeRepr info when info.IsErased -> GenTypeAux cenv m tyenv VoidNotOK ptrsOK (info.BaseTypeForErased(m, g.obj_ty)) + | _ -> #endif GenTyAppAux cenv m tyenv (GenTyconRef tcref) tinst @@ -567,18 +683,22 @@ and GenTypeAux cenv m (tyenv: TypeReprEnv) voidOK ptrsOK ty = ignore voidOK #endif match stripTyEqnsAndMeasureEqns g ty with - | TType_app (tcref, tinst, _) -> - GenNamedTyAppAux cenv m tyenv ptrsOK tcref tinst + | TType_app (tcref, tinst, _) -> GenNamedTyAppAux cenv m tyenv ptrsOK tcref tinst - | TType_tuple (tupInfo, args) -> - GenTypeAux cenv m tyenv VoidNotOK ptrsOK (mkCompiledTupleTy g (evalTupInfoIsStruct tupInfo) args) + | TType_tuple (tupInfo, args) -> GenTypeAux cenv m tyenv VoidNotOK ptrsOK (mkCompiledTupleTy g (evalTupInfoIsStruct tupInfo) args) | TType_fun (dty, returnTy, _) -> EraseClosures.mkILFuncTy cenv.ilxPubCloEnv (GenTypeArgAux cenv m tyenv dty) (GenTypeArgAux cenv m tyenv returnTy) | TType_anon (anonInfo, tinst) -> let tref = anonInfo.ILTypeRef - let boxity = if evalAnonInfoIsStruct anonInfo then ILBoxity.AsValue else ILBoxity.AsObject + + let boxity = + if evalAnonInfoIsStruct anonInfo then + ILBoxity.AsValue + else + ILBoxity.AsObject + GenILTyAppAux cenv m tyenv (tref, boxity, None) tinst | TType_ucase (ucref, args) -> @@ -587,14 +707,15 @@ and GenTypeAux cenv m (tyenv: TypeReprEnv) voidOK ptrsOK ty = | TType_forall (tps, tau) -> let tps = DropErasedTypars tps - if tps.IsEmpty then GenTypeAux cenv m tyenv VoidNotOK ptrsOK tau - else EraseClosures.mkILTyFuncTy cenv.ilxPubCloEnv - | TType_var (tp, _) -> - mkILTyvarTy tyenv[tp, m] + if tps.IsEmpty then + GenTypeAux cenv m tyenv VoidNotOK ptrsOK tau + else + EraseClosures.mkILTyFuncTy cenv.ilxPubCloEnv + + | TType_var (tp, _) -> mkILTyvarTy tyenv[tp, m] - | TType_measure _ -> - g.ilg.typ_Int32 + | TType_measure _ -> g.ilg.typ_Int32 //-------------------------------------------------------------------------- // Generate ILX references to closures, classunions etc. given a tyenv @@ -602,48 +723,70 @@ and GenTypeAux cenv m (tyenv: TypeReprEnv) voidOK ptrsOK ty = and GenUnionCaseRef (cenv: cenv) m tyenv i (fspecs: RecdField[]) = let g = cenv.g - fspecs |> Array.mapi (fun j fspec -> - let ilFieldDef = mkILInstanceField(fspec.LogicalName, GenType cenv m tyenv fspec.FormalType, None, ILMemberAccess.Public) - // These properties on the "field" of an alternative end up going on a property generated by cu_erase.fs - IlxUnionCaseField - (ilFieldDef.With(customAttrs = mkILCustomAttrs [(mkCompilationMappingAttrWithVariantNumAndSeqNum g (int SourceConstructFlags.Field) i j )]))) + fspecs + |> Array.mapi (fun j fspec -> + let ilFieldDef = + mkILInstanceField (fspec.LogicalName, GenType cenv m tyenv fspec.FormalType, None, ILMemberAccess.Public) + // These properties on the "field" of an alternative end up going on a property generated by cu_erase.fs + IlxUnionCaseField( + ilFieldDef.With( + customAttrs = + mkILCustomAttrs + [ + (mkCompilationMappingAttrWithVariantNumAndSeqNum g (int SourceConstructFlags.Field) i j) + ] + ) + )) and GenUnionRef (cenv: cenv) m (tcref: TyconRef) = let g = cenv.g let tycon = tcref.Deref - assert(not tycon.IsTypeAbbrev) + assert (not tycon.IsTypeAbbrev) + match tycon.UnionTypeInfo with | ValueNone -> failwith "GenUnionRef m" | ValueSome funion -> - cached funion.CompiledRepresentation (fun () -> - let tyenvinner = TypeReprEnv.Empty.ForTycon tycon - match tcref.CompiledRepresentation with - | CompiledTypeRepr.ILAsmOpen _ -> failwith "GenUnionRef m: unexpected ASM tyrep" - | CompiledTypeRepr.ILAsmNamed (tref, _, _) -> - let alternatives = - tycon.UnionCasesArray |> Array.mapi (fun i cspec -> - { altName=cspec.CompiledName - altCustomAttrs=emptyILCustomAttrs - altFields = GenUnionCaseRef cenv m tyenvinner i cspec.RecdFieldsArray }) - let nullPermitted = IsUnionTypeWithNullAsTrueValue g tycon - let hasHelpers = ComputeUnionHasHelpers g tcref - let boxity = (if tcref.IsStructOrEnumTycon then ILBoxity.AsValue else ILBoxity.AsObject) - IlxUnionRef(boxity, tref, alternatives, nullPermitted, hasHelpers)) + cached funion.CompiledRepresentation (fun () -> + let tyenvinner = TypeReprEnv.Empty.ForTycon tycon + + match tcref.CompiledRepresentation with + | CompiledTypeRepr.ILAsmOpen _ -> failwith "GenUnionRef m: unexpected ASM tyrep" + | CompiledTypeRepr.ILAsmNamed (tref, _, _) -> + let alternatives = + tycon.UnionCasesArray + |> Array.mapi (fun i cspec -> + { + altName = cspec.CompiledName + altCustomAttrs = emptyILCustomAttrs + altFields = GenUnionCaseRef cenv m tyenvinner i cspec.RecdFieldsArray + }) + + let nullPermitted = IsUnionTypeWithNullAsTrueValue g tycon + let hasHelpers = ComputeUnionHasHelpers g tcref + + let boxity = + (if tcref.IsStructOrEnumTycon then + ILBoxity.AsValue + else + ILBoxity.AsObject) + + IlxUnionRef(boxity, tref, alternatives, nullPermitted, hasHelpers)) and ComputeUnionHasHelpers g (tcref: TyconRef) = - if tyconRefEq g tcref g.unit_tcr_canon then NoHelpers - elif tyconRefEq g tcref g.list_tcr_canon then SpecialFSharpListHelpers - elif tyconRefEq g tcref g.option_tcr_canon then SpecialFSharpOptionHelpers + if tyconRefEq g tcref g.unit_tcr_canon then + NoHelpers + elif tyconRefEq g tcref g.list_tcr_canon then + SpecialFSharpListHelpers + elif tyconRefEq g tcref g.option_tcr_canon then + SpecialFSharpOptionHelpers else - match TryFindFSharpAttribute g g.attrib_DefaultAugmentationAttribute tcref.Attribs with - | Some(Attrib(_, _, [ AttribBoolArg b ], _, _, _, _)) -> - if b then AllHelpers else NoHelpers - | Some (Attrib(_, _, _, _, _, _, m)) -> - errorR(Error(FSComp.SR.ilDefaultAugmentationAttributeCouldNotBeDecoded(), m)) - AllHelpers - | _ -> - AllHelpers (* not hiddenRepr *) + match TryFindFSharpAttribute g g.attrib_DefaultAugmentationAttribute tcref.Attribs with + | Some (Attrib (_, _, [ AttribBoolArg b ], _, _, _, _)) -> if b then AllHelpers else NoHelpers + | Some (Attrib (_, _, _, _, _, _, m)) -> + errorR (Error(FSComp.SR.ilDefaultAugmentationAttributeCouldNotBeDecoded (), m)) + AllHelpers + | _ -> AllHelpers (* not hiddenRepr *) and GenUnionSpec (cenv: cenv) m tyenv tcref tyargs = let curef = GenUnionRef cenv m tcref @@ -659,24 +802,30 @@ and GenType cenv m tyenv ty = and GenTypes cenv m tyenv tys = List.map (GenType cenv m tyenv) tys -and GenTypePermitVoid cenv m tyenv ty = (GenTypeAux cenv m tyenv VoidOK PtrTypesNotOK ty) +and GenTypePermitVoid cenv m tyenv ty = + (GenTypeAux cenv m tyenv VoidOK PtrTypesNotOK ty) -and GenTypesPermitVoid cenv m tyenv tys = List.map (GenTypePermitVoid cenv m tyenv) tys +and GenTypesPermitVoid cenv m tyenv tys = + List.map (GenTypePermitVoid cenv m tyenv) tys and GenTyApp cenv m tyenv repr tyargs = GenTyAppAux cenv m tyenv repr tyargs -and GenNamedTyApp cenv m tyenv tcref tinst = GenNamedTyAppAux cenv m tyenv PtrTypesNotOK tcref tinst +and GenNamedTyApp cenv m tyenv tcref tinst = + GenNamedTyAppAux cenv m tyenv PtrTypesNotOK tcref tinst /// IL void types are only generated for return types and GenReturnType cenv m tyenv returnTyOpt = match returnTyOpt with | None -> ILType.Void | Some returnTy -> - let ilTy = GenTypeAux cenv m tyenv VoidNotOK(*1*) PtrTypesOK returnTy (*1: generate void from unit, but not accept void *) + let ilTy = + GenTypeAux cenv m tyenv VoidNotOK (*1*) PtrTypesOK returnTy (*1: generate void from unit, but not accept void *) + GenReadOnlyModReqIfNecessary cenv.g returnTy ilTy and GenParamType cenv m tyenv isSlotSig ty = let ilTy = GenTypeAux cenv m tyenv VoidNotOK PtrTypesOK ty + if isSlotSig then GenReadOnlyModReqIfNecessary cenv.g ty ilTy else @@ -687,7 +836,8 @@ and GenParamTypes cenv m tyenv isSlotSig tys = and GenTypeArgs cenv m tyenv tyargs = GenTypeArgsAux cenv m tyenv tyargs -and GenTypePermitVoidAux cenv m tyenv ty = GenTypeAux cenv m tyenv VoidOK PtrTypesNotOK ty +and GenTypePermitVoidAux cenv m tyenv ty = + GenTypeAux cenv m tyenv VoidOK PtrTypesNotOK ty // Static fields generally go in a private InitializationCodeAndBackingFields section. This is to ensure all static // fields are initialized only in their class constructors (we generate one primary @@ -705,46 +855,54 @@ and GenTypePermitVoidAux cenv m tyenv ty = GenTypeAux cenv m tyenv VoidOK PtrTyp let GenFieldSpecForStaticField (isInteractive, g, ilContainerTy, vspec: Val, nm, m, cloc, ilTy) = if isInteractive || HasFSharpAttribute g g.attrib_LiteralAttribute vspec.Attribs then let fieldName = vspec.CompiledName g.CompilerGlobalState - let fieldName = if isInteractive then CompilerGeneratedName fieldName else fieldName + + let fieldName = + if isInteractive then + CompilerGeneratedName fieldName + else + fieldName + mkILFieldSpecInTy (ilContainerTy, fieldName, ilTy) else let fieldName = // Ensure that we have an g.CompilerGlobalState - assert(g.CompilerGlobalState |> Option.isSome) - g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName (nm, m) + assert (g.CompilerGlobalState |> Option.isSome) + g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName(nm, m) + let ilFieldContainerTy = mkILTyForCompLoc (CompLocForInitClass cloc) mkILFieldSpecInTy (ilFieldContainerTy, fieldName, ilTy) - let GenRecdFieldRef m cenv (tyenv: TypeReprEnv) (rfref: RecdFieldRef) tyargs = - // Fixup references to the fields of a struct machine template - // templateStructTy = ResumableStateMachine - // templateTyconRef = ResumableStateMachine<'Data> - // templateTypeArgs = - // templateTypeInst = 'Data -> TaskStateMachineData - // cloFreeTyvars = <'FreeTyVars> - // ilCloTy = clo<'FreeTyVars> w.r.t envinner - // rfref = ResumableStateMachine<'Data>::Result - // rfref.RecdField.FormalType = 'Data match tyenv.TemplateReplacement with - | Some (tcref2, ilCloTyRef, cloFreeTyvars, templateTypeInst) when tyconRefEq cenv.g rfref.TyconRef tcref2 -> - let ilCloTy = + | Some (tcref2, ilCloTyRef, cloFreeTyvars, templateTypeInst) when tyconRefEq cenv.g rfref.TyconRef tcref2 -> + // Fixup references to the fields of a struct machine template + // templateStructTy = ResumableStateMachine + // templateTyconRef = ResumableStateMachine<'Data> + // templateTypeArgs = + // templateTypeInst = 'Data -> TaskStateMachineData + // cloFreeTyvars = <'FreeTyVars> + // ilCloTy = clo<'FreeTyVars> w.r.t envinner + // rfref = ResumableStateMachine<'Data>::Result + // rfref.RecdField.FormalType = 'Data + let ilCloTy = let cloInst = List.map mkTyparTy cloFreeTyvars let ilTypeInst = GenTypeArgsAux cenv m tyenv cloInst mkILValueTy ilCloTyRef ilTypeInst let tyenvinner = TypeReprEnv.Empty.ForTypars cloFreeTyvars - mkILFieldSpecInTy(ilCloTy, - ComputeFieldName rfref.Tycon rfref.RecdField, - GenType cenv m tyenvinner (instType templateTypeInst rfref.RecdField.FormalType)) - | _ -> + + mkILFieldSpecInTy ( + ilCloTy, + ComputeFieldName rfref.Tycon rfref.RecdField, + GenType cenv m tyenvinner (instType templateTypeInst rfref.RecdField.FormalType) + ) + | _ -> let tyenvinner = TypeReprEnv.Empty.ForTycon rfref.Tycon let ilTy = GenTyApp cenv m tyenv rfref.TyconRef.CompiledRepresentation tyargs - mkILFieldSpecInTy(ilTy, - ComputeFieldName rfref.Tycon rfref.RecdField, - GenType cenv m tyenvinner rfref.RecdField.FormalType) + mkILFieldSpecInTy (ilTy, ComputeFieldName rfref.Tycon rfref.RecdField, GenType cenv m tyenvinner rfref.RecdField.FormalType) -let GenExnType amap m tyenv (ecref: TyconRef) = GenTyApp amap m tyenv ecref.CompiledRepresentation [] +let GenExnType amap m tyenv (ecref: TyconRef) = + GenTyApp amap m tyenv ecref.CompiledRepresentation [] type ArityInfo = int list @@ -843,45 +1001,44 @@ type ArityInfo = int list [] type IlxClosureInfo = - { /// The whole expression for the closure - cloExpr: Expr + { + /// The whole expression for the closure + cloExpr: Expr - /// The name of the generated closure class - cloName: string + /// The name of the generated closure class + cloName: string - /// The counts of curried arguments for the closure - cloArityInfo: ArityInfo + /// The counts of curried arguments for the closure + cloArityInfo: ArityInfo - /// The formal return type - ilCloFormalReturnTy: ILType + /// The formal return type + ilCloFormalReturnTy: ILType - /// An immutable array of free variable descriptions for the closure - ilCloAllFreeVars: IlxClosureFreeVar[] + /// An immutable array of free variable descriptions for the closure + ilCloAllFreeVars: IlxClosureFreeVar[] - /// The ILX specification for the closure - cloSpec: IlxClosureSpec + /// The ILX specification for the closure + cloSpec: IlxClosureSpec - /// The generic parameters for the closure, i.e. the type variables it captures - cloILGenericParams: ILGenericParameterDefs + /// The generic parameters for the closure, i.e. the type variables it captures + cloILGenericParams: ILGenericParameterDefs - /// The captured variables for the closure - cloFreeVars: Val list + /// The captured variables for the closure + cloFreeVars: Val list - cloFreeTyvars: Typars + cloFreeTyvars: Typars - cloWitnessInfos: TraitWitnessInfos + cloWitnessInfos: TraitWitnessInfos - /// ILX view of the lambdas for the closures - ilCloLambdas: IlxClosureLambdas + /// ILX view of the lambdas for the closures + ilCloLambdas: IlxClosureLambdas } - //-------------------------------------------------------------------------- // ValStorage //-------------------------------------------------------------------------- - /// Describes the storage for a value [] type ValStorage = @@ -901,14 +1058,12 @@ type ValStorage = optShadowLocal: OptionalShadowLocal /// Indicates the value is represented as a property that recomputes it each time it is referenced. Used for simple constants that do not cause initialization triggers - | StaticProperty of - ilGetterMethSpec: ILMethodSpec * - optShadowLocal: OptionalShadowLocal + | StaticProperty of ilGetterMethSpec: ILMethodSpec * optShadowLocal: OptionalShadowLocal /// Indicates the value is represented as an IL method (in a "main" class for a F# /// compilation unit, or as a member) according to its inferred or specified arity. | Method of - topValInfo: ValReprInfo * + valReprInfo: ValReprInfo * valRef: ValRef * ilMethSpec: ILMethodSpec * ilMethSpecWithWitnesses: ILMethodSpec * @@ -922,20 +1077,14 @@ type ValStorage = retInfo: ArgReprInfo /// Indicates the value is stored at the given position in the closure environment accessed via "ldarg 0" - | Env of - ilCloTyInner: ILType * - ilField: ILFieldSpec * - localCloInfo: (FreeTyvars * NamedLocalIlxClosureInfo ref) option + | Env of ilCloTyInner: ILType * ilField: ILFieldSpec * localCloInfo: (FreeTyvars * NamedLocalIlxClosureInfo ref) option /// Indicates that the value is an argument of a method being generated | Arg of index: int /// Indicates that the value is stored in local of the method being generated. NamedLocalIlxClosureInfo is normally empty. /// It is non-empty for 'local type functions', see comments on definition of NamedLocalIlxClosureInfo. - | Local of - index: int * - realloc: bool * - localCloInfo: (FreeTyvars * NamedLocalIlxClosureInfo ref) option + | Local of index: int * realloc: bool * localCloInfo: (FreeTyvars * NamedLocalIlxClosureInfo ref) option /// Indicates if there is a shadow local storage for a local, to make sure it gets a good name in debugging and OptionalShadowLocal = @@ -954,9 +1103,9 @@ and NamedLocalIlxClosureInfo = /// Indicates the overall representation decisions for all the elements of a namespace of module and ModuleStorage = { - Vals: Lazy> + Vals: Lazy> - SubModules: Lazy> + SubModules: Lazy> } override _.ToString() = "" @@ -988,97 +1137,95 @@ and BranchCallItem = /// Represents a place we can branch to and Mark = | Mark of ILCodeLabel + member x.CodeLabel = (let (Mark lab) = x in lab) /// Represents "what to do next after we generate this expression" and sequel = - | EndFilter + | EndFilter - /// Exit a 'handler' block. The integer says which local to save result in - | LeaveHandler of - isFinally: bool * - whereToSaveOpt: (int * ILType) option * - afterHandler: Mark * - hasResult: bool + /// Exit a 'handler' block. The integer says which local to save result in + | LeaveHandler of isFinally: bool * whereToSaveOpt: (int * ILType) option * afterHandler: Mark * hasResult: bool - /// Branch to the given mark - | Br of Mark + /// Branch to the given mark + | Br of Mark - /// Execute the given comparison-then-branch instructions on the result of the expression - /// If the branch isn't taken then drop through. - | CmpThenBrOrContinue of Pops * ILInstr list + /// Execute the given comparison-then-branch instructions on the result of the expression + /// If the branch isn't taken then drop through. + | CmpThenBrOrContinue of Pops * ILInstr list - /// Continue and leave the value on the IL computation stack - | Continue + /// Continue and leave the value on the IL computation stack + | Continue - /// The value then do something else - | DiscardThen of sequel + /// The value then do something else + | DiscardThen of sequel - /// Return from the method - | Return + /// Return from the method + | Return - /// End a scope of local variables. Used at end of 'let' and 'let rec' blocks to get tail recursive setting - /// of end-of-scope marks - | EndLocalScope of sequel * Mark + /// End a scope of local variables. Used at end of 'let' and 'let rec' blocks to get tail recursive setting + /// of end-of-scope marks + | EndLocalScope of sequel * Mark - /// Return from a method whose return type is void - | ReturnVoid + /// Return from a method whose return type is void + | ReturnVoid and Pushes = ILType list and Pops = int /// The overall environment at a particular point in the declaration/expression tree. and IlxGenEnv = - { /// The representation decisions for the (non-erased) type parameters that are in scope - tyenv: TypeReprEnv + { + /// The representation decisions for the (non-erased) type parameters that are in scope + tyenv: TypeReprEnv - /// An ILType for some random type in this assembly - someTypeInThisAssembly: ILType + /// An ILType for some random type in this assembly + someTypeInThisAssembly: ILType - /// Indicates if we are generating code for the last file in a .EXE - isFinalFile: bool + /// Indicates if we are generating code for the last file in a .EXE + isFinalFile: bool - /// Indicates the default "place" for stuff we're currently generating - cloc: CompileLocation + /// Indicates the default "place" for stuff we're currently generating + cloc: CompileLocation - /// The sequel to use for an "early exit" in a state machine, e.g. a return from the middle of an - /// async block - exitSequel: sequel + /// The sequel to use for an "early exit" in a state machine, e.g. a return from the middle of an + /// async block + exitSequel: sequel - /// Hiding information down the signature chain, used to compute what's public to the assembly - sigToImplRemapInfo: (Remap * SignatureHidingInfo) list + /// Hiding information down the signature chain, used to compute what's public to the assembly + sigToImplRemapInfo: (Remap * SignatureHidingInfo) list - /// The open/open-type declarations in scope - imports: ILDebugImports option + /// The open/open-type declarations in scope + imports: ILDebugImports option - /// All values in scope - valsInScope: ValMap> + /// All values in scope + valsInScope: ValMap> - /// All witnesses in scope and their mapping to storage for the witness value. - witnessesInScope: TraitWitnessInfoHashMap + /// All witnesses in scope and their mapping to storage for the witness value. + witnessesInScope: TraitWitnessInfoHashMap - /// Suppress witnesses when not generating witness-passing code - suppressWitnesses: bool + /// Suppress witnesses when not generating witness-passing code + suppressWitnesses: bool - /// For optimizing direct tail recursion to a loop - mark says where to branch to. Length is 0 or 1. - /// REVIEW: generalize to arbitrary nested local loops?? - innerVals: (ValRef * (BranchCallItem * Mark)) list + /// For optimizing direct tail recursion to a loop - mark says where to branch to. Length is 0 or 1. + /// REVIEW: generalize to arbitrary nested local loops?? + innerVals: (ValRef * (BranchCallItem * Mark)) list - /// Full list of enclosing bound values. First non-compiler-generated element is used to help give nice names for closures and other expressions. - letBoundVars: ValRef list + /// Full list of enclosing bound values. First non-compiler-generated element is used to help give nice names for closures and other expressions. + letBoundVars: ValRef list - /// The set of IL local variable indexes currently in use by lexically scoped variables, to allow reuse on different branches. - /// Really an integer set. - liveLocals: IntMap + /// The set of IL local variable indexes currently in use by lexically scoped variables, to allow reuse on different branches. + /// Really an integer set. + liveLocals: IntMap - /// Are we under the scope of a try, catch or finally? If so we can't tailcall. SEH = structured exception handling - withinSEH: bool + /// Are we under the scope of a try, catch or finally? If so we can't tailcall. SEH = structured exception handling + withinSEH: bool - /// Are we inside of a recursive let binding, while loop, or a for loop? - isInLoop: bool + /// Are we inside of a recursive let binding, while loop, or a for loop? + isInLoop: bool - /// Indicates that the .locals init flag should be set on a method and all its nested methods and lambdas - initLocals: bool + /// Indicates that the .locals init flag should be set on a method and all its nested methods and lambdas + initLocals: bool } override _.ToString() = "" @@ -1087,17 +1234,30 @@ let discard = DiscardThen Continue let discardAndReturnVoid = DiscardThen ReturnVoid let SetIsInLoop isInLoop eenv = - if eenv.isInLoop = isInLoop then eenv - else { eenv with isInLoop = isInLoop } + if eenv.isInLoop = isInLoop then + eenv + else + { eenv with isInLoop = isInLoop } -let EnvForTypars tps eenv = {eenv with tyenv = eenv.tyenv.ForTypars tps } +let EnvForTypars tps eenv = + { eenv with + tyenv = eenv.tyenv.ForTypars tps + } -let EnvForTycon tps eenv = {eenv with tyenv = eenv.tyenv.ForTycon tps } +let EnvForTycon tps eenv = + { eenv with + tyenv = eenv.tyenv.ForTycon tps + } -let AddTyparsToEnv typars (eenv: IlxGenEnv) = {eenv with tyenv = eenv.tyenv.Add typars} +let AddTyparsToEnv typars (eenv: IlxGenEnv) = + { eenv with + tyenv = eenv.tyenv.Add typars + } let AddSignatureRemapInfo _msg (rpi, mhi) eenv = - { eenv with sigToImplRemapInfo = (mkRepackageRemapping rpi, mhi) :: eenv.sigToImplRemapInfo } + { eenv with + sigToImplRemapInfo = (mkRepackageRemapping rpi, mhi) :: eenv.sigToImplRemapInfo + } let OutputStorage (pps: TextWriter) s = match s with @@ -1114,7 +1274,10 @@ let OutputStorage (pps: TextWriter) s = //-------------------------------------------------------------------------- let AddStorageForVal (g: TcGlobals) (v, s) eenv = - let eenv = { eenv with valsInScope = eenv.valsInScope.Add v s } + let eenv = + { eenv with + valsInScope = eenv.valsInScope.Add v s + } // If we're compiling fslib then also bind the value as a non-local path to // allow us to resolve the compiler-non-local-references that arise from env.fs // @@ -1134,18 +1297,29 @@ let AddStorageForVal (g: TcGlobals) (v, s) eenv = //System.Diagnostics.Debug.Assert(false, msg) eenv | ValueSome gv -> - { eenv with valsInScope = eenv.valsInScope.Add gv s } + { eenv with + valsInScope = eenv.valsInScope.Add gv s + } else eenv let AddStorageForLocalVals g vals eenv = List.foldBack (fun (v, s) acc -> AddStorageForVal g (v, notlazy s) acc) vals eenv +let RemoveTemplateReplacement eenv = + { eenv with + tyenv = eenv.tyenv.WithoutTemplateReplacement() + } + let AddTemplateReplacement eenv (tcref, ftyvs, ilTy, inst) = - { eenv with tyenv = eenv.tyenv.WithTemplateReplacement (tcref, ftyvs, ilTy, inst) } + { eenv with + tyenv = eenv.tyenv.WithTemplateReplacement(tcref, ftyvs, ilTy, inst) + } -let AddStorageForLocalWitness eenv (w,s) = - { eenv with witnessesInScope = eenv.witnessesInScope.SetItem (w, s) } +let AddStorageForLocalWitness eenv (w, s) = + { eenv with + witnessesInScope = eenv.witnessesInScope.SetItem(w, s) + } let AddStorageForLocalWitnesses witnesses eenv = (eenv, witnesses) ||> List.fold AddStorageForLocalWitness @@ -1154,19 +1328,23 @@ let AddStorageForLocalWitnesses witnesses eenv = // Lookup eenv //-------------------------------------------------------------------------- -let StorageForVal g m v eenv = +let StorageForVal m v eenv = let v = - try eenv.valsInScope[v] + try + eenv.valsInScope[v] with :? KeyNotFoundException -> - assert false - errorR(Error(FSComp.SR.ilUndefinedValue(showL(valAtBindL g v)), m)) - notlazy (Arg 668(* random value for post-hoc diagnostic analysis on generated tree *) ) + assert false + errorR (Error(FSComp.SR.ilUndefinedValue (showL (valAtBindL v)), m)) + notlazy (Arg 668 (* random value for post-hoc diagnostic analysis on generated tree *) ) + v.Force() -let StorageForValRef g m (v: ValRef) eenv = StorageForVal g m v.Deref eenv +let StorageForValRef m (v: ValRef) eenv = StorageForVal m v.Deref eenv let ComputeGenerateWitnesses (g: TcGlobals) eenv = - g.generateWitnesses && not eenv.witnessesInScope.IsEmpty && not eenv.suppressWitnesses + g.generateWitnesses + && not eenv.witnessesInScope.IsEmpty + && not eenv.suppressWitnesses let TryStorageForWitness (_g: TcGlobals) eenv (w: TraitWitnessInfo) = match eenv.witnessesInScope.TryGetValue w with @@ -1182,9 +1360,11 @@ let GetMethodSpecForMemberVal cenv (memberInfo: ValMemberInfo) (vref: ValRef) = let g = cenv.g let m = vref.Range let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal vref.Deref + let tps, witnessInfos, curriedArgInfos, returnTy, retInfo = - assert vref.ValReprInfo.IsSome - GetTopValTypeInCompiledForm g vref.ValReprInfo.Value numEnclosingTypars vref.Type m + assert vref.ValReprInfo.IsSome + GetTopValTypeInCompiledForm g vref.ValReprInfo.Value numEnclosingTypars vref.Type m + let tyenvUnderTypars = TypeReprEnv.Empty.ForTypars tps let flatArgInfos = List.concat curriedArgInfos let isCtor = (memberInfo.MemberFlags.MemberKind = SynMemberKind.Constructor) @@ -1192,7 +1372,10 @@ let GetMethodSpecForMemberVal cenv (memberInfo: ValMemberInfo) (vref: ValRef) = let parentTcref = vref.TopValDeclaringEntity let parentTypars = parentTcref.TyparsNoRange let numParentTypars = parentTypars.Length - if tps.Length < numParentTypars then error(InternalError("CodeGen check: type checking did not ensure that this method is sufficiently generic", m)) + + if tps.Length < numParentTypars then + error (InternalError("CodeGen check: type checking did not ensure that this method is sufficiently generic", m)) + let ctps, mtps = List.splitAt numParentTypars tps let isCompiledAsInstance = ValRefIsCompiledAsInstanceMember g vref @@ -1200,44 +1383,70 @@ let GetMethodSpecForMemberVal cenv (memberInfo: ValMemberInfo) (vref: ValRef) = let ilRetTy = GenReturnType cenv m tyenvUnderTypars returnTy if isCtor || cctor then ILType.Void else ilRetTy - let ilTy = GenType cenv m tyenvUnderTypars (mkAppTy parentTcref (List.map mkTyparTy ctps)) + let ilTy = + GenType cenv m tyenvUnderTypars (mkAppTy parentTcref (List.map mkTyparTy ctps)) let nm = vref.CompiledName g.CompilerGlobalState + if isCompiledAsInstance || isCtor then // Find the 'this' argument type if any let thisTy, flatArgInfos = - if isCtor then (GetFSharpViewOfReturnType g returnTy), flatArgInfos + if isCtor then + (GetFSharpViewOfReturnType g returnTy), flatArgInfos else - match flatArgInfos with - | [] -> error(InternalError("This instance method '" + vref.LogicalName + "' has no arguments", m)) - | (h, _) :: t -> h, t + match flatArgInfos with + | [] -> error (InternalError("This instance method '" + vref.LogicalName + "' has no arguments", m)) + | (h, _) :: t -> h, t let thisTy = if isByrefTy g thisTy then destByrefTy g thisTy else thisTy let thisArgTys = argsOfAppTy g thisTy + if numParentTypars <> thisArgTys.Length then - let msg = - sprintf - "CodeGen check: type checking did not quantify the correct number of type variables for this method, #parentTypars = %d, #mtps = %d, #thisArgTys = %d" - numParentTypars mtps.Length thisArgTys.Length - warning(InternalError(msg, m)) + let msg = + sprintf + "CodeGen check: type checking did not quantify the correct number of type variables for this method, #parentTypars = %d, #mtps = %d, #thisArgTys = %d" + numParentTypars + mtps.Length + thisArgTys.Length + + warning (InternalError(msg, m)) else - List.iter2 - (fun gtp ty2 -> - if not (typeEquiv g (mkTyparTy gtp) ty2) then - warning(InternalError("CodeGen check: type checking did not quantify the correct type variables for this method: generalization list contained " - + gtp.Name + "#" + string gtp.Stamp + " and list from 'this' pointer contained " + (showL(typeL ty2)), m))) - ctps - thisArgTys + List.iter2 + (fun gtp ty2 -> + if not (typeEquiv g (mkTyparTy gtp) ty2) then + warning ( + InternalError( + "CodeGen check: type checking did not quantify the correct type variables for this method: generalization list contained " + + gtp.Name + + "#" + + string gtp.Stamp + + " and list from 'this' pointer contained " + + (showL (typeL ty2)), + m + ) + )) + ctps + thisArgTys + let methodArgTys, paramInfos = List.unzip flatArgInfos - let isSlotSig = memberInfo.MemberFlags.IsDispatchSlot || memberInfo.MemberFlags.IsOverrideOrExplicitImpl + + let isSlotSig = + memberInfo.MemberFlags.IsDispatchSlot + || memberInfo.MemberFlags.IsOverrideOrExplicitImpl + let ilMethodArgTys = GenParamTypes cenv m tyenvUnderTypars isSlotSig methodArgTys let ilMethodInst = GenTypeArgs cenv m tyenvUnderTypars (List.map mkTyparTy mtps) - let mspec = mkILInstanceMethSpecInTy (ilTy, nm, ilMethodArgTys, ilActualRetTy, ilMethodInst) + + let mspec = + mkILInstanceMethSpecInTy (ilTy, nm, ilMethodArgTys, ilActualRetTy, ilMethodInst) + let mspecW = if not g.generateWitnesses || witnessInfos.IsEmpty then mspec else - let ilWitnessArgTys = GenTypes cenv m tyenvUnderTypars (GenWitnessTys g witnessInfos) + let ilWitnessArgTys = + GenTypes cenv m tyenvUnderTypars (GenWitnessTys g witnessInfos) + let nmW = ExtraWitnessMethodName nm mkILInstanceMethSpecInTy (ilTy, nmW, ilWitnessArgTys @ ilMethodArgTys, ilActualRetTy, ilMethodInst) @@ -1246,170 +1455,240 @@ let GetMethodSpecForMemberVal cenv (memberInfo: ValMemberInfo) (vref: ValRef) = let methodArgTys, paramInfos = List.unzip flatArgInfos let ilMethodArgTys = GenParamTypes cenv m tyenvUnderTypars false methodArgTys let ilMethodInst = GenTypeArgs cenv m tyenvUnderTypars (List.map mkTyparTy mtps) - let mspec = mkILStaticMethSpecInTy (ilTy, nm, ilMethodArgTys, ilActualRetTy, ilMethodInst) + + let mspec = + mkILStaticMethSpecInTy (ilTy, nm, ilMethodArgTys, ilActualRetTy, ilMethodInst) + let mspecW = if not g.generateWitnesses || witnessInfos.IsEmpty then mspec else - let ilWitnessArgTys = GenTypes cenv m tyenvUnderTypars (GenWitnessTys g witnessInfos) + let ilWitnessArgTys = + GenTypes cenv m tyenvUnderTypars (GenWitnessTys g witnessInfos) + let nmW = ExtraWitnessMethodName nm mkILStaticMethSpecInTy (ilTy, nmW, ilWitnessArgTys @ ilMethodArgTys, ilActualRetTy, ilMethodInst) mspec, mspecW, ctps, mtps, curriedArgInfos, paramInfos, retInfo, witnessInfos, methodArgTys, returnTy /// Determine how a top-level value is represented, when representing as a field, by computing an ILFieldSpec -let ComputeFieldSpecForVal(optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, isInteractive, g, ilTyForProperty, vspec: Val, nm, m, cloc, ilTy, ilGetterMethRef) = +let ComputeFieldSpecForVal + ( + optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, + isInteractive, + g, + ilTyForProperty, + vspec: Val, + nm, + m, + cloc, + ilTy, + ilGetterMethRef + ) = assert vspec.IsCompiledAsTopLevel - let generate() = GenFieldSpecForStaticField (isInteractive, g, ilTyForProperty, vspec, nm, m, cloc, ilTy) + + let generate () = + GenFieldSpecForStaticField(isInteractive, g, ilTyForProperty, vspec, nm, m, cloc, ilTy) + match optIntraAssemblyInfo with - | None -> generate() + | None -> generate () | Some intraAssemblyInfo -> match intraAssemblyInfo.StaticFieldInfo.TryGetValue ilGetterMethRef with | true, res -> res | _ -> - let res = generate() - intraAssemblyInfo.StaticFieldInfo[ilGetterMethRef] <- res + let res = generate () + intraAssemblyInfo.StaticFieldInfo[ ilGetterMethRef ] <- res res /// Compute the representation information for an F#-declared value (not a member nor a function). /// Mutable and literal static fields must have stable names and live in the "public" location -let ComputeStorageForFSharpValue amap (g:TcGlobals) cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy (vref: ValRef) m = +let ComputeStorageForFSharpValue amap (g: TcGlobals) cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy (vref: ValRef) m = let nm = vref.CompiledName g.CompilerGlobalState let vspec = vref.Deref - let ilTy = GenType amap m TypeReprEnv.Empty returnTy (* TypeReprEnv.Empty ok: not a field in a generic class *) + + let ilTy = + GenType amap m TypeReprEnv.Empty returnTy (* TypeReprEnv.Empty ok: not a field in a generic class *) + let ilTyForProperty = mkILTyForCompLoc cloc let attribs = vspec.Attribs let hasLiteralAttr = HasFSharpAttribute g g.attrib_LiteralAttribute attribs let ilTypeRefForProperty = ilTyForProperty.TypeRef - let ilGetterMethRef = mkILMethRef (ilTypeRefForProperty, ILCallingConv.Static, "get_"+nm, 0, [], ilTy) - let ilSetterMethRef = mkILMethRef (ilTypeRefForProperty, ILCallingConv.Static, "set_"+nm, 0, [ilTy], ILType.Void) - let ilFieldSpec = ComputeFieldSpecForVal(optIntraAssemblyInfo, isInteractive, g, ilTyForProperty, vspec, nm, m, cloc, ilTy, ilGetterMethRef) - StaticPropertyWithField (ilFieldSpec, vref, hasLiteralAttr, ilTyForProperty, nm, ilTy, ilGetterMethRef, ilSetterMethRef, optShadowLocal) + + let ilGetterMethRef = + mkILMethRef (ilTypeRefForProperty, ILCallingConv.Static, "get_" + nm, 0, [], ilTy) + + let ilSetterMethRef = + mkILMethRef (ilTypeRefForProperty, ILCallingConv.Static, "set_" + nm, 0, [ ilTy ], ILType.Void) + + let ilFieldSpec = + ComputeFieldSpecForVal(optIntraAssemblyInfo, isInteractive, g, ilTyForProperty, vspec, nm, m, cloc, ilTy, ilGetterMethRef) + + StaticPropertyWithField(ilFieldSpec, vref, hasLiteralAttr, ilTyForProperty, nm, ilTy, ilGetterMethRef, ilSetterMethRef, optShadowLocal) /// Compute the representation information for an F#-declared member -let ComputeStorageForFSharpMember cenv topValInfo memberInfo (vref: ValRef) m = - let mspec, mspecW, ctps, mtps, curriedArgInfos, paramInfos, retInfo, witnessInfos, methodArgTys, _ = GetMethodSpecForMemberVal cenv memberInfo vref - Method (topValInfo, vref, mspec, mspecW, m, ctps, mtps, curriedArgInfos, paramInfos, witnessInfos, methodArgTys, retInfo) +let ComputeStorageForFSharpMember cenv valReprInfo memberInfo (vref: ValRef) m = + let mspec, mspecW, ctps, mtps, curriedArgInfos, paramInfos, retInfo, witnessInfos, methodArgTys, _ = + GetMethodSpecForMemberVal cenv memberInfo vref + + Method(valReprInfo, vref, mspec, mspecW, m, ctps, mtps, curriedArgInfos, paramInfos, witnessInfos, methodArgTys, retInfo) /// Compute the representation information for an F#-declared function in a module or an F#-declared extension member. /// Note, there is considerable overlap with ComputeStorageForFSharpMember/GetMethodSpecForMemberVal and these could be /// rationalized. -let ComputeStorageForFSharpFunctionOrFSharpExtensionMember (cenv: cenv) cloc topValInfo (vref: ValRef) m = +let ComputeStorageForFSharpFunctionOrFSharpExtensionMember (cenv: cenv) cloc valReprInfo (vref: ValRef) m = let g = cenv.g let nm = vref.CompiledName g.CompilerGlobalState let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal vref.Deref - let tps, witnessInfos, curriedArgInfos, returnTy, retInfo = GetTopValTypeInCompiledForm g topValInfo numEnclosingTypars vref.Type m + + let tps, witnessInfos, curriedArgInfos, returnTy, retInfo = + GetTopValTypeInCompiledForm g valReprInfo numEnclosingTypars vref.Type m + let tyenvUnderTypars = TypeReprEnv.Empty.ForTypars tps let methodArgTys, paramInfos = curriedArgInfos |> List.concat |> List.unzip let ilMethodArgTys = GenParamTypes cenv m tyenvUnderTypars false methodArgTys let ilRetTy = GenReturnType cenv m tyenvUnderTypars returnTy let ilLocTy = mkILTyForCompLoc cloc let ilMethodInst = GenTypeArgs cenv m tyenvUnderTypars (List.map mkTyparTy tps) - let mspec = mkILStaticMethSpecInTy (ilLocTy, nm, ilMethodArgTys, ilRetTy, ilMethodInst) + + let mspec = + mkILStaticMethSpecInTy (ilLocTy, nm, ilMethodArgTys, ilRetTy, ilMethodInst) + let mspecW = if not g.generateWitnesses || witnessInfos.IsEmpty then mspec else - let ilWitnessArgTys = GenTypes cenv m tyenvUnderTypars (GenWitnessTys g witnessInfos) + let ilWitnessArgTys = + GenTypes cenv m tyenvUnderTypars (GenWitnessTys g witnessInfos) + mkILStaticMethSpecInTy (ilLocTy, ExtraWitnessMethodName nm, (ilWitnessArgTys @ ilMethodArgTys), ilRetTy, ilMethodInst) - Method (topValInfo, vref, mspec, mspecW, m, [], tps, curriedArgInfos, paramInfos, witnessInfos, methodArgTys, retInfo) + + Method(valReprInfo, vref, mspec, mspecW, m, [], tps, curriedArgInfos, paramInfos, witnessInfos, methodArgTys, retInfo) /// Determine if an F#-declared value, method or function is compiled as a method. let IsFSharpValCompiledAsMethod g (v: Val) = match v.ValReprInfo with | None -> false - | Some topValInfo -> - not (isUnitTy g v.Type && not v.IsMemberOrModuleBinding && not v.IsMutable) && - not v.IsCompiledAsStaticPropertyWithoutField && - match GetTopValTypeInFSharpForm g topValInfo v.Type v.Range with - | [], [], _, _ when not v.IsMember -> false - | _ -> true + | Some valReprInfo -> + not (isUnitTy g v.Type && not v.IsMemberOrModuleBinding && not v.IsMutable) + && not v.IsCompiledAsStaticPropertyWithoutField + && match GetTopValTypeInFSharpForm g valReprInfo v.Type v.Range with + | [], [], _, _ when not v.IsMember -> false + | _ -> true /// Determine how a top level value is represented, when it is being represented /// as a method. This depends on its type and other representation information. /// If it's a function or is polymorphic, then it gets represented as a /// method (possibly and instance method). Otherwise it gets represented as a /// static field and property. -let ComputeStorageForTopVal (cenv, g, optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, isInteractive, optShadowLocal, vref: ValRef, cloc) = - - if isUnitTy g vref.Type && not vref.IsMemberOrModuleBinding && not vref.IsMutable then - Null - else - let topValInfo = - match vref.ValReprInfo with - | None -> error(InternalError("ComputeStorageForTopVal: no arity found for " + showL(valRefL vref), vref.Range)) - | Some a -> a - - let m = vref.Range - let nm = vref.CompiledName g.CompilerGlobalState - - if vref.Deref.IsCompiledAsStaticPropertyWithoutField then - let nm = "get_"+nm - let tyenvUnderTypars = TypeReprEnv.Empty.ForTypars [] - let ilRetTy = GenType cenv m tyenvUnderTypars vref.Type - let ty = mkILTyForCompLoc cloc - let mspec = mkILStaticMethSpecInTy (ty, nm, [], ilRetTy, []) - - StaticProperty (mspec, optShadowLocal) +let ComputeStorageForTopVal + ( + cenv, + g, + optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, + isInteractive, + optShadowLocal, + vref: ValRef, + cloc + ) = + + if isUnitTy g vref.Type && not vref.IsMemberOrModuleBinding && not vref.IsMutable then + Null else + let valReprInfo = + match vref.ValReprInfo with + | None -> error (InternalError("ComputeStorageForTopVal: no arity found for " + showL (valRefL vref), vref.Range)) + | Some a -> a + + let m = vref.Range + let nm = vref.CompiledName g.CompilerGlobalState + + if vref.Deref.IsCompiledAsStaticPropertyWithoutField then + let nm = "get_" + nm + let tyenvUnderTypars = TypeReprEnv.Empty.ForTypars [] + let ilRetTy = GenType cenv m tyenvUnderTypars vref.Type + let ty = mkILTyForCompLoc cloc + let mspec = mkILStaticMethSpecInTy (ty, nm, [], ilRetTy, []) + + StaticProperty(mspec, optShadowLocal) + else - // Determine when a static field is required. - // - // REVIEW: This call to GetTopValTypeInFSharpForm is only needed to determine if this is a (type) function or a value - // We should just look at the arity - match GetTopValTypeInFSharpForm g topValInfo vref.Type vref.Range with - | [], [], returnTy, _ when not vref.IsMember -> - ComputeStorageForFSharpValue cenv g cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy vref m - | _ -> - match vref.MemberInfo with - | Some memberInfo when not vref.IsExtensionMember -> - ComputeStorageForFSharpMember cenv topValInfo memberInfo vref m + // Determine when a static field is required. + // + // REVIEW: This call to GetTopValTypeInFSharpForm is only needed to determine if this is a (type) function or a value + // We should just look at the arity + match GetTopValTypeInFSharpForm g valReprInfo vref.Type vref.Range with + | [], [], returnTy, _ when not vref.IsMember -> + ComputeStorageForFSharpValue cenv g cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy vref m | _ -> - ComputeStorageForFSharpFunctionOrFSharpExtensionMember cenv cloc topValInfo vref m + match vref.MemberInfo with + | Some memberInfo when not vref.IsExtensionMember -> ComputeStorageForFSharpMember cenv valReprInfo memberInfo vref m + | _ -> ComputeStorageForFSharpFunctionOrFSharpExtensionMember cenv cloc valReprInfo vref m /// Determine how an F#-declared value, function or member is represented, if it is in the assembly being compiled. let ComputeAndAddStorageForLocalTopVal (cenv, g, intraAssemblyFieldTable, isInteractive, optShadowLocal) cloc (v: Val) eenv = - let storage = ComputeStorageForTopVal (cenv, g, Some intraAssemblyFieldTable, isInteractive, optShadowLocal, mkLocalValRef v, cloc) + let storage = + ComputeStorageForTopVal(cenv, g, Some intraAssemblyFieldTable, isInteractive, optShadowLocal, mkLocalValRef v, cloc) + AddStorageForVal g (v, notlazy storage) eenv /// Determine how an F#-declared value, function or member is represented, if it is an external assembly. let ComputeStorageForNonLocalTopVal cenv g cloc modref (v: Val) = match v.ValReprInfo with - | None -> error(InternalError("ComputeStorageForNonLocalTopVal, expected an arity for " + v.LogicalName, v.Range)) - | Some _ -> ComputeStorageForTopVal (cenv, g, None, false, NoShadowLocal, mkNestedValRef modref v, cloc) + | None -> error (InternalError("ComputeStorageForNonLocalTopVal, expected an arity for " + v.LogicalName, v.Range)) + | Some _ -> ComputeStorageForTopVal(cenv, g, None, false, NoShadowLocal, mkNestedValRef modref v, cloc) /// Determine how all the F#-declared top level values, functions and members are represented, for an external module or namespace. let rec AddStorageForNonLocalModuleOrNamespaceRef cenv g cloc acc (modref: ModuleOrNamespaceRef) (modul: ModuleOrNamespace) = let acc = - (acc, modul.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions) ||> List.fold (fun acc smodul -> - AddStorageForNonLocalModuleOrNamespaceRef cenv g (CompLocForSubModuleOrNamespace cloc smodul) acc (modref.NestedTyconRef smodul) smodul) + (acc, modul.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions) + ||> List.fold (fun acc smodul -> + AddStorageForNonLocalModuleOrNamespaceRef + cenv + g + (CompLocForSubModuleOrNamespace cloc smodul) + acc + (modref.NestedTyconRef smodul) + smodul) let acc = - (acc, modul.ModuleOrNamespaceType.AllValsAndMembers) ||> Seq.fold (fun acc v -> - AddStorageForVal g (v, lazy (ComputeStorageForNonLocalTopVal cenv g cloc modref v)) acc) + (acc, modul.ModuleOrNamespaceType.AllValsAndMembers) + ||> Seq.fold (fun acc v -> AddStorageForVal g (v, lazy (ComputeStorageForNonLocalTopVal cenv g cloc modref v)) acc) + acc /// Determine how all the F#-declared top level values, functions and members are represented, for an external assembly. let AddStorageForExternalCcu cenv g eenv (ccu: CcuThunk) = - if not ccu.IsFSharp then eenv else - let cloc = CompLocForCcu ccu - let eenv = - List.foldBack - (fun smodul acc -> - let cloc = CompLocForSubModuleOrNamespace cloc smodul - let modref = mkNonLocalCcuRootEntityRef ccu smodul - AddStorageForNonLocalModuleOrNamespaceRef cenv g cloc acc modref smodul) - ccu.RootModulesAndNamespaces - eenv - let eenv = - let eref = ERefNonLocalPreResolved ccu.Contents (mkNonLocalEntityRef ccu [| |]) - (eenv, ccu.Contents.ModuleOrNamespaceType.AllValsAndMembers) ||> Seq.fold (fun acc v -> - AddStorageForVal g (v, lazy (ComputeStorageForNonLocalTopVal cenv g cloc eref v)) acc) - eenv + if not ccu.IsFSharp then + eenv + else + let cloc = CompLocForCcu ccu + + let eenv = + List.foldBack + (fun smodul acc -> + let cloc = CompLocForSubModuleOrNamespace cloc smodul + let modref = mkNonLocalCcuRootEntityRef ccu smodul + AddStorageForNonLocalModuleOrNamespaceRef cenv g cloc acc modref smodul) + ccu.RootModulesAndNamespaces + eenv + + let eenv = + let eref = ERefNonLocalPreResolved ccu.Contents (mkNonLocalEntityRef ccu [||]) + + (eenv, ccu.Contents.ModuleOrNamespaceType.AllValsAndMembers) + ||> Seq.fold (fun acc v -> AddStorageForVal g (v, lazy (ComputeStorageForNonLocalTopVal cenv g cloc eref v)) acc) + + eenv /// Record how all the top level F#-declared values, functions and members are represented, for a local module or namespace. let rec AddBindingsForLocalModuleType allocVal cloc eenv (mty: ModuleOrNamespaceType) = - let eenv = List.fold (fun eenv submodul -> AddBindingsForLocalModuleType allocVal (CompLocForSubModuleOrNamespace cloc submodul) eenv submodul.ModuleOrNamespaceType) eenv mty.ModuleAndNamespaceDefinitions + let eenv = + List.fold + (fun eenv submodul -> + AddBindingsForLocalModuleType allocVal (CompLocForSubModuleOrNamespace cloc submodul) eenv submodul.ModuleOrNamespaceType) + eenv + mty.ModuleAndNamespaceDefinitions + let eenv = Seq.fold (fun eenv v -> allocVal cloc v eenv) eenv mty.AllValsAndMembers eenv @@ -1420,94 +1699,121 @@ let AddExternalCcusToIlxGenEnv cenv g eenv ccus = /// Record how all the unrealized abstract slots are represented, for a type definition. let AddBindingsForTycon allocVal (cloc: CompileLocation) (tycon: Tycon) eenv = let unrealizedSlots = - if tycon.IsFSharpObjectModelTycon - then tycon.FSharpObjectModelTypeInfo.fsobjmodel_vslots - else [] - (eenv, unrealizedSlots) ||> List.fold (fun eenv vref -> allocVal cloc vref.Deref eenv) + if tycon.IsFSharpObjectModelTycon then + tycon.FSharpObjectModelTypeInfo.fsobjmodel_vslots + else + [] + + (eenv, unrealizedSlots) + ||> List.fold (fun eenv vref -> allocVal cloc vref.Deref eenv) /// Record how constructs are represented, for a sequence of definitions in a module or namespace fragment. let AddDebugImportsToEnv (cenv: cenv) eenv (openDecls: OpenDeclaration list) = let ilImports = - [| - for openDecl in openDecls do - for modul in openDecl.Modules do - if modul.IsNamespace then - ILDebugImport.ImportNamespace (fullDisplayTextOfModRef modul) - else - ILDebugImport.ImportType (mkILNonGenericBoxedTy modul.CompiledRepresentationForNamedType) - for t in openDecl.Types do - let m = defaultArg openDecl.Range Range.range0 - ILDebugImport.ImportType (GenType cenv m TypeReprEnv.Empty t) + [| + for openDecl in openDecls do + for modul in openDecl.Modules do + if modul.IsNamespace then + ILDebugImport.ImportNamespace(fullDisplayTextOfModRef modul) + else + ILDebugImport.ImportType(mkILNonGenericBoxedTy modul.CompiledRepresentationForNamedType) + + for t in openDecl.Types do + let m = defaultArg openDecl.Range Range.range0 + ILDebugImport.ImportType(GenType cenv m TypeReprEnv.Empty t) |] if ilImports.Length = 0 then eenv else // We flatten _all_ the import scopes, creating repetition, because C# debug engine doesn't seem to handle - // nesting of import scopes at all. This means every new "open" in, say, a nested module in F# causes - // duplication of all the implicit/enclosing "open" in within the debug information. + // nesting of import scopes at all. This means every new "open" in, say, a nested module in F# causes + // duplication of all the implicit/enclosing "open" in within the debug information. // However overall there are not very many "open" declarations and debug information can be large // so this is not considered a problem. let imports = - [| match eenv.imports with - | None -> () - | Some parent -> yield! parent.Imports - yield! ilImports |] - |> Array.filter (function + [| + match eenv.imports with + | None -> () + | Some parent -> yield! parent.Imports + yield! ilImports + |] + |> Array.filter (function | ILDebugImport.ImportNamespace _ -> true | ILDebugImport.ImportType t -> - t.IsNominal && + t.IsNominal + && // We filter out FSI_NNNN types (dynamic modules), since we don't really need them in the import tables. - not (t.QualifiedName.StartsWithOrdinal FsiDynamicModulePrefix - && t.TypeRef.Scope = ILScopeRef.Local )) - |> Array.distinctBy (function + not ( + t.QualifiedName.StartsWithOrdinal FsiDynamicModulePrefix + && t.TypeRef.Scope = ILScopeRef.Local + )) + |> Array.distinctBy (function | ILDebugImport.ImportNamespace nsp -> nsp | ILDebugImport.ImportType t -> t.QualifiedName) - - { eenv with imports = Some { Parent = None; Imports = imports } } + + { eenv with + imports = Some { Parent = None; Imports = imports } + } let rec AddBindingsForModuleContents allocVal cloc eenv x = match x with - | TMDefRec(_isRec, _opens, tycons, mbinds, _) -> + | TMDefRec (_isRec, _opens, tycons, mbinds, _) -> // Virtual don't have 'let' bindings and must be added to the environment let eenv = List.foldBack (AddBindingsForTycon allocVal cloc) tycons eenv let eenv = List.foldBack (AddBindingsForModuleBinding allocVal cloc) mbinds eenv eenv - | TMDefLet(bind, _) -> - allocVal cloc bind.Var eenv - | TMDefDo _ -> - eenv - | TMDefOpens _-> - eenv - | TMDefs mdefs -> - (eenv, mdefs) ||> List.fold (AddBindingsForModuleContents allocVal cloc) + | TMDefLet (bind, _) -> allocVal cloc bind.Var eenv + | TMDefDo _ -> eenv + | TMDefOpens _ -> eenv + | TMDefs mdefs -> (eenv, mdefs) ||> List.fold (AddBindingsForModuleContents allocVal cloc) /// Record how constructs are represented, for a module or namespace. and AddBindingsForModuleBinding allocVal cloc x eenv = match x with - | ModuleOrNamespaceBinding.Binding bind -> - allocVal cloc bind.Var eenv + | ModuleOrNamespaceBinding.Binding bind -> allocVal cloc bind.Var eenv | ModuleOrNamespaceBinding.Module (mspec, mdef) -> let cloc = - if mspec.IsNamespace then cloc - else CompLocForFixedModule cloc.QualifiedNameOfFile cloc.TopImplQualifiedName mspec + if mspec.IsNamespace then + cloc + else + CompLocForFixedModule cloc.QualifiedNameOfFile cloc.TopImplQualifiedName mspec AddBindingsForModuleContents allocVal cloc eenv mdef /// Record how constructs are represented, for the values and functions defined in a module or namespace fragment. -and AddBindingsForModuleTopVals _g allocVal _cloc eenv vs = - List.foldBack allocVal vs eenv +and AddBindingsForModuleTopVals _g allocVal _cloc eenv vs = List.foldBack allocVal vs eenv /// Put the partial results for a generated fragment (i.e. a part of a CCU generated by FSI) /// into the stored results for the whole CCU. /// isIncrementalFragment = true --> "typed input" /// isIncrementalFragment = false --> "#load" -let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (cenv: cenv, isIncrementalFragment, g, ccu, fragName, intraAssemblyInfo, eenv, implFiles) = +let AddIncrementalLocalAssemblyFragmentToIlxGenEnv + ( + cenv: cenv, + isIncrementalFragment, + g, + ccu, + fragName, + intraAssemblyInfo, + eenv, + implFiles + ) = let cloc = CompLocForFragment fragName ccu - let allocVal = ComputeAndAddStorageForLocalTopVal (cenv, g, intraAssemblyInfo, true, NoShadowLocal) - (eenv, implFiles) ||> List.fold (fun eenv implFile -> - let (CheckedImplFile (qualifiedNameOfFile=qname; signature=signature; contents=contents)) = implFile - let cloc = { cloc with TopImplQualifiedName = qname.Text } + + let allocVal = + ComputeAndAddStorageForLocalTopVal(cenv, g, intraAssemblyInfo, true, NoShadowLocal) + + (eenv, implFiles) + ||> List.fold (fun eenv implFile -> + let (CheckedImplFile (qualifiedNameOfFile = qname; signature = signature; contents = contents)) = + implFile + + let cloc = + { cloc with + TopImplQualifiedName = qname.Text + } + if isIncrementalFragment then AddBindingsForModuleContents allocVal cloc eenv contents else @@ -1519,17 +1825,19 @@ let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (cenv: cenv, isIncrementalFra /// Generate IL debugging information. let GenILSourceMarker (g: TcGlobals) (m: range) = - ILDebugPoint.Create(document=g.memoize_file m.FileIndex, - line=m.StartLine, - // NOTE: .NET && VS measure first column as column 1 - column= m.StartColumn+1, - endLine= m.EndLine, - endColumn=m.EndColumn+1) + ILDebugPoint.Create( + document = g.memoize_file m.FileIndex, + line = m.StartLine, + // NOTE: .NET && VS measure first column as column 1 + column = m.StartColumn + 1, + endLine = m.EndLine, + endColumn = m.EndColumn + 1 + ) /// Optionally generate DebugRange for methods. This gets attached to the whole method. let GenPossibleILDebugRange (cenv: cenv) m = if cenv.options.generateDebugSymbols then - Some (GenILSourceMarker cenv.g m ) + Some(GenILSourceMarker cenv.g m) else None @@ -1538,40 +1846,38 @@ let GenPossibleILDebugRange (cenv: cenv) m = //-------------------------------------------------------------------------- let HashRangeSorted (ht: IDictionary<_, int * _>) = - [ for KeyValue(_k, v) in ht -> v ] |> List.sortBy fst |> List.map snd + [ for KeyValue (_k, v) in ht -> v ] |> List.sortBy fst |> List.map snd let MergeOptions m o1 o2 = match o1, o2 with - | Some x, None | None, Some x -> Some x + | Some x, None + | None, Some x -> Some x | None, None -> None | Some x, Some _ -> #if DEBUG - // This warning fires on some code that also triggers this warning: - // The implementation of a specified generic interface - // required a method implementation not fully supported by F# Interactive. In - // the unlikely event that the resulting class fails to load then compile - // the interface type into a statically-compiled DLL and reference it using '#r' - // The code is OK so we don't print this. - errorR(InternalError("MergeOptions: two values given", m)) + // This warning fires on some code that also triggers this warning: + // The implementation of a specified generic interface + // required a method implementation not fully supported by F# Interactive. In + // the unlikely event that the resulting class fails to load then compile + // the interface type into a statically-compiled DLL and reference it using '#r' + // The code is OK so we don't print this. + errorR (InternalError("MergeOptions: two values given", m)) #else - ignore m + ignore m #endif - Some x + Some x let MergePropertyPair m (pd: ILPropertyDef) (pdef: ILPropertyDef) = - pd.With(getMethod=MergeOptions m pd.GetMethod pdef.GetMethod, - setMethod=MergeOptions m pd.SetMethod pdef.SetMethod) + pd.With(getMethod = MergeOptions m pd.GetMethod pdef.GetMethod, setMethod = MergeOptions m pd.SetMethod pdef.SetMethod) type PropKey = PropKey of string * ILTypes * ILThisConvention let AddPropertyDefToHash (m: range) (ht: Dictionary) (pdef: ILPropertyDef) = let nm = PropKey(pdef.Name, pdef.Args, pdef.CallingConv) - match ht.TryGetValue nm with - | true, (idx, pd) -> - ht[nm] <- (idx, MergePropertyPair m pd pdef) - | _ -> - ht[nm] <- (ht.Count, pdef) + match ht.TryGetValue nm with + | true, (idx, pd) -> ht[nm] <- (idx, MergePropertyPair m pd pdef) + | _ -> ht[nm] <- (ht.Count, pdef) /// Merge a whole group of properties all at once let MergePropertyDefs m ilPropertyDefs = @@ -1587,16 +1893,21 @@ let MergePropertyDefs m ilPropertyDefs = type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = let gmethods = ResizeArray(0) let gfields = ResizeArray(0) - let gproperties: Dictionary = Dictionary<_, _>(3, HashIdentity.Structural) + + let gproperties: Dictionary = + Dictionary<_, _>(3, HashIdentity.Structural) + let gevents = ResizeArray(0) let gnested = TypeDefsBuilder() member b.Close() = - tdef.With(methods = mkILMethods (tdef.Methods.AsList() @ ResizeArray.toList gmethods), - fields = mkILFields (tdef.Fields.AsList() @ ResizeArray.toList gfields), - properties = mkILProperties (tdef.Properties.AsList() @ HashRangeSorted gproperties ), - events = mkILEvents (tdef.Events.AsList() @ ResizeArray.toList gevents), - nestedTypes = mkILTypeDefs (tdef.NestedTypes.AsList() @ gnested.Close())) + tdef.With( + methods = mkILMethods (tdef.Methods.AsList() @ ResizeArray.toList gmethods), + fields = mkILFields (tdef.Fields.AsList() @ ResizeArray.toList gfields), + properties = mkILProperties (tdef.Properties.AsList() @ HashRangeSorted gproperties), + events = mkILEvents (tdef.Events.AsList() @ ResizeArray.toList gevents), + nestedTypes = mkILTypeDefs (tdef.NestedTypes.AsList() @ gnested.Close()) + ) member b.AddEventDef edef = gevents.Add edef @@ -1607,6 +1918,7 @@ type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = match tdefDiscards with | Some (mdefDiscard, _) -> mdefDiscard ilMethodDef | None -> false + if not discard then gmethods.Add ilMethodDef @@ -1621,6 +1933,7 @@ type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = match tdefDiscards with | Some (_, pdefDiscard) -> pdefDiscard pdef | None -> false + if not discard then AddPropertyDefToHash m gproperties pdef @@ -1628,12 +1941,15 @@ type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = match ResizeArray.tryFindIndex cond gmethods with | Some idx -> gmethods[idx] <- prependInstrsToMethod instrs gmethods[idx] | None -> - let body = mkMethodBody (false, [], 1, nonBranchingInstrsToCode instrs, tag, imports) - gmethods.Add(mkILClassCtor body) + let body = + mkMethodBody (false, [], 1, nonBranchingInstrsToCode instrs, tag, imports) + gmethods.Add(mkILClassCtor body) and TypeDefsBuilder() = - let tdefs: HashMultiMap = HashMultiMap(0, HashIdentity.Structural) + let tdefs: HashMultiMap = + HashMultiMap(0, HashIdentity.Structural) + let mutable countDown = System.Int32.MaxValue member b.Close() = @@ -1641,20 +1957,26 @@ and TypeDefsBuilder() = // Ideally it shouldn't matter which order we use. // However, for some tests FSI generated code appears sensitive to the order, especially for nested types. - [ for b, eliminateIfEmpty in HashRangeSorted tdefs do - let tdef = b.Close() - // Skip the type if it is empty - if not eliminateIfEmpty - || not (tdef.NestedTypes.AsList()).IsEmpty - || not (tdef.Fields.AsList()).IsEmpty - || not (tdef.Events.AsList()).IsEmpty - || not (tdef.Properties.AsList()).IsEmpty - || not (Array.isEmpty (tdef.Methods.AsArray())) then - yield tdef ] + [ + for b, eliminateIfEmpty in HashRangeSorted tdefs do + let tdef = b.Close() + // Skip the type if it is empty + if + not eliminateIfEmpty + || not (tdef.NestedTypes.AsList()).IsEmpty + || not (tdef.Fields.AsList()).IsEmpty + || not (tdef.Events.AsList()).IsEmpty + || not (tdef.Properties.AsList()).IsEmpty + || not (Array.isEmpty (tdef.Methods.AsArray())) + then + yield tdef + ] member b.FindTypeDefBuilder nm = - try tdefs[nm] |> snd |> fst - with :? KeyNotFoundException -> failwith ("FindTypeDefBuilder: " + nm + " not found") + try + tdefs[nm] |> snd |> fst + with :? KeyNotFoundException -> + failwith ("FindTypeDefBuilder: " + nm + " not found") member b.FindNestedTypeDefsBuilder path = List.fold (fun (acc: TypeDefsBuilder) x -> acc.FindTypeDefBuilder(x).NestedTypeDefs) b path @@ -1663,171 +1985,267 @@ and TypeDefsBuilder() = b.FindNestedTypeDefsBuilder(tref.Enclosing).FindTypeDefBuilder(tref.Name) member b.AddTypeDef(tdef: ILTypeDef, eliminateIfEmpty, addAtEnd, tdefDiscards) = - let idx = if addAtEnd then (countDown <- countDown - 1; countDown) else tdefs.Count - tdefs.Add (tdef.Name, (idx, (TypeDefBuilder(tdef, tdefDiscards), eliminateIfEmpty))) + let idx = + if addAtEnd then + (countDown <- countDown - 1 + countDown) + else + tdefs.Count + + tdefs.Add(tdef.Name, (idx, (TypeDefBuilder(tdef, tdefDiscards), eliminateIfEmpty))) type AnonTypeGenerationTable() = // Dictionary is safe here as it will only be used during the codegen stage - will happen on a single thread. - let dict = Dictionary(HashIdentity.Structural) + let dict = + Dictionary(HashIdentity.Structural) + member _.Table = dict /// Assembly generation buffers type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf = let g = cenv.g // The Abstract IL table of types - let gtdefs= TypeDefsBuilder() + let gtdefs = TypeDefsBuilder() // The definitions of top level values, as quotations. // Dictionary is safe here as it will only be used during the codegen stage - will happen on a single thread. - let mutable reflectedDefinitions: Dictionary = Dictionary(HashIdentity.Reference) + let mutable reflectedDefinitions: Dictionary = + Dictionary(HashIdentity.Reference) + let mutable extraBindingsToGenerate = [] // A memoization table for generating value types for big constant arrays let rawDataValueTypeGenerator = - MemoizationTable( + MemoizationTable( (fun (cloc, size) -> - let name = CompilerGeneratedName ("T" + string(newUnique()) + "_" + string size + "Bytes") // Type names ending ...$T_37Bytes - let vtdef = mkRawDataValueTypeDef g.iltyp_ValueType (name, size, 0us) - let vtref = NestedTypeRefForCompLoc cloc vtdef.Name - let vtspec = mkILTySpec(vtref, []) - let vtdef = vtdef.WithAccess(ComputeTypeAccess vtref true) - mgbuf.AddTypeDef(vtref, vtdef, false, true, None) - vtspec), - keyComparer=HashIdentity.Structural) + let name = + CompilerGeneratedName("T" + string (newUnique ()) + "_" + string size + "Bytes") // Type names ending ...$T_37Bytes + + let vtdef = mkRawDataValueTypeDef g.iltyp_ValueType (name, size, 0us) + let vtref = NestedTypeRefForCompLoc cloc vtdef.Name + let vtspec = mkILTySpec (vtref, []) + let vtdef = vtdef.WithAccess(ComputeTypeAccess vtref true) + mgbuf.AddTypeDef(vtref, vtdef, false, true, None) + vtspec), + keyComparer = HashIdentity.Structural + ) let generateAnonType genToStringMethod (isStruct, ilTypeRef, nms) = - let propTys = [ for i, nm in Array.indexed nms -> nm, ILType.TypeVar (uint16 i) ] + let propTys = [ for i, nm in Array.indexed nms -> nm, ILType.TypeVar(uint16 i) ] // Note that this alternative below would give the same names as C#, but the generated // comparison/equality doesn't know about these names. //let flds = [ for (i, nm) in Array.indexed nms -> (nm, "<" + nm + ">" + "i__Field", ILType.TypeVar (uint16 i)) ] - let ilCtorRef = mkILMethRef(ilTypeRef, ILCallingConv.Instance, ".ctor", 0, List.map snd propTys, ILType.Void) + let ilCtorRef = + mkILMethRef (ilTypeRef, ILCallingConv.Instance, ".ctor", 0, List.map snd propTys, ILType.Void) let ilMethodRefs = - [| for propName, propTy in propTys -> - mkILMethRef (ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], propTy) |] + [| + for propName, propTy in propTys -> mkILMethRef (ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], propTy) + |] - let ilTy = mkILNamedTy (if isStruct then ILBoxity.AsValue else ILBoxity.AsObject) ilTypeRef (List.map snd propTys) + let ilTy = + mkILNamedTy (if isStruct then ILBoxity.AsValue else ILBoxity.AsObject) ilTypeRef (List.map snd propTys) if ilTypeRef.Scope.IsLocalRef then - let flds = [ for i, nm in Array.indexed nms -> (nm, nm + "@", ILType.TypeVar (uint16 i)) ] + let flds = + [ for i, nm in Array.indexed nms -> (nm, nm + "@", ILType.TypeVar(uint16 i)) ] let ilGenericParams = - [ for nm in nms -> - { Name = sprintf "<%s>j__TPar" nm - Constraints = [] - Variance=NonVariant - CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs - HasReferenceTypeConstraint=false - HasNotNullableValueTypeConstraint=false - HasDefaultConstructorConstraint= false - MetadataIndex = NoMetadataIdx } ] - - let ilTy = mkILFormalNamedTy (if isStruct then ILBoxity.AsValue else ILBoxity.AsObject) ilTypeRef ilGenericParams + [ + for nm in nms -> + { + Name = sprintf "<%s>j__TPar" nm + Constraints = [] + Variance = NonVariant + CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs + HasReferenceTypeConstraint = false + HasNotNullableValueTypeConstraint = false + HasDefaultConstructorConstraint = false + MetadataIndex = NoMetadataIdx + } + ] + + let ilTy = + mkILFormalNamedTy (if isStruct then ILBoxity.AsValue else ILBoxity.AsObject) ilTypeRef ilGenericParams // Generate the IL fields let ilFieldDefs = mkILFields - [ for _, fldName, fldTy in flds -> - // Don't hide fields when splitting to multiple assemblies. - let access = - if cenv.options.isInteractive && cenv.options.fsiMultiAssemblyEmit then ILMemberAccess.Public - else ILMemberAccess.Private - let fdef = mkILInstanceField (fldName, fldTy, None, access) - fdef.With(customAttrs = mkILCustomAttrs [ g.DebuggerBrowsableNeverAttribute ]) ] + [ + for _, fldName, fldTy in flds -> + // Don't hide fields when splitting to multiple assemblies. + let access = + if cenv.options.isInteractive && cenv.options.fsiMultiAssemblyEmit then + ILMemberAccess.Public + else + ILMemberAccess.Private + + let fdef = mkILInstanceField (fldName, fldTy, None, access) + fdef.With(customAttrs = mkILCustomAttrs [ g.DebuggerBrowsableNeverAttribute ]) + ] // Generate property definitions for the fields compiled as properties let ilProperties = mkILProperties - [ for i, (propName, _fldName, fldTy) in List.indexed flds -> - ILPropertyDef(name=propName, - attributes=PropertyAttributes.None, - setMethod=None, - getMethod=Some(mkILMethRef(ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], fldTy )), - callingConv=ILCallingConv.Instance.ThisConv, - propertyType=fldTy, - init= None, - args=[], - customAttrs=mkILCustomAttrs [ mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i ]) ] + [ + for i, (propName, _fldName, fldTy) in List.indexed flds -> + ILPropertyDef( + name = propName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some(mkILMethRef (ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], fldTy)), + callingConv = ILCallingConv.Instance.ThisConv, + propertyType = fldTy, + init = None, + args = [], + customAttrs = mkILCustomAttrs [ mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i ] + ) + ] let ilMethods = - [ for propName, fldName, fldTy in flds -> - mkLdfldMethodDef ("get_" + propName, ILMemberAccess.Public, false, ilTy, fldName, fldTy) - yield! genToStringMethod ilTy ] + [ + for propName, fldName, fldTy in flds -> + let attrs = if isStruct then [ GenReadOnlyAttribute g ] else [] + mkLdfldMethodDef ("get_" + propName, ILMemberAccess.Public, false, ilTy, fldName, fldTy, attrs) + yield! genToStringMethod ilTy + ] let ilBaseTy = (if isStruct then g.iltyp_ValueType else g.ilg.typ_Object) let ilBaseTySpec = (if isStruct then None else Some ilBaseTy.TypeSpec) - let ilCtorDef = mkILSimpleStorageCtorWithParamNames(ilBaseTySpec, ilTy, [], flds, ILMemberAccess.Public, None, None) + + let ilCtorDef = + mkILSimpleStorageCtorWithParamNames (ilBaseTySpec, ilTy, [], flds, ILMemberAccess.Public, None, None) // Create a tycon that looks exactly like a record definition, to help drive the generation of equality/comparison code let m = range0 + let tps = - [ for nm in nms -> - let stp = SynTypar(mkSynId m ("T"+nm), TyparStaticReq.None, true) - Construct.NewTypar (TyparKind.Type, TyparRigidity.WarnIfNotRigid, stp, false, TyparDynamicReq.Yes, [], true, true) ] + [ + for nm in nms -> + let stp = SynTypar(mkSynId m ("T" + nm), TyparStaticReq.None, true) + Construct.NewTypar(TyparKind.Type, TyparRigidity.WarnIfNotRigid, stp, false, TyparDynamicReq.Yes, [], true, true) + ] let tycon = - let lmtyp = MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType ModuleOrType) + let lmtyp = MaybeLazy.Strict(Construct.NewEmptyModuleOrNamespaceType ModuleOrType) let cpath = CompPath(ilTypeRef.Scope, []) - Construct.NewTycon(Some cpath, ilTypeRef.Name, m, taccessPublic, taccessPublic, TyparKind.Type, LazyWithContext.NotLazy tps, XmlDoc.Empty, false, false, false, lmtyp) + + Construct.NewTycon( + Some cpath, + ilTypeRef.Name, + m, + taccessPublic, + taccessPublic, + TyparKind.Type, + LazyWithContext.NotLazy tps, + XmlDoc.Empty, + false, + false, + false, + lmtyp + ) if isStruct then tycon.SetIsStructRecordOrUnion true tycon.entity_tycon_repr <- - TFSharpRecdRepr - (Construct.MakeRecdFieldsTable - ((tps, flds) ||> List.map2 (fun tp (propName, _fldName, _fldTy) -> - Construct.NewRecdField false None (mkSynId m propName) false (mkTyparTy tp) true false [] [] XmlDoc.Empty taccessPublic false))) + TFSharpRecdRepr( + Construct.MakeRecdFieldsTable( + (tps, flds) + ||> List.map2 (fun tp (propName, _fldName, _fldTy) -> + Construct.NewRecdField + false + None + (mkSynId m propName) + false + (mkTyparTy tp) + true + false + [] + [] + XmlDoc.Empty + taccessPublic + false) + ) + ) let tcref = mkLocalTyconRef tycon - let typ = generalizedTyconRef g tcref + let ty = generalizedTyconRef g tcref let tcaug = tcref.TypeContents tcaug.tcaug_interfaces <- - [ (g.mk_IStructuralComparable_ty, true, m) - (g.mk_IComparable_ty, true, m) - (mkAppTy g.system_GenericIComparable_tcref [typ], true, m) - (g.mk_IStructuralEquatable_ty, true, m) - (mkAppTy g.system_GenericIEquatable_tcref [typ], true, m) ] + [ + (g.mk_IStructuralComparable_ty, true, m) + (g.mk_IComparable_ty, true, m) + (mkAppTy g.system_GenericIComparable_tcref [ ty ], true, m) + (g.mk_IStructuralEquatable_ty, true, m) + (mkAppTy g.system_GenericIEquatable_tcref [ ty ], true, m) + ] let vspec1, vspec2 = AugmentWithHashCompare.MakeValsForEqualsAugmentation g tcref - let evspec1, evspec2, evspec3 = AugmentWithHashCompare.MakeValsForEqualityWithComparerAugmentation g tcref + + let evspec1, evspec2, evspec3 = + AugmentWithHashCompare.MakeValsForEqualityWithComparerAugmentation g tcref + let cvspec1, cvspec2 = AugmentWithHashCompare.MakeValsForCompareAugmentation g tcref - let cvspec3 = AugmentWithHashCompare.MakeValsForCompareWithComparerAugmentation g tcref - tcaug.SetCompare (mkLocalValRef cvspec1, mkLocalValRef cvspec2) - tcaug.SetCompareWith (mkLocalValRef cvspec3) - tcaug.SetEquals (mkLocalValRef vspec1, mkLocalValRef vspec2) - tcaug.SetHashAndEqualsWith (mkLocalValRef evspec1, mkLocalValRef evspec2, mkLocalValRef evspec3) + let cvspec3 = + AugmentWithHashCompare.MakeValsForCompareWithComparerAugmentation g tcref + + tcaug.SetCompare(mkLocalValRef cvspec1, mkLocalValRef cvspec2) + tcaug.SetCompareWith(mkLocalValRef cvspec3) + tcaug.SetEquals(mkLocalValRef vspec1, mkLocalValRef vspec2) + tcaug.SetHashAndEqualsWith(mkLocalValRef evspec1, mkLocalValRef evspec2, mkLocalValRef evspec3) // Build the ILTypeDef. We don't rely on the normal record generation process because we want very specific field names - let ilTypeDefAttribs = mkILCustomAttrs [ g.CompilerGeneratedAttribute; mkCompilationMappingAttr g (int SourceConstructFlags.RecordType) ] + let ilTypeDefAttribs = + mkILCustomAttrs + [ + g.CompilerGeneratedAttribute + mkCompilationMappingAttr g (int SourceConstructFlags.RecordType) + ] - let ilInterfaceTys = [ for ity, _, _ in tcaug.tcaug_interfaces -> GenType cenv m (TypeReprEnv.Empty.ForTypars tps) ity ] + let ilInterfaceTys = + [ + for intfTy, _, _ in tcaug.tcaug_interfaces -> GenType cenv m (TypeReprEnv.Empty.ForTypars tps) intfTy + ] let ilTypeDef = - mkILGenericClass (ilTypeRef.Name, ILTypeDefAccess.Public, ilGenericParams, ilBaseTy, ilInterfaceTys, - mkILMethods (ilCtorDef :: ilMethods), ilFieldDefs, emptyILTypeDefs, - ilProperties, mkILEvents [], ilTypeDefAttribs, - ILTypeInit.BeforeField) + mkILGenericClass ( + ilTypeRef.Name, + ILTypeDefAccess.Public, + ilGenericParams, + ilBaseTy, + ilInterfaceTys, + mkILMethods (ilCtorDef :: ilMethods), + ilFieldDefs, + emptyILTypeDefs, + ilProperties, + mkILEvents [], + ilTypeDefAttribs, + ILTypeInit.BeforeField + ) let ilTypeDef = ilTypeDef.WithSealed(true).WithSerializable(true) mgbuf.AddTypeDef(ilTypeRef, ilTypeDef, false, true, None) let extraBindings = - [ yield! AugmentWithHashCompare.MakeBindingsForCompareAugmentation g tycon - yield! AugmentWithHashCompare.MakeBindingsForCompareWithComparerAugmentation g tycon - yield! AugmentWithHashCompare.MakeBindingsForEqualityWithComparerAugmentation g tycon - yield! AugmentWithHashCompare.MakeBindingsForEqualsAugmentation g tycon ] + [ + yield! AugmentWithHashCompare.MakeBindingsForCompareAugmentation g tycon + yield! AugmentWithHashCompare.MakeBindingsForCompareWithComparerAugmentation g tycon + yield! AugmentWithHashCompare.MakeBindingsForEqualityWithComparerAugmentation g tycon + yield! AugmentWithHashCompare.MakeBindingsForEqualsAugmentation g tycon + ] let optimizedExtraBindings = - extraBindings |> List.map (fun (TBind(a, b, c)) -> + extraBindings + |> List.map (fun (TBind (a, b, c)) -> // Disable method splitting for bindings related to anonymous records TBind(a, cenv.optimizeDuringCodeGen true b, c)) @@ -1840,96 +2258,124 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu /// static init fields on script modules. let mutable scriptInitFspecs: (ILFieldSpec * range) list = [] - member _.AddScriptInitFieldSpec (fieldSpec, range) = + member _.AddScriptInitFieldSpec(fieldSpec, range) = scriptInitFspecs <- (fieldSpec, range) :: scriptInitFspecs /// This initializes the script in #load and fsc command-line order causing their /// side effects to be executed. - member mgbuf.AddInitializeScriptsInOrderToEntryPoint (imports) = + member mgbuf.AddInitializeScriptsInOrderToEntryPoint(imports) = // Get the entry point and initialized any scripts in order. match explicitEntryPointInfo with | Some tref -> - let InitializeCompiledScript(fspec, m) = + let InitializeCompiledScript (fspec, m) = let ilDebugRange = GenPossibleILDebugRange cenv m - mgbuf.AddExplicitInitToSpecificMethodDef((fun (md: ILMethodDef) -> md.IsEntryPoint), tref, fspec, ilDebugRange, imports, [], []) + + mgbuf.AddExplicitInitToSpecificMethodDef( + (fun (md: ILMethodDef) -> md.IsEntryPoint), + tref, + fspec, + ilDebugRange, + imports, + [], + [] + ) + scriptInitFspecs |> List.iter InitializeCompiledScript | None -> () - member _.GenerateRawDataValueType (cloc, size) = + member _.GenerateRawDataValueType(cloc, size) = // Byte array literals require a ValueType of size the required number of bytes. // With fsi.exe, S.R.Emit TypeBuilder CreateType has restrictions when a ValueType VT is nested inside a type T, and T has a field of type VT. // To avoid this situation, these ValueTypes are generated under the private implementation rather than in the current cloc. [was bug 1532]. let cloc = CompLocForPrivateImplementationDetails cloc rawDataValueTypeGenerator.Apply((cloc, size)) - member _.GenerateAnonType (genToStringMethod, anonInfo: AnonRecdTypeInfo) = + member _.GenerateAnonType(genToStringMethod, anonInfo: AnonRecdTypeInfo) = let isStruct = evalAnonInfoIsStruct anonInfo let key = anonInfo.Stamp + if not (anonTypeTable.Table.ContainsKey key) then - let info = generateAnonType genToStringMethod (isStruct, anonInfo.ILTypeRef, anonInfo.SortedNames) - anonTypeTable.Table[key] <- info + let info = + generateAnonType genToStringMethod (isStruct, anonInfo.ILTypeRef, anonInfo.SortedNames) + + anonTypeTable.Table[ key ] <- info - member this.LookupAnonType (genToStringMethod, anonInfo: AnonRecdTypeInfo) = + member this.LookupAnonType(genToStringMethod, anonInfo: AnonRecdTypeInfo) = match anonTypeTable.Table.TryGetValue anonInfo.Stamp with | true, res -> res | _ -> - if anonInfo.ILTypeRef.Scope.IsLocalRef then - failwithf "the anonymous record %A has not been generated in the pre-phase of generating this module" anonInfo.ILTypeRef - this.GenerateAnonType (genToStringMethod, anonInfo) - anonTypeTable.Table[anonInfo.Stamp] + if anonInfo.ILTypeRef.Scope.IsLocalRef then + failwithf "the anonymous record %A has not been generated in the pre-phase of generating this module" anonInfo.ILTypeRef - member _.GrabExtraBindingsToGenerate () = + this.GenerateAnonType(genToStringMethod, anonInfo) + anonTypeTable.Table[anonInfo.Stamp] + + member _.GrabExtraBindingsToGenerate() = let result = extraBindingsToGenerate extraBindingsToGenerate <- [] result - member _.AddTypeDef (tref: ILTypeRef, tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) = - gtdefs.FindNestedTypeDefsBuilder(tref.Enclosing).AddTypeDef(tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) + member _.AddTypeDef(tref: ILTypeRef, tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) = + gtdefs + .FindNestedTypeDefsBuilder(tref.Enclosing) + .AddTypeDef(tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) - member _.GetCurrentFields (tref: ILTypeRef) = + member _.GetCurrentFields(tref: ILTypeRef) = gtdefs.FindNestedTypeDefBuilder(tref).GetCurrentFields() - member _.AddReflectedDefinition (vspec: Val, expr) = + member _.AddReflectedDefinition(vspec: Val, expr) = // preserve order by storing index of item let n = reflectedDefinitions.Count reflectedDefinitions.Add(vspec, (vspec.CompiledName cenv.g.CompilerGlobalState, n, expr)) - member _.ReplaceNameOfReflectedDefinition (vspec, newName) = + member _.ReplaceNameOfReflectedDefinition(vspec, newName) = match reflectedDefinitions.TryGetValue vspec with | true, (name, n, expr) when name <> newName -> reflectedDefinitions[vspec] <- (newName, n, expr) | _ -> () - member _.AddMethodDef (tref: ILTypeRef, ilMethodDef) = + member _.AddMethodDef(tref: ILTypeRef, ilMethodDef) = gtdefs.FindNestedTypeDefBuilder(tref).AddMethodDef(ilMethodDef) + if ilMethodDef.IsEntryPoint then explicitEntryPointInfo <- Some tref - member _.AddExplicitInitToSpecificMethodDef (cond, tref, fspec, sourceOpt, imports, feefee, seqpt) = + member _.AddExplicitInitToSpecificMethodDef(cond, tref, fspec, sourceOpt, imports, feefee, seqpt) = // Authoring a .cctor with effects forces the cctor for the 'initialization' module by doing a dummy store & load of a field // Doing both a store and load keeps FxCop happier because it thinks the field is useful let instrs = - [ yield! (if condition "NO_ADD_FEEFEE_TO_CCTORS" then [] elif condition "ADD_SEQPT_TO_CCTORS" then seqpt else feefee) // mark start of hidden code - yield mkLdcInt32 0 - yield mkNormalStsfld fspec - yield mkNormalLdsfld fspec - yield AI_pop] - gtdefs.FindNestedTypeDefBuilder(tref).PrependInstructionsToSpecificMethodDef(cond, instrs, sourceOpt, imports) - - member _.AddEventDef (tref, edef) = + [ + yield! + (if condition "NO_ADD_FEEFEE_TO_CCTORS" then [] + elif condition "ADD_SEQPT_TO_CCTORS" then seqpt + else feefee) // mark start of hidden code + yield mkLdcInt32 0 + yield mkNormalStsfld fspec + yield mkNormalLdsfld fspec + yield AI_pop + ] + + gtdefs + .FindNestedTypeDefBuilder(tref) + .PrependInstructionsToSpecificMethodDef(cond, instrs, sourceOpt, imports) + + member _.AddEventDef(tref, edef) = gtdefs.FindNestedTypeDefBuilder(tref).AddEventDef(edef) - member _.AddFieldDef (tref, ilFieldDef) = + member _.AddFieldDef(tref, ilFieldDef) = gtdefs.FindNestedTypeDefBuilder(tref).AddFieldDef(ilFieldDef) - member _.AddOrMergePropertyDef (tref, pdef, m) = + member _.AddOrMergePropertyDef(tref, pdef, m) = gtdefs.FindNestedTypeDefBuilder(tref).AddOrMergePropertyDef(pdef, m) member _.Close() = // old implementation adds new element to the head of list so result was accumulated in reversed order let orderedReflectedDefinitions = - [for KeyValue(vspec, (name, n, expr)) in reflectedDefinitions -> n, ((name, vspec), expr)] + [ + for KeyValue (vspec, (name, n, expr)) in reflectedDefinitions -> n, ((name, vspec), expr) + ] |> List.sortBy (fst >> (~-)) // invert the result to get 'order-by-descending' behavior (items in list are 0..* so we don't need to worry about int.MinValue) |> List.map snd + gtdefs.Close(), orderedReflectedDefinitions member _.cenv = cenv @@ -1939,22 +2385,21 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu /// Record the types of the things on the evaluation stack. /// Used for the few times we have to flush the IL evaluation stack and to compute maxStack. let pop (i: int) : Pops = i -let Push tys: Pushes = tys + +let Push tys : Pushes = tys let Push0 = Push [] -let FeeFee (cenv: cenv) = (if cenv.options.testFlagEmitFeeFeeAs100001 then 100001 else 0x00feefee) +let FeeFee (cenv: cenv) = + (if cenv.options.testFlagEmitFeeFeeAs100001 then + 100001 + else + 0x00feefee) + let FeeFeeInstr (cenv: cenv) doc = - I_seqpoint (ILDebugPoint.Create(document = doc, - line = FeeFee cenv, - column = 0, - endLine = FeeFee cenv, - endColumn = 0)) + I_seqpoint(ILDebugPoint.Create(document = doc, line = FeeFee cenv, column = 0, endLine = FeeFee cenv, endColumn = 0)) /// Buffers for IL code generation -type CodeGenBuffer(m: range, - mgbuf: AssemblyBuilder, - methodName, - alreadyUsedArgs: int) = +type CodeGenBuffer(m: range, mgbuf: AssemblyBuilder, methodName, alreadyUsedArgs: int) = let g = mgbuf.cenv.g let locals = ResizeArray<(string * (Mark * Mark)) list * ILType * bool>(10) @@ -1970,46 +2415,58 @@ type CodeGenBuffer(m: range, let mutable anyDocument = None // we collect an arbitrary document in order to emit the header FeeFee if needed let codeLabelToPC: Dictionary = Dictionary<_, _>(10) - let codeLabelToCodeLabel: Dictionary = Dictionary<_, _>(10) + + let codeLabelToCodeLabel: Dictionary = + Dictionary<_, _>(10) let rec lab2pc n lbl = - if n = System.Int32.MaxValue then error(InternalError("recursive label graph", m)) + if n = System.Int32.MaxValue then + error (InternalError("recursive label graph", m)) + match codeLabelToCodeLabel.TryGetValue lbl with | true, l -> lab2pc (n + 1) l | _ -> codeLabelToPC[lbl] // Add a nop to make way for the first debug point. - do if mgbuf.cenv.options.generateDebugSymbols then - let doc = g.memoize_file m.FileIndex - let i = FeeFeeInstr mgbuf.cenv doc - codebuf.Add i // for the FeeFee or a better debug point + do + if mgbuf.cenv.options.generateDebugSymbols then + let doc = g.memoize_file m.FileIndex + let i = FeeFeeInstr mgbuf.cenv doc + codebuf.Add i // for the FeeFee or a better debug point - member _.DoPushes (pushes: Pushes) = + member _.DoPushes(pushes: Pushes) = for ty in pushes do - stack <- ty :: stack - nstack <- nstack + 1 - maxStack <- Operators.max maxStack nstack + stack <- ty :: stack + nstack <- nstack + 1 + maxStack <- Operators.max maxStack nstack - member _.DoPops (n: Pops) = + member _.DoPops(n: Pops) = for i = 0 to n - 1 do - match stack with - | [] -> - let msg = sprintf "pop on empty stack during code generation, methodName = %s, m = %s" methodName (stringOfRange m) - System.Diagnostics.Debug.Assert(false, msg) - warning(InternalError(msg, m)) - | _ :: t -> - stack <- t - nstack <- nstack - 1 + match stack with + | [] -> + let msg = + sprintf "pop on empty stack during code generation, methodName = %s, m = %s" methodName (stringOfRange m) + + System.Diagnostics.Debug.Assert(false, msg) + warning (InternalError(msg, m)) + | _ :: t -> + stack <- t + nstack <- nstack - 1 member _.GetCurrentStack() = stack member _.AssertEmptyStack() = if not (isNil stack) then let msg = - sprintf "stack flush didn't work, or extraneous expressions left on stack before stack restore, methodName = %s, stack = %+A, m = %s" - methodName stack (stringOfRange m) + sprintf + "stack flush didn't work, or extraneous expressions left on stack before stack restore, methodName = %s, stack = %+A, m = %s" + methodName + stack + (stringOfRange m) + System.Diagnostics.Debug.Assert(false, msg) - warning(InternalError(msg, m)) + warning (InternalError(msg, m)) + () member cgbuf.EmitInstr(pops, pushes, i) = @@ -2017,7 +2474,7 @@ type CodeGenBuffer(m: range, cgbuf.DoPushes pushes codebuf.Add i - member cgbuf.EmitInstrs (pops, pushes, is) = + member cgbuf.EmitInstrs(pops, pushes, is) = cgbuf.DoPops pops cgbuf.DoPushes pushes is |> List.iter codebuf.Add @@ -2025,14 +2482,16 @@ type CodeGenBuffer(m: range, member private _.EnsureNopBetweenDebugPoints() = // Always add a nop between debug points to help .NET get the stepping right // Don't do this after a FeeFee marker for hidden code - if (codebuf.Count > 0 && - (match codebuf[codebuf.Count-1] with - | I_seqpoint sm when sm.Line <> FeeFee mgbuf.cenv -> true - | _ -> false)) then + if + (codebuf.Count > 0 + && (match codebuf[codebuf.Count - 1] with + | I_seqpoint sm when sm.Line <> FeeFee mgbuf.cenv -> true + | _ -> false)) + then codebuf.Add(AI_nop) - member cgbuf.EmitDebugPoint (m: range) = + member cgbuf.EmitDebugPoint(m: range) = if mgbuf.cenv.options.generateDebugSymbols then let attr = GenILSourceMarker g m @@ -2041,13 +2500,14 @@ type CodeGenBuffer(m: range, // Replace a FeeFee seqpoint with a better debug point let n = codebuf.Count + let isSingleFeeFee = - match codebuf[n-1] with + match codebuf[n - 1] with | I_seqpoint sm -> (sm.Line = FeeFee mgbuf.cenv) | _ -> false if isSingleFeeFee then - codebuf[n-1] <- i + codebuf[n - 1] <- i else cgbuf.EnsureNopBetweenDebugPoints() codebuf.Add i @@ -2063,8 +2523,9 @@ type CodeGenBuffer(m: range, // don't emit just after another FeeFee let n = codebuf.Count + let isSingleFeeFee = - match codebuf[n-1] with + match codebuf[n - 1] with | I_seqpoint sm -> (sm.Line = FeeFee mgbuf.cenv) | _ -> false @@ -2072,45 +2533,48 @@ type CodeGenBuffer(m: range, cgbuf.EnsureNopBetweenDebugPoints() codebuf.Add i - member _.EmitExceptionClause clause = - exnSpecs.Add clause + member _.EmitExceptionClause clause = exnSpecs.Add clause member _.GenerateDelayMark(_nm) = - let lab = generateCodeLabel() - Mark lab + let lab = generateCodeLabel () + Mark lab member _.SetCodeLabelToCodeLabel(lab1, lab2) = #if DEBUG if codeLabelToCodeLabel.ContainsKey lab1 then - let msg = sprintf "two values given for label %s, methodName = %s, m = %s" (formatCodeLabel lab1) methodName (stringOfRange m) + let msg = + sprintf "two values given for label %s, methodName = %s, m = %s" (formatCodeLabel lab1) methodName (stringOfRange m) + System.Diagnostics.Debug.Assert(false, msg) - warning(InternalError(msg, m)) + warning (InternalError(msg, m)) #endif codeLabelToCodeLabel[lab1] <- lab2 member _.SetCodeLabelToPC(lab, pc) = #if DEBUG if codeLabelToPC.ContainsKey lab then - let msg = sprintf "two values given for label %s, methodName = %s, m = %s" (formatCodeLabel lab) methodName (stringOfRange m) + let msg = + sprintf "two values given for label %s, methodName = %s, m = %s" (formatCodeLabel lab) methodName (stringOfRange m) + System.Diagnostics.Debug.Assert(false, msg) - warning(InternalError(msg, m)) + warning (InternalError(msg, m)) #endif codeLabelToPC[lab] <- pc - member cgbuf.SetMark (mark1: Mark, mark2: Mark) = + member cgbuf.SetMark(mark1: Mark, mark2: Mark) = cgbuf.SetCodeLabelToCodeLabel(mark1.CodeLabel, mark2.CodeLabel) - member cgbuf.SetMarkToHere (Mark lab) = + member cgbuf.SetMarkToHere(Mark lab) = cgbuf.SetCodeLabelToPC(lab, codebuf.Count) - member cgbuf.SetMarkToHereIfNecessary (inplabOpt: Mark option) = + member cgbuf.SetMarkToHereIfNecessary(inplabOpt: Mark option) = match inplabOpt with | None -> () | Some inplab -> cgbuf.SetMarkToHere inplab - member cgbuf.SetMarkOrEmitBranchIfNecessary (inplabOpt: Mark option, target: Mark) = + member cgbuf.SetMarkOrEmitBranchIfNecessary(inplabOpt: Mark option, target: Mark) = match inplabOpt with - | None -> cgbuf.EmitInstr (pop 0, Push0, I_br target.CodeLabel) + | None -> cgbuf.EmitInstr(pop 0, Push0, I_br target.CodeLabel) | Some inplab -> cgbuf.SetMark(inplab, target) member cgbuf.SetStack s = @@ -2137,10 +2601,9 @@ type CodeGenBuffer(m: range, match ResizeArray.tryFindIndexi cond locals with | Some j -> let prevRanges, _, isFixed = locals[j] - locals[j] <- ((ranges@prevRanges), ty, isFixed) + locals[j] <- ((ranges @ prevRanges), ty, isFixed) j, true - | None -> - cgbuf.AllocLocal(ranges, ty, isFixed), false + | None -> cgbuf.AllocLocal(ranges, ty, isFixed), false member _.Close() = @@ -2148,8 +2611,15 @@ type CodeGenBuffer(m: range, // Fixup the first instruction to be a FeeFee debug point if needed let instrs = - instrs |> Array.mapi (fun idx i2 -> - if idx = 0 && (match i2 with AI_nop -> true | _ -> false) && anyDocument.IsSome then + instrs + |> Array.mapi (fun idx i2 -> + if + idx = 0 + && (match i2 with + | AI_nop -> true + | _ -> false) + && anyDocument.IsSome + then // This special dummy debug point says skip the start of the method hasDebugPoints <- true FeeFeeInstr mgbuf.cenv anyDocument.Value @@ -2158,8 +2628,13 @@ type CodeGenBuffer(m: range, let codeLabels = let dict = Dictionary.newWithSize (codeLabelToPC.Count + codeLabelToCodeLabel.Count) - for kvp in codeLabelToPC do dict.Add(kvp.Key, lab2pc 0 kvp.Key) - for kvp in codeLabelToCodeLabel do dict.Add(kvp.Key, lab2pc 0 kvp.Key) + + for kvp in codeLabelToPC do + dict.Add(kvp.Key, lab2pc 0 kvp.Key) + + for kvp in codeLabelToCodeLabel do + dict.Add(kvp.Key, lab2pc 0 kvp.Key) + dict (ResizeArray.toList locals, maxStack, codeLabels, instrs, ResizeArray.toList exnSpecs, hasDebugPoints) @@ -2179,36 +2654,44 @@ module CG = //-------------------------------------------------------------------------- let GenString cenv cgbuf s = - CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.ilg.typ_String]) (I_ldstr s) + CG.EmitInstr cgbuf (pop 0) (Push [ cenv.g.ilg.typ_String ]) (I_ldstr s) -let GenConstArray cenv (cgbuf: CodeGenBuffer) eenv ilElementType (data:'a[]) (write: ByteBuffer -> 'a -> unit) = +let GenConstArray cenv (cgbuf: CodeGenBuffer) eenv ilElementType (data: 'a[]) (write: ByteBuffer -> 'a -> unit) = let g = cenv.g use buf = ByteBuffer.Create data.Length data |> Array.iter (write buf) let bytes = buf.AsMemory().ToArray() let ilArrayType = mkILArr1DTy ilElementType + if data.Length = 0 then - CG.EmitInstrs cgbuf (pop 0) (Push [ilArrayType]) [ mkLdcInt32 0; I_newarr (ILArrayShape.SingleDimensional, ilElementType); ] + CG.EmitInstrs cgbuf (pop 0) (Push [ ilArrayType ]) [ mkLdcInt32 0; I_newarr(ILArrayShape.SingleDimensional, ilElementType) ] else let vtspec = cgbuf.mgbuf.GenerateRawDataValueType(eenv.cloc, bytes.Length) - let ilFieldName = CompilerGeneratedName ("field" + string(newUnique())) + let ilFieldName = CompilerGeneratedName("field" + string (newUnique ())) let fty = ILType.Value vtspec - let ilFieldDef = mkILStaticField (ilFieldName, fty, None, Some bytes, ILMemberAccess.Assembly) - let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs [ g.DebuggerBrowsableNeverAttribute ]) + + let ilFieldDef = + mkILStaticField (ilFieldName, fty, None, Some bytes, ILMemberAccess.Assembly) + + let ilFieldDef = + ilFieldDef.With(customAttrs = mkILCustomAttrs [ g.DebuggerBrowsableNeverAttribute ]) + let fspec = mkILFieldSpecInTy (mkILTyForCompLoc eenv.cloc, ilFieldName, fty) CountStaticFieldDef() cgbuf.mgbuf.AddFieldDef(fspec.DeclaringTypeRef, ilFieldDef) - CG.EmitInstrs cgbuf - (pop 0) - (Push [ ilArrayType; ilArrayType; g.iltyp_RuntimeFieldHandle ]) - [ mkLdcInt32 data.Length - I_newarr (ILArrayShape.SingleDimensional, ilElementType) - AI_dup - I_ldtoken (ILToken.ILField fspec) ] - CG.EmitInstr cgbuf - (pop 2) - Push0 - (mkNormalCall (mkInitializeArrayMethSpec g)) + + CG.EmitInstrs + cgbuf + (pop 0) + (Push [ ilArrayType; ilArrayType; g.iltyp_RuntimeFieldHandle ]) + [ + mkLdcInt32 data.Length + I_newarr(ILArrayShape.SingleDimensional, ilElementType) + AI_dup + I_ldtoken(ILToken.ILField fspec) + ] + + CG.EmitInstr cgbuf (pop 2) Push0 (mkNormalCall (mkInitializeArrayMethSpec g)) //------------------------------------------------------------------------- // This is the main code generation routine. It is used to generate @@ -2221,21 +2704,27 @@ let CodeGenThen (cenv: cenv) mgbuf (entryPointInfo, methodName, eenv, alreadyUse let finish = CG.GenerateDelayMark cgbuf "mfinish" let innerVals = entryPointInfo |> List.map (fun (v, kind) -> (v, (kind, start))) - // When debugging, put the "this" parameter in a local that has the right name + // When debugging, put the "this" parameter in a local that has the right name match selfArgOpt with - | Some selfArg when selfArg.LogicalName <> "this" && not (selfArg.LogicalName.StartsWith("_")) && not cenv.options.localOptimizationsEnabled -> + | Some selfArg when + selfArg.LogicalName <> "this" + && not (selfArg.LogicalName.StartsWith("_")) + && not cenv.options.localOptimizationsEnabled + -> let ilTy = selfArg.Type |> GenType cenv m eenv.tyenv - let idx = cgbuf.AllocLocal([(selfArg.LogicalName, (start, finish)) ], ilTy, false) + let idx = cgbuf.AllocLocal([ (selfArg.LogicalName, (start, finish)) ], ilTy, false) cgbuf.EmitStartOfHiddenCode() - CG.EmitInstrs cgbuf (pop 0) Push0 [ mkLdarg0; I_stloc (uint16 idx) ] + CG.EmitInstrs cgbuf (pop 0) Push0 [ mkLdarg0; I_stloc(uint16 idx) ] | _ -> () // Call the given code generator - codeGenFunction cgbuf + codeGenFunction + cgbuf { eenv with - withinSEH=false - liveLocals=IntMap.empty() - innerVals = innerVals} + withinSEH = false + liveLocals = IntMap.empty () + innerVals = innerVals + } cgbuf.SetMarkToHere finish @@ -2246,42 +2735,43 @@ let CodeGenThen (cenv: cenv) mgbuf (entryPointInfo, methodName, eenv, alreadyUse |> List.mapi (fun i (nms, _, _isFixed) -> List.map (fun nm -> (i, nm)) nms) |> List.concat |> List.map (fun (i, (nm, (start, finish))) -> - { Range=(start.CodeLabel, finish.CodeLabel) - DebugMappings= [{ LocalIndex=i; LocalName=nm }] }) + { + Range = (start.CodeLabel, finish.CodeLabel) + DebugMappings = [ { LocalIndex = i; LocalName = nm } ] + }) let ilLocals = locals |> List.map (fun (infos, ty, isFixed) -> - let loc = - // in interactive environment, attach name and range info to locals to improve debug experience - if cenv.options.isInteractive && cenv.options.generateDebugSymbols then - match infos with - | [(nm, (start, finish))] -> mkILLocal ty (Some(nm, start.CodeLabel, finish.CodeLabel)) - // REVIEW: what do these cases represent? - | _ :: _ - | [] -> mkILLocal ty None - // if not interactive, don't bother adding this info - else - mkILLocal ty None - if isFixed then { loc with IsPinned=true } else loc) + let loc = + // in interactive environment, attach name and range info to locals to improve debug experience + if cenv.options.isInteractive && cenv.options.generateDebugSymbols then + match infos with + | [ (nm, (start, finish)) ] -> mkILLocal ty (Some(nm, start.CodeLabel, finish.CodeLabel)) + // REVIEW: what do these cases represent? + | _ :: _ + | [] -> mkILLocal ty None + // if not interactive, don't bother adding this info + else + mkILLocal ty None - (ilLocals, - maxStack, - lab2pc, - code, - exnSpecs, - localDebugSpecs, - hasDebugPoints) + if isFixed then { loc with IsPinned = true } else loc) + + (ilLocals, maxStack, lab2pc, code, exnSpecs, localDebugSpecs, hasDebugPoints) let CodeGenMethod cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, selfArgOpt, codeGenFunction, m) = let locals, maxStack, lab2pc, instrs, exns, localDebugSpecs, hasDebugPoints = - CodeGenThen cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, selfArgOpt, codeGenFunction, m) + CodeGenThen cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, selfArgOpt, codeGenFunction, m) let code = buildILCode methodName lab2pc instrs exns localDebugSpecs // Attach a source range to the method. Only do this if it has some debug points. - let ilDebugRange = if hasDebugPoints then GenPossibleILDebugRange cenv m else None + let ilDebugRange = + if hasDebugPoints then + GenPossibleILDebugRange cenv m + else + None let ilImports = eenv.imports @@ -2289,8 +2779,9 @@ let CodeGenMethod cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, let maxStack = maxStack + 2 // Build an Abstract IL method - let body = mkILMethodBody (eenv.initLocals, locals, maxStack, code, ilDebugRange, ilImports) - + let body = + mkILMethodBody (eenv.initLocals, locals, maxStack, code, ilDebugRange, ilImports) + instrs, body let StartDelayedLocalScope nm cgbuf = @@ -2324,7 +2815,8 @@ let BindingEmitsNoCode g (b: Binding) = IsFSharpValCompiledAsMethod g b.Var /// /// Returns (useWholeExprRange, sequencePointForBind, sequencePointGenerationFlagForRhsOfBind) let ComputeDebugPointForBinding g bind = - let (TBind(_, e, spBind)) = bind + let (TBind (_, e, spBind)) = bind + if BindingEmitsNoCode g bind then false, None else @@ -2334,7 +2826,9 @@ let ComputeDebugPointForBinding g bind = | DebugPointAtBinding.NoneAtDo, _ -> false, None | DebugPointAtBinding.NoneAtLet, _ -> false, None // Don't emit debug points for lambdas. - | _, (Expr.Lambda _ | Expr.TyLambda _) -> false, None + | _, + (Expr.Lambda _ + | Expr.TyLambda _) -> false, None | DebugPointAtBinding.Yes m, _ -> false, Some m //------------------------------------------------------------------------- @@ -2342,245 +2836,258 @@ let ComputeDebugPointForBinding g bind = //------------------------------------------------------------------------- let rec GenExpr cenv cgbuf eenv (expr: Expr) sequel = - cenv.stackGuard.Guard <| fun () -> + cenv.stackGuard.Guard + <| fun () -> - GenExprAux cenv cgbuf eenv expr sequel + GenExprAux cenv cgbuf eenv expr sequel /// Process the debug point and check for alternative ways to generate this expression. /// Returns 'true' if the expression was processed by alternative means. and GenExprPreSteps (cenv: cenv) (cgbuf: CodeGenBuffer) eenv expr sequel = let g = cenv.g - + // Check for the '__debugPoint" construct for inlined code match expr with - | Expr.Sequential((DebugPointExpr g debugPointName) as dpExpr, codeExpr, NormalSeq, m) -> - match cenv.namedDebugPointsForInlinedCode.TryGetValue({Range=m; Name=debugPointName}) with - | false, _ when debugPointName = "" -> - CG.EmitDebugPoint cgbuf m + | Expr.Sequential ((DebugPointExpr g debugPointName) as dpExpr, codeExpr, NormalSeq, m) -> + match cenv.namedDebugPointsForInlinedCode.TryGetValue({ Range = m; Name = debugPointName }) with + | false, _ when debugPointName = "" -> CG.EmitDebugPoint cgbuf m | false, _ -> // printfn $"---- Unfound debug point {debugPointName} at {m}" // for KeyValue(k,v) in cenv.namedDebugPointsForInlinedCode do // printfn $"{k.Range} , {k.Name} -> {v}" let others = - [ for k in cenv.namedDebugPointsForInlinedCode.Keys do - if Range.equals m k.Range then - yield k.Name ] + [ + for k in cenv.namedDebugPointsForInlinedCode.Keys do + if Range.equals m k.Range then + yield k.Name + ] |> String.concat "," - informationalWarning(Error(FSComp.SR.ilxGenUnknownDebugPoint(debugPointName, others), dpExpr.Range)) + + informationalWarning (Error(FSComp.SR.ilxGenUnknownDebugPoint (debugPointName, others), dpExpr.Range)) CG.EmitDebugPoint cgbuf m | true, dp -> // printfn $"---- Found debug point {debugPointName} at {m} --> {dp}" CG.EmitDebugPoint cgbuf dp + GenExpr cenv cgbuf eenv codeExpr sequel true | _ -> - //ProcessDebugPointForExpr cenv cgbuf expr - - match (if compileSequenceExpressions then LowerComputedCollectionExpressions.LowerComputedListOrArrayExpr cenv.tcVal g cenv.amap expr else None) with - | Some altExpr -> - GenExpr cenv cgbuf eenv altExpr sequel - true - | None -> + //ProcessDebugPointForExpr cenv cgbuf expr - match (if compileSequenceExpressions then LowerSequenceExpressions.ConvertSequenceExprToObject g cenv.amap expr else None) with - | Some info -> - GenSequenceExpr cenv cgbuf eenv info sequel - true - | None -> + let lowering = + if compileSequenceExpressions then + LowerComputedCollectionExpressions.LowerComputedListOrArrayExpr cenv.tcVal g cenv.amap expr + else + None - match LowerStateMachineExpr cenv.g expr with - | LoweredStateMachineResult.Lowered res -> - checkLanguageFeatureError cenv.g.langVersion LanguageFeature.ResumableStateMachines expr.Range - GenStructStateMachine cenv cgbuf eenv res sequel - true - | LoweredStateMachineResult.UseAlternative (msg, altExpr) -> - checkLanguageFeatureError cenv.g.langVersion LanguageFeature.ResumableStateMachines expr.Range - warning(Error(FSComp.SR.reprStateMachineNotCompilable(msg), expr.Range)) - GenExpr cenv cgbuf eenv altExpr sequel - true - | LoweredStateMachineResult.NoAlternative msg -> - checkLanguageFeatureError cenv.g.langVersion LanguageFeature.ResumableStateMachines expr.Range - errorR(Error(FSComp.SR.reprStateMachineNotCompilableNoAlternative(msg), expr.Range)) - GenDefaultValue cenv cgbuf eenv (tyOfExpr cenv.g expr, expr.Range) - true - | LoweredStateMachineResult.NotAStateMachine -> - match expr with - | IfUseResumableStateMachinesExpr g (_thenExpr, elseExpr) -> - GenExpr cenv cgbuf eenv elseExpr sequel + match lowering with + | Some altExpr -> + GenExpr cenv cgbuf eenv altExpr sequel true - | _ -> - false + | None -> + + let lowering = + if compileSequenceExpressions then + LowerSequenceExpressions.ConvertSequenceExprToObject g cenv.amap expr + else + None + + match lowering with + | Some info -> + GenSequenceExpr cenv cgbuf eenv info sequel + true + | None -> + + match LowerStateMachineExpr cenv.g expr with + | LoweredStateMachineResult.Lowered res -> + let eenv = RemoveTemplateReplacement eenv + checkLanguageFeatureError cenv.g.langVersion LanguageFeature.ResumableStateMachines expr.Range + GenStructStateMachine cenv cgbuf eenv res sequel + true + | LoweredStateMachineResult.UseAlternative (msg, altExpr) -> + // When prepping to generate a state machine, we can remove any trace of the template struct + // type for the internal state of any enclosing state machine, as they do not interact. This + // is important if the nested state machine generates dynamic code (LoweredStateMachineResult.UseAlternative). + let eenv = RemoveTemplateReplacement eenv + checkLanguageFeatureError cenv.g.langVersion LanguageFeature.ResumableStateMachines expr.Range + warning (Error(FSComp.SR.reprStateMachineNotCompilable (msg), expr.Range)) + GenExpr cenv cgbuf eenv altExpr sequel + true + | LoweredStateMachineResult.NoAlternative msg -> + let eenv = RemoveTemplateReplacement eenv + checkLanguageFeatureError cenv.g.langVersion LanguageFeature.ResumableStateMachines expr.Range + errorR (Error(FSComp.SR.reprStateMachineNotCompilableNoAlternative (msg), expr.Range)) + GenDefaultValue cenv cgbuf eenv (tyOfExpr cenv.g expr, expr.Range) + true + | LoweredStateMachineResult.NotAStateMachine -> + match expr with + | IfUseResumableStateMachinesExpr g (_thenExpr, elseExpr) -> + GenExpr cenv cgbuf eenv elseExpr sequel + true + | _ -> false and GenExprAux (cenv: cenv) (cgbuf: CodeGenBuffer) eenv expr (sequel: sequel) = let g = cenv.g let expr = stripExpr expr // Process the debug point and see if there's a replacement technique to process this expression - if GenExprPreSteps cenv cgbuf eenv expr sequel then () else + if GenExprPreSteps cenv cgbuf eenv expr sequel then + () + else - match expr with - // Most generation of linear expressions is implemented routinely using tailcalls and the correct sequels. - // This is because the element of expansion happens to be the final thing generated in most cases. However - // for large lists we have to process the linearity separately - | Expr.Sequential _ - | Expr.Let _ - | LinearOpExpr _ - | Expr.Match _ -> - GenLinearExpr cenv cgbuf eenv expr sequel false id |> ignore + match expr with + // Most generation of linear expressions is implemented routinely using tailcalls and the correct sequels. + // This is because the element of expansion happens to be the final thing generated in most cases. However + // for large lists we have to process the linearity separately + | Expr.Sequential _ + | Expr.Let _ + | LinearOpExpr _ + | Expr.Match _ -> GenLinearExpr cenv cgbuf eenv expr sequel false id |> ignore + + | Expr.DebugPoint (DebugPointAtLeafExpr.Yes m, innerExpr) -> + CG.EmitDebugPoint cgbuf m + GenExpr cenv cgbuf eenv innerExpr sequel + + | Expr.Const (c, m, ty) -> GenConstant cenv cgbuf eenv (c, m, ty) sequel + + | Expr.LetRec (binds, body, m, _) -> GenLetRec cenv cgbuf eenv (binds, body, m) sequel + + | Expr.Lambda _ + | Expr.TyLambda _ -> GenLambda cenv cgbuf eenv false [] expr sequel + + | Expr.App (Expr.Val (vref, _, m) as v, _, tyargs, [], _) when + List.forall (isMeasureTy g) tyargs + && ( + // inline only values that are stored in local variables + match StorageForValRef m vref eenv with + | ValStorage.Local _ -> true + | _ -> false) + -> + // application of local type functions with type parameters = measure types and body = local value - inline the body + GenExpr cenv cgbuf eenv v sequel + + | Expr.App (f, fty, tyargs, curriedArgs, m) -> GenApp cenv cgbuf eenv (f, fty, tyargs, curriedArgs, m) sequel + + | Expr.Val (v, _, m) -> GenGetVal cenv cgbuf eenv (v, m) sequel + + | Expr.Op (op, tyargs, args, m) -> + match op, args, tyargs with + | TOp.ExnConstr c, _, _ -> GenAllocExn cenv cgbuf eenv (c, args, m) sequel + | TOp.UnionCase c, _, _ -> GenAllocUnionCase cenv cgbuf eenv (c, tyargs, args, m) sequel + | TOp.Recd (isCtor, tcref), _, _ -> GenAllocRecd cenv cgbuf eenv isCtor (tcref, tyargs, args, m) sequel + | TOp.AnonRecd anonInfo, _, _ -> GenAllocAnonRecd cenv cgbuf eenv (anonInfo, tyargs, args, m) sequel + | TOp.AnonRecdGet (anonInfo, n), [ e ], _ -> GenGetAnonRecdField cenv cgbuf eenv (anonInfo, e, tyargs, n, m) sequel + | TOp.TupleFieldGet (tupInfo, n), [ e ], _ -> GenGetTupleField cenv cgbuf eenv (tupInfo, e, tyargs, n, m) sequel + | TOp.ExnFieldGet (ecref, n), [ e ], _ -> GenGetExnField cenv cgbuf eenv (e, ecref, n, m) sequel + | TOp.UnionCaseFieldGet (ucref, n), [ e ], _ -> GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel + | TOp.UnionCaseFieldGetAddr (ucref, n, _readonly), [ e ], _ -> + GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel + | TOp.UnionCaseTagGet ucref, [ e ], _ -> GenGetUnionCaseTag cenv cgbuf eenv (e, ucref, tyargs, m) sequel + | TOp.UnionCaseProof ucref, [ e ], _ -> GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel + | TOp.ExnFieldSet (ecref, n), [ e; e2 ], _ -> GenSetExnField cenv cgbuf eenv (e, ecref, n, e2, m) sequel + | TOp.UnionCaseFieldSet (ucref, n), [ e; e2 ], _ -> GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel + | TOp.ValFieldGet f, [ e ], _ -> GenGetRecdField cenv cgbuf eenv (e, f, tyargs, m) sequel + | TOp.ValFieldGet f, [], _ -> GenGetStaticField cenv cgbuf eenv (f, tyargs, m) sequel + | TOp.ValFieldGetAddr (f, _readonly), [ e ], _ -> GenGetRecdFieldAddr cenv cgbuf eenv (e, f, tyargs, m) sequel + | TOp.ValFieldGetAddr (f, _readonly), [], _ -> GenGetStaticFieldAddr cenv cgbuf eenv (f, tyargs, m) sequel + | TOp.ValFieldSet f, [ e1; e2 ], _ -> GenSetRecdField cenv cgbuf eenv (e1, f, tyargs, e2, m) sequel + | TOp.ValFieldSet f, [ e2 ], _ -> GenSetStaticField cenv cgbuf eenv (f, tyargs, e2, m) sequel + | TOp.Tuple tupInfo, _, _ -> GenAllocTuple cenv cgbuf eenv (tupInfo, args, tyargs, m) sequel + | TOp.ILAsm (instrs, retTypes), _, _ -> GenAsmCode cenv cgbuf eenv (instrs, tyargs, args, retTypes, m) sequel + | TOp.While (sp, _), [ Expr.Lambda (_, _, _, [ _ ], e1, _, _); Expr.Lambda (_, _, _, [ _ ], e2, _, _) ], [] -> + GenWhileLoop cenv cgbuf eenv (sp, e1, e2, m) sequel + | TOp.IntegerForLoop (spFor, spTo, dir), + [ Expr.Lambda (_, _, _, [ _ ], e1, _, _); Expr.Lambda (_, _, _, [ _ ], e2, _, _); Expr.Lambda (_, _, _, [ v ], e3, _, _) ], + [] -> GenIntegerForLoop cenv cgbuf eenv (spFor, spTo, v, e1, dir, e2, e3, m) sequel + | TOp.TryFinally (spTry, spFinally), + [ Expr.Lambda (_, _, _, [ _ ], e1, _, _); Expr.Lambda (_, _, _, [ _ ], e2, _, _) ], + [ resTy ] -> GenTryFinally cenv cgbuf eenv (e1, e2, m, resTy, spTry, spFinally) sequel + | TOp.TryWith (spTry, spWith), + [ Expr.Lambda (_, _, _, [ _ ], e1, _, _); Expr.Lambda (_, _, _, [ vf ], ef, _, _); Expr.Lambda (_, _, _, [ vh ], eh, _, _) ], + [ resTy ] -> GenTryWith cenv cgbuf eenv (e1, vf, ef, vh, eh, m, resTy, spTry, spWith) sequel + | TOp.ILCall (isVirtual, _, isStruct, isCtor, valUseFlag, _, noTailCall, ilMethRef, enclTypeInst, methInst, returnTypes), + args, + [] -> + GenILCall + cenv + cgbuf + eenv + (isVirtual, isStruct, isCtor, valUseFlag, noTailCall, ilMethRef, enclTypeInst, methInst, args, returnTypes, m) + sequel + | TOp.RefAddrGet _readonly, [ e ], [ ty ] -> GenGetAddrOfRefCellField cenv cgbuf eenv (e, ty, m) sequel + | TOp.Coerce, [ e ], [ tgtTy; srcTy ] -> GenCoerce cenv cgbuf eenv (e, tgtTy, m, srcTy) sequel + | TOp.Reraise, [], [ retTy ] -> GenReraise cenv cgbuf eenv (retTy, m) sequel + | TOp.TraitCall traitInfo, args, [] -> GenTraitCall cenv cgbuf eenv (traitInfo, args, m) expr sequel + | TOp.LValueOp (LSet, v), [ e ], [] -> GenSetVal cenv cgbuf eenv (v, e, m) sequel + | TOp.LValueOp (LByrefGet, v), [], [] -> GenGetByref cenv cgbuf eenv (v, m) sequel + | TOp.LValueOp (LByrefSet, v), [ e ], [] -> GenSetByref cenv cgbuf eenv (v, e, m) sequel + | TOp.LValueOp (LAddrOf _, v), [], [] -> GenGetValAddr cenv cgbuf eenv (v, m) sequel + | TOp.Array, elems, [ elemTy ] -> GenNewArray cenv cgbuf eenv (elems, elemTy, m) sequel + | TOp.Bytes bytes, [], [] -> + if cenv.options.emitConstantArraysUsingStaticDataBlobs then + GenConstArray cenv cgbuf eenv g.ilg.typ_Byte bytes (fun buf b -> buf.EmitByte b) + GenSequel cenv eenv.cloc cgbuf sequel + else + GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkByte g m) bytes), g.byte_ty, m) sequel + | TOp.UInt16s arr, [], [] -> + if cenv.options.emitConstantArraysUsingStaticDataBlobs then + GenConstArray cenv cgbuf eenv g.ilg.typ_UInt16 arr (fun buf b -> buf.EmitUInt16 b) + GenSequel cenv eenv.cloc cgbuf sequel + else + GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkUInt16 g m) arr), g.uint16_ty, m) sequel + | TOp.Goto label, _, _ -> + if cgbuf.mgbuf.cenv.options.generateDebugSymbols then + cgbuf.EmitStartOfHiddenCode() + CG.EmitInstr cgbuf (pop 0) Push0 AI_nop - | Expr.DebugPoint (DebugPointAtLeafExpr.Yes m, innerExpr) -> - CG.EmitDebugPoint cgbuf m - GenExpr cenv cgbuf eenv innerExpr sequel - - | Expr.Const (c, m, ty) -> - GenConstant cenv cgbuf eenv (c, m, ty) sequel - - | Expr.LetRec (binds, body, m, _) -> - GenLetRec cenv cgbuf eenv (binds, body, m) sequel - - | Expr.Lambda _ | Expr.TyLambda _ -> - GenLambda cenv cgbuf eenv false [] expr sequel - - | Expr.App (Expr.Val (vref, _, m) as v, _, tyargs, [], _) when - List.forall (isMeasureTy g) tyargs && - ( - // inline only values that are stored in local variables - match StorageForValRef g m vref eenv with - | ValStorage.Local _ -> true - | _ -> false - ) -> - // application of local type functions with type parameters = measure types and body = local value - inline the body - GenExpr cenv cgbuf eenv v sequel - - | Expr.App (f, fty, tyargs, curriedArgs, m) -> - GenApp cenv cgbuf eenv (f, fty, tyargs, curriedArgs, m) sequel - - | Expr.Val (v, _, m) -> - GenGetVal cenv cgbuf eenv (v, m) sequel - - | Expr.Op (op, tyargs, args, m) -> - match op, args, tyargs with - | TOp.ExnConstr c, _, _ -> - GenAllocExn cenv cgbuf eenv (c, args, m) sequel - | TOp.UnionCase c, _, _ -> - GenAllocUnionCase cenv cgbuf eenv (c, tyargs, args, m) sequel - | TOp.Recd (isCtor, tycon), _, _ -> - GenAllocRecd cenv cgbuf eenv isCtor (tycon, tyargs, args, m) sequel - | TOp.AnonRecd anonInfo, _, _ -> - GenAllocAnonRecd cenv cgbuf eenv (anonInfo, tyargs, args, m) sequel - | TOp.AnonRecdGet (anonInfo, n), [e], _ -> - GenGetAnonRecdField cenv cgbuf eenv (anonInfo, e, tyargs, n, m) sequel - | TOp.TupleFieldGet (tupInfo, n), [e], _ -> - GenGetTupleField cenv cgbuf eenv (tupInfo, e, tyargs, n, m) sequel - | TOp.ExnFieldGet (ecref, n), [e], _ -> - GenGetExnField cenv cgbuf eenv (e, ecref, n, m) sequel - | TOp.UnionCaseFieldGet (ucref, n), [e], _ -> - GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel - | TOp.UnionCaseFieldGetAddr (ucref, n, _readonly), [e], _ -> - GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel - | TOp.UnionCaseTagGet ucref, [e], _ -> - GenGetUnionCaseTag cenv cgbuf eenv (e, ucref, tyargs, m) sequel - | TOp.UnionCaseProof ucref, [e], _ -> - GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel - | TOp.ExnFieldSet (ecref, n), [e;e2], _ -> - GenSetExnField cenv cgbuf eenv (e, ecref, n, e2, m) sequel - | TOp.UnionCaseFieldSet (ucref, n), [e;e2], _ -> - GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel - | TOp.ValFieldGet f, [e], _ -> - GenGetRecdField cenv cgbuf eenv (e, f, tyargs, m) sequel - | TOp.ValFieldGet f, [], _ -> - GenGetStaticField cenv cgbuf eenv (f, tyargs, m) sequel - | TOp.ValFieldGetAddr (f, _readonly), [e], _ -> - GenGetRecdFieldAddr cenv cgbuf eenv (e, f, tyargs, m) sequel - | TOp.ValFieldGetAddr (f, _readonly), [], _ -> - GenGetStaticFieldAddr cenv cgbuf eenv (f, tyargs, m) sequel - | TOp.ValFieldSet f, [e1;e2], _ -> - GenSetRecdField cenv cgbuf eenv (e1, f, tyargs, e2, m) sequel - | TOp.ValFieldSet f, [e2], _ -> - GenSetStaticField cenv cgbuf eenv (f, tyargs, e2, m) sequel - | TOp.Tuple tupInfo, _, _ -> - GenAllocTuple cenv cgbuf eenv (tupInfo, args, tyargs, m) sequel - | TOp.ILAsm (instrs, retTypes), _, _ -> - GenAsmCode cenv cgbuf eenv (instrs, tyargs, args, retTypes, m) sequel - | TOp.While (sp, _), [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _)], [] -> - GenWhileLoop cenv cgbuf eenv (sp, e1, e2, m) sequel - | TOp.IntegerForLoop (spFor, spTo, dir), [Expr.Lambda (_, _, _, [_], e1, _, _);Expr.Lambda (_, _, _, [_], e2, _, _);Expr.Lambda (_, _, _, [v], e3, _, _)], [] -> - GenIntegerForLoop cenv cgbuf eenv (spFor, spTo, v, e1, dir, e2, e3, m) sequel - | TOp.TryFinally (spTry, spFinally), [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [_], e2, _, _)], [resty] -> - GenTryFinally cenv cgbuf eenv (e1, e2, m, resty, spTry, spFinally) sequel - | TOp.TryWith (spTry, spWith), [Expr.Lambda (_, _, _, [_], e1, _, _); Expr.Lambda (_, _, _, [vf], ef, _, _);Expr.Lambda (_, _, _, [vh], eh, _, _)], [resty] -> - GenTryWith cenv cgbuf eenv (e1, vf, ef, vh, eh, m, resty, spTry, spWith) sequel - | TOp.ILCall (isVirtual, _, isStruct, isCtor, valUseFlag, _, noTailCall, ilMethRef, enclTypeInst, methInst, returnTypes), args, [] -> - GenILCall cenv cgbuf eenv (isVirtual, isStruct, isCtor, valUseFlag, noTailCall, ilMethRef, enclTypeInst, methInst, args, returnTypes, m) sequel - | TOp.RefAddrGet _readonly, [e], [ty] -> GenGetAddrOfRefCellField cenv cgbuf eenv (e, ty, m) sequel - | TOp.Coerce, [e], [tgty;srcty] -> GenCoerce cenv cgbuf eenv (e, tgty, m, srcty) sequel - | TOp.Reraise, [], [rtnty] -> GenReraise cenv cgbuf eenv (rtnty, m) sequel - | TOp.TraitCall traitInfo, args, [] -> GenTraitCall cenv cgbuf eenv (traitInfo, args, m) expr sequel - | TOp.LValueOp (LSet, v), [e], [] -> GenSetVal cenv cgbuf eenv (v, e, m) sequel - | TOp.LValueOp (LByrefGet, v), [], [] -> GenGetByref cenv cgbuf eenv (v, m) sequel - | TOp.LValueOp (LByrefSet, v), [e], [] -> GenSetByref cenv cgbuf eenv (v, e, m) sequel - | TOp.LValueOp (LAddrOf _, v), [], [] -> GenGetValAddr cenv cgbuf eenv (v, m) sequel - | TOp.Array, elems, [elemTy] -> GenNewArray cenv cgbuf eenv (elems, elemTy, m) sequel - | TOp.Bytes bytes, [], [] -> - if cenv.options.emitConstantArraysUsingStaticDataBlobs then - GenConstArray cenv cgbuf eenv g.ilg.typ_Byte bytes (fun buf b -> buf.EmitByte b) - GenSequel cenv eenv.cloc cgbuf sequel - else - GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkByte g m) bytes), g.byte_ty, m) sequel - | TOp.UInt16s arr, [], [] -> - if cenv.options.emitConstantArraysUsingStaticDataBlobs then - GenConstArray cenv cgbuf eenv g.ilg.typ_UInt16 arr (fun buf b -> buf.EmitUInt16 b) - GenSequel cenv eenv.cloc cgbuf sequel - else - GenNewArraySimple cenv cgbuf eenv (List.ofArray (Array.map (mkUInt16 g m) arr), g.uint16_ty, m) sequel - | TOp.Goto label, _, _ -> - if cgbuf.mgbuf.cenv.options.generateDebugSymbols then - cgbuf.EmitStartOfHiddenCode() - CG.EmitInstr cgbuf (pop 0) Push0 AI_nop - CG.EmitInstr cgbuf (pop 0) Push0 (I_br label) + CG.EmitInstr cgbuf (pop 0) Push0 (I_br label) // NOTE: discard sequel - | TOp.Return, [e], _ -> - GenExpr cenv cgbuf eenv e eenv.exitSequel + | TOp.Return, [ e ], _ -> GenExpr cenv cgbuf eenv e eenv.exitSequel // NOTE: discard sequel - | TOp.Return, [], _ -> - GenSequel cenv eenv.cloc cgbuf ReturnVoid + | TOp.Return, [], _ -> GenSequel cenv eenv.cloc cgbuf ReturnVoid // NOTE: discard sequel - | TOp.Label label, _, _ -> - cgbuf.SetMarkToHere (Mark label) - GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel - | _ -> error(InternalError("Unexpected operator node expression", expr.Range)) + | TOp.Label label, _, _ -> + cgbuf.SetMarkToHere(Mark label) + GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel + | _ -> error (InternalError("Unexpected operator node expression", expr.Range)) - | Expr.StaticOptimization (constraints, e2, e3, m) -> - GenStaticOptimization cenv cgbuf eenv (constraints, e2, e3, m) sequel + | Expr.StaticOptimization (constraints, e2, e3, m) -> GenStaticOptimization cenv cgbuf eenv (constraints, e2, e3, m) sequel - | Expr.Obj (_, ty, _, _, [meth], [], m) when isDelegateTy g ty -> - GenDelegateExpr cenv cgbuf eenv expr (meth, m) sequel + | Expr.Obj (_, ty, _, _, [ meth ], [], m) when isDelegateTy g ty -> GenDelegateExpr cenv cgbuf eenv expr (meth, m) sequel - | Expr.Obj (_, ty, basev, basecall, overrides, interfaceImpls, m) -> - GenObjectExpr cenv cgbuf eenv expr (ty, basev, basecall, overrides, interfaceImpls, m) sequel + | Expr.Obj (_, ty, basev, basecall, overrides, interfaceImpls, m) -> + GenObjectExpr cenv cgbuf eenv expr (ty, basev, basecall, overrides, interfaceImpls, m) sequel - | Expr.Quote (ast, conv, _, m, ty) -> - GenQuotation cenv cgbuf eenv (ast, conv, m, ty) sequel + | Expr.Quote (ast, conv, _, m, ty) -> GenQuotation cenv cgbuf eenv (ast, conv, m, ty) sequel - | Expr.WitnessArg (traitInfo, m) -> - GenWitnessArgFromTraitInfo cenv cgbuf eenv m traitInfo - GenSequel cenv eenv.cloc cgbuf sequel + | Expr.WitnessArg (traitInfo, m) -> + GenWitnessArgFromTraitInfo cenv cgbuf eenv m traitInfo + GenSequel cenv eenv.cloc cgbuf sequel - | Expr.Link _ -> failwith "Unexpected reclink" + | Expr.Link _ -> failwith "Unexpected reclink" - | Expr.TyChoose (_, _, m) -> error(InternalError("Unexpected Expr.TyChoose", m)) + | Expr.TyChoose (_, _, m) -> error (InternalError("Unexpected Expr.TyChoose", m)) and GenExprs cenv cgbuf eenv es = List.iter (fun e -> GenExpr cenv cgbuf eenv e Continue) es and CodeGenMethodForExpr cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, selfArgOpt, expr0, sequel0) = let eenv = { eenv with exitSequel = sequel0 } + let _, code = - CodeGenMethod cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, selfArgOpt, - (fun cgbuf eenv -> GenExpr cenv cgbuf eenv expr0 sequel0), - expr0.Range) + CodeGenMethod + cenv + mgbuf + (entryPointInfo, + methodName, + eenv, + alreadyUsedArgs, + selfArgOpt, + (fun cgbuf eenv -> GenExpr cenv cgbuf eenv expr0 sequel0), + expr0.Range) + code //-------------------------------------------------------------------------- @@ -2590,33 +3097,36 @@ and CodeGenMethodForExpr cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUs /// Adjust the sequel for an implicit discard (e.g. a discard that occurs by /// not generating a 'unit' expression at all) and sequelAfterDiscard sequel = - match sequel with - | LeaveHandler (isFinally, whereToSaveResultOpt, afterHandler, true) -> - // If we're not saving the result as we leave a handler and we're doing a discard - // then we can just adjust the sequel to record the fact we've implicitly done a discard - if isFinally || whereToSaveResultOpt.IsNone then - Some (LeaveHandler (isFinally, whereToSaveResultOpt, afterHandler, false)) - else - None - | DiscardThen sequel -> Some sequel - | EndLocalScope(sq, mark) -> sequelAfterDiscard sq |> Option.map (fun sq -> EndLocalScope(sq, mark)) - | _ -> None + match sequel with + | LeaveHandler (isFinally, whereToSaveResultOpt, afterHandler, true) -> + // If we're not saving the result as we leave a handler and we're doing a discard + // then we can just adjust the sequel to record the fact we've implicitly done a discard + if isFinally || whereToSaveResultOpt.IsNone then + Some(LeaveHandler(isFinally, whereToSaveResultOpt, afterHandler, false)) + else + None + | DiscardThen sequel -> Some sequel + | EndLocalScope (sq, mark) -> sequelAfterDiscard sq |> Option.map (fun sq -> EndLocalScope(sq, mark)) + | _ -> None and sequelIgnoringEndScopesAndDiscard sequel = let sequel = sequelIgnoreEndScopes sequel + match sequelAfterDiscard sequel with | Some sq -> sq | None -> sequel and sequelIgnoreEndScopes sequel = match sequel with - | EndLocalScope(sq, _) -> sequelIgnoreEndScopes sq + | EndLocalScope (sq, _) -> sequelIgnoreEndScopes sq | sq -> sq (* commit any 'EndLocalScope' nodes in the sequel and return the residue *) and GenSequelEndScopes cgbuf sequel = match sequel with - | EndLocalScope(sq, m) -> CG.SetMarkToHere cgbuf m; GenSequelEndScopes cgbuf sq + | EndLocalScope (sq, m) -> + CG.SetMarkToHere cgbuf m + GenSequelEndScopes cgbuf sq | _ -> () and StringOfSequel sequel = @@ -2632,94 +3142,97 @@ and StringOfSequel sequel = | EndFilter -> "EndFilter" and GenSequel cenv cloc cgbuf sequel = - let sq = sequelIgnoreEndScopes sequel - (match sq with - | Continue -> () - | DiscardThen sq -> - CG.EmitInstr cgbuf (pop 1) Push0 AI_pop - GenSequel cenv cloc cgbuf sq - | ReturnVoid -> - CG.EmitInstr cgbuf (pop 0) Push0 I_ret - | CmpThenBrOrContinue(pops, bri) -> - CG.EmitInstrs cgbuf pops Push0 bri - | Return -> - CG.EmitInstr cgbuf (pop 1) Push0 I_ret - | EndLocalScope _ -> failwith "EndLocalScope unexpected" - | Br x -> - // Emit a NOP in debug code in case the branch instruction gets eliminated - // because it is a "branch to next instruction". This prevents two unrelated debug points - // (the one before the branch and the one after) being coalesced together - if cgbuf.mgbuf.cenv.options.generateDebugSymbols then - cgbuf.EmitStartOfHiddenCode() - CG.EmitInstr cgbuf (pop 0) Push0 AI_nop - - CG.EmitInstr cgbuf (pop 0) Push0 (I_br x.CodeLabel) - - | LeaveHandler (isFinally, whereToSaveResultOpt, afterHandler, hasResult) -> - if hasResult then - if isFinally then - CG.EmitInstr cgbuf (pop 1) Push0 AI_pop - else - match whereToSaveResultOpt with - | None -> - CG.EmitInstr cgbuf (pop 1) Push0 AI_pop - | Some (whereToSaveResult, _) -> - EmitSetLocal cgbuf whereToSaveResult - CG.EmitInstr cgbuf (pop 0) Push0 (if isFinally then I_endfinally else I_leave(afterHandler.CodeLabel)) - - | EndFilter -> - CG.EmitInstr cgbuf (pop 1) Push0 I_endfilter - ) - GenSequelEndScopes cgbuf sequel + let sq = sequelIgnoreEndScopes sequel + + (match sq with + | Continue -> () + | DiscardThen sq -> + CG.EmitInstr cgbuf (pop 1) Push0 AI_pop + GenSequel cenv cloc cgbuf sq + | ReturnVoid -> CG.EmitInstr cgbuf (pop 0) Push0 I_ret + | CmpThenBrOrContinue (pops, bri) -> CG.EmitInstrs cgbuf pops Push0 bri + | Return -> CG.EmitInstr cgbuf (pop 1) Push0 I_ret + | EndLocalScope _ -> failwith "EndLocalScope unexpected" + | Br x -> + // Emit a NOP in debug code in case the branch instruction gets eliminated + // because it is a "branch to next instruction". This prevents two unrelated debug points + // (the one before the branch and the one after) being coalesced together + if cgbuf.mgbuf.cenv.options.generateDebugSymbols then + cgbuf.EmitStartOfHiddenCode() + CG.EmitInstr cgbuf (pop 0) Push0 AI_nop + + CG.EmitInstr cgbuf (pop 0) Push0 (I_br x.CodeLabel) + + | LeaveHandler (isFinally, whereToSaveResultOpt, afterHandler, hasResult) -> + if hasResult then + if isFinally then + CG.EmitInstr cgbuf (pop 1) Push0 AI_pop + else + match whereToSaveResultOpt with + | None -> CG.EmitInstr cgbuf (pop 1) Push0 AI_pop + | Some (whereToSaveResult, _) -> EmitSetLocal cgbuf whereToSaveResult + + CG.EmitInstr + cgbuf + (pop 0) + Push0 + (if isFinally then + I_endfinally + else + I_leave(afterHandler.CodeLabel)) + | EndFilter -> CG.EmitInstr cgbuf (pop 1) Push0 I_endfilter) + + GenSequelEndScopes cgbuf sequel //-------------------------------------------------------------------------- // Generate constants //-------------------------------------------------------------------------- and GenConstant cenv cgbuf eenv (c, m, ty) sequel = - let g = cenv.g - let ilTy = GenType cenv m eenv.tyenv ty - // Check if we need to generate the value at all - match sequelAfterDiscard sequel with - | None -> - match TryEliminateDesugaredConstants g m c with - | Some e -> - GenExpr cenv cgbuf eenv e Continue - | None -> - let emitInt64Constant i = - // see https://github.com/dotnet/fsharp/pull/3620 - // and https://github.com/dotnet/fsharp/issue/8683 - // and https://github.com/dotnet/roslyn/blob/98f12bb/src/Compilers/Core/Portable/CodeGen/ILBuilderEmit.cs#L679 - if i >= int64 System.Int32.MinValue && i <= int64 System.Int32.MaxValue then - CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [ mkLdcInt32 (int32 i); AI_conv DT_I8 ] - elif i >= int64 System.UInt32.MinValue && i <= int64 System.UInt32.MaxValue then - CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [ mkLdcInt32 (int32 i); AI_conv DT_U8 ] - else - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcInt64 i) - match c with - | Const.Bool b -> CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Bool]) (mkLdcInt32 (if b then 1 else 0)) - | Const.SByte i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.Int16 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.Int32 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 i) - | Const.Int64 i -> emitInt64Constant i - | Const.IntPtr i -> CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [iLdcInt64 i; AI_conv DT_I ] - | Const.Byte i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.UInt16 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.UInt32 i -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdcInt32 (int32 i)) - | Const.UInt64 i -> emitInt64Constant (int64 i) - | Const.UIntPtr i -> CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [iLdcInt64 (int64 i); AI_conv DT_U ] - | Const.Double f -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (AI_ldc (DT_R8, ILConst.R8 f)) - | Const.Single f -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (AI_ldc (DT_R4, ILConst.R4 f)) - | Const.Char c -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) ( mkLdcInt32 (int c)) - | Const.String s -> GenString cenv cgbuf s - | Const.Unit -> GenUnit cenv eenv m cgbuf - | Const.Zero -> GenDefaultValue cenv cgbuf eenv (ty, m) - | Const.Decimal _ -> failwith "unreachable" - GenSequel cenv eenv.cloc cgbuf sequel - | Some sq -> - // Even if we didn't need to generate the value then maybe we still have to branch or return - GenSequel cenv eenv.cloc cgbuf sq + let g = cenv.g + let ilTy = GenType cenv m eenv.tyenv ty + // Check if we need to generate the value at all + match sequelAfterDiscard sequel with + | None -> + match TryEliminateDesugaredConstants g m c with + | Some e -> GenExpr cenv cgbuf eenv e Continue + | None -> + let emitInt64Constant i = + // see https://github.com/dotnet/fsharp/pull/3620 + // and https://github.com/dotnet/fsharp/issue/8683 + // and https://github.com/dotnet/roslyn/blob/98f12bb/src/Compilers/Core/Portable/CodeGen/ILBuilderEmit.cs#L679 + if i >= int64 System.Int32.MinValue && i <= int64 System.Int32.MaxValue then + CG.EmitInstrs cgbuf (pop 0) (Push [ ilTy ]) [ mkLdcInt32 (int32 i); AI_conv DT_I8 ] + elif i >= int64 System.UInt32.MinValue && i <= int64 System.UInt32.MaxValue then + CG.EmitInstrs cgbuf (pop 0) (Push [ ilTy ]) [ mkLdcInt32 (int32 i); AI_conv DT_U8 ] + else + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (iLdcInt64 i) + + match c with + | Const.Bool b -> CG.EmitInstr cgbuf (pop 0) (Push [ g.ilg.typ_Bool ]) (mkLdcInt32 (if b then 1 else 0)) + | Const.SByte i -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdcInt32 (int32 i)) + | Const.Int16 i -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdcInt32 (int32 i)) + | Const.Int32 i -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdcInt32 i) + | Const.Int64 i -> emitInt64Constant i + | Const.IntPtr i -> CG.EmitInstrs cgbuf (pop 0) (Push [ ilTy ]) [ iLdcInt64 i; AI_conv DT_I ] + | Const.Byte i -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdcInt32 (int32 i)) + | Const.UInt16 i -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdcInt32 (int32 i)) + | Const.UInt32 i -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdcInt32 (int32 i)) + | Const.UInt64 i -> emitInt64Constant (int64 i) + | Const.UIntPtr i -> CG.EmitInstrs cgbuf (pop 0) (Push [ ilTy ]) [ iLdcInt64 (int64 i); AI_conv DT_U ] + | Const.Double f -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (AI_ldc(DT_R8, ILConst.R8 f)) + | Const.Single f -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (AI_ldc(DT_R4, ILConst.R4 f)) + | Const.Char c -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdcInt32 (int c)) + | Const.String s -> GenString cenv cgbuf s + | Const.Unit -> GenUnit cenv eenv m cgbuf + | Const.Zero -> GenDefaultValue cenv cgbuf eenv (ty, m) + | Const.Decimal _ -> failwith "unreachable" + + GenSequel cenv eenv.cloc cgbuf sequel + | Some sq -> + // Even if we didn't need to generate the value then maybe we still have to branch or return + GenSequel cenv eenv.cloc cgbuf sq and GenUnitTy cenv eenv m = match cenv.ilUnitTy with @@ -2730,13 +3243,14 @@ and GenUnitTy cenv eenv m = | Some res -> res and GenUnit cenv eenv m cgbuf = - CG.EmitInstr cgbuf (pop 0) (Push [GenUnitTy cenv eenv m]) AI_ldnull + CG.EmitInstr cgbuf (pop 0) (Push [ GenUnitTy cenv eenv m ]) AI_ldnull and GenUnitThenSequel cenv eenv m cloc cgbuf sequel = match sequelAfterDiscard sequel with | Some sq -> GenSequel cenv cloc cgbuf sq - | None -> GenUnit cenv eenv m cgbuf; GenSequel cenv cloc cgbuf sequel - + | None -> + GenUnit cenv eenv m cgbuf + GenSequel cenv cloc cgbuf sequel //-------------------------------------------------------------------------- // Generate simple data-related constructs @@ -2747,151 +3261,184 @@ and GenAllocTuple cenv cgbuf eenv (tupInfo, args, argTys, m) sequel = let tupInfo = evalTupInfoIsStruct tupInfo let tcref, tys, args, newm = mkCompiledTuple cenv.g tupInfo (argTys, args, m) let ty = GenNamedTyApp cenv newm eenv.tyenv tcref tys - let ntyvars = if (tys.Length - 1) < goodTupleFields then (tys.Length - 1) else goodTupleFields - let formalTyvars = [ for n in 0 .. ntyvars do yield mkILTyvarTy (uint16 n) ] + + let ntyvars = + if (tys.Length - 1) < goodTupleFields then + (tys.Length - 1) + else + goodTupleFields + + let formalTyvars = + [ + for n in 0..ntyvars do + yield mkILTyvarTy (uint16 n) + ] GenExprs cenv cgbuf eenv args // Generate a reference to the constructor - CG.EmitInstr cgbuf (pop args.Length) (Push [ty]) - (mkNormalNewobj - (mkILCtorMethSpecForTy (ty, formalTyvars))) + CG.EmitInstr cgbuf (pop args.Length) (Push [ ty ]) (mkNormalNewobj (mkILCtorMethSpecForTy (ty, formalTyvars))) GenSequel cenv eenv.cloc cgbuf sequel and GenGetTupleField cenv cgbuf eenv (tupInfo, e, tys, n, m) sequel = let tupInfo = evalTupInfoIsStruct tupInfo + let rec getCompiledTupleItem g (e, tys: TTypes, n, m) = let ar = tys.Length - if ar <= 0 then failwith "getCompiledTupleItem" + + if ar <= 0 then + failwith "getCompiledTupleItem" elif ar < maxTuple then - let tcr' = mkCompiledTupleTyconRef g tupInfo ar - let ty = GenNamedTyApp cenv m eenv.tyenv tcr' tys + let tcref = mkCompiledTupleTyconRef g tupInfo ar + let ty = GenNamedTyApp cenv m eenv.tyenv tcref tys mkGetTupleItemN g m n ty tupInfo e tys[n] else let tysA, tysB = List.splitAfter goodTupleFields tys let tyB = mkCompiledTupleTy g tupInfo tysB - let tys' = tysA@[tyB] - let tcr' = mkCompiledTupleTyconRef g tupInfo (List.length tys') - let ty' = GenNamedTyApp cenv m eenv.tyenv tcr' tys' - let n' = (min n goodTupleFields) - let elast = mkGetTupleItemN g m n' ty' tupInfo e tys'[n'] + let tysC = tysA @ [ tyB ] + let tcref = mkCompiledTupleTyconRef g tupInfo (List.length tysC) + let tyR = GenNamedTyApp cenv m eenv.tyenv tcref tysC + let nR = min n goodTupleFields + let elast = mkGetTupleItemN g m nR tyR tupInfo e tysC[nR] + if n < goodTupleFields then elast else - getCompiledTupleItem g (elast, tysB, n-goodTupleFields, m) + getCompiledTupleItem g (elast, tysB, n - goodTupleFields, m) + GenExpr cenv cgbuf eenv (getCompiledTupleItem cenv.g (e, tys, n, m)) sequel and GenAllocExn cenv cgbuf eenv (c, args, m) sequel = GenExprs cenv cgbuf eenv args let ty = GenExnType cenv m eenv.tyenv c let flds = recdFieldsOfExnDefRef c - let argTys = flds |> List.map (fun rfld -> GenType cenv m eenv.tyenv rfld.FormalType) + + let argTys = + flds |> List.map (fun rfld -> GenType cenv m eenv.tyenv rfld.FormalType) + let mspec = mkILCtorMethSpecForTy (ty, argTys) - CG.EmitInstr cgbuf - (pop args.Length) (Push [ty]) - (mkNormalNewobj mspec) + CG.EmitInstr cgbuf (pop args.Length) (Push [ ty ]) (mkNormalNewobj mspec) GenSequel cenv eenv.cloc cgbuf sequel -and GenAllocUnionCaseCore cenv cgbuf eenv (c,tyargs,n,m) = - let cuspec,idx = GenUnionCaseSpec cenv m eenv.tyenv c tyargs - CG.EmitInstrs cgbuf (pop n) (Push [cuspec.DeclaringType]) (EraseUnions.mkNewData cenv.g.ilg (cuspec, idx)) +and GenAllocUnionCaseCore cenv cgbuf eenv (c, tyargs, n, m) = + let cuspec, idx = GenUnionCaseSpec cenv m eenv.tyenv c tyargs + CG.EmitInstrs cgbuf (pop n) (Push [ cuspec.DeclaringType ]) (EraseUnions.mkNewData cenv.g.ilg (cuspec, idx)) -and GenAllocUnionCase cenv cgbuf eenv (c,tyargs,args,m) sequel = +and GenAllocUnionCase cenv cgbuf eenv (c, tyargs, args, m) sequel = GenExprs cenv cgbuf eenv args - GenAllocUnionCaseCore cenv cgbuf eenv (c,tyargs,args.Length,m) + GenAllocUnionCaseCore cenv cgbuf eenv (c, tyargs, args.Length, m) GenSequel cenv eenv.cloc cgbuf sequel and GenLinearExpr cenv cgbuf eenv expr sequel preSteps (contf: FakeUnit -> FakeUnit) = let expr = stripExpr expr + match expr with | Expr.Sequential (e1, e2, specialSeqFlag, _) -> // Process the debug point and see if there's a replacement technique to process this expression - if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then contf Fake else - - match specialSeqFlag with - | NormalSeq -> - GenExpr cenv cgbuf eenv e1 discard - GenLinearExpr cenv cgbuf eenv e2 sequel true contf - | ThenDoSeq -> - // "e then ()" with DebugPointAtSequential.SuppressStmt is used - // in mkDebugPoint to emit a debug point on "e". However we don't want this to interfere - // with tailcalls, so detect this case and throw the "then ()" away, having already - // worked out "spExpr" up above. - match e2 with - | Expr.Const (Const.Unit, _, _) -> - GenExpr cenv cgbuf eenv e1 sequel - | _ -> - let g = cenv.g - let isUnit = isUnitTy g (tyOfExpr g e1) - if isUnit then - GenExpr cenv cgbuf eenv e1 discard - GenExpr cenv cgbuf eenv e2 discard - GenUnitThenSequel cenv eenv e2.Range eenv.cloc cgbuf sequel - else - GenExpr cenv cgbuf eenv e1 Continue - GenExpr cenv cgbuf eenv e2 discard - GenSequel cenv eenv.cloc cgbuf sequel + if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then contf Fake + else + + match specialSeqFlag with + | NormalSeq -> + GenExpr cenv cgbuf eenv e1 discard + GenLinearExpr cenv cgbuf eenv e2 sequel true contf + | ThenDoSeq -> + // "e then ()" with DebugPointAtSequential.SuppressStmt is used + // in mkDebugPoint to emit a debug point on "e". However we don't want this to interfere + // with tailcalls, so detect this case and throw the "then ()" away, having already + // worked out "spExpr" up above. + match e2 with + | Expr.Const (Const.Unit, _, _) -> GenExpr cenv cgbuf eenv e1 sequel + | _ -> + let g = cenv.g + let isUnit = isUnitTy g (tyOfExpr g e1) + + if isUnit then + GenExpr cenv cgbuf eenv e1 discard + GenExpr cenv cgbuf eenv e2 discard + GenUnitThenSequel cenv eenv e2.Range eenv.cloc cgbuf sequel + else + GenExpr cenv cgbuf eenv e1 Continue + GenExpr cenv cgbuf eenv e2 discard + GenSequel cenv eenv.cloc cgbuf sequel + + contf Fake | Expr.Let (bind, body, _, _) -> // Process the debug point and see if there's a replacement technique to process this expression - if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then contf Fake else + if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then + contf Fake + else - // This case implemented here to get a guaranteed tailcall - // Make sure we generate the debug point outside the scope of the variable - let startMark, endMark as scopeMarks = StartDelayedLocalScope "let" cgbuf - let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind - GenDebugPointForBind cenv cgbuf bind - GenBindingAfterDebugPoint cenv cgbuf eenv bind false (Some startMark) + // This case implemented here to get a guaranteed tailcall + // Make sure we generate the debug point outside the scope of the variable + let startMark, endMark as scopeMarks = StartDelayedLocalScope "let" cgbuf + let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind + GenDebugPointForBind cenv cgbuf bind + GenBindingAfterDebugPoint cenv cgbuf eenv bind false (Some startMark) - // Generate the body - GenLinearExpr cenv cgbuf eenv body (EndLocalScope(sequel, endMark)) true contf + // Generate the body + GenLinearExpr cenv cgbuf eenv body (EndLocalScope(sequel, endMark)) true contf | Expr.Match (spBind, _exprm, tree, targets, m, ty) -> // Process the debug point and see if there's a replacement technique to process this expression - if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then contf Fake else - - match spBind with - | DebugPointAtBinding.Yes m -> CG.EmitDebugPoint cgbuf m - | DebugPointAtBinding.NoneAtDo - | DebugPointAtBinding.NoneAtLet - | DebugPointAtBinding.NoneAtInvisible - | DebugPointAtBinding.NoneAtSticky -> () - - // First try the common cases where we don't need a join point. - match tree with - | TDSuccess _ -> - failwith "internal error: matches that immediately succeed should have been normalized using mkAndSimplifyMatch" + if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then + contf Fake + else - | _ -> - // Create a join point - let stackAtTargets = cgbuf.GetCurrentStack() // the stack at the target of each clause - let sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin = GenJoinPoint cenv cgbuf "match" eenv ty m sequel - - // Stack: "stackAtTargets" is "stack prior to any match-testing" and also "stack at the start of each branch-RHS". - // match-testing (dtrees) should not contribute to the stack. - // Each branch-RHS (targets) may contribute to the stack, leaving it in the "stackAfterJoin" state, for the join point. - // Since code is branching and joining, the cgbuf stack is maintained manually. - GenDecisionTreeAndTargets cenv cgbuf stackAtTargets eenv tree targets sequelOnBranches (contf << (fun Fake -> - CG.SetMarkToHere cgbuf afterJoin + match spBind with + | DebugPointAtBinding.Yes m -> CG.EmitDebugPoint cgbuf m + | DebugPointAtBinding.NoneAtDo + | DebugPointAtBinding.NoneAtLet + | DebugPointAtBinding.NoneAtInvisible + | DebugPointAtBinding.NoneAtSticky -> () - //assert(cgbuf.GetCurrentStack() = stackAfterJoin) // REVIEW: Since gen_dtree* now sets stack, stack should be stackAfterJoin at this point... - CG.SetStack cgbuf stackAfterJoin - // If any values are left on the stack after the join then we're certainly going to do something with them - // For example, we may be about to execute a 'stloc' for - // - // let y2 = if System.DateTime.Now.Year < 2000 then 1 else 2 - // - // or a 'stelem' for - // - // arr.[0] <- if System.DateTime.Now.Year > 2000 then 1 else 2 - // - // In both cases, any instructions that come after this point will be falsely associated with the last branch of the control - // prior to the join point. This is base, e.g. see FSharp 1.0 bug 5155 - if not (isNil stackAfterJoin) then - cgbuf.EmitStartOfHiddenCode() + // First try the common cases where we don't need a join point. + match tree with + | TDSuccess _ -> + failwith "internal error: matches that immediately succeed should have been normalized using mkAndSimplifyMatch" - GenSequel cenv eenv.cloc cgbuf sequelAfterJoin - Fake)) + | _ -> + // Create a join point + let stackAtTargets = cgbuf.GetCurrentStack() // the stack at the target of each clause + + let sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin = + GenJoinPoint cenv cgbuf "match" eenv ty m sequel + + // Stack: "stackAtTargets" is "stack prior to any match-testing" and also "stack at the start of each branch-RHS". + // match-testing (dtrees) should not contribute to the stack. + // Each branch-RHS (targets) may contribute to the stack, leaving it in the "stackAfterJoin" state, for the join point. + // Since code is branching and joining, the cgbuf stack is maintained manually. + GenDecisionTreeAndTargets + cenv + cgbuf + stackAtTargets + eenv + tree + targets + sequelOnBranches + (contf + << (fun Fake -> + CG.SetMarkToHere cgbuf afterJoin + + //assert(cgbuf.GetCurrentStack() = stackAfterJoin) // REVIEW: Since gen_dtree* now sets stack, stack should be stackAfterJoin at this point... + CG.SetStack cgbuf stackAfterJoin + // If any values are left on the stack after the join then we're certainly going to do something with them + // For example, we may be about to execute a 'stloc' for + // + // let y2 = if System.DateTime.Now.Year < 2000 then 1 else 2 + // + // or a 'stelem' for + // + // arr.[0] <- if System.DateTime.Now.Year > 2000 then 1 else 2 + // + // In both cases, any instructions that come after this point will be falsely associated with the last branch of the control + // prior to the join point. This is base, e.g. see FSharp 1.0 bug 5155 + if not (isNil stackAfterJoin) then + cgbuf.EmitStartOfHiddenCode() + + GenSequel cenv eenv.cloc cgbuf sequelAfterJoin + Fake)) | Expr.DebugPoint (DebugPointAtLeafExpr.Yes m, innerExpr) -> CG.EmitDebugPoint cgbuf m @@ -2899,19 +3446,30 @@ and GenLinearExpr cenv cgbuf eenv expr sequel preSteps (contf: FakeUnit -> FakeU | LinearOpExpr (TOp.UnionCase c, tyargs, argsFront, argLast, m) -> // Process the debug point and see if there's a replacement technique to process this expression - if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then contf Fake else + if preSteps && GenExprPreSteps cenv cgbuf eenv expr sequel then + contf Fake + else - GenExprs cenv cgbuf eenv argsFront - GenLinearExpr cenv cgbuf eenv argLast Continue true (contf << (fun Fake -> - GenAllocUnionCaseCore cenv cgbuf eenv (c, tyargs, argsFront.Length + 1, m) - GenSequel cenv eenv.cloc cgbuf sequel - Fake)) + GenExprs cenv cgbuf eenv argsFront + + GenLinearExpr + cenv + cgbuf + eenv + argLast + Continue + true + (contf + << (fun Fake -> + GenAllocUnionCaseCore cenv cgbuf eenv (c, tyargs, argsFront.Length + 1, m) + GenSequel cenv eenv.cloc cgbuf sequel + Fake)) | _ -> GenExpr cenv cgbuf eenv expr sequel contf Fake -and GenAllocRecd cenv cgbuf eenv ctorInfo (tcref,argTys,args,m) sequel = +and GenAllocRecd cenv cgbuf eenv ctorInfo (tcref, argTys, args, m) sequel = let ty = GenNamedTyApp cenv m eenv.tyenv tcref argTys // Filter out fields with default initialization @@ -2922,10 +3480,21 @@ and GenAllocRecd cenv cgbuf eenv ctorInfo (tcref,argTys,args,m) sequel = match ctorInfo with | RecdExprIsObjInit -> - (args, relevantFields) ||> List.iter2 (fun e f -> - CG.EmitInstr cgbuf (pop 0) (Push (if tcref.IsStructOrEnumTycon then [ILType.Byref ty] else [ty])) mkLdarg0 - GenExpr cenv cgbuf eenv e Continue - GenFieldStore false cenv cgbuf eenv (tcref.MakeNestedRecdFieldRef f, argTys, m) discard) + (args, relevantFields) + ||> List.iter2 (fun e f -> + CG.EmitInstr + cgbuf + (pop 0) + (Push( + if tcref.IsStructOrEnumTycon then + [ ILType.Byref ty ] + else + [ ty ] + )) + mkLdarg0 + + GenExpr cenv cgbuf eenv e Continue + GenFieldStore false cenv cgbuf eenv (tcref.MakeNestedRecdFieldRef f, argTys, m) discard) // Object construction doesn't generate a true value. // Object constructions will always just get thrown away so this is safe GenSequel cenv eenv.cloc cgbuf sequel @@ -2933,28 +3502,39 @@ and GenAllocRecd cenv cgbuf eenv ctorInfo (tcref,argTys,args,m) sequel = GenExprs cenv cgbuf eenv args // generate a reference to the record constructor let tyenvinner = eenv.tyenv.ForTyconRef tcref - CG.EmitInstr cgbuf (pop args.Length) (Push [ty]) - (mkNormalNewobj - (mkILCtorMethSpecForTy (ty, relevantFields |> List.map (fun f -> GenType cenv m tyenvinner f.FormalType) ))) + + CG.EmitInstr + cgbuf + (pop args.Length) + (Push [ ty ]) + (mkNormalNewobj (mkILCtorMethSpecForTy (ty, relevantFields |> List.map (fun f -> GenType cenv m tyenvinner f.FormalType)))) + GenSequel cenv eenv.cloc cgbuf sequel and GenAllocAnonRecd cenv cgbuf eenv (anonInfo: AnonRecdTypeInfo, tyargs, args, m) sequel = - let anonCtor, _anonMethods, anonType = cgbuf.mgbuf.LookupAnonType ((fun ilThisTy -> GenToStringMethod cenv eenv ilThisTy m), anonInfo) + let anonCtor, _anonMethods, anonType = + cgbuf.mgbuf.LookupAnonType((fun ilThisTy -> GenToStringMethod cenv eenv ilThisTy m), anonInfo) + let boxity = anonType.Boxity GenExprs cenv cgbuf eenv args let ilTypeArgs = GenTypeArgs cenv m eenv.tyenv tyargs - let anonTypeWithInst = mkILTy boxity (mkILTySpec(anonType.TypeSpec.TypeRef, ilTypeArgs)) - CG.EmitInstr cgbuf (pop args.Length) (Push [anonTypeWithInst]) (mkNormalNewobj (mkILMethSpec(anonCtor, boxity, ilTypeArgs, []))) + + let anonTypeWithInst = + mkILTy boxity (mkILTySpec (anonType.TypeSpec.TypeRef, ilTypeArgs)) + + CG.EmitInstr cgbuf (pop args.Length) (Push [ anonTypeWithInst ]) (mkNormalNewobj (mkILMethSpec (anonCtor, boxity, ilTypeArgs, []))) GenSequel cenv eenv.cloc cgbuf sequel and GenGetAnonRecdField cenv cgbuf eenv (anonInfo: AnonRecdTypeInfo, e, tyargs, n, m) sequel = - let _anonCtor, anonMethods, anonType = cgbuf.mgbuf.LookupAnonType ((fun ilThisTy -> GenToStringMethod cenv eenv ilThisTy m), anonInfo) + let _anonCtor, anonMethods, anonType = + cgbuf.mgbuf.LookupAnonType((fun ilThisTy -> GenToStringMethod cenv eenv ilThisTy m), anonInfo) + let boxity = anonType.Boxity let ilTypeArgs = GenTypeArgs cenv m eenv.tyenv tyargs let anonMethod = anonMethods[n] let anonFieldType = ilTypeArgs[n] GenExpr cenv cgbuf eenv e Continue - CG.EmitInstr cgbuf (pop 1) (Push [anonFieldType]) (mkNormalCall (mkILMethSpec(anonMethod, boxity, ilTypeArgs, []))) + CG.EmitInstr cgbuf (pop 1) (Push [ anonFieldType ]) (mkNormalCall (mkILMethSpec (anonMethod, boxity, ilTypeArgs, []))) GenSequel cenv eenv.cloc cgbuf sequel and GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel = @@ -2962,103 +3542,187 @@ and GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel = let ilArrTy = mkILArr1DTy ilElemTy if List.isEmpty elems && cenv.g.isArrayEmptyAvailable then - mkNormalCall (mkILMethSpecInTy (cenv.g.ilg.typ_Array, ILCallingConv.Static, "Empty", [], mkILArr1DTy (mkILTyvarTy 0us), [ilElemTy])) - |> CG.EmitInstr cgbuf (pop 0) (Push [ilArrTy]) + mkNormalCall ( + mkILMethSpecInTy (cenv.g.ilg.typ_Array, ILCallingConv.Static, "Empty", [], mkILArr1DTy (mkILTyvarTy 0us), [ ilElemTy ]) + ) + |> CG.EmitInstr cgbuf (pop 0) (Push [ ilArrTy ]) else - CG.EmitInstrs cgbuf (pop 0) (Push [ilArrTy]) [ (AI_ldc (DT_I4, ILConst.I4 elems.Length)); I_newarr (ILArrayShape.SingleDimensional, ilElemTy) ] - elems |> List.iteri (fun i e -> - CG.EmitInstrs cgbuf (pop 0) (Push [ilArrTy; cenv.g.ilg.typ_Int32]) [ AI_dup; (AI_ldc (DT_I4, ILConst.I4 i)) ] + CG.EmitInstrs + cgbuf + (pop 0) + (Push [ ilArrTy ]) + [ + (AI_ldc(DT_I4, ILConst.I4 elems.Length)) + I_newarr(ILArrayShape.SingleDimensional, ilElemTy) + ] + + elems + |> List.iteri (fun i e -> + CG.EmitInstrs cgbuf (pop 0) (Push [ ilArrTy; cenv.g.ilg.typ_Int32 ]) [ AI_dup; (AI_ldc(DT_I4, ILConst.I4 i)) ] GenExpr cenv cgbuf eenv e Continue - CG.EmitInstr cgbuf (pop 3) Push0 (I_stelem_any (ILArrayShape.SingleDimensional, ilElemTy))) - + CG.EmitInstr cgbuf (pop 3) Push0 (I_stelem_any(ILArrayShape.SingleDimensional, ilElemTy))) + GenSequel cenv eenv.cloc cgbuf sequel and GenNewArray cenv cgbuf eenv (elems: Expr list, elemTy, m) sequel = - // REVIEW: The restriction against enum types here has to do with Dev10/Dev11 bug 872799 - // GenConstArray generates a call to RuntimeHelpers.InitializeArray. On CLR 2.0/x64 and CLR 4.0/x64/x86, - // InitializeArray is a JIT intrinsic that will result in invalid runtime CodeGen when initializing an array - // of enum types. Until bug 872799 is fixed, we'll need to generate arrays the "simple" way for enum types - // Also note - C# never uses InitializeArray for enum types, so this change puts us on equal footing with them. - if elems.Length <= 5 || not cenv.options.emitConstantArraysUsingStaticDataBlobs || (isEnumTy cenv.g elemTy) then - GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel - else - // Try to emit a constant byte-blob array - let elemsArray = Array.ofList elems - let test, write = - match stripDebugPoints elemsArray[0] with - | Expr.Const (Const.Bool _, _, _) -> - (function Const.Bool _ -> true | _ -> false), - (fun (buf: ByteBuffer) -> function Const.Bool b -> buf.EmitBoolAsByte b | _ -> failwith "unreachable") - | Expr.Const (Const.Char _, _, _) -> - (function Const.Char _ -> true | _ -> false), - (fun buf -> function Const.Char b -> buf.EmitInt32AsUInt16 (int b) | _ -> failwith "unreachable") - | Expr.Const (Const.Byte _, _, _) -> - (function Const.Byte _ -> true | _ -> false), - (fun buf -> function Const.Byte b -> buf.EmitByte b | _ -> failwith "unreachable") - | Expr.Const (Const.UInt16 _, _, _) -> - (function Const.UInt16 _ -> true | _ -> false), - (fun buf -> function Const.UInt16 b -> buf.EmitUInt16 b | _ -> failwith "unreachable") - | Expr.Const (Const.UInt32 _, _, _) -> - (function Const.UInt32 _ -> true | _ -> false), - (fun buf -> function Const.UInt32 b -> buf.EmitInt32 (int32 b) | _ -> failwith "unreachable") - | Expr.Const (Const.UInt64 _, _, _) -> - (function Const.UInt64 _ -> true | _ -> false), - (fun buf -> function Const.UInt64 b -> buf.EmitInt64 (int64 b) | _ -> failwith "unreachable") - | Expr.Const (Const.SByte _, _, _) -> - (function Const.SByte _ -> true | _ -> false), - (fun buf -> function Const.SByte b -> buf.EmitByte (byte b) | _ -> failwith "unreachable") - | Expr.Const (Const.Int16 _, _, _) -> - (function Const.Int16 _ -> true | _ -> false), - (fun buf -> function Const.Int16 b -> buf.EmitUInt16 (uint16 b) | _ -> failwith "unreachable") - | Expr.Const (Const.Int32 _, _, _) -> - (function Const.Int32 _ -> true | _ -> false), - (fun buf -> function Const.Int32 b -> buf.EmitInt32 b | _ -> failwith "unreachable") - | Expr.Const (Const.Int64 _, _, _) -> - (function Const.Int64 _ -> true | _ -> false), - (fun buf -> function Const.Int64 b -> buf.EmitInt64 b | _ -> failwith "unreachable") - | _ -> (function _ -> false), (fun _ _ -> failwith "unreachable") - - if elemsArray |> Array.forall (function Expr.Const (c, _, _) -> test c | _ -> false) then - let ilElemTy = GenType cenv m eenv.tyenv elemTy - GenConstArray cenv cgbuf eenv ilElemTy elemsArray (fun buf -> function Expr.Const (c, _, _) -> write buf c | _ -> failwith "unreachable") - GenSequel cenv eenv.cloc cgbuf sequel - - else - GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel - -and GenCoerce cenv cgbuf eenv (e, tgty, m, srcty) sequel = + // REVIEW: The restriction against enum types here has to do with Dev10/Dev11 bug 872799 + // GenConstArray generates a call to RuntimeHelpers.InitializeArray. On CLR 2.0/x64 and CLR 4.0/x64/x86, + // InitializeArray is a JIT intrinsic that will result in invalid runtime CodeGen when initializing an array + // of enum types. Until bug 872799 is fixed, we'll need to generate arrays the "simple" way for enum types + // Also note - C# never uses InitializeArray for enum types, so this change puts us on equal footing with them. + if + elems.Length <= 5 + || not cenv.options.emitConstantArraysUsingStaticDataBlobs + || (isEnumTy cenv.g elemTy) + then + GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel + else + // Try to emit a constant byte-blob array + let elemsArray = Array.ofList elems + + let test, write = + match stripDebugPoints elemsArray[0] with + | Expr.Const (Const.Bool _, _, _) -> + (function + | Const.Bool _ -> true + | _ -> false), + (fun (buf: ByteBuffer) -> + function + | Const.Bool b -> buf.EmitBoolAsByte b + | _ -> failwith "unreachable") + | Expr.Const (Const.Char _, _, _) -> + (function + | Const.Char _ -> true + | _ -> false), + (fun buf -> + function + | Const.Char b -> buf.EmitInt32AsUInt16(int b) + | _ -> failwith "unreachable") + | Expr.Const (Const.Byte _, _, _) -> + (function + | Const.Byte _ -> true + | _ -> false), + (fun buf -> + function + | Const.Byte b -> buf.EmitByte b + | _ -> failwith "unreachable") + | Expr.Const (Const.UInt16 _, _, _) -> + (function + | Const.UInt16 _ -> true + | _ -> false), + (fun buf -> + function + | Const.UInt16 b -> buf.EmitUInt16 b + | _ -> failwith "unreachable") + | Expr.Const (Const.UInt32 _, _, _) -> + (function + | Const.UInt32 _ -> true + | _ -> false), + (fun buf -> + function + | Const.UInt32 b -> buf.EmitInt32(int32 b) + | _ -> failwith "unreachable") + | Expr.Const (Const.UInt64 _, _, _) -> + (function + | Const.UInt64 _ -> true + | _ -> false), + (fun buf -> + function + | Const.UInt64 b -> buf.EmitInt64(int64 b) + | _ -> failwith "unreachable") + | Expr.Const (Const.SByte _, _, _) -> + (function + | Const.SByte _ -> true + | _ -> false), + (fun buf -> + function + | Const.SByte b -> buf.EmitByte(byte b) + | _ -> failwith "unreachable") + | Expr.Const (Const.Int16 _, _, _) -> + (function + | Const.Int16 _ -> true + | _ -> false), + (fun buf -> + function + | Const.Int16 b -> buf.EmitUInt16(uint16 b) + | _ -> failwith "unreachable") + | Expr.Const (Const.Int32 _, _, _) -> + (function + | Const.Int32 _ -> true + | _ -> false), + (fun buf -> + function + | Const.Int32 b -> buf.EmitInt32 b + | _ -> failwith "unreachable") + | Expr.Const (Const.Int64 _, _, _) -> + (function + | Const.Int64 _ -> true + | _ -> false), + (fun buf -> + function + | Const.Int64 b -> buf.EmitInt64 b + | _ -> failwith "unreachable") + | _ -> + (function + | _ -> false), + (fun _ _ -> failwith "unreachable") + + if + elemsArray + |> Array.forall (function + | Expr.Const (c, _, _) -> test c + | _ -> false) + then + let ilElemTy = GenType cenv m eenv.tyenv elemTy + + GenConstArray cenv cgbuf eenv ilElemTy elemsArray (fun buf -> + function + | Expr.Const (c, _, _) -> write buf c + | _ -> failwith "unreachable") + + GenSequel cenv eenv.cloc cgbuf sequel + + else + GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel + +and GenCoerce cenv cgbuf eenv (e, tgtTy, m, srcTy) sequel = let g = cenv.g // Is this an upcast? - if TypeDefinitelySubsumesTypeNoCoercion 0 g cenv.amap m tgty srcty && + if + TypeDefinitelySubsumesTypeNoCoercion 0 g cenv.amap m tgtTy srcTy + && // Do an extra check - should not be needed - TypeFeasiblySubsumesType 0 g cenv.amap m tgty NoCoerce srcty + TypeFeasiblySubsumesType 0 g cenv.amap m tgtTy NoCoerce srcTy then - if isInterfaceTy g tgty then + if isInterfaceTy g tgtTy then GenExpr cenv cgbuf eenv e Continue - let ilToTy = GenType cenv m eenv.tyenv tgty + let ilToTy = GenType cenv m eenv.tyenv tgtTy // Section "III.1.8.1.3 Merging stack states" of ECMA-335 implies that no unboxing // is required, but we still push the coerced type on to the code gen buffer. - CG.EmitInstrs cgbuf (pop 1) (Push [ilToTy]) [] + CG.EmitInstrs cgbuf (pop 1) (Push [ ilToTy ]) [] GenSequel cenv eenv.cloc cgbuf sequel else GenExpr cenv cgbuf eenv e sequel else GenExpr cenv cgbuf eenv e Continue - if not (isObjTy g srcty) then - let ilFromTy = GenType cenv m eenv.tyenv srcty - CG.EmitInstr cgbuf (pop 1) (Push [g.ilg.typ_Object]) (I_box ilFromTy) - if not (isObjTy g tgty) then - let ilToTy = GenType cenv m eenv.tyenv tgty - CG.EmitInstr cgbuf (pop 1) (Push [ilToTy]) (I_unbox_any ilToTy) + + if not (isObjTy g srcTy) then + let ilFromTy = GenType cenv m eenv.tyenv srcTy + CG.EmitInstr cgbuf (pop 1) (Push [ g.ilg.typ_Object ]) (I_box ilFromTy) + + if not (isObjTy g tgtTy) then + let ilToTy = GenType cenv m eenv.tyenv tgtTy + CG.EmitInstr cgbuf (pop 1) (Push [ ilToTy ]) (I_unbox_any ilToTy) + GenSequel cenv eenv.cloc cgbuf sequel -and GenReraise cenv cgbuf eenv (rtnty, m) sequel = - let ilReturnTy = GenType cenv m eenv.tyenv rtnty +and GenReraise cenv cgbuf eenv (retTy, m) sequel = + let ilReturnTy = GenType cenv m eenv.tyenv retTy CG.EmitInstr cgbuf (pop 0) Push0 I_rethrow // [See comment related to I_throw]. // Rethrow does not return. Required to push dummy value on the stack. // This follows prior behaviour by prim-types reraise<_>. - CG.EmitInstrs cgbuf (pop 0) (Push [ilReturnTy]) [AI_ldnull; I_unbox_any ilReturnTy ] + CG.EmitInstrs cgbuf (pop 0) (Push [ ilReturnTy ]) [ AI_ldnull; I_unbox_any ilReturnTy ] GenSequel cenv eenv.cloc cgbuf sequel and GenGetExnField cenv cgbuf eenv (e, ecref, fieldNum, m) sequel = @@ -3070,8 +3734,10 @@ and GenGetExnField cenv cgbuf eenv (e, ecref, fieldNum, m) sequel = let fld = List.item fieldNum exnc.TrueInstanceFieldsAsList let ftyp = GenType cenv m eenv.tyenv fld.FormalType - let mspec = mkILNonGenericInstanceMethSpecInTy (ty, "get_" + fld.LogicalName, [], ftyp) - CG.EmitInstr cgbuf (pop 1) (Push [ftyp]) (mkNormalCall mspec) + let mspec = + mkILNonGenericInstanceMethSpecInTy (ty, "get_" + fld.LogicalName, [], ftyp) + + CG.EmitInstr cgbuf (pop 1) (Push [ ftyp ]) (mkNormalCall mspec) GenSequel cenv eenv.cloc cgbuf sequel @@ -3084,18 +3750,29 @@ and GenSetExnField cenv cgbuf eenv (e, ecref, fieldNum, e2, m) sequel = let ftyp = GenType cenv m eenv.tyenv fld.FormalType let ilFieldName = ComputeFieldName exnc fld GenExpr cenv cgbuf eenv e2 Continue - CG.EmitInstr cgbuf (pop 2) Push0 (mkNormalStfld(mkILFieldSpecInTy (ty, ilFieldName, ftyp))) + CG.EmitInstr cgbuf (pop 2) Push0 (mkNormalStfld (mkILFieldSpecInTy (ty, ilFieldName, ftyp))) GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel and UnionCodeGen (cgbuf: CodeGenBuffer) = { new EraseUnions.ICodeGen with member _.CodeLabel m = m.CodeLabel - member _.GenerateDelayMark() = CG.GenerateDelayMark cgbuf "unionCodeGenMark" - member _.GenLocal ilTy = cgbuf.AllocLocal([], ilTy, false) |> uint16 + + member _.GenerateDelayMark() = + CG.GenerateDelayMark cgbuf "unionCodeGenMark" + + member _.GenLocal ilTy = + cgbuf.AllocLocal([], ilTy, false) |> uint16 + member _.SetMarkToHere m = CG.SetMarkToHere cgbuf m - member _.MkInvalidCastExnNewobj () = mkInvalidCastExnNewobj cgbuf.mgbuf.cenv.g + + member _.MkInvalidCastExnNewobj() = + mkInvalidCastExnNewobj cgbuf.mgbuf.cenv.g + member _.EmitInstr x = CG.EmitInstr cgbuf (pop 0) (Push []) x - member _.EmitInstrs xs = CG.EmitInstrs cgbuf (pop 0) (Push []) xs } + + member _.EmitInstrs xs = + CG.EmitInstrs cgbuf (pop 0) (Push []) xs + } and GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel = let g = cenv.g @@ -3104,7 +3781,7 @@ and GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel = let fty = EraseUnions.GetILTypeForAlternative cuspec idx let avoidHelpers = entityRefInThisAssembly g.compilingFSharpCore ucref.TyconRef EraseUnions.emitCastData g.ilg (UnionCodeGen cgbuf) (false, avoidHelpers, cuspec, idx) - CG.EmitInstrs cgbuf (pop 1) (Push [fty]) [ ] // push/pop to match the line above + CG.EmitInstrs cgbuf (pop 1) (Push [ fty ]) [] // push/pop to match the line above GenSequel cenv eenv.cloc cgbuf sequel and GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel = @@ -3115,7 +3792,7 @@ and GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel = let cuspec, idx = GenUnionCaseSpec cenv m eenv.tyenv ucref tyargs let fty = actualTypOfIlxUnionField cuspec idx n let avoidHelpers = entityRefInThisAssembly g.compilingFSharpCore ucref.TyconRef - CG.EmitInstr cgbuf (pop 1) (Push [fty]) (EraseUnions.mkLdData (avoidHelpers, cuspec, idx, n)) + CG.EmitInstr cgbuf (pop 1) (Push [ fty ]) (EraseUnions.mkLdData (avoidHelpers, cuspec, idx, n)) GenSequel cenv eenv.cloc cgbuf sequel and GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel = @@ -3126,7 +3803,7 @@ and GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel = let cuspec, idx = GenUnionCaseSpec cenv m eenv.tyenv ucref tyargs let fty = actualTypOfIlxUnionField cuspec idx n let avoidHelpers = entityRefInThisAssembly g.compilingFSharpCore ucref.TyconRef - CG.EmitInstr cgbuf (pop 1) (Push [ILType.Byref fty]) (EraseUnions.mkLdDataAddr (avoidHelpers, cuspec, idx, n)) + CG.EmitInstr cgbuf (pop 1) (Push [ ILType.Byref fty ]) (EraseUnions.mkLdDataAddr (avoidHelpers, cuspec, idx, n)) GenSequel cenv eenv.cloc cgbuf sequel and GenGetUnionCaseTag cenv cgbuf eenv (e, tcref, tyargs, m) sequel = @@ -3135,7 +3812,7 @@ and GenGetUnionCaseTag cenv cgbuf eenv (e, tcref, tyargs, m) sequel = let cuspec = GenUnionSpec cenv m eenv.tyenv tcref tyargs let avoidHelpers = entityRefInThisAssembly g.compilingFSharpCore tcref EraseUnions.emitLdDataTag g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec) - CG.EmitInstrs cgbuf (pop 1) (Push [g.ilg.typ_Int32]) [ ] // push/pop to match the line above + CG.EmitInstrs cgbuf (pop 1) (Push [ g.ilg.typ_Int32 ]) [] // push/pop to match the line above GenSequel cenv eenv.cloc cgbuf sequel and GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel = @@ -3144,7 +3821,7 @@ and GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel = let cuspec, idx = GenUnionCaseSpec cenv m eenv.tyenv ucref tyargs let avoidHelpers = entityRefInThisAssembly g.compilingFSharpCore ucref.TyconRef EraseUnions.emitCastData g.ilg (UnionCodeGen cgbuf) (false, avoidHelpers, cuspec, idx) - CG.EmitInstrs cgbuf (pop 1) (Push [cuspec.DeclaringType]) [ ] // push/pop to match the line above + CG.EmitInstrs cgbuf (pop 1) (Push [ cuspec.DeclaringType ]) [] // push/pop to match the line above GenExpr cenv cgbuf eenv e2 Continue CG.EmitInstr cgbuf (pop 2) Push0 (EraseUnions.mkStData (cuspec, idx, n)) GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel @@ -3152,12 +3829,12 @@ and GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel = and GenGetRecdFieldAddr cenv cgbuf eenv (e, f, tyargs, m) sequel = GenExpr cenv cgbuf eenv e Continue let fref = GenRecdFieldRef m cenv eenv.tyenv f tyargs - CG.EmitInstr cgbuf (pop 1) (Push [ILType.Byref fref.ActualType]) (I_ldflda fref) + CG.EmitInstr cgbuf (pop 1) (Push [ ILType.Byref fref.ActualType ]) (I_ldflda fref) GenSequel cenv eenv.cloc cgbuf sequel and GenGetStaticFieldAddr cenv cgbuf eenv (f, tyargs, m) sequel = let fspec = GenRecdFieldRef m cenv eenv.tyenv f tyargs - CG.EmitInstr cgbuf (pop 0) (Push [ILType.Byref fspec.ActualType]) (I_ldsflda fspec) + CG.EmitInstr cgbuf (pop 0) (Push [ ILType.Byref fspec.ActualType ]) (I_ldsflda fspec) GenSequel cenv eenv.cloc cgbuf sequel and GenGetRecdField cenv cgbuf eenv (e, f, tyargs, m) sequel = @@ -3178,31 +3855,61 @@ and GenSetStaticField cenv cgbuf eenv (f, tyargs, e2, m) sequel = GenExpr cenv cgbuf eenv e2 Continue GenFieldStore true cenv cgbuf eenv (f, tyargs, m) sequel -and mk_field_pops isStatic n = if isStatic then pop n else pop (n+1) - +and mk_field_pops isStatic n = if isStatic then pop n else pop (n + 1) and GenFieldGet isStatic cenv cgbuf eenv (rfref: RecdFieldRef, tyargs, m) = let fspec = GenRecdFieldRef m cenv eenv.tyenv rfref tyargs let vol = if rfref.RecdField.IsVolatile then Volatile else Nonvolatile - if useGenuineField rfref.Tycon rfref.RecdField || entityRefInThisAssembly cenv.g.compilingFSharpCore rfref.TyconRef then - let instr = if isStatic then I_ldsfld(vol, fspec) else I_ldfld (ILAlignment.Aligned, vol, fspec) - CG.EmitInstr cgbuf (mk_field_pops isStatic 0) (Push [fspec.ActualType]) instr + + if + useGenuineField rfref.Tycon rfref.RecdField + || entityRefInThisAssembly cenv.g.compilingFSharpCore rfref.TyconRef + then + let instr = + if isStatic then + I_ldsfld(vol, fspec) + else + I_ldfld(ILAlignment.Aligned, vol, fspec) + + CG.EmitInstr cgbuf (mk_field_pops isStatic 0) (Push [ fspec.ActualType ]) instr else - let cconv = if isStatic then ILCallingConv.Static else ILCallingConv.Instance - let mspec = mkILMethSpecInTy (fspec.DeclaringType, cconv, "get_" + rfref.RecdField.rfield_id.idText, [], fspec.FormalType, []) - CG.EmitInstr cgbuf (mk_field_pops isStatic 0) (Push [fspec.ActualType]) (mkNormalCall mspec) + let cconv = + if isStatic then + ILCallingConv.Static + else + ILCallingConv.Instance + + let mspec = + mkILMethSpecInTy (fspec.DeclaringType, cconv, "get_" + rfref.RecdField.rfield_id.idText, [], fspec.FormalType, []) + + CG.EmitInstr cgbuf (mk_field_pops isStatic 0) (Push [ fspec.ActualType ]) (mkNormalCall mspec) and GenFieldStore isStatic cenv cgbuf eenv (rfref: RecdFieldRef, tyargs, m) sequel = let fspec = GenRecdFieldRef m cenv eenv.tyenv rfref tyargs let fld = rfref.RecdField + if fld.IsMutable && not (useGenuineField rfref.Tycon fld) then - let cconv = if isStatic then ILCallingConv.Static else ILCallingConv.Instance - let mspec = mkILMethSpecInTy (fspec.DeclaringType, cconv, "set_" + fld.rfield_id.idText, [fspec.FormalType], ILType.Void, []) + let cconv = + if isStatic then + ILCallingConv.Static + else + ILCallingConv.Instance + + let mspec = + mkILMethSpecInTy (fspec.DeclaringType, cconv, "set_" + fld.rfield_id.idText, [ fspec.FormalType ], ILType.Void, []) + CG.EmitInstr cgbuf (mk_field_pops isStatic 1) Push0 (mkNormalCall mspec) else let vol = if rfref.RecdField.IsVolatile then Volatile else Nonvolatile - let instr = if isStatic then I_stsfld (vol, fspec) else I_stfld (ILAlignment.Aligned, vol, fspec) + + let instr = + if isStatic then + I_stsfld(vol, fspec) + else + I_stfld(ILAlignment.Aligned, vol, fspec) + CG.EmitInstr cgbuf (mk_field_pops isStatic 1) Push0 instr + GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel //-------------------------------------------------------------------------- @@ -3213,45 +3920,51 @@ and GenFieldStore isStatic cenv cgbuf eenv (rfref: RecdFieldRef, tyargs, m) sequ /// to a method or value compiled as a method taking no arguments and GenUntupledArgsDiscardingLoneUnit cenv cgbuf eenv m numObjArgs curriedArgInfos args = let g = cenv.g + match curriedArgInfos, args with // Type.M() // new C() - | [[]], [arg] when numObjArgs = 0 -> + | [ [] ], [ arg ] when numObjArgs = 0 -> assert isUnitTy g (tyOfExpr g arg) GenExpr cenv cgbuf eenv arg discard // obj.M() - | [[_];[]], [arg1;arg2] when numObjArgs = 1 -> + | [ [ _ ]; [] ], [ arg1; arg2 ] when numObjArgs = 1 -> assert isUnitTy g (tyOfExpr g arg2) GenExpr cenv cgbuf eenv arg1 Continue GenExpr cenv cgbuf eenv arg2 discard | _ -> - (curriedArgInfos, args) ||> List.iter2 (fun argInfos x -> - GenUntupledArgExpr cenv cgbuf eenv m argInfos x) + (curriedArgInfos, args) + ||> List.iter2 (fun argInfos x -> GenUntupledArgExpr cenv cgbuf eenv m argInfos x) /// Codegen arguments and GenUntupledArgExpr cenv cgbuf eenv m argInfos expr = let g = cenv.g let numRequiredExprs = List.length argInfos + if numRequiredExprs = 0 then () elif numRequiredExprs = 1 then GenExpr cenv cgbuf eenv expr Continue elif isRefTupleExpr expr then let es = tryDestRefTupleExpr expr - if es.Length <> numRequiredExprs then error(InternalError("GenUntupledArgExpr (2)", m)) + + if es.Length <> numRequiredExprs then + error (InternalError("GenUntupledArgExpr (2)", m)) + es |> List.iter (fun x -> GenExpr cenv cgbuf eenv x Continue) else let ty = tyOfExpr g expr let locv, loce = mkCompGenLocal m "arg" ty let bind = mkCompGenBind locv expr + LocalScope "untuple" cgbuf (fun scopeMarks -> let eenvinner = AllocStorageForBind cenv cgbuf scopeMarks eenv bind GenBinding cenv cgbuf eenvinner bind false let tys = destRefTupleTy g ty assert (tys.Length = numRequiredExprs) - argInfos |> List.iteri (fun i _ -> GenGetTupleField cenv cgbuf eenvinner (tupInfoRef, loce, tys, i, m) Continue) - ) + argInfos + |> List.iteri (fun i _ -> GenGetTupleField cenv cgbuf eenvinner (tupInfoRef, loce, tys, i, m) Continue)) //-------------------------------------------------------------------------- // Generate calls (try to detect direct calls) @@ -3260,11 +3973,13 @@ and GenUntupledArgExpr cenv cgbuf eenv m argInfos expr = and GenWitnessArgFromTraitInfo cenv cgbuf eenv m traitInfo = let g = cenv.g let storage = TryStorageForWitness g eenv traitInfo.TraitKey + match storage with | None -> let witnessExpr = - ConstraintSolver.CodegenWitnessArgForTraitConstraint cenv.tcVal g cenv.amap m traitInfo + ConstraintSolver.CodegenWitnessArgForTraitConstraint cenv.tcVal g cenv.amap m traitInfo |> CommitOperationResult + match witnessExpr with | Choice1Of2 _traitInfo -> System.Diagnostics.Debug.Assert(false, "expected storage for witness") @@ -3279,6 +3994,7 @@ and GenWitnessArgFromTraitInfo cenv cgbuf eenv m traitInfo = and GenWitnessArgFromWitnessInfo cenv cgbuf eenv m witnessInfo = let g = cenv.g let storage = TryStorageForWitness g eenv witnessInfo + match storage with | None -> System.Diagnostics.Debug.Assert(false, "expected storage for witness") @@ -3306,40 +4022,42 @@ and GenWitnessArgs cenv cgbuf eenv m tps tyargs = for witnessArg in mwitnesses do match witnessArg with - | Choice1Of2 traitInfo -> - GenWitnessArgFromTraitInfo cenv cgbuf eenv m traitInfo - | Choice2Of2 arg -> - GenExpr cenv cgbuf eenv arg Continue + | Choice1Of2 traitInfo -> GenWitnessArgFromTraitInfo cenv cgbuf eenv m traitInfo + | Choice2Of2 arg -> GenExpr cenv cgbuf eenv arg Continue and IsBranchTailcall (cenv: cenv) eenv (v: ValRef, tyargs, curriedArgs: _ list) sequel = let g = cenv.g + match ListAssoc.tryFind g.valRefEq v eenv.innerVals with | Some (kind, _) -> - not v.IsConstructor && + not v.IsConstructor + && // when branch-calling methods we must have the right type parameters (match kind with - | BranchCallClosure _ -> true - | BranchCallMethod (_, _, tps, _, _, _) -> - (List.lengthsEqAndForall2 (fun ty tp -> typeEquiv g ty (mkTyparTy tp)) tyargs tps)) && + | BranchCallClosure _ -> true + | BranchCallMethod (_, _, tps, _, _, _) -> (List.lengthsEqAndForall2 (fun ty tp -> typeEquiv g ty (mkTyparTy tp)) tyargs tps)) + && // must be exact #args, ignoring tupling - we untuple if needed below (let arityInfo = match kind with | BranchCallClosure arityInfo - | BranchCallMethod (arityInfo, _, _, _, _, _) -> arityInfo - arityInfo.Length = curriedArgs.Length - ) && - // no tailcall out of exception handler, etc. - (match sequelIgnoringEndScopesAndDiscard sequel with - | Return - | ReturnVoid -> true - | _ -> false) + | BranchCallMethod (arityInfo, _, _, _, _, _) -> arityInfo + + arityInfo.Length = curriedArgs.Length) + && + // no tailcall out of exception handler, etc. + (match sequelIgnoringEndScopesAndDiscard sequel with + | Return + | ReturnVoid -> true + | _ -> false) | None -> false and GenApp (cenv: cenv) cgbuf eenv (f, fty, tyargs, curriedArgs, m) sequel = - let g = cenv.g - match (stripDebugPoints f, tyargs, curriedArgs) with - // Look for tailcall to turn into branch - | Expr.Val (v, _, _), _, _ when IsBranchTailcall cenv eenv (v, tyargs, curriedArgs) sequel -> + let g = cenv.g + + match (stripDebugPoints f, tyargs, curriedArgs) with + // Look for tailcall to turn into branch + | Expr.Val (v, _, _), _, _ when IsBranchTailcall cenv eenv (v, tyargs, curriedArgs) sequel -> let kind, mark = ListAssoc.find g.valRefEq v eenv.innerVals // already checked above in when guard // Generate the arguments for the direct tail call. @@ -3355,10 +4073,10 @@ and GenApp (cenv: cenv) cgbuf eenv (f, fty, tyargs, curriedArgs, m) sequel = let numArgs = List.sum arityInfo for i = numArgs - 1 downto 0 do - CG.EmitInstr cgbuf (pop 1) Push0 (I_starg (uint16 (cgbuf.PreallocatedArgCount + i))) + CG.EmitInstr cgbuf (pop 1) Push0 (I_starg(uint16 (cgbuf.PreallocatedArgCount + i))) | BranchCallMethod (arityInfo, curriedArgInfos, _, numObjArgs, numWitnessArgs, numMethodArgs) -> - assert (curriedArgInfos.Length = arityInfo.Length ) + assert (curriedArgInfos.Length = arityInfo.Length) assert (curriedArgInfos.Length = curriedArgs.Length) //assert (curriedArgInfos.Length = numArgs ) @@ -3372,201 +4090,252 @@ and GenApp (cenv: cenv) cgbuf eenv (f, fty, tyargs, curriedArgs, m) sequel = if v.IsExtensionMember then match curriedArgInfos, curriedArgs with // static extension method with empty arguments. - | [[]], [_] when numObjArgs = 0 -> 0 + | [ [] ], [ _ ] when numObjArgs = 0 -> 0 // instance extension method with empty arguments. - | [[_];[]], [_;_] when numObjArgs = 0 -> 1 + | [ [ _ ]; [] ], [ _; _ ] when numObjArgs = 0 -> 1 | _ -> numMethodArgs - else numMethodArgs + else + numMethodArgs for i = numArgs - 1 downto 0 do - CG.EmitInstr cgbuf (pop 1) Push0 (I_starg (uint16 (cgbuf.PreallocatedArgCount + numObjArgs + numWitnessArgs + i))) + CG.EmitInstr cgbuf (pop 1) Push0 (I_starg(uint16 (cgbuf.PreallocatedArgCount + numObjArgs + numWitnessArgs + i))) // Note, we don't reassign the witness arguments as these wont' have changed, because the type parameters are identical for i = numObjArgs - 1 downto 0 do - CG.EmitInstr cgbuf (pop 1) Push0 (I_starg (uint16 (cgbuf.PreallocatedArgCount + i))) + CG.EmitInstr cgbuf (pop 1) Push0 (I_starg(uint16 (cgbuf.PreallocatedArgCount + i))) CG.EmitInstr cgbuf (pop 0) Push0 (I_br mark.CodeLabel) GenSequelEndScopes cgbuf sequel - // PhysicalEquality becomes cheap reference equality once - // a nominal type is known. We can't replace it for variable types since - // a "ceq" instruction can't be applied to variable type values. - | Expr.Val (v, _, _), [ty], [arg1;arg2] when - (valRefEq g v g.reference_equality_inner_vref) - && isAppTy g ty -> - - GenExpr cenv cgbuf eenv arg1 Continue - GenExpr cenv cgbuf eenv arg2 Continue - CG.EmitInstr cgbuf (pop 2) (Push [g.ilg.typ_Bool]) AI_ceq - GenSequel cenv eenv.cloc cgbuf sequel - - | Expr.Val (v, _, m), _, _ - when valRefEq g v g.cgh__resumeAt_vref || - valRefEq g v g.cgh__resumableEntry_vref || - valRefEq g v g.cgh__stateMachine_vref - -> - errorR(Error(FSComp.SR.ilxgenInvalidConstructInStateMachineDuringCodegen(v.DisplayName), m)) - CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Object]) AI_ldnull + // PhysicalEquality becomes cheap reference equality once + // a nominal type is known. We can't replace it for variable types since + // a "ceq" instruction can't be applied to variable type values. + | Expr.Val (v, _, _), [ ty ], [ arg1; arg2 ] when (valRefEq g v g.reference_equality_inner_vref) && isAppTy g ty -> + + GenExpr cenv cgbuf eenv arg1 Continue + GenExpr cenv cgbuf eenv arg2 Continue + CG.EmitInstr cgbuf (pop 2) (Push [ g.ilg.typ_Bool ]) AI_ceq + GenSequel cenv eenv.cloc cgbuf sequel + + | Expr.Val (v, _, m), _, _ when + valRefEq g v g.cgh__resumeAt_vref + || valRefEq g v g.cgh__resumableEntry_vref + || valRefEq g v g.cgh__stateMachine_vref + -> + errorR (Error(FSComp.SR.ilxgenInvalidConstructInStateMachineDuringCodegen (v.DisplayName), m)) + CG.EmitInstr cgbuf (pop 0) (Push [ g.ilg.typ_Object ]) AI_ldnull GenSequel cenv eenv.cloc cgbuf sequel - // Emit "methodhandleof" calls as ldtoken instructions - // - // The token for the "GenericMethodDefinition" is loaded - | Expr.Val (v, _, m), _, [arg] when valRefEq g v g.methodhandleof_vref -> - let (|OptionalCoerce|) x = match stripDebugPoints x with Expr.Op (TOp.Coerce _, _, [arg], _) -> arg | x -> x - let (|OptionalTyapp|) x = match stripDebugPoints x with Expr.App (f, _, [_], [], _) -> f | x -> x + // Emit "methodhandleof" calls as ldtoken instructions + // + // The token for the "GenericMethodDefinition" is loaded + | Expr.Val (v, _, m), _, [ arg ] when valRefEq g v g.methodhandleof_vref -> + let (|OptionalCoerce|) x = + match stripDebugPoints x with + | Expr.Op (TOp.Coerce _, _, [ arg ], _) -> arg + | x -> x + + let (|OptionalTyapp|) x = + match stripDebugPoints x with + | Expr.App (f, _, [ _ ], [], _) -> f + | x -> x + match stripDebugPoints arg with // Generate ldtoken instruction for "methodhandleof(fun (a, b, c) -> f(a, b, c))" // where f is an F# function value or F# method - | Expr.Lambda (_, _, _, _, DebugPoints(Expr.App (OptionalCoerce(OptionalTyapp(Expr.Val (vref, _, _))), _, _, _, _), _), _, _) -> + | Expr.Lambda (_, _, _, _, DebugPoints (Expr.App (OptionalCoerce (OptionalTyapp (Expr.Val (vref, _, _))), _, _, _, _), _), _, _) -> + + let storage = StorageForValRef m vref eenv - let storage = StorageForValRef g m vref eenv match storage with | Method (_, _, mspec, _, _, _, _, _, _, _, _, _) -> - CG.EmitInstr cgbuf (pop 0) (Push [g.iltyp_RuntimeMethodHandle]) (I_ldtoken (ILToken.ILMethod mspec)) - | _ -> - errorR(Error(FSComp.SR.ilxgenUnexpectedArgumentToMethodHandleOfDuringCodegen(), m)) + CG.EmitInstr cgbuf (pop 0) (Push [ g.iltyp_RuntimeMethodHandle ]) (I_ldtoken(ILToken.ILMethod mspec)) + | _ -> errorR (Error(FSComp.SR.ilxgenUnexpectedArgumentToMethodHandleOfDuringCodegen (), m)) // Generate ldtoken instruction for "methodhandleof(fun (a, b, c) -> obj.M(a, b, c))" // where M is an IL method. - | Expr.Lambda (_, _, _, _, DebugPoints (Expr.Op (TOp.ILCall (_, _, isStruct, _, _, _, _, ilMethRef, enclTypeInst, methInst, _), _, _, _), _), _, _) -> + | Expr.Lambda (_, + _, + _, + _, + DebugPoints (Expr.Op (TOp.ILCall (_, _, isStruct, _, _, _, _, ilMethRef, enclTypeInst, methInst, _), _, _, _), _), + _, + _) -> let boxity = (if isStruct then AsValue else AsObject) - let mkFormalParams gparams = gparams |> DropErasedTyargs |> List.mapi (fun n _gf -> mkILTyvarTy (uint16 n)) - let ilGenericMethodSpec = mkILMethSpec (ilMethRef, boxity, mkFormalParams enclTypeInst, mkFormalParams methInst) - let i = I_ldtoken (ILToken.ILMethod ilGenericMethodSpec) - CG.EmitInstr cgbuf (pop 0) (Push [g.iltyp_RuntimeMethodHandle]) i + + let mkFormalParams gparams = + gparams |> DropErasedTyargs |> List.mapi (fun n _gf -> mkILTyvarTy (uint16 n)) + + let ilGenericMethodSpec = + mkILMethSpec (ilMethRef, boxity, mkFormalParams enclTypeInst, mkFormalParams methInst) + + let i = I_ldtoken(ILToken.ILMethod ilGenericMethodSpec) + CG.EmitInstr cgbuf (pop 0) (Push [ g.iltyp_RuntimeMethodHandle ]) i | _ -> System.Diagnostics.Debug.Assert(false, sprintf "Break for invalid methodhandleof argument expression") //System.Diagnostics.Debugger.Break() - errorR(Error(FSComp.SR.ilxgenUnexpectedArgumentToMethodHandleOfDuringCodegen(), m)) + errorR (Error(FSComp.SR.ilxgenUnexpectedArgumentToMethodHandleOfDuringCodegen (), m)) GenSequel cenv eenv.cloc cgbuf sequel - // Optimize calls to top methods when given "enough" arguments. - | Expr.Val (vref, valUseFlags, _), _, _ - when - (let storage = StorageForValRef g m vref eenv - match storage with - | Method (topValInfo, vref, _, _, _, _, _, _, _, _, _, _) -> - (let tps, argTys, _, _ = GetTopValTypeInFSharpForm g topValInfo vref.Type m - tps.Length = tyargs.Length && - argTys.Length <= curriedArgs.Length) - | _ -> false) -> + // Optimize calls to top methods when given "enough" arguments. + | Expr.Val (vref, valUseFlags, _), _, _ when + (let storage = StorageForValRef m vref eenv - let storage = StorageForValRef g m vref eenv - match storage with - | Method (topValInfo, vref, mspec, mspecW, _, ctps, mtps, curriedArgInfos, _, _, _, _) -> + match storage with + | Method (valReprInfo, vref, _, _, _, _, _, _, _, _, _, _) -> + (let tps, argTys, _, _ = GetTopValTypeInFSharpForm g valReprInfo vref.Type m + tps.Length = tyargs.Length && argTys.Length <= curriedArgs.Length) + | _ -> false) + -> - let nowArgs, laterArgs = List.splitAt curriedArgInfos.Length curriedArgs + let storage = StorageForValRef m vref eenv - let actualRetTy = applyTys cenv.g vref.Type (tyargs, nowArgs) + match storage with + | Method (valReprInfo, vref, mspec, mspecW, _, ctps, mtps, curriedArgInfos, _, _, _, _) -> - let _, witnessInfos, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm cenv.g topValInfo ctps.Length vref.Type m + let nowArgs, laterArgs = List.splitAt curriedArgInfos.Length curriedArgs - let mspec = - let generateWitnesses = ComputeGenerateWitnesses g eenv - if not generateWitnesses || witnessInfos.IsEmpty then - mspec - else - mspecW - - let ilTyArgs = GenTypeArgs cenv m eenv.tyenv tyargs - - // For instance method calls chop off some type arguments, which are already - // carried by the class. Also work out if it's a virtual call. - let _, virtualCall, newobj, isSuperInit, isSelfInit, takesInstanceArg, _, _ = GetMemberCallInfo g (vref, valUseFlags) - - // numEnclILTypeArgs will include unit-of-measure args, unfortunately. For now, just cut-and-paste code from GetMemberCallInfo - // @REVIEW: refactor this - let numEnclILTypeArgs = - match vref.MemberInfo with - | Some _ when not vref.IsExtensionMember -> - List.length(vref.MemberApparentEntity.TyparsNoRange |> DropErasedTypars) - | _ -> 0 - - let ilEnclArgTys, ilMethArgTys = - if ilTyArgs.Length < numEnclILTypeArgs then error(InternalError("length mismatch", m)) - List.splitAt numEnclILTypeArgs ilTyArgs - - let boxity = mspec.DeclaringType.Boxity - let mspec = mkILMethSpec (mspec.MethodRef, boxity, ilEnclArgTys, ilMethArgTys) - - // "Unit" return types on static methods become "void" - let mustGenerateUnitAfterCall = Option.isNone returnTy - - let ccallInfo = - match valUseFlags with - | PossibleConstrainedCall ty -> Some ty - | _ -> None - - let isBaseCall = match valUseFlags with VSlotDirectCall -> true | _ -> false - - let isTailCall = - if isNil laterArgs && not isSelfInit then - let isDllImport = IsValRefIsDllImport g vref - let hasByrefArg = mspec.FormalArgTypes |> List.exists IsILTypeByref - let makesNoCriticalTailcalls = vref.MakesNoCriticalTailcalls - let hasStructObjArg = (boxity=AsValue) && takesInstanceArg - CanTailcall(hasStructObjArg, ccallInfo, eenv.withinSEH, hasByrefArg, mustGenerateUnitAfterCall, isDllImport, isSelfInit, makesNoCriticalTailcalls, sequel) - else - Normalcall - - let useICallVirt = virtualCall || useCallVirt cenv boxity mspec isBaseCall - - let callInstr = - match valUseFlags with - | PossibleConstrainedCall ty -> - let ilThisTy = GenType cenv m eenv.tyenv ty - I_callconstraint ( isTailCall, ilThisTy, mspec, None) - | _ -> - if newobj then I_newobj (mspec, None) - elif useICallVirt then I_callvirt (isTailCall, mspec, None) - else I_call (isTailCall, mspec, None) - - // ok, now we're ready to generate - if isSuperInit || isSelfInit then - CG.EmitInstr cgbuf (pop 0) (Push [mspec.DeclaringType ]) mkLdarg0 - - if not cenv.g.generateWitnesses || witnessInfos.IsEmpty then - () // no witness args - else - let _ctyargs, mtyargs = List.splitAt ctps.Length tyargs - GenWitnessArgs cenv cgbuf eenv m mtps mtyargs - - GenUntupledArgsDiscardingLoneUnit cenv cgbuf eenv m vref.NumObjArgs curriedArgInfos nowArgs - - // Generate laterArgs (for effects) and save - LocalScope "callstack" cgbuf (fun scopeMarks -> + let actualRetTy = applyTys cenv.g vref.Type (tyargs, nowArgs) + + let _, witnessInfos, curriedArgInfos, returnTy, _ = + GetTopValTypeInCompiledForm cenv.g valReprInfo ctps.Length vref.Type m + + let mspec = + let generateWitnesses = ComputeGenerateWitnesses g eenv + + if not generateWitnesses || witnessInfos.IsEmpty then + mspec + else + mspecW + + let ilTyArgs = GenTypeArgs cenv m eenv.tyenv tyargs + + // For instance method calls chop off some type arguments, which are already + // carried by the class. Also work out if it's a virtual call. + let _, virtualCall, newobj, isSuperInit, isSelfInit, takesInstanceArg, _, _ = + GetMemberCallInfo g (vref, valUseFlags) + + // numEnclILTypeArgs will include unit-of-measure args, unfortunately. For now, just cut-and-paste code from GetMemberCallInfo + // @REVIEW: refactor this + let numEnclILTypeArgs = + match vref.MemberInfo with + | Some _ when not vref.IsExtensionMember -> List.length (vref.MemberApparentEntity.TyparsNoRange |> DropErasedTypars) + | _ -> 0 + + let ilEnclArgTys, ilMethArgTys = + if ilTyArgs.Length < numEnclILTypeArgs then + error (InternalError("length mismatch", m)) + + List.splitAt numEnclILTypeArgs ilTyArgs + + let boxity = mspec.DeclaringType.Boxity + let mspec = mkILMethSpec (mspec.MethodRef, boxity, ilEnclArgTys, ilMethArgTys) + + // "Unit" return types on static methods become "void" + let mustGenerateUnitAfterCall = Option.isNone returnTy + + let ccallInfo = + match valUseFlags with + | PossibleConstrainedCall ty -> Some ty + | _ -> None + + let isBaseCall = + match valUseFlags with + | VSlotDirectCall -> true + | _ -> false + + let isTailCall = + if isNil laterArgs && not isSelfInit then + let isDllImport = IsValRefIsDllImport g vref + let hasByrefArg = mspec.FormalArgTypes |> List.exists IsILTypeByref + let makesNoCriticalTailcalls = vref.MakesNoCriticalTailcalls + let hasStructObjArg = (boxity = AsValue) && takesInstanceArg + + CanTailcall( + hasStructObjArg, + ccallInfo, + eenv.withinSEH, + hasByrefArg, + mustGenerateUnitAfterCall, + isDllImport, + isSelfInit, + makesNoCriticalTailcalls, + sequel + ) + else + Normalcall + + let useICallVirt = virtualCall || useCallVirt cenv boxity mspec isBaseCall + + let callInstr = + match valUseFlags with + | PossibleConstrainedCall ty -> + let ilThisTy = GenType cenv m eenv.tyenv ty + I_callconstraint(isTailCall, ilThisTy, mspec, None) + | _ -> + if newobj then I_newobj(mspec, None) + elif useICallVirt then I_callvirt(isTailCall, mspec, None) + else I_call(isTailCall, mspec, None) + + // ok, now we're ready to generate + if isSuperInit || isSelfInit then + CG.EmitInstr cgbuf (pop 0) (Push [ mspec.DeclaringType ]) mkLdarg0 + + if not cenv.g.generateWitnesses || witnessInfos.IsEmpty then + () // no witness args + else + let _ctyargs, mtyargs = List.splitAt ctps.Length tyargs + GenWitnessArgs cenv cgbuf eenv m mtps mtyargs + + GenUntupledArgsDiscardingLoneUnit cenv cgbuf eenv m vref.NumObjArgs curriedArgInfos nowArgs + + // Generate laterArgs (for effects) and save + LocalScope "callstack" cgbuf (fun scopeMarks -> let whereSaved, eenv = - (eenv, laterArgs) ||> List.mapFold (fun eenv laterArg -> + (eenv, laterArgs) + ||> List.mapFold (fun eenv laterArg -> // Only save arguments that have effects if Optimizer.ExprHasEffect g laterArg then let ilTy = laterArg |> tyOfExpr g |> GenType cenv m eenv.tyenv + let locName = // Ensure that we have an g.CompilerGlobalState - assert(g.CompilerGlobalState |> Option.isSome) - g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("arg", m), ilTy, false + assert (g.CompilerGlobalState |> Option.isSome) + g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName("arg", m), ilTy, false + let loc, _realloc, eenv = AllocLocal cenv cgbuf eenv true locName scopeMarks GenExpr cenv cgbuf eenv laterArg Continue EmitSetLocal cgbuf loc - Choice1Of2 (ilTy, loc), eenv + Choice1Of2(ilTy, loc), eenv else Choice2Of2 laterArg, eenv) let nargs = mspec.FormalArgTypes.Length - let pushes = if mustGenerateUnitAfterCall || isSuperInit || isSelfInit then Push0 else (Push [(GenType cenv m eenv.tyenv actualRetTy)]) + + let pushes = + if mustGenerateUnitAfterCall || isSuperInit || isSelfInit then + Push0 + else + (Push [ (GenType cenv m eenv.tyenv actualRetTy) ]) + CG.EmitInstr cgbuf (pop (nargs + (if mspec.CallingConv.IsStatic || newobj then 0 else 1))) pushes callInstr // For isSuperInit, load the 'this' pointer as the pretend 'result' of the operation. It will be popped again in most cases - if isSuperInit then CG.EmitInstr cgbuf (pop 0) (Push [mspec.DeclaringType]) mkLdarg0 + if isSuperInit then + CG.EmitInstr cgbuf (pop 0) (Push [ mspec.DeclaringType ]) mkLdarg0 // When generating debug code, generate a 'nop' after a 'call' that returns 'void' // This is what C# does, as it allows the call location to be maintained correctly in the stack frame - if cenv.options.generateDebugSymbols && mustGenerateUnitAfterCall && (isTailCall = Normalcall) then + if + cenv.options.generateDebugSymbols + && mustGenerateUnitAfterCall + && (isTailCall = Normalcall) + then CG.EmitInstr cgbuf (pop 0) Push0 AI_nop if isNil laterArgs then @@ -3575,40 +4344,62 @@ and GenApp (cenv: cenv) cgbuf eenv (f, fty, tyargs, curriedArgs, m) sequel = CommitCallSequel cenv eenv m eenv.cloc cgbuf mustGenerateUnitAfterCall sequel else //printfn "%d EXTRA ARGS IN TOP APP at %s" laterArgs.Length (stringOfRange m) - whereSaved |> List.iter (function + whereSaved + |> List.iter (function | Choice1Of2 (ilTy, loc) -> EmitGetLocal cgbuf ilTy loc | Choice2Of2 expr -> GenExpr cenv cgbuf eenv expr Continue) + GenIndirectCall cenv cgbuf eenv (actualRetTy, [], laterArgs, m) sequel) - | _ -> failwith "??" + | _ -> failwith "??" // This case is for getting/calling a value, when we can't call it directly. // However, we know the type instantiation for the value. // In this case we can often generate a type-specific local expression for the value. // This reduces the number of dynamic type applications. - | Expr.Val (vref, _, _), _, _ -> - GenGetValRefAndSequel cenv cgbuf eenv m vref (Some (tyargs, curriedArgs, m, sequel)) - - | _ -> - (* worst case: generate a first-class function value and call *) - GenExpr cenv cgbuf eenv f Continue - GenCurriedArgsAndIndirectCall cenv cgbuf eenv (fty, tyargs, curriedArgs, m) sequel + | Expr.Val (vref, _, _), _, _ -> GenGetValRefAndSequel cenv cgbuf eenv m vref (Some(tyargs, curriedArgs, m, sequel)) -and CanTailcall (hasStructObjArg, ccallInfo, withinSEH, hasByrefArg, mustGenerateUnitAfterCall, isDllImport, isSelfInit, makesNoCriticalTailcalls, sequel) = + | _ -> + (* worst case: generate a first-class function value and call *) + GenExpr cenv cgbuf eenv f Continue + GenCurriedArgsAndIndirectCall cenv cgbuf eenv (fty, tyargs, curriedArgs, m) sequel + +and CanTailcall + ( + hasStructObjArg, + ccallInfo, + withinSEH, + hasByrefArg, + mustGenerateUnitAfterCall, + isDllImport, + isSelfInit, + makesNoCriticalTailcalls, + sequel + ) = // Can't tailcall with a struct object arg since it involves a byref // Can't tailcall with a .NET 2.0 generic constrained call since it involves a byref - if not hasStructObjArg && Option.isNone ccallInfo && not withinSEH && not hasByrefArg && - not isDllImport && not isSelfInit && not makesNoCriticalTailcalls && + if + not hasStructObjArg + && Option.isNone ccallInfo + && not withinSEH + && not hasByrefArg + && not isDllImport + && not isSelfInit + && not makesNoCriticalTailcalls + && // We can tailcall even if we need to generate "unit", as long as we're about to throw the value away anyway as par of the return. // We can tailcall if we don't need to generate "unit", as long as we're about to return. (match sequelIgnoreEndScopes sequel with - | ReturnVoid | Return -> not mustGenerateUnitAfterCall + | ReturnVoid + | Return -> not mustGenerateUnitAfterCall | DiscardThen ReturnVoid -> mustGenerateUnitAfterCall | _ -> false) - then Tailcall - else Normalcall + then + Tailcall + else + Normalcall /// Choose the names for TraitWitnessInfo representations in arguments and free variables and ChooseWitnessInfoNames takenNames (witnessInfos: TraitWitnessInfo list) = @@ -3619,26 +4410,30 @@ and ChooseWitnessInfoNames takenNames (witnessInfos: TraitWitnessInfo list) = /// Represent the TraitWitnessInfos as arguments, e.g. in local type functions and ArgStorageForWitnessInfos (cenv: cenv) (eenv: IlxGenEnv) takenNames pretakenArgs m (witnessInfos: TraitWitnessInfo list) = let names = ChooseWitnessInfoNames takenNames witnessInfos + (witnessInfos, List.indexed names) ||> List.map2 (fun w (i, nm) -> let ty = GenWitnessTy cenv.g w - let ilTy = GenType cenv m eenv.tyenv ty + let ilTy = GenType cenv m eenv.tyenv ty let ilParam = mkILParam (Some nm, ilTy) - let storage = Arg (i+pretakenArgs) + let storage = Arg(i + pretakenArgs) ilParam, (w, storage)) |> List.unzip /// Represent the TraitWitnessInfos as free variables, e.g. in closures and FreeVarStorageForWitnessInfos (cenv: cenv) (eenv: IlxGenEnv) takenNames ilCloTyInner m (witnessInfos: TraitWitnessInfo list) = let names = ChooseWitnessInfoNames takenNames witnessInfos + (witnessInfos, names) ||> List.map2 (fun w nm -> let ty = GenWitnessTy cenv.g w - let ilTy = GenType cenv m eenv.tyenv ty + let ilTy = GenType cenv m eenv.tyenv ty let ilFv = mkILFreeVar (nm, true, ilTy) + let storage = let ilField = mkILFieldSpecInTy (ilCloTyInner, ilFv.fvName, ilFv.fvType) Env(ilCloTyInner, ilField, None) + ilFv, (w, storage)) |> List.unzip @@ -3651,14 +4446,17 @@ and FreeVarStorageForWitnessInfos (cenv: cenv) (eenv: IlxGenEnv) takenNames ilCl // let foo() = // let a = 0<_> // () -// in debug code , here `a` will be a TyLamba. However the compiled representation of +// in debug code , here `a` will be a TyLamba. However the compiled representation of // `a` is an integer. -and IsLocalErasedTyLambda g eenv (v: Val) e = +and IsLocalErasedTyLambda eenv (v: Val) e = match e with | Expr.TyLambda (_, tyargs, body, _, _) when - tyargs |> List.forall (fun tp -> tp.IsErased) && - (match StorageForVal g v.Range v eenv with Local _ -> true | _ -> false) -> - match stripExpr body with + tyargs |> List.forall (fun tp -> tp.IsErased) + && (match StorageForVal v.Range v eenv with + | Local _ -> true + | _ -> false) + -> + match stripExpr body with | Expr.Lambda _ -> None | _ -> Some body | _ -> None @@ -3668,9 +4466,11 @@ and IsLocalErasedTyLambda g eenv (v: Val) e = //-------------------------------------------------------------------------- and IsNamedLocalTypeFuncVal g (v: Val) expr = - not v.IsCompiledAsTopLevel && - IsGenericValWithGenericConstraints g v && - (match stripExpr expr with Expr.TyLambda _ -> true | _ -> false) + not v.IsCompiledAsTopLevel + && IsGenericValWithGenericConstraints g v + && (match stripExpr expr with + | Expr.TyLambda _ -> true + | _ -> false) and AddDirectTyparWitnessParams cenv eenv cloinfo m = let directTypars = @@ -3680,6 +4480,7 @@ and AddDirectTyparWitnessParams cenv eenv cloinfo m = let directWitnessInfos = let generateWitnesses = ComputeGenerateWitnesses cenv.g eenv + if generateWitnesses then // The 0 here represents that a closure doesn't reside within a generic class - there are no "enclosing class type parameters" to lop off. GetTraitWitnessInfosOfTypars cenv.g 0 directTypars @@ -3690,6 +4491,7 @@ and AddDirectTyparWitnessParams cenv eenv cloinfo m = let ilDirectWitnessParams, ilDirectWitnessParamsStorage = let pretakenArgs = 1 ArgStorageForWitnessInfos cenv eenv [] pretakenArgs m directWitnessInfos + let eenv = eenv |> AddStorageForLocalWitnesses ilDirectWitnessParamsStorage directTypars, ilDirectWitnessParams, directWitnessInfos, eenv @@ -3700,8 +4502,10 @@ and GenNamedLocalTyFuncCall cenv (cgbuf: CodeGenBuffer) eenv ty cloinfo tyargs m let ilTyArgs = tyargs |> GenTypeArgs cenv m eenv.tyenv let ilCloTy = cloinfo.cloSpec.ILType + let ilDirectGenericParams, ilDirectWitnessParams, directWitnessInfos = let eenvinner = EnvForTypars cloinfo.cloFreeTyvars eenv + let directTypars = match cloinfo.cloExpr with | Expr.TyLambda (_, tvs, _, _, _) -> tvs @@ -3710,36 +4514,41 @@ and GenNamedLocalTyFuncCall cenv (cgbuf: CodeGenBuffer) eenv ty cloinfo tyargs m let eenvinner = AddTyparsToEnv directTypars eenvinner let ilDirectGenericParams = GenGenericParams cenv eenvinner directTypars - let _directTypars, ilDirectWitnessParams, directWitnessInfos, _eenv = AddDirectTyparWitnessParams cenv eenvinner cloinfo m + + let _directTypars, ilDirectWitnessParams, directWitnessInfos, _eenv = + AddDirectTyparWitnessParams cenv eenvinner cloinfo m + ilDirectGenericParams, ilDirectWitnessParams, directWitnessInfos - if not (List.length ilDirectGenericParams = ilTyArgs.Length) then errorR(Error(FSComp.SR.ilIncorrectNumberOfTypeArguments(), m)) + if not (List.length ilDirectGenericParams = ilTyArgs.Length) then + errorR (Error(FSComp.SR.ilIncorrectNumberOfTypeArguments (), m)) // Recover result (value or reference types) via unbox_any. - CG.EmitInstr cgbuf (pop 1) (Push [ilCloTy]) (I_unbox_any ilCloTy) + CG.EmitInstr cgbuf (pop 1) (Push [ ilCloTy ]) (I_unbox_any ilCloTy) let actualRetTy = applyTys g ty (tyargs, []) let ilDirectWitnessParamsTys = ilDirectWitnessParams |> List.map (fun p -> p.Type) - let ilDirectInvokeMethSpec = mkILInstanceMethSpecInTy(ilCloTy, "DirectInvoke", ilDirectWitnessParamsTys, cloinfo.ilCloFormalReturnTy, ilTyArgs) + + let ilDirectInvokeMethSpec = + mkILInstanceMethSpecInTy (ilCloTy, "DirectInvoke", ilDirectWitnessParamsTys, cloinfo.ilCloFormalReturnTy, ilTyArgs) GenWitnessArgsFromWitnessInfos cenv cgbuf eenv m directWitnessInfos let ilActualRetTy = GenType cenv m eenv.tyenv actualRetTy CountCallFuncInstructions() - CG.EmitInstr cgbuf (pop (1+ilDirectWitnessParamsTys.Length)) (Push [ilActualRetTy]) (mkNormalCall ilDirectInvokeMethSpec) + CG.EmitInstr cgbuf (pop (1 + ilDirectWitnessParamsTys.Length)) (Push [ ilActualRetTy ]) (mkNormalCall ilDirectInvokeMethSpec) actualRetTy - /// Generate an indirect call, converting to an ILX callfunc instruction -and GenCurriedArgsAndIndirectCall cenv cgbuf eenv (functy, tyargs, curriedArgs, m) sequel = +and GenCurriedArgsAndIndirectCall cenv cgbuf eenv (funcTy, tyargs, curriedArgs, m) sequel = // Generate the curried arguments to the indirect call GenExprs cenv cgbuf eenv curriedArgs - GenIndirectCall cenv cgbuf eenv (functy, tyargs, curriedArgs, m) sequel + GenIndirectCall cenv cgbuf eenv (funcTy, tyargs, curriedArgs, m) sequel /// Generate an indirect call, converting to an ILX callfunc instruction -and GenIndirectCall cenv cgbuf eenv (functy, tyargs, curriedArgs, m) sequel = +and GenIndirectCall cenv cgbuf eenv (funcTy, tyargs, curriedArgs, m) sequel = let g = cenv.g // Fold in the new types into the environment as we generate the formal types. @@ -3747,38 +4556,49 @@ and GenIndirectCall cenv cgbuf eenv (functy, tyargs, curriedArgs, m) sequel = // keep only non-erased type arguments when computing indirect call let tyargs = DropErasedTyargs tyargs - let typars, formalFuncTy = tryDestForallTy g functy + let typars, formalFuncTy = tryDestForallTy g funcTy let feenv = eenv.tyenv.Add typars // This does two phases: REVIEW: the code is too complex for what it's achieving and should be rewritten let formalRetTy, appBuilder = - ((formalFuncTy, id), curriedArgs) ||> List.fold (fun (formalFuncTy, appBuilder) _ -> + ((formalFuncTy, id), curriedArgs) + ||> List.fold (fun (formalFuncTy, appBuilder) _ -> let dty, rty = destFunTy cenv.g formalFuncTy (rty, (fun acc -> appBuilder (Apps_app(GenType cenv m feenv dty, acc))))) - let ilxRetApps = Apps_done (GenType cenv m feenv formalRetTy) + let ilxRetApps = Apps_done(GenType cenv m feenv formalRetTy) List.foldBack (fun tyarg acc -> Apps_tyapp(GenType cenv m eenv.tyenv tyarg, acc)) tyargs (appBuilder ilxRetApps) - let actualRetTy = applyTys g functy (tyargs, curriedArgs) + let actualRetTy = applyTys g funcTy (tyargs, curriedArgs) let ilActualRetTy = GenType cenv m eenv.tyenv actualRetTy // Check if any byrefs are involved to make sure we don't tailcall let hasByrefArg = let rec check x = - match x with - | Apps_tyapp(_, apps) -> check apps - | Apps_app(arg, apps) -> IsILTypeByref arg || check apps - | _ -> false + match x with + | Apps_tyapp (_, apps) -> check apps + | Apps_app (arg, apps) -> IsILTypeByref arg || check apps + | _ -> false + check ilxClosureApps - let isTailCall = CanTailcall(false, None, eenv.withinSEH, hasByrefArg, false, false, false, false, sequel) + let isTailCall = + CanTailcall(false, None, eenv.withinSEH, hasByrefArg, false, false, false, false, sequel) + CountCallFuncInstructions() // Generate the code code an ILX callfunc operation - let instrs = EraseClosures.mkCallFunc cenv.ilxPubCloEnv (fun ty -> cgbuf.AllocLocal([], ty, false) |> uint16) eenv.tyenv.Count isTailCall ilxClosureApps - CG.EmitInstrs cgbuf (pop (1+curriedArgs.Length)) (Push [ilActualRetTy]) instrs + let instrs = + EraseClosures.mkCallFunc + cenv.ilxPubCloEnv + (fun ty -> cgbuf.AllocLocal([], ty, false) |> uint16) + eenv.tyenv.Count + isTailCall + ilxClosureApps + + CG.EmitInstrs cgbuf (pop (1 + curriedArgs.Length)) (Push [ ilActualRetTy ]) instrs // Done compiling indirect call... GenSequel cenv eenv.cloc cgbuf sequel @@ -3798,24 +4618,38 @@ and GenTry cenv cgbuf eenv scopeMarks (e1, m, resultTy, spTry) = let startTryMark = CG.GenerateMark cgbuf "startTryMark" let endTryMark = CG.GenerateDelayMark cgbuf "endTryMark" let afterHandler = CG.GenerateDelayMark cgbuf "afterHandler" - let ilResultTyOpt = + + let ilResultTyOpt = if isUnitTy g resultTy then None else - Some (GenType cenv m eenvinner.tyenv resultTy) + Some(GenType cenv m eenvinner.tyenv resultTy) let whereToSaveOpt, eenvinner = - match ilResultTyOpt with + match ilResultTyOpt with | None -> None, eenvinner | Some ilResultTy -> // Ensure that we have an g.CompilerGlobalState - assert(cenv.g.CompilerGlobalState |> Option.isSome) + assert (cenv.g.CompilerGlobalState |> Option.isSome) + let whereToSave, _realloc, eenvinner = - AllocLocal cenv cgbuf eenvinner true (cenv.g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("tryres", m), ilResultTy, false) (startTryMark, endTryMark) - Some (whereToSave, ilResultTy), eenvinner + AllocLocal + cenv + cgbuf + eenvinner + true + (cenv.g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName("tryres", m), ilResultTy, false) + (startTryMark, endTryMark) - let exitSequel = LeaveHandler (false, whereToSaveOpt, afterHandler, true) - let eenvinner = {eenvinner with withinSEH = true; exitSequel = exitSequel} + Some(whereToSave, ilResultTy), eenvinner + + let exitSequel = LeaveHandler(false, whereToSaveOpt, afterHandler, true) + + let eenvinner = + { eenvinner with + withinSEH = true + exitSequel = exitSequel + } // Generate the body of the try. GenExpr cenv cgbuf eenvinner e1 exitSequel @@ -3825,194 +4659,213 @@ and GenTry cenv cgbuf eenv scopeMarks (e1, m, resultTy, spTry) = /// Determine if a filter block is side-effect free, meaning it can be run on the first pass and /// the pattern match logic repeated on the second pass. -/// +/// /// Filter blocks are only ever generated by pattern match compilation so we can safely look for particular -/// constructs. +/// constructs. and eligibleForFilter (cenv: cenv) expr = - let rec check expr = - match expr with - | Expr.Let (TBind(_, be, _), body, _, _) -> - check be && check body - | Expr.DebugPoint(_, expr) -> check expr - | Expr.Match (_spBind, _exprm, dtree, targets, _, _) -> - checkDecisionTree dtree && - targets |> Array.forall (fun (TTarget(_, e, _)) -> check e) - | Expr.Const _ -> true - | Expr.Op(TOp.ILAsm([ I_isinst _ ], _), _, _, _) -> true - | Expr.Op(TOp.UnionCaseTagGet _, _, _, _) -> true - | Expr.Op(TOp.ExnFieldGet _, _, _, _) -> true - | Expr.Op(TOp.UnionCaseFieldGet _, _, _, _) -> true - | Expr.Op(TOp.ValFieldGet _, _, _, _) -> true - | Expr.Op(TOp.TupleFieldGet _, _, _, _) -> true - | Expr.Op(TOp.Coerce _, _, _, _) -> true - | Expr.Val _ -> true - | _ -> false - - and checkDecisionTree dtree = - match dtree with - | TDSwitch(ve, cases, dflt, _) -> - check ve && - cases |> List.forall checkDecisionTreeCase && - dflt |> Option.forall checkDecisionTree - | TDSuccess (es, _) -> es |> List.forall check - | TDBind(bind, rest) -> check bind.Expr && checkDecisionTree rest - - and checkDecisionTreeCase dcase = - let (TCase(test, tree)) = dcase - checkDecisionTree tree && - match test with - | DecisionTreeTest.UnionCase _ -> true - | DecisionTreeTest.ArrayLength _ -> true - | DecisionTreeTest.Const _ -> true - | DecisionTreeTest.IsNull -> true - | DecisionTreeTest.IsInst _ -> true - | DecisionTreeTest.ActivePatternCase _ -> false // must only be run once - | DecisionTreeTest.Error _ -> false - - let isTrivial = - match expr with - | DebugPoints (Expr.Const _, _) -> true - | _ -> false - - // Filters seem to generate invalid code for the ilreflect.fs backend - (cenv.options.ilxBackend = IlxGenBackend.IlWriteBackend) && - not isTrivial && - check expr - -and GenTryWith cenv cgbuf eenv (e1, valForFilter: Val, filterExpr, valForHandler: Val, handlerExpr, m, resty, spTry, spWith) sequel = + let rec check expr = + match expr with + | Expr.Let (TBind (_, be, _), body, _, _) -> check be && check body + | Expr.DebugPoint (_, expr) -> check expr + | Expr.Match (_spBind, _exprm, dtree, targets, _, _) -> + checkDecisionTree dtree + && targets |> Array.forall (fun (TTarget (_, e, _)) -> check e) + | Expr.Const _ -> true + | Expr.Op (TOp.ILAsm ([ I_isinst _ ], _), _, _, _) -> true + | Expr.Op (TOp.UnionCaseTagGet _, _, _, _) -> true + | Expr.Op (TOp.ExnFieldGet _, _, _, _) -> true + | Expr.Op (TOp.UnionCaseFieldGet _, _, _, _) -> true + | Expr.Op (TOp.ValFieldGet _, _, _, _) -> true + | Expr.Op (TOp.TupleFieldGet _, _, _, _) -> true + | Expr.Op (TOp.Coerce _, _, _, _) -> true + | Expr.Val _ -> true + | _ -> false + + and checkDecisionTree dtree = + match dtree with + | TDSwitch (ve, cases, dflt, _) -> + check ve + && cases |> List.forall checkDecisionTreeCase + && dflt |> Option.forall checkDecisionTree + | TDSuccess (es, _) -> es |> List.forall check + | TDBind (bind, rest) -> check bind.Expr && checkDecisionTree rest + + and checkDecisionTreeCase dcase = + let (TCase (test, tree)) = dcase + + checkDecisionTree tree + && match test with + | DecisionTreeTest.UnionCase _ -> true + | DecisionTreeTest.ArrayLength _ -> true + | DecisionTreeTest.Const _ -> true + | DecisionTreeTest.IsNull -> true + | DecisionTreeTest.IsInst _ -> true + | DecisionTreeTest.ActivePatternCase _ -> false // must only be run once + | DecisionTreeTest.Error _ -> false + + let isTrivial = + match expr with + | DebugPoints (Expr.Const _, _) -> true + | _ -> false + + // Filters seem to generate invalid code for the ilreflect.fs backend + (cenv.options.ilxBackend = IlxGenBackend.IlWriteBackend) + && not isTrivial + && check expr + +and GenTryWith cenv cgbuf eenv (e1, valForFilter: Val, filterExpr, valForHandler: Val, handlerExpr, m, resTy, spTry, spWith) sequel = let g = cenv.g // Save the stack - gross because IL flushes the stack at the exn. handler // note: eenvinner notes spill vars are live LocalScope "trystack" cgbuf (fun scopeMarks -> - let whereToSaveOpt, eenvinner, stack, tryMarks, afterHandler = GenTry cenv cgbuf eenv scopeMarks (e1, m, resty, spTry) - - let seh = - if cenv.options.generateFilterBlocks || eligibleForFilter cenv filterExpr then - let startOfFilter = CG.GenerateMark cgbuf "startOfFilter" - let afterFilter = CG.GenerateDelayMark cgbuf "afterFilter" - let sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin = GenJoinPoint cenv cgbuf "filter" eenv g.int_ty m EndFilter - let eenvinner = { eenvinner with exitSequel = sequelOnBranches } - // We emit the debug point for the 'with' keyword span on the start of the filter - // block. However the targets of the filter block pattern matching should not get any - // debug points (they will be 'true'/'false' values indicating if the exception has been - // caught or not). - // - // The targets of the handler block DO get debug points. Thus the expected behaviour - // for a try/with with a complex pattern is that we hit the "with" before the filter is run - // and then jump to the handler for the successful catch (or continue with exception handling - // if the filter fails) - match spWith with - | DebugPointAtWith.Yes m -> CG.EmitDebugPoint cgbuf m - | DebugPointAtWith.No -> () - - CG.SetStack cgbuf [g.ilg.typ_Object] - let _, eenvinner = AllocLocalVal cenv cgbuf valForFilter eenvinner None (startOfFilter, afterFilter) - CG.EmitInstr cgbuf (pop 1) (Push [g.iltyp_Exception]) (I_castclass g.iltyp_Exception) - - GenStoreVal cenv cgbuf eenvinner valForFilter.Range valForFilter - - // Why SPSuppress? Because we do not emit a debug point at the start of the List.filter - we've already put one on - // the 'with' keyword above - GenExpr cenv cgbuf eenvinner filterExpr sequelOnBranches - CG.SetMarkToHere cgbuf afterJoin - CG.SetStack cgbuf stackAfterJoin - GenSequel cenv eenv.cloc cgbuf sequelAfterJoin - let endOfFilter = CG.GenerateMark cgbuf "endOfFilter" - let filterMarks = (startOfFilter.CodeLabel, endOfFilter.CodeLabel) - CG.SetMarkToHere cgbuf afterFilter - - let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" - - CG.SetStack cgbuf [g.ilg.typ_Object] - let _, eenvinner = AllocLocalVal cenv cgbuf valForHandler eenvinner None (startOfHandler, afterHandler) - CG.EmitInstr cgbuf (pop 1) (Push [g.iltyp_Exception]) (I_castclass g.iltyp_Exception) - GenStoreVal cenv cgbuf eenvinner valForHandler.Range valForHandler - - let exitSequel = LeaveHandler (false, whereToSaveOpt, afterHandler, true) - GenExpr cenv cgbuf eenvinner handlerExpr exitSequel - - let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" - let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) - ILExceptionClause.FilterCatch(filterMarks, handlerMarks) - else - let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" - - match spWith with - | DebugPointAtWith.Yes m -> CG.EmitDebugPoint cgbuf m - | DebugPointAtWith.No -> () - - CG.SetStack cgbuf [g.ilg.typ_Object] - let _, eenvinner = AllocLocalVal cenv cgbuf valForHandler eenvinner None (startOfHandler, afterHandler) - CG.EmitInstr cgbuf (pop 1) (Push [g.iltyp_Exception]) (I_castclass g.iltyp_Exception) - - GenStoreVal cenv cgbuf eenvinner m valForHandler - - let exitSequel = LeaveHandler (false, whereToSaveOpt, afterHandler, true) - let eenvinner = { eenvinner with exitSequel = exitSequel } - GenExpr cenv cgbuf eenvinner handlerExpr exitSequel - - let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" - let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) - ILExceptionClause.TypeCatch(g.ilg.typ_Object, handlerMarks) - - cgbuf.EmitExceptionClause - { Clause = seh - Range= tryMarks } - - CG.SetMarkToHere cgbuf afterHandler - CG.SetStack cgbuf [] - - cgbuf.EmitStartOfHiddenCode() - - // Restore the stack and load the result - EmitRestoreStack cgbuf stack - - match whereToSaveOpt with - | Some (whereToSave, ilResultTy) -> - EmitGetLocal cgbuf ilResultTy whereToSave - GenSequel cenv eenv.cloc cgbuf sequel - | None -> - GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel - ) - - -and GenTryFinally cenv cgbuf eenv (bodyExpr, handlerExpr, m, resty, spTry, spFinally) sequel = + let whereToSaveOpt, eenvinner, stack, tryMarks, afterHandler = + GenTry cenv cgbuf eenv scopeMarks (e1, m, resTy, spTry) + + let seh = + if cenv.options.generateFilterBlocks || eligibleForFilter cenv filterExpr then + let startOfFilter = CG.GenerateMark cgbuf "startOfFilter" + let afterFilter = CG.GenerateDelayMark cgbuf "afterFilter" + + let sequelOnBranches, afterJoin, stackAfterJoin, sequelAfterJoin = + GenJoinPoint cenv cgbuf "filter" eenv g.int_ty m EndFilter + + let eenvinner = + { eenvinner with + exitSequel = sequelOnBranches + } + // We emit the debug point for the 'with' keyword span on the start of the filter + // block. However the targets of the filter block pattern matching should not get any + // debug points (they will be 'true'/'false' values indicating if the exception has been + // caught or not). + // + // The targets of the handler block DO get debug points. Thus the expected behaviour + // for a try/with with a complex pattern is that we hit the "with" before the filter is run + // and then jump to the handler for the successful catch (or continue with exception handling + // if the filter fails) + match spWith with + | DebugPointAtWith.Yes m -> CG.EmitDebugPoint cgbuf m + | DebugPointAtWith.No -> () + + CG.SetStack cgbuf [ g.ilg.typ_Object ] + + let _, eenvinner = + AllocLocalVal cenv cgbuf valForFilter eenvinner None (startOfFilter, afterFilter) + + CG.EmitInstr cgbuf (pop 1) (Push [ g.iltyp_Exception ]) (I_castclass g.iltyp_Exception) + + GenStoreVal cgbuf eenvinner valForFilter.Range valForFilter + + // Why SPSuppress? Because we do not emit a debug point at the start of the List.filter - we've already put one on + // the 'with' keyword above + GenExpr cenv cgbuf eenvinner filterExpr sequelOnBranches + CG.SetMarkToHere cgbuf afterJoin + CG.SetStack cgbuf stackAfterJoin + GenSequel cenv eenv.cloc cgbuf sequelAfterJoin + let endOfFilter = CG.GenerateMark cgbuf "endOfFilter" + let filterMarks = (startOfFilter.CodeLabel, endOfFilter.CodeLabel) + CG.SetMarkToHere cgbuf afterFilter + + let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" + + CG.SetStack cgbuf [ g.ilg.typ_Object ] + + let _, eenvinner = + AllocLocalVal cenv cgbuf valForHandler eenvinner None (startOfHandler, afterHandler) + + CG.EmitInstr cgbuf (pop 1) (Push [ g.iltyp_Exception ]) (I_castclass g.iltyp_Exception) + GenStoreVal cgbuf eenvinner valForHandler.Range valForHandler + + let exitSequel = LeaveHandler(false, whereToSaveOpt, afterHandler, true) + GenExpr cenv cgbuf eenvinner handlerExpr exitSequel + + let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" + let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) + ILExceptionClause.FilterCatch(filterMarks, handlerMarks) + else + let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" + + match spWith with + | DebugPointAtWith.Yes m -> CG.EmitDebugPoint cgbuf m + | DebugPointAtWith.No -> () + + CG.SetStack cgbuf [ g.ilg.typ_Object ] + + let _, eenvinner = + AllocLocalVal cenv cgbuf valForHandler eenvinner None (startOfHandler, afterHandler) + + CG.EmitInstr cgbuf (pop 1) (Push [ g.iltyp_Exception ]) (I_castclass g.iltyp_Exception) + + GenStoreVal cgbuf eenvinner m valForHandler + + let exitSequel = LeaveHandler(false, whereToSaveOpt, afterHandler, true) + + let eenvinner = + { eenvinner with + exitSequel = exitSequel + } + + GenExpr cenv cgbuf eenvinner handlerExpr exitSequel + + let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" + let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) + ILExceptionClause.TypeCatch(g.ilg.typ_Object, handlerMarks) + + cgbuf.EmitExceptionClause { Clause = seh; Range = tryMarks } + + CG.SetMarkToHere cgbuf afterHandler + CG.SetStack cgbuf [] + + cgbuf.EmitStartOfHiddenCode() + + // Restore the stack and load the result + EmitRestoreStack cgbuf stack + + match whereToSaveOpt with + | Some (whereToSave, ilResultTy) -> + EmitGetLocal cgbuf ilResultTy whereToSave + GenSequel cenv eenv.cloc cgbuf sequel + | None -> GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel) + +and GenTryFinally cenv cgbuf eenv (bodyExpr, handlerExpr, m, resTy, spTry, spFinally) sequel = // Save the stack - needed because IL flushes the stack at the exn. handler // note: eenvinner notes spill vars are live LocalScope "trystack" cgbuf (fun scopeMarks -> - let whereToSaveOpt, eenvinner, stack, tryMarks, afterHandler = GenTry cenv cgbuf eenv scopeMarks (bodyExpr, m, resty, spTry) - - // Now the catch/finally block - let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" - CG.SetStack cgbuf [] - - match spFinally with - | DebugPointAtFinally.Yes m -> CG.EmitDebugPoint cgbuf m - | DebugPointAtFinally.No -> () - - let exitSequel = LeaveHandler (true, whereToSaveOpt, afterHandler, true) - GenExpr cenv cgbuf eenvinner handlerExpr exitSequel - let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" - let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) - cgbuf.EmitExceptionClause - { Clause = ILExceptionClause.Finally handlerMarks - Range = tryMarks } - - CG.SetMarkToHere cgbuf afterHandler - CG.SetStack cgbuf [] - - // Restore the stack and load the result - cgbuf.EmitStartOfHiddenCode() - EmitRestoreStack cgbuf stack - match whereToSaveOpt with - | Some (whereToSave, ilResultTy) -> - EmitGetLocal cgbuf ilResultTy whereToSave - GenSequel cenv eenv.cloc cgbuf sequel - | None -> - GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel - ) + let whereToSaveOpt, eenvinner, stack, tryMarks, afterHandler = + GenTry cenv cgbuf eenv scopeMarks (bodyExpr, m, resTy, spTry) + + // Now the catch/finally block + let startOfHandler = CG.GenerateMark cgbuf "startOfHandler" + CG.SetStack cgbuf [] + + match spFinally with + | DebugPointAtFinally.Yes m -> CG.EmitDebugPoint cgbuf m + | DebugPointAtFinally.No -> () + + let exitSequel = LeaveHandler(true, whereToSaveOpt, afterHandler, true) + GenExpr cenv cgbuf eenvinner handlerExpr exitSequel + let endOfHandler = CG.GenerateMark cgbuf "endOfHandler" + let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) + + cgbuf.EmitExceptionClause + { + Clause = ILExceptionClause.Finally handlerMarks + Range = tryMarks + } + + CG.SetMarkToHere cgbuf afterHandler + CG.SetStack cgbuf [] + + // Restore the stack and load the result + cgbuf.EmitStartOfHiddenCode() + EmitRestoreStack cgbuf stack + + match whereToSaveOpt with + | Some (whereToSave, ilResultTy) -> + EmitGetLocal cgbuf ilResultTy whereToSave + GenSequel cenv eenv.cloc cgbuf sequel + | None -> GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel) //-------------------------------------------------------------------------- // Generate for-loop @@ -4035,15 +4888,29 @@ and GenIntegerForLoop cenv cgbuf eenv (spFor, spTo, v, e1, dir, e2, loopBody, m) let test = CG.GenerateDelayMark cgbuf "for_test" let stack, eenvinner = EmitSaveStack cenv cgbuf eenv m (start, finish) - let isUp = (match dir with | FSharpForLoopUp | CSharpForLoopUp -> true | FSharpForLoopDown -> false) - let isFSharpStyle = (match dir with FSharpForLoopUp | FSharpForLoopDown -> true | CSharpForLoopUp -> false) + let isUp = + (match dir with + | FSharpForLoopUp + | CSharpForLoopUp -> true + | FSharpForLoopDown -> false) + + let isFSharpStyle = + (match dir with + | FSharpForLoopUp + | FSharpForLoopDown -> true + | CSharpForLoopUp -> false) let finishIdx, eenvinner = if isFSharpStyle then // Ensure that we have an g.CompilerGlobalState - assert(g.CompilerGlobalState |> Option.isSome) - let vName = g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("endLoop", m) - let v, _realloc, eenvinner = AllocLocal cenv cgbuf eenvinner true (vName, g.ilg.typ_Int32, false) (start, finish) + assert (g.CompilerGlobalState |> Option.isSome) + + let vName = + g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName("endLoop", m) + + let v, _realloc, eenvinner = + AllocLocal cenv cgbuf eenvinner true (vName, g.ilg.typ_Int32, false) (start, finish) + v, eenvinner else -1, eenvinner @@ -4055,13 +4922,14 @@ and GenIntegerForLoop cenv cgbuf eenv (spFor, spTo, v, e1, dir, e2, loopBody, m) | DebugPointAtFor.No -> () GenExpr cenv cgbuf eenv e1 Continue - GenStoreVal cenv cgbuf eenvinner m v + GenStoreVal cgbuf eenvinner m v + if isFSharpStyle then GenExpr cenv cgbuf eenvinner e2 Continue EmitSetLocal cgbuf finishIdx EmitGetLocal cgbuf g.ilg.typ_Int32 finishIdx GenGetLocalVal cenv cgbuf eenvinner e2.Range v None - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp ((if isUp then BI_blt else BI_bgt), finish.CodeLabel)) + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp((if isUp then BI_blt else BI_bgt), finish.CodeLabel)) else CG.EmitInstr cgbuf (pop 0) Push0 (I_br test.CodeLabel) @@ -4073,13 +4941,13 @@ and GenIntegerForLoop cenv cgbuf eenv (spFor, spTo, v, e1, dir, e2, loopBody, m) // GenExpr cenv cgbuf eenvinner loopBody discard - + // v++ or v-- GenGetLocalVal cenv cgbuf eenvinner e2.Range v None - CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Int32]) (mkLdcInt32 1) + CG.EmitInstr cgbuf (pop 0) (Push [ g.ilg.typ_Int32 ]) (mkLdcInt32 1) CG.EmitInstr cgbuf (pop 1) Push0 (if isUp then AI_add else AI_sub) - GenStoreVal cenv cgbuf eenvinner m v + GenStoreVal cgbuf eenvinner m v // .text CG.SetMarkToHere cgbuf test @@ -4093,12 +4961,17 @@ and GenIntegerForLoop cenv cgbuf eenv (spFor, spTo, v, e1, dir, e2, loopBody, m) GenGetLocalVal cenv cgbuf eenvinner e2.Range v None - let cmp = match dir with FSharpForLoopUp | FSharpForLoopDown -> BI_bne_un | CSharpForLoopUp -> BI_blt - let e2Sequel = (CmpThenBrOrContinue (pop 2, [ I_brcmp(cmp, inner.CodeLabel) ])) + let cmp = + match dir with + | FSharpForLoopUp + | FSharpForLoopDown -> BI_bne_un + | CSharpForLoopUp -> BI_blt + + let e2Sequel = (CmpThenBrOrContinue(pop 2, [ I_brcmp(cmp, inner.CodeLabel) ])) if isFSharpStyle then EmitGetLocal cgbuf g.ilg.typ_Int32 finishIdx - CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Int32]) (mkLdcInt32 1) + CG.EmitInstr cgbuf (pop 0) (Push [ g.ilg.typ_Int32 ]) (mkLdcInt32 1) CG.EmitInstr cgbuf (pop 1) Push0 (if isUp then AI_add else AI_sub) GenSequel cenv eenv.cloc cgbuf e2Sequel else @@ -4119,7 +4992,7 @@ and GenWhileLoop cenv cgbuf eenv (spWhile, condExpr, bodyExpr, m) sequel = let eenv = SetIsInLoop true eenv // jmp test; body; test; if testPassed then jmp body else finish - // + // // This is a pattern recognized by the JIT and it results in the most efficient assembly. if cgbuf.GetCurrentStack().IsEmpty then let startTest = CG.GenerateDelayMark cgbuf "startTest" @@ -4133,7 +5006,7 @@ and GenWhileLoop cenv cgbuf eenv (spWhile, condExpr, bodyExpr, m) sequel = | DebugPointAtWhile.No -> () CG.SetMarkToHere cgbuf startTest - GenExpr cenv cgbuf eenv condExpr (CmpThenBrOrContinue (pop 1, [ I_brcmp (BI_brtrue, startBody.CodeLabel) ])) + GenExpr cenv cgbuf eenv condExpr (CmpThenBrOrContinue(pop 1, [ I_brcmp(BI_brtrue, startBody.CodeLabel) ])) // In the rare cases when there is something already on the stack, e.g. // @@ -4152,9 +5025,9 @@ and GenWhileLoop cenv cgbuf eenv (spWhile, condExpr, bodyExpr, m) sequel = let startTest = CG.GenerateMark cgbuf "startTest" - GenExpr cenv cgbuf eenv condExpr (CmpThenBrOrContinue (pop 1, [ I_brcmp (BI_brfalse, finish.CodeLabel) ])) + GenExpr cenv cgbuf eenv condExpr (CmpThenBrOrContinue(pop 1, [ I_brcmp(BI_brfalse, finish.CodeLabel) ])) - GenExpr cenv cgbuf eenv bodyExpr (DiscardThen (Br startTest)) + GenExpr cenv cgbuf eenv bodyExpr (DiscardThen(Br startTest)) CG.SetMarkToHere cgbuf finish GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel @@ -4170,84 +5043,112 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = let g = cenv.g let ilTyArgs = GenTypesPermitVoid cenv m eenv.tyenv tyargs let ilReturnTys = GenTypesPermitVoid cenv m eenv.tyenv returnTys + let ilAfterInst = - il |> List.filter (function AI_nop -> false | _ -> true) - |> List.map (fun i -> - let err s = - errorR(InternalError(sprintf "%s: bad instruction: %A" s i, m)) - - let modFieldSpec fspec = - if isNil ilTyArgs then - fspec - else - {fspec with DeclaringType= - let ty = fspec.DeclaringType - let tspec = ty.TypeSpec - mkILTy ty.Boxity (mkILTySpec(tspec.TypeRef, ilTyArgs)) } - match i, ilTyArgs with - | I_unbox_any (ILType.TypeVar _), [tyarg] -> I_unbox_any tyarg - | I_box (ILType.TypeVar _), [tyarg] -> I_box tyarg - | I_isinst (ILType.TypeVar _), [tyarg] -> I_isinst tyarg - | I_castclass (ILType.TypeVar _), [tyarg] -> I_castclass tyarg - | I_newarr (shape, ILType.TypeVar _), [tyarg] -> I_newarr (shape, tyarg) - | I_ldelem_any (shape, ILType.TypeVar _), [tyarg] -> I_ldelem_any (shape, tyarg) - | I_ldelema (ro, _, shape, ILType.TypeVar _), [tyarg] -> I_ldelema (ro, false, shape, tyarg) - | I_stelem_any (shape, ILType.TypeVar _), [tyarg] -> I_stelem_any (shape, tyarg) - | I_ldobj (a, b, ILType.TypeVar _), [tyarg] -> I_ldobj (a, b, tyarg) - | I_stobj (a, b, ILType.TypeVar _), [tyarg] -> I_stobj (a, b, tyarg) - | I_ldtoken (ILToken.ILType (ILType.TypeVar _)), [tyarg] -> I_ldtoken (ILToken.ILType tyarg) - | I_sizeof (ILType.TypeVar _), [tyarg] -> I_sizeof tyarg - | I_cpobj (ILType.TypeVar _), [tyarg] -> I_cpobj tyarg - | I_initobj (ILType.TypeVar _), [tyarg] -> I_initobj tyarg - | I_ldfld (al, vol, fspec), _ -> I_ldfld (al, vol, modFieldSpec fspec) - | I_ldflda fspec, _ -> I_ldflda (modFieldSpec fspec) - | I_stfld (al, vol, fspec), _ -> I_stfld (al, vol, modFieldSpec fspec) - | I_stsfld (vol, fspec), _ -> I_stsfld (vol, modFieldSpec fspec) - | I_ldsfld (vol, fspec), _ -> I_ldsfld (vol, modFieldSpec fspec) - | I_ldsflda fspec, _ -> I_ldsflda (modFieldSpec fspec) - | EI_ilzero(ILType.TypeVar _), [tyarg] -> EI_ilzero tyarg + il + |> List.filter (function + | AI_nop -> false + | _ -> true) + |> List.map (fun i -> + let err s = + errorR (InternalError(sprintf "%s: bad instruction: %A" s i, m)) + + let modFieldSpec fspec = + if isNil ilTyArgs then + fspec + else + { fspec with + DeclaringType = + let ty = fspec.DeclaringType + let tspec = ty.TypeSpec + mkILTy ty.Boxity (mkILTySpec (tspec.TypeRef, ilTyArgs)) + } + + match i, ilTyArgs with + | I_unbox_any (ILType.TypeVar _), [ tyarg ] -> I_unbox_any tyarg + | I_box (ILType.TypeVar _), [ tyarg ] -> I_box tyarg + | I_isinst (ILType.TypeVar _), [ tyarg ] -> I_isinst tyarg + | I_castclass (ILType.TypeVar _), [ tyarg ] -> I_castclass tyarg + | I_newarr (shape, ILType.TypeVar _), [ tyarg ] -> I_newarr(shape, tyarg) + | I_ldelem_any (shape, ILType.TypeVar _), [ tyarg ] -> I_ldelem_any(shape, tyarg) + | I_ldelema (ro, _, shape, ILType.TypeVar _), [ tyarg ] -> I_ldelema(ro, false, shape, tyarg) + | I_stelem_any (shape, ILType.TypeVar _), [ tyarg ] -> I_stelem_any(shape, tyarg) + | I_ldobj (a, b, ILType.TypeVar _), [ tyarg ] -> I_ldobj(a, b, tyarg) + | I_stobj (a, b, ILType.TypeVar _), [ tyarg ] -> I_stobj(a, b, tyarg) + | I_ldtoken (ILToken.ILType (ILType.TypeVar _)), [ tyarg ] -> I_ldtoken(ILToken.ILType tyarg) + | I_sizeof (ILType.TypeVar _), [ tyarg ] -> I_sizeof tyarg + | I_cpobj (ILType.TypeVar _), [ tyarg ] -> I_cpobj tyarg + | I_initobj (ILType.TypeVar _), [ tyarg ] -> I_initobj tyarg + | I_ldfld (al, vol, fspec), _ -> I_ldfld(al, vol, modFieldSpec fspec) + | I_ldflda fspec, _ -> I_ldflda(modFieldSpec fspec) + | I_stfld (al, vol, fspec), _ -> I_stfld(al, vol, modFieldSpec fspec) + | I_stsfld (vol, fspec), _ -> I_stsfld(vol, modFieldSpec fspec) + | I_ldsfld (vol, fspec), _ -> I_ldsfld(vol, modFieldSpec fspec) + | I_ldsflda fspec, _ -> I_ldsflda(modFieldSpec fspec) + | EI_ilzero (ILType.TypeVar _), [ tyarg ] -> EI_ilzero tyarg | AI_nop, _ -> i - // These are embedded in the IL for a an initonly ldfld, i.e. - // here's the relevant comment from tc.fs - // "Add an I_nop if this is an initonly field to make sure we never recognize it as an lvalue. See mkExprAddrOfExpr." + // These are embedded in the IL for a an initonly ldfld, i.e. + // here's the relevant comment from tc.fs + // "Add an I_nop if this is an initonly field to make sure we never recognize it as an lvalue. See mkExprAddrOfExpr." | _ -> - if not (isNil tyargs) then err "Bad polymorphic IL instruction" + if not (isNil tyargs) then + err "Bad polymorphic IL instruction" + i) + match ilAfterInst, args, sequel, ilReturnTys with | [ EI_ilzero _ ], _, _, _ -> - match tyargs with - | [ty] -> - GenDefaultValue cenv cgbuf eenv (ty, m) - GenSequel cenv eenv.cloc cgbuf sequel - | _ -> failwith "Bad polymorphic IL instruction" + match tyargs with + | [ ty ] -> + GenDefaultValue cenv cgbuf eenv (ty, m) + GenSequel cenv eenv.cloc cgbuf sequel + | _ -> failwith "Bad polymorphic IL instruction" // ldnull; cgt.un then branch is used to test for null and can become a direct brtrue/brfalse - | [ AI_ldnull; AI_cgt_un ], [arg1], CmpThenBrOrContinue(1, [ I_brcmp (bi, label1) ]), _ -> + | [ AI_ldnull; AI_cgt_un ], [ arg1 ], CmpThenBrOrContinue (1, [ I_brcmp (bi, label1) ]), _ -> - GenExpr cenv cgbuf eenv arg1 (CmpThenBrOrContinue(pop 1, [ I_brcmp (bi, label1) ])) + GenExpr cenv cgbuf eenv arg1 (CmpThenBrOrContinue(pop 1, [ I_brcmp(bi, label1) ])) // Strip off any ("ceq" x false) when the sequel is a comparison branch and change the BI_brfalse to a BI_brtrue // This is the instruction sequence for "not" // For these we can just generate the argument and change the test (from a brfalse to a brtrue and vice versa) | ([ AI_ceq ], - [arg1; Expr.Const ((Const.Bool false | Const.SByte 0y| Const.Int16 0s | Const.Int32 0 | Const.Int64 0L | Const.Byte 0uy| Const.UInt16 0us | Const.UInt32 0u | Const.UInt64 0UL), _, _) ], - CmpThenBrOrContinue(1, [I_brcmp (BI_brfalse | BI_brtrue as bi, label1) ]), + [ arg1 + Expr.Const ((Const.Bool false + | Const.SByte 0y + | Const.Int16 0s + | Const.Int32 0 + | Const.Int64 0L + | Const.Byte 0uy + | Const.UInt16 0us + | Const.UInt32 0u + | Const.UInt64 0UL), + _, + _) ], + CmpThenBrOrContinue (1, + [ I_brcmp ((BI_brfalse + | BI_brtrue) as bi, + label1) ]), _) -> - let bi = match bi with BI_brtrue -> BI_brfalse | _ -> BI_brtrue - GenExpr cenv cgbuf eenv arg1 (CmpThenBrOrContinue(pop 1, [ I_brcmp (bi, label1) ])) + let bi = + match bi with + | BI_brtrue -> BI_brfalse + | _ -> BI_brtrue + + GenExpr cenv cgbuf eenv arg1 (CmpThenBrOrContinue(pop 1, [ I_brcmp(bi, label1) ])) // Query; when do we get a 'ret' in IL assembly code? - | [ I_ret ], [arg1], sequel, [_ilRetTy] -> + | [ I_ret ], [ arg1 ], sequel, [ _ilRetTy ] -> GenExpr cenv cgbuf eenv arg1 Continue CG.EmitInstr cgbuf (pop 1) Push0 I_ret GenSequelEndScopes cgbuf sequel // Query; when do we get a 'ret' in IL assembly code? - | [ I_ret ], [], sequel, [_ilRetTy] -> + | [ I_ret ], [], sequel, [ _ilRetTy ] -> CG.EmitInstr cgbuf (pop 1) Push0 I_ret GenSequelEndScopes cgbuf sequel @@ -4258,7 +5159,7 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = // (nb. a fake value can always be generated by a "ldnull unbox.any ty" sequence *) // So in the worst case we generate a fake (never-taken) branch to a piece of code to generate *) // the fake value *) - | [ I_throw ], [arg1], sequel, [ilRetTy] -> + | [ I_throw ], [ arg1 ], sequel, [ ilRetTy ] -> match sequelIgnoreEndScopes sequel with | s when IsSequelImmediate s -> (* In most cases we can avoid doing this... *) @@ -4269,10 +5170,10 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = let after1 = CG.GenerateDelayMark cgbuf "fake_join" let after2 = CG.GenerateDelayMark cgbuf "fake_join" let after3 = CG.GenerateDelayMark cgbuf "fake_join" - CG.EmitInstrs cgbuf (pop 0) Push0 [mkLdcInt32 0; I_brcmp (BI_brfalse, after2.CodeLabel) ] + CG.EmitInstrs cgbuf (pop 0) Push0 [ mkLdcInt32 0; I_brcmp(BI_brfalse, after2.CodeLabel) ] CG.SetMarkToHere cgbuf after1 - CG.EmitInstrs cgbuf (pop 0) (Push [ilRetTy]) [AI_ldnull; I_unbox_any ilRetTy; I_br after3.CodeLabel ] + CG.EmitInstrs cgbuf (pop 0) (Push [ ilRetTy ]) [ AI_ldnull; I_unbox_any ilRetTy; I_br after3.CodeLabel ] CG.SetMarkToHere cgbuf after2 GenExpr cenv cgbuf eenv arg1 Continue @@ -4280,47 +5181,47 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = CG.SetMarkToHere cgbuf after3 GenSequel cenv eenv.cloc cgbuf sequel | _ -> - // float or float32 or float<_> or float32<_> - let anyfpType ty = typeEquivAux EraseMeasures g g.float_ty ty || typeEquivAux EraseMeasures g g.float32_ty ty - - // Otherwise generate the arguments, and see if we can use a I_brcmp rather than a comparison followed by an I_brfalse/I_brtrue - GenExprs cenv cgbuf eenv args - match ilAfterInst, sequel with - - // NOTE: THESE ARE NOT VALID ON FLOATING POINT DUE TO NaN. Hence INLINE ASM ON FP. MUST BE CAREFULLY WRITTEN - - | [ AI_clt ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bge, label1)) - | [ AI_cgt ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_ble, label1)) - | [ AI_clt_un ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bge_un, label1)) - | [ AI_cgt_un ], CmpThenBrOrContinue(1, [I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_ble_un, label1)) - | [ AI_ceq ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bne_un, label1)) - - // THESE ARE VALID ON FP w.r.t. NaN - - | [ AI_clt ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brtrue, label1) ]) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_blt, label1)) - | [ AI_cgt ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brtrue, label1) ]) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bgt, label1)) - | [ AI_clt_un ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brtrue, label1) ]) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_blt_un, label1)) - | [ AI_cgt_un ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brtrue, label1) ]) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bgt_un, label1)) - | [ AI_ceq ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brtrue, label1) ]) -> - CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_beq, label1)) - | _ -> - // Failing that, generate the real IL leaving value(s) on the stack - CG.EmitInstrs cgbuf (pop args.Length) (Push ilReturnTys) ilAfterInst - - // If no return values were specified generate a "unit" - if isNil returnTys then - GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel - else - GenSequel cenv eenv.cloc cgbuf sequel + // float or float32 or float<_> or float32<_> + let anyfpType ty = + typeEquivAux EraseMeasures g g.float_ty ty + || typeEquivAux EraseMeasures g g.float32_ty ty + + // Otherwise generate the arguments, and see if we can use a I_brcmp rather than a comparison followed by an I_brfalse/I_brtrue + GenExprs cenv cgbuf eenv args + + match ilAfterInst, sequel with + + // NOTE: THESE ARE NOT VALID ON FLOATING POINT DUE TO NaN. Hence INLINE ASM ON FP. MUST BE CAREFULLY WRITTEN + + | [ AI_clt ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bge, label1)) + | [ AI_cgt ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_ble, label1)) + | [ AI_clt_un ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bge_un, label1)) + | [ AI_cgt_un ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_ble_un, label1)) + | [ AI_ceq ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bne_un, label1)) + + // THESE ARE VALID ON FP w.r.t. NaN + + | [ AI_clt ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brtrue, label1) ]) -> CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_blt, label1)) + | [ AI_cgt ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brtrue, label1) ]) -> CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bgt, label1)) + | [ AI_clt_un ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brtrue, label1) ]) -> + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_blt_un, label1)) + | [ AI_cgt_un ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brtrue, label1) ]) -> + CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bgt_un, label1)) + | [ AI_ceq ], CmpThenBrOrContinue (1, [ I_brcmp (BI_brtrue, label1) ]) -> CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_beq, label1)) + | _ -> + // Failing that, generate the real IL leaving value(s) on the stack + CG.EmitInstrs cgbuf (pop args.Length) (Push ilReturnTys) ilAfterInst + + // If no return values were specified generate a "unit" + if isNil returnTys then + GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel + else + GenSequel cenv eenv.cloc cgbuf sequel //-------------------------------------------------------------------------- // Generate expression quotations @@ -4329,38 +5230,53 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = and GenQuotation cenv cgbuf eenv (ast, qdataCell, m, ety) sequel = let g = cenv.g let suppressWitnesses = eenv.suppressWitnesses + let referencedTypeDefs, typeSplices, exprSplices, astSpec = match qdataCell.Value with - | Some (data1, data2) -> - if suppressWitnesses then data1 else data2 + | Some (data1, data2) -> if suppressWitnesses then data1 else data2 | None -> try - let qscope = QuotationTranslator.QuotationGenerationScope.Create (g, cenv.amap, cenv.viewCcu, cenv.tcVal, QuotationTranslator.IsReflectedDefinition.No) + let qscope = + QuotationTranslator.QuotationGenerationScope.Create( + g, + cenv.amap, + cenv.viewCcu, + cenv.tcVal, + QuotationTranslator.IsReflectedDefinition.No + ) + let astSpec = QuotationTranslator.ConvExprPublic qscope suppressWitnesses ast let referencedTypeDefs, typeSplices, exprSplices = qscope.Close() referencedTypeDefs, List.map fst typeSplices, List.map fst exprSplices, astSpec - with - QuotationTranslator.InvalidQuotedTerm e -> error e + with QuotationTranslator.InvalidQuotedTerm e -> + error e let astSerializedBytes = QuotationPickler.pickle astSpec let someTypeInModuleExpr = mkTypeOfExpr cenv m eenv.someTypeInThisAssembly let rawTy = mkRawQuotedExprTy g - let typeSpliceExprs = List.map (GenType cenv m eenv.tyenv >> (mkTypeOfExpr cenv m)) typeSplices - let bytesExpr = Expr.Op (TOp.Bytes astSerializedBytes, [], [], m) + let typeSpliceExprs = + List.map (GenType cenv m eenv.tyenv >> (mkTypeOfExpr cenv m)) typeSplices + + let bytesExpr = Expr.Op(TOp.Bytes astSerializedBytes, [], [], m) let deserializeExpr = let qf = QuotationTranslator.QuotationGenerationScope.ComputeQuotationFormat g + if qf.SupportsDeserializeEx then - let referencedTypeDefExprs = List.map (mkILNonGenericBoxedTy >> mkTypeOfExpr cenv m) referencedTypeDefs + let referencedTypeDefExprs = + List.map (mkILNonGenericBoxedTy >> mkTypeOfExpr cenv m) referencedTypeDefs + let referencedTypeDefsExpr = mkArray (g.system_Type_ty, referencedTypeDefExprs, m) let typeSplicesExpr = mkArray (g.system_Type_ty, typeSpliceExprs, m) let spliceArgsExpr = mkArray (rawTy, exprSplices, m) mkCallDeserializeQuotationFSharp40Plus g m someTypeInModuleExpr referencedTypeDefsExpr typeSplicesExpr spliceArgsExpr bytesExpr else - let mkList ty els = List.foldBack (mkCons g ty) els (mkNil g m ty) + let mkList ty els = + List.foldBack (mkCons g ty) els (mkNil g m ty) + let typeSplicesExpr = mkList g.system_Type_ty typeSpliceExprs let spliceArgsExpr = mkList rawTy exprSplices mkCallDeserializeQuotationFSharp20Plus g m someTypeInModuleExpr typeSplicesExpr spliceArgsExpr bytesExpr @@ -4372,22 +5288,54 @@ and GenQuotation cenv cgbuf eenv (ast, qdataCell, m, ety) sequel = mkCallCastQuotation g m (List.head (argsOfAppTy g ety)) deserializeExpr else deserializeExpr + GenExpr cenv cgbuf eenv afterCastExpr sequel //-------------------------------------------------------------------------- // Generate calls to IL methods //-------------------------------------------------------------------------- -and GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilMethRef: ILMethodRef, enclArgTys, methArgTys, argExprs, returnTys, m) sequel = +and GenILCall + cenv + cgbuf + eenv + (virt, valu, newobj, valUseFlags, isDllImport, ilMethRef: ILMethodRef, enclArgTys, methArgTys, argExprs, returnTys, m) + sequel + = let hasByrefArg = ilMethRef.ArgTypes |> List.exists IsILTypeByref - let isSuperInit = match valUseFlags with CtorValUsedAsSuperInit -> true | _ -> false - let isBaseCall = match valUseFlags with VSlotDirectCall -> true | _ -> false - let ccallInfo = match valUseFlags with PossibleConstrainedCall ty -> Some ty | _ -> None + + let isSuperInit = + match valUseFlags with + | CtorValUsedAsSuperInit -> true + | _ -> false + + let isBaseCall = + match valUseFlags with + | VSlotDirectCall -> true + | _ -> false + + let ccallInfo = + match valUseFlags with + | PossibleConstrainedCall ty -> Some ty + | _ -> None + let boxity = (if valu then AsValue else AsObject) let mustGenerateUnitAfterCall = isNil returnTys let makesNoCriticalTailcalls = (newobj || not virt) // Don't tailcall for 'newobj', or 'call' to IL code let hasStructObjArg = valu && ilMethRef.CallingConv.IsInstance - let tail = CanTailcall(hasStructObjArg, ccallInfo, eenv.withinSEH, hasByrefArg, mustGenerateUnitAfterCall, isDllImport, false, makesNoCriticalTailcalls, sequel) + + let tail = + CanTailcall( + hasStructObjArg, + ccallInfo, + eenv.withinSEH, + hasByrefArg, + mustGenerateUnitAfterCall, + isDllImport, + false, + makesNoCriticalTailcalls, + sequel + ) let ilEnclArgTys = GenTypeArgs cenv m eenv.tyenv enclArgTys let ilMethArgTys = GenTypeArgs cenv m eenv.tyenv methArgTys @@ -4397,43 +5345,51 @@ and GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilM // Load the 'this' pointer to pass to the superclass constructor. This argument is not // in the expression tree since it can't be treated like an ordinary value - if isSuperInit then CG.EmitInstr cgbuf (pop 0) (Push [ilMethSpec.DeclaringType]) mkLdarg0 + if isSuperInit then + CG.EmitInstr cgbuf (pop 0) (Push [ ilMethSpec.DeclaringType ]) mkLdarg0 + GenExprs cenv cgbuf eenv argExprs + let il = if newobj then - I_newobj (ilMethSpec, None) + I_newobj(ilMethSpec, None) else match ccallInfo with | Some objArgTy -> let ilObjArgTy = GenType cenv m eenv.tyenv objArgTy - I_callconstraint (tail, ilObjArgTy, ilMethSpec, None) + I_callconstraint(tail, ilObjArgTy, ilMethSpec, None) | None -> - if useICallVirt then I_callvirt (tail, ilMethSpec, None) - else I_call (tail, ilMethSpec, None) + if useICallVirt then + I_callvirt(tail, ilMethSpec, None) + else + I_call(tail, ilMethSpec, None) CG.EmitInstr cgbuf (pop (argExprs.Length + (if isSuperInit then 1 else 0))) (if isSuperInit then Push0 else Push ilReturnTys) il // Load the 'this' pointer as the pretend 'result' of the isSuperInit operation. // It will be immediately popped in most cases, but may also be used as the target of some "property set" operations. - if isSuperInit then CG.EmitInstr cgbuf (pop 0) (Push [ilMethSpec.DeclaringType]) mkLdarg0 + if isSuperInit then + CG.EmitInstr cgbuf (pop 0) (Push [ ilMethSpec.DeclaringType ]) mkLdarg0 + CommitCallSequel cenv eenv m eenv.cloc cgbuf mustGenerateUnitAfterCall sequel and CommitCallSequel cenv eenv m cloc cgbuf mustGenerateUnitAfterCall sequel = - if mustGenerateUnitAfterCall - then GenUnitThenSequel cenv eenv m cloc cgbuf sequel - else GenSequel cenv cloc cgbuf sequel - + if mustGenerateUnitAfterCall then + GenUnitThenSequel cenv eenv m cloc cgbuf sequel + else + GenSequel cenv cloc cgbuf sequel and MakeNotSupportedExnExpr cenv eenv (argExpr, m) = let g = cenv.g - let ety = mkAppTy (g.FindSysTyconRef ["System"] "NotSupportedException") [] + let ety = mkAppTy (g.FindSysTyconRef [ "System" ] "NotSupportedException") [] let ilTy = GenType cenv m eenv.tyenv ety - let mref = mkILCtorMethSpecForTy(ilTy, [g.ilg.typ_String]).MethodRef - Expr.Op (TOp.ILCall (false, false, false, true, NormalValUse, false, false, mref, [], [], [ety]), [], [argExpr], m) + let mref = mkILCtorMethSpecForTy(ilTy, [ g.ilg.typ_String ]).MethodRef + Expr.Op(TOp.ILCall(false, false, false, true, NormalValUse, false, false, mref, [], [], [ ety ]), [], [ argExpr ], m) and GenTraitCall (cenv: cenv) cgbuf eenv (traitInfo: TraitConstraintInfo, argExprs, m) expr sequel = let g = cenv.g let generateWitnesses = ComputeGenerateWitnesses g eenv + let witness = if generateWitnesses then TryStorageForWitness g eenv traitInfo.TraitKey @@ -4449,19 +5405,23 @@ and GenTraitCall (cenv: cenv) cgbuf eenv (traitInfo: TraitConstraintInfo, argExp | None -> - // If witnesses are available, we should now always find trait witnesses in scope - assert not generateWitnesses + // If witnesses are available, we should now always find trait witnesses in scope + assert not generateWitnesses - let minfoOpt = CommitOperationResult (ConstraintSolver.CodegenWitnessExprForTraitConstraint cenv.tcVal g cenv.amap m traitInfo argExprs) - match minfoOpt with - | None -> - let exnArg = mkString g m (FSComp.SR.ilDynamicInvocationNotSupported(traitInfo.MemberName)) - let exnExpr = MakeNotSupportedExnExpr cenv eenv (exnArg, m) - let replacementExpr = mkThrow m (tyOfExpr g expr) exnExpr - GenExpr cenv cgbuf eenv replacementExpr sequel - | Some expr -> - let expr = cenv.optimizeDuringCodeGen false expr - GenExpr cenv cgbuf eenv expr sequel + let minfoOpt = + CommitOperationResult(ConstraintSolver.CodegenWitnessExprForTraitConstraint cenv.tcVal g cenv.amap m traitInfo argExprs) + + match minfoOpt with + | None -> + let exnArg = + mkString g m (FSComp.SR.ilDynamicInvocationNotSupported (traitInfo.MemberName)) + + let exnExpr = MakeNotSupportedExnExpr cenv eenv (exnArg, m) + let replacementExpr = mkThrow m (tyOfExpr g expr) exnExpr + GenExpr cenv cgbuf eenv replacementExpr sequel + | Some expr -> + let expr = cenv.optimizeDuringCodeGen false expr + GenExpr cenv cgbuf eenv expr sequel //-------------------------------------------------------------------------- // Generate byref-related operations @@ -4469,40 +5429,53 @@ and GenTraitCall (cenv: cenv) cgbuf eenv (traitInfo: TraitConstraintInfo, argExp and GenGetAddrOfRefCellField cenv cgbuf eenv (e, ty, m) sequel = GenExpr cenv cgbuf eenv e Continue - let fref = GenRecdFieldRef m cenv eenv.tyenv (mkRefCellContentsRef cenv.g) [ty] - CG.EmitInstr cgbuf (pop 1) (Push [ILType.Byref fref.ActualType]) (I_ldflda fref) + let fref = GenRecdFieldRef m cenv eenv.tyenv (mkRefCellContentsRef cenv.g) [ ty ] + CG.EmitInstr cgbuf (pop 1) (Push [ ILType.Byref fref.ActualType ]) (I_ldflda fref) GenSequel cenv eenv.cloc cgbuf sequel and GenGetValAddr cenv cgbuf eenv (v: ValRef, m) sequel = let vspec = v.Deref let ilTy = GenTypeOfVal cenv eenv vspec - let storage = StorageForValRef cenv.g m v eenv + let storage = StorageForValRef m v eenv match storage with - | Local (idx, _, None) -> - CG.EmitInstr cgbuf (pop 0) (Push [ILType.Byref ilTy]) (I_ldloca (uint16 idx)) + | Local (idx, _, None) -> CG.EmitInstr cgbuf (pop 0) (Push [ ILType.Byref ilTy ]) (I_ldloca(uint16 idx)) - | Arg idx -> - CG.EmitInstr cgbuf (pop 0) (Push [ILType.Byref ilTy]) (I_ldarga (uint16 idx)) + | Arg idx -> CG.EmitInstr cgbuf (pop 0) (Push [ ILType.Byref ilTy ]) (I_ldarga(uint16 idx)) | StaticPropertyWithField (fspec, _vref, hasLiteralAttr, _ilTyForProperty, _, ilTy, _, _, _) -> - if hasLiteralAttr then errorR(Error(FSComp.SR.ilAddressOfLiteralFieldIsInvalid(), m)) - let ilTy = if ilTy.IsNominal && ilTy.Boxity = ILBoxity.AsValue then ILType.Byref ilTy else ilTy + if hasLiteralAttr then + errorR (Error(FSComp.SR.ilAddressOfLiteralFieldIsInvalid (), m)) + + let ilTy = + if ilTy.IsNominal && ilTy.Boxity = ILBoxity.AsValue then + ILType.Byref ilTy + else + ilTy + EmitGetStaticFieldAddr cgbuf ilTy fspec - | Env (_, ilField, _) -> - CG.EmitInstrs cgbuf (pop 0) (Push [ILType.Byref ilTy]) [ mkLdarg0; mkNormalLdflda ilField ] + | Env (_, ilField, _) -> CG.EmitInstrs cgbuf (pop 0) (Push [ ILType.Byref ilTy ]) [ mkLdarg0; mkNormalLdflda ilField ] + + | Local (_, _, Some _) + | StaticProperty _ + | Method _ + | Env _ + | Null -> + errorR (Error(FSComp.SR.ilAddressOfValueHereIsInvalid (v.DisplayName), m)) - | Local (_, _, Some _) | StaticProperty _ | Method _ | Env _ | Null -> - errorR(Error(FSComp.SR.ilAddressOfValueHereIsInvalid(v.DisplayName), m)) - CG.EmitInstr cgbuf (pop 1) (Push [ILType.Byref ilTy]) (I_ldarga (uint16 669 (* random value for post-hoc diagnostic analysis on generated tree *) )) + CG.EmitInstr + cgbuf + (pop 1) + (Push [ ILType.Byref ilTy ]) + (I_ldarga(uint16 669 (* random value for post-hoc diagnostic analysis on generated tree *) )) GenSequel cenv eenv.cloc cgbuf sequel and GenGetByref cenv cgbuf eenv (v: ValRef, m) sequel = GenGetLocalVRef cenv cgbuf eenv m v None let ilTy = GenType cenv m eenv.tyenv (destByrefTy cenv.g v.Type) - CG.EmitInstr cgbuf (pop 1) (Push [ilTy]) (mkNormalLdobj ilTy) + CG.EmitInstr cgbuf (pop 1) (Push [ ilTy ]) (mkNormalLdobj ilTy) GenSequel cenv eenv.cloc cgbuf sequel and GenSetByref cenv cgbuf eenv (v: ValRef, e, m) sequel = @@ -4515,33 +5488,44 @@ and GenSetByref cenv cgbuf eenv (v: ValRef, e, m) sequel = and GenDefaultValue cenv cgbuf eenv (ty, m) = let g = cenv.g let ilTy = GenType cenv m eenv.tyenv ty + if isRefTy g ty then - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) AI_ldnull + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) AI_ldnull else match tryTcrefOfAppTy g ty with - | ValueSome tcref when (tyconRefEq g g.system_SByte_tcref tcref || - tyconRefEq g g.system_Int16_tcref tcref || - tyconRefEq g g.system_Int32_tcref tcref || - tyconRefEq g g.system_Bool_tcref tcref || - tyconRefEq g g.system_Byte_tcref tcref || - tyconRefEq g g.system_Char_tcref tcref || - tyconRefEq g g.system_UInt16_tcref tcref || - tyconRefEq g g.system_UInt32_tcref tcref) -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) iLdcZero - | ValueSome tcref when (tyconRefEq g g.system_Int64_tcref tcref || - tyconRefEq g g.system_UInt64_tcref tcref) -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcInt64 0L) - | ValueSome tcref when (tyconRefEq g g.system_Single_tcref tcref) -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcSingle 0.0f) - | ValueSome tcref when (tyconRefEq g g.system_Double_tcref tcref) -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (iLdcDouble 0.0) + | ValueSome tcref when + (tyconRefEq g g.system_SByte_tcref tcref + || tyconRefEq g g.system_Int16_tcref tcref + || tyconRefEq g g.system_Int32_tcref tcref + || tyconRefEq g g.system_Bool_tcref tcref + || tyconRefEq g g.system_Byte_tcref tcref + || tyconRefEq g g.system_Char_tcref tcref + || tyconRefEq g g.system_UInt16_tcref tcref + || tyconRefEq g g.system_UInt32_tcref tcref) + -> + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) iLdcZero + | ValueSome tcref when + (tyconRefEq g g.system_Int64_tcref tcref + || tyconRefEq g g.system_UInt64_tcref tcref) + -> + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (iLdcInt64 0L) + | ValueSome tcref when (tyconRefEq g g.system_Single_tcref tcref) -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (iLdcSingle 0.0f) + | ValueSome tcref when (tyconRefEq g g.system_Double_tcref tcref) -> CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (iLdcDouble 0.0) | _ -> let ilTy = GenType cenv m eenv.tyenv ty + LocalScope "ilzero" cgbuf (fun scopeMarks -> let locIdx, realloc, _ = // Ensure that we have an g.CompilerGlobalState - assert(g.CompilerGlobalState |> Option.isSome) - AllocLocal cenv cgbuf eenv true (g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("default", m), ilTy, false) scopeMarks + assert (g.CompilerGlobalState |> Option.isSome) + + AllocLocal + cenv + cgbuf + eenv + true + (g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName("default", m), ilTy, false) + scopeMarks // We can normally rely on .NET IL zero-initialization of the temporaries // we create to get zero values for struct types. // @@ -4556,8 +5540,7 @@ and GenDefaultValue cenv cgbuf eenv (ty, m) = if (realloc || not eenv.initLocals || eenv.isInLoop) && not (IsILTypeByref ilTy) then EmitInitLocal cgbuf ilTy locIdx - EmitGetLocal cgbuf ilTy locIdx - ) + EmitGetLocal cgbuf ilTy locIdx) //-------------------------------------------------------------------------- // Generate generic parameters @@ -4565,51 +5548,72 @@ and GenDefaultValue cenv cgbuf eenv (ty, m) = and GenGenericParam cenv eenv (tp: Typar) = let g = cenv.g + let subTypeConstraints = tp.Constraints - |> List.choose (function | TyparConstraint.CoercesTo(ty, _) -> Some ty | _ -> None) + |> List.choose (function + | TyparConstraint.CoercesTo (ty, _) -> Some ty + | _ -> None) |> List.map (GenTypeAux cenv tp.Range eenv.tyenv VoidNotOK PtrTypesNotOK) let refTypeConstraint = tp.Constraints - |> List.exists (function TyparConstraint.IsReferenceType _ -> true | TyparConstraint.SupportsNull _ -> true | _ -> false) + |> List.exists (function + | TyparConstraint.IsReferenceType _ -> true + | TyparConstraint.SupportsNull _ -> true + | _ -> false) let notNullableValueTypeConstraint = - tp.Constraints |> List.exists (function TyparConstraint.IsNonNullableStruct _ -> true | _ -> false) + tp.Constraints + |> List.exists (function + | TyparConstraint.IsNonNullableStruct _ -> true + | _ -> false) let defaultConstructorConstraint = - tp.Constraints |> List.exists (function TyparConstraint.RequiresDefaultConstructor _ -> true | _ -> false) + tp.Constraints + |> List.exists (function + | TyparConstraint.RequiresDefaultConstructor _ -> true + | _ -> false) let tpName = - // use the CompiledName if given - // Inference variables get given an IL name "TA, TB" etc. - let nm = - match tp.ILName with - | None -> tp.Name - | Some nm -> nm - // Some special rules apply when compiling Fsharp.Core.dll to avoid a proliferation of [] attributes on type parameters - if g.compilingFSharpCore then - match nm with - | "U" -> "TResult" - | "U1" -> "TResult1" - | "U2" -> "TResult2" - | _ -> - if nm.TrimEnd([| '0' .. '9' |]).Length = 1 then nm - elif nm.Length >= 1 && nm[0] = 'T' && (nm.Length = 1 || not (System.Char.IsLower nm[1])) then nm - else "T" + (String.capitalize nm) - else - nm + // use the CompiledName if given + // Inference variables get given an IL name "TA, TB" etc. + let nm = + match tp.ILName with + | None -> tp.Name + | Some nm -> nm + // Some special rules apply when compiling Fsharp.Core.dll to avoid a proliferation of [] attributes on type parameters + if g.compilingFSharpCore then + match nm with + | "U" -> "TResult" + | "U1" -> "TResult1" + | "U2" -> "TResult2" + | _ -> + if nm.TrimEnd([| '0' .. '9' |]).Length = 1 then + nm + elif + nm.Length >= 1 + && nm[0] = 'T' + && (nm.Length = 1 || not (System.Char.IsLower nm[1])) + then + nm + else + "T" + (String.capitalize nm) + else + nm let tpAttrs = mkILCustomAttrs (GenAttrs cenv eenv tp.Attribs) - { Name = tpName - Constraints = subTypeConstraints - Variance = NonVariant - CustomAttrsStored = storeILCustomAttrs tpAttrs - MetadataIndex = NoMetadataIdx - HasReferenceTypeConstraint = refTypeConstraint - HasNotNullableValueTypeConstraint = notNullableValueTypeConstraint - HasDefaultConstructorConstraint = defaultConstructorConstraint } + { + Name = tpName + Constraints = subTypeConstraints + Variance = NonVariant + CustomAttrsStored = storeILCustomAttrs tpAttrs + MetadataIndex = NoMetadataIdx + HasReferenceTypeConstraint = refTypeConstraint + HasNotNullableValueTypeConstraint = notNullableValueTypeConstraint + HasDefaultConstructorConstraint = defaultConstructorConstraint + } //-------------------------------------------------------------------------- // Generate object expressions as ILX "closures" @@ -4617,29 +5621,33 @@ and GenGenericParam cenv eenv (tp: Typar) = /// Generates the data used for parameters at definitions of abstract method slots such as interface methods or override methods. and GenSlotParam m cenv eenv slotParam : ILParameter = - let (TSlotParam(nm, ty, inFlag, outFlag, optionalFlag, attribs)) = slotParam + let (TSlotParam (nm, ty, inFlag, outFlag, optionalFlag, attribs)) = slotParam let ilTy = GenParamType cenv m eenv.tyenv true ty - let inFlag2, outFlag2, optionalFlag2, defaultParamValue, paramMarshal2, attribs = GenParamAttribs cenv ty attribs + + let inFlag2, outFlag2, optionalFlag2, defaultParamValue, paramMarshal2, attribs = + GenParamAttribs cenv ty attribs let ilAttribs = GenAttrs cenv eenv attribs let ilAttribs = match GenReadOnlyAttributeIfNecessary cenv.g ty with - | Some attr -> ilAttribs @ [attr] + | Some attr -> ilAttribs @ [ attr ] | None -> ilAttribs - { Name=nm - Type= ilTy - Default=defaultParamValue - Marshal=paramMarshal2 - IsIn=inFlag || inFlag2 - IsOut=outFlag || outFlag2 - IsOptional=optionalFlag || optionalFlag2 - CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs ilAttribs) - MetadataIndex = NoMetadataIdx } + { + Name = nm + Type = ilTy + Default = defaultParamValue + Marshal = paramMarshal2 + IsIn = inFlag || inFlag2 + IsOut = outFlag || outFlag2 + IsOptional = optionalFlag || optionalFlag2 + CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs ilAttribs) + MetadataIndex = NoMetadataIdx + } and GenFormalSlotsig m cenv eenv slotsig = - let (TSlotSig(_, ty, ctps, mtps, paraml, returnTy)) = slotsig + let (TSlotSig (_, ty, ctps, mtps, paraml, returnTy)) = slotsig let paraml = List.concat paraml let ilTy = GenType cenv m eenv.tyenv ty let eenvForSlotSig = EnvForTypars (ctps @ mtps) eenv @@ -4648,42 +5656,74 @@ and GenFormalSlotsig m cenv eenv slotsig = ilTy, ilParams, ilRet and GenOverridesSpec cenv eenv slotsig m = - let (TSlotSig(nameOfOverridenMethod, _, _, methodTypars, _, _)) = slotsig - let ilOverrideTy, ilOverrideParams, ilOverrideRet = GenFormalSlotsig m cenv eenv slotsig + let (TSlotSig (nameOfOverridenMethod, _, _, methodTypars, _, _)) = slotsig + + let ilOverrideTy, ilOverrideParams, ilOverrideRet = + GenFormalSlotsig m cenv eenv slotsig + let ilOverrideTyRef = ilOverrideTy.TypeRef - let ilOverrideMethRef = mkILMethRef(ilOverrideTyRef, ILCallingConv.Instance, nameOfOverridenMethod, List.length (DropErasedTypars methodTypars), typesOfILParams ilOverrideParams, ilOverrideRet.Type) + + let ilOverrideMethRef = + mkILMethRef ( + ilOverrideTyRef, + ILCallingConv.Instance, + nameOfOverridenMethod, + List.length (DropErasedTypars methodTypars), + typesOfILParams ilOverrideParams, + ilOverrideRet.Type + ) + OverridesSpec(ilOverrideMethRef, ilOverrideTy) and GenFormalReturnType m cenv eenvFormal returnTy : ILReturn = let ilRetTy = GenReturnType cenv m eenvFormal.tyenv returnTy let ilRet = mkILReturn ilRetTy + match returnTy with | None -> ilRet | Some ty -> - match GenReadOnlyAttributeIfNecessary cenv.g ty with - | Some attr -> ilRet.WithCustomAttrs (mkILCustomAttrs (ilRet.CustomAttrs.AsList() @ [attr])) - | None -> ilRet + match GenReadOnlyAttributeIfNecessary cenv.g ty with + | Some attr -> ilRet.WithCustomAttrs(mkILCustomAttrs (ilRet.CustomAttrs.AsList() @ [ attr ])) + | None -> ilRet -and instSlotParam inst (TSlotParam(nm, ty, inFlag, fl2, fl3, attrs)) = +and instSlotParam inst (TSlotParam (nm, ty, inFlag, fl2, fl3, attrs)) = TSlotParam(nm, instType inst ty, inFlag, fl2, fl3, attrs) -and GenActualSlotsig m cenv eenv (TSlotSig(_, ty, ctps, mtps, ilSlotParams, ilSlotRetTy)) methTyparsOfOverridingMethod (methodParams: Val list) = +and GenActualSlotsig + m + cenv + eenv + (TSlotSig (_, ty, ctps, mtps, ilSlotParams, ilSlotRetTy)) + methTyparsOfOverridingMethod + (methodParams: Val list) + = let ilSlotParams = List.concat ilSlotParams - let instForSlotSig = mkTyparInst (ctps@mtps) (argsOfAppTy cenv.g ty @ generalizeTypars methTyparsOfOverridingMethod) - let ilParams = ilSlotParams |> List.map (instSlotParam instForSlotSig >> GenSlotParam m cenv eenv) + + let instForSlotSig = + mkTyparInst (ctps @ mtps) (argsOfAppTy cenv.g ty @ generalizeTypars methTyparsOfOverridingMethod) + + let ilParams = + ilSlotParams + |> List.map (instSlotParam instForSlotSig >> GenSlotParam m cenv eenv) // Use the better names if available let ilParams = if ilParams.Length = methodParams.Length then - (ilParams, methodParams) ||> List.map2 (fun p pv -> { p with Name = Some (nameOfVal pv) }) - else ilParams + (ilParams, methodParams) + ||> List.map2 (fun p pv -> { p with Name = Some(nameOfVal pv) }) + else + ilParams + + let ilRetTy = + GenReturnType cenv m eenv.tyenv (Option.map (instType instForSlotSig) ilSlotRetTy) - let ilRetTy = GenReturnType cenv m eenv.tyenv (Option.map (instType instForSlotSig) ilSlotRetTy) let iLRet = mkILReturn ilRetTy ilParams, iLRet and GenNameOfOverridingMethod cenv (useMethodImpl, slotsig) = - let (TSlotSig(nameOfOverridenMethod, enclTypOfOverridenMethod, _, _, _, _)) = slotsig + let (TSlotSig (nameOfOverridenMethod, enclTypOfOverridenMethod, _, _, _, _)) = + slotsig + if useMethodImpl then qualifiedInterfaceImplementationName cenv.g enclTypOfOverridenMethod nameOfOverridenMethod else @@ -4693,35 +5733,56 @@ and GenMethodImpl cenv eenv (useMethodImpl, slotsig) m = let ilOverridesSpec = GenOverridesSpec cenv eenv slotsig m let nameOfOverridingMethod = GenNameOfOverridingMethod cenv (useMethodImpl, slotsig) + nameOfOverridingMethod, (fun (ilTyForOverriding, methTyparsOfOverridingMethod) -> let eenvForOverrideBy = AddTyparsToEnv methTyparsOfOverridingMethod eenv - let ilParamsOfOverridingMethod, ilReturnOfOverridingMethod = GenActualSlotsig m cenv eenvForOverrideBy slotsig methTyparsOfOverridingMethod [] - let ilOverrideMethGenericParams = GenGenericParams cenv eenvForOverrideBy methTyparsOfOverridingMethod + + let ilParamsOfOverridingMethod, ilReturnOfOverridingMethod = + GenActualSlotsig m cenv eenvForOverrideBy slotsig methTyparsOfOverridingMethod [] + + let ilOverrideMethGenericParams = + GenGenericParams cenv eenvForOverrideBy methTyparsOfOverridingMethod + let ilOverrideMethGenericArgs = mkILFormalGenericArgs 0 ilOverrideMethGenericParams - let ilOverrideBy = mkILInstanceMethSpecInTy(ilTyForOverriding, nameOfOverridingMethod, typesOfILParams ilParamsOfOverridingMethod, ilReturnOfOverridingMethod.Type, ilOverrideMethGenericArgs) - { Overrides = ilOverridesSpec - OverrideBy = ilOverrideBy }) + + let ilOverrideBy = + mkILInstanceMethSpecInTy ( + ilTyForOverriding, + nameOfOverridingMethod, + typesOfILParams ilParamsOfOverridingMethod, + ilReturnOfOverridingMethod.Type, + ilOverrideMethGenericArgs + ) + + { + Overrides = ilOverridesSpec + OverrideBy = ilOverrideBy + }) and bindBaseOrThisVarOpt cenv eenv baseValOpt = match baseValOpt with | None -> eenv | Some basev -> AddStorageForVal cenv.g (basev, notlazy (Arg 0)) eenv -and fixupVirtualSlotFlags (mdef: ILMethodDef) = - mdef.WithHideBySig() +and fixupVirtualSlotFlags (mdef: ILMethodDef) = mdef.WithHideBySig() and renameMethodDef nameOfOverridingMethod (mdef: ILMethodDef) = - mdef.With(name=nameOfOverridingMethod) + 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 GenObjectMethod cenv eenvinner (cgbuf: CodeGenBuffer) useMethodImpl tmethod = let g = cenv.g - let (TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methParams, methBodyExpr, m)) = tmethod - let (TSlotSig(nameOfOverridenMethod, _, _, _, _, _)) = slotsig + let (TObjExprMethod (slotsig, attribs, methTyparsOfOverridingMethod, methParams, methBodyExpr, m)) = + tmethod + + let (TSlotSig (nameOfOverridenMethod, _, _, _, _, _)) = slotsig // Check if we're compiling the property as a .NET event if CompileAsEvent g attribs then @@ -4742,53 +5803,75 @@ and GenObjectMethod cenv eenvinner (cgbuf: CodeGenBuffer) useMethodImpl tmethod let ilAttribs = GenAttrs cenv eenvinner attribs // Args are stored starting at #0, the args include the self parameter - let eenvForMeth = AddStorageForLocalVals g (methParams |> List.mapi (fun i v -> (v, Arg i))) eenvUnderTypars + let eenvForMeth = + AddStorageForLocalVals g (methParams |> List.mapi (fun i v -> (v, Arg i))) eenvUnderTypars - let sequel = (if slotSigHasVoidReturnTy slotsig then discardAndReturnVoid else Return) + let sequel = + (if slotSigHasVoidReturnTy slotsig then + discardAndReturnVoid + else + Return) - let ilMethodBody = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], nameOfOverridenMethod, eenvForMeth, 0, selfArgOpt, methBodyExpr, sequel) + let ilMethodBody = + CodeGenMethodForExpr cenv cgbuf.mgbuf ([], nameOfOverridenMethod, eenvForMeth, 0, selfArgOpt, methBodyExpr, sequel) - let nameOfOverridingMethod, methodImplGenerator = GenMethodImpl cenv eenvinner (useMethodImpl, slotsig) methBodyExpr.Range + let nameOfOverridingMethod, methodImplGenerator = + GenMethodImpl cenv eenvinner (useMethodImpl, slotsig) methBodyExpr.Range let mdef = - mkILGenericVirtualMethod - (nameOfOverridingMethod, - ILMemberAccess.Public, - GenGenericParams cenv eenvUnderTypars methTyparsOfOverridingMethod, - ilParamsOfOverridingMethod, - ilReturnOfOverridingMethod, - MethodBody.IL (lazy ilMethodBody)) + mkILGenericVirtualMethod ( + nameOfOverridingMethod, + ILMemberAccess.Public, + GenGenericParams cenv eenvUnderTypars methTyparsOfOverridingMethod, + ilParamsOfOverridingMethod, + ilReturnOfOverridingMethod, + MethodBody.IL(lazy ilMethodBody) + ) // fixup attributes to generate a method impl let mdef = if useMethodImpl then fixupMethodImplFlags mdef else mdef let mdef = fixupVirtualSlotFlags mdef let mdef = mdef.With(customAttrs = mkILCustomAttrs ilAttribs) - [(useMethodImpl, methodImplGenerator, methTyparsOfOverridingMethod), mdef] + [ (useMethodImpl, methodImplGenerator, methTyparsOfOverridingMethod), mdef ] and GenStructStateMachine cenv cgbuf eenvouter (res: LoweredStateMachine) sequel = - let (LoweredStateMachine - (templateStructTy, dataTy, stateVars, thisVars, - (moveNextThisVar, moveNextBody), - (setStateMachineThisVar, setStateMachineStateVar, setStateMachineBody), - (afterCodeThisVar, afterCodeBody))) = res + let (LoweredStateMachine (templateStructTy, + dataTy, + stateVars, + thisVars, + (moveNextThisVar, moveNextBody), + (setStateMachineThisVar, setStateMachineStateVar, setStateMachineBody), + (afterCodeThisVar, afterCodeBody))) = + res + let m = moveNextBody.Range let g = cenv.g let amap = cenv.amap - let stateVarsSet = stateVars |> List.map (fun vref -> vref.Deref) |> Zset.ofList valOrder + let stateVarsSet = + stateVars |> List.map (fun vref -> vref.Deref) |> Zset.ofList valOrder // Find the free variables of the closure, to make them further fields of the object. - let cloinfo, _, eenvinner = - // State vars are only populated for state machine objects + let cloinfo, _, eenvinner = + // State vars are only populated for state machine objects // // Like in GenSequenceExpression we pretend any stateVars and the stateMachineVar are bound in the outer environment. This prevents the being // considered true free variables that need to be passed to the constructor. // // Note, the 'let' bindings for the stateVars have already been transformed to 'set' expressions, and thus the stateVars are now // free variables of the expression. - let eenvouter = eenvouter |> AddStorageForLocalVals g (stateVars |> List.map (fun v -> v.Deref, Local(0, false, None))) - let eenvouter = eenvouter |> AddStorageForLocalVals g (thisVars |> List.map (fun v -> v.Deref, Local(0, false, None))) - let eenvouter = eenvouter |> AddStorageForLocalVals g [ (moveNextThisVar, Local(0, false, None)) ] + let eenvouter = + eenvouter + |> AddStorageForLocalVals g (stateVars |> List.map (fun v -> v.Deref, Local(0, false, None))) + + let eenvouter = + eenvouter + |> AddStorageForLocalVals g (thisVars |> List.map (fun v -> v.Deref, Local(0, false, None))) + + let eenvouter = + eenvouter + |> AddStorageForLocalVals g [ (moveNextThisVar, Local(0, false, None)) ] + GetIlxClosureInfo cenv m ILBoxity.AsValue false false (mkLocalValRef moveNextThisVar :: thisVars) eenvouter moveNextBody let cloFreeVars = cloinfo.cloFreeVars @@ -4799,8 +5882,9 @@ and GenStructStateMachine cenv cgbuf eenvouter (res: LoweredStateMachine) sequel let ilCloTypeRef = cloinfo.cloSpec.TypeRef let ilCloTy = mkILValueTy ilCloTypeRef ilCloGenericActuals - // The closure implements what ever interfaces the template implements. - let interfaceTys = GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes g cenv.amap m templateStructTy + // The closure implements what ever interfaces the template implements. + let interfaceTys = + GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes g cenv.amap m templateStructTy let ilInterfaceTys = List.map (GenType cenv m eenvinner.tyenv) interfaceTys @@ -4808,113 +5892,223 @@ and GenStructStateMachine cenv cgbuf eenvouter (res: LoweredStateMachine) sequel let templateTyconRef, templateTypeArgs = destAppTy g templateStructTy let templateTypeInst = mkTyconRefInst templateTyconRef templateTypeArgs + let eenvinner = AddTemplateReplacement eenvinner (templateTyconRef, ilCloTypeRef, cloinfo.cloFreeTyvars, templateTypeInst) let infoReader = InfoReader.InfoReader(g, cenv.amap) // We codegen the IResumableStateMachine implementation for each generated struct type - let getResumptionPointThisVar, getResumptionPointBody = + let getResumptionPointThisVar, getResumptionPointBody = let fieldName = "ResumptionPoint" let thisVar = moveNextThisVar // reusing the this var from the MoveNext implementation - let finfo = - match infoReader.GetRecordOrClassFieldsOfType(Some fieldName, AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere, m, templateStructTy) with - | [finfo] -> finfo - | _ -> error(InternalError(sprintf "expected class field %s not found" fieldName, m)) + + let finfo = + match + infoReader.GetRecordOrClassFieldsOfType( + Some fieldName, + AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere, + m, + templateStructTy + ) + with + | [ finfo ] -> finfo + | _ -> error (InternalError(sprintf "expected class field %s not found" fieldName, m)) + thisVar, mkRecdFieldGetViaExprAddr (exprForVal m thisVar, finfo.RecdFieldRef, finfo.TypeInst, m) - let (getDataThisVar, getDataBody), (setDataThisVar, setDataValueVar, setDataBody) = + let (getDataThisVar, getDataBody), (setDataThisVar, setDataValueVar, setDataBody) = let fieldName = "Data" let thisVar = moveNextThisVar // reusing the this var from the MoveNext implementation - let setDataValueVar, setDataValueExpr = mkCompGenLocal m "value" dataTy - let finfo = - match infoReader.GetRecordOrClassFieldsOfType(Some fieldName, AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere, m, templateStructTy) with - | [finfo] -> finfo - | _ -> error(InternalError(sprintf "expected class field %s not found" fieldName, m)) + let setDataValueVar, setDataValueExpr = mkCompGenLocal m "value" dataTy + + let finfo = + match + infoReader.GetRecordOrClassFieldsOfType( + Some fieldName, + AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere, + m, + templateStructTy + ) + with + | [ finfo ] -> finfo + | _ -> error (InternalError(sprintf "expected class field %s not found" fieldName, m)) + (thisVar, mkRecdFieldGetViaExprAddr (exprForVal m thisVar, finfo.RecdFieldRef, finfo.TypeInst, m)), (thisVar, setDataValueVar, mkRecdFieldSetViaExprAddr (exprForVal m thisVar, finfo.RecdFieldRef, finfo.TypeInst, setDataValueExpr, m)) let methods = - [ ((mkLocalValRef moveNextThisVar::thisVars), [], g.mk_IAsyncStateMachine_ty, "MoveNext", moveNextBody); - ([mkLocalValRef setStateMachineThisVar], [setStateMachineStateVar], g.mk_IAsyncStateMachine_ty, "SetStateMachine", setStateMachineBody); - ([mkLocalValRef getResumptionPointThisVar], [], g.mk_IResumableStateMachine_ty dataTy, "get_ResumptionPoint", getResumptionPointBody); - ([mkLocalValRef getDataThisVar], [], g.mk_IResumableStateMachine_ty dataTy, "get_Data", getDataBody); - ([mkLocalValRef setDataThisVar], [setDataValueVar], g.mk_IResumableStateMachine_ty dataTy, "set_Data", setDataBody); ] + [ + ((mkLocalValRef moveNextThisVar :: thisVars), [], g.mk_IAsyncStateMachine_ty, "MoveNext", moveNextBody) + ([ mkLocalValRef setStateMachineThisVar ], + [ setStateMachineStateVar ], + g.mk_IAsyncStateMachine_ty, + "SetStateMachine", + setStateMachineBody) + ([ mkLocalValRef getResumptionPointThisVar ], + [], + g.mk_IResumableStateMachine_ty dataTy, + "get_ResumptionPoint", + getResumptionPointBody) + ([ mkLocalValRef getDataThisVar ], [], g.mk_IResumableStateMachine_ty dataTy, "get_Data", getDataBody) + ([ mkLocalValRef setDataThisVar ], [ setDataValueVar ], g.mk_IResumableStateMachine_ty dataTy, "set_Data", setDataBody) + ] let mdefs = - [ for thisVals, argVals, interfaceTy, imethName, bodyR in methods do - let eenvinner = eenvinner |> AddStorageForLocalVals g [(moveNextThisVar, Arg 0) ] - let m = bodyR.Range - let implementedMeth = - match InfoReader.TryFindIntrinsicMethInfo infoReader m AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere imethName interfaceTy with - | [meth] when meth.IsInstance -> meth - | _ -> error(InternalError(sprintf "expected method %s not found" imethName, m)) - let argTys = implementedMeth.GetParamTypes(cenv.amap, m, []) |> List.concat - let retTy = implementedMeth.GetCompiledReturnType(cenv.amap, m, []) - let ilRetTy = GenReturnType cenv m eenvinner.tyenv retTy - let ilArgTys = argTys |> GenTypes cenv m eenvinner.tyenv - if ilArgTys.Length <> argVals.Length then - error(InternalError(sprintf "expected method arg count of %d, got %d for method %s" argVals.Length ilArgTys.Length imethName, m)) - let eenvinner = eenvinner |> AddStorageForLocalVals g (thisVals |> List.map (fun v -> (v.Deref, Arg 0))) - let eenvinner = eenvinner |> AddStorageForLocalVals g (argVals |> List.mapi (fun i v -> v, Arg (i+1))) - let sequel = if retTy.IsNone then discardAndReturnVoid else Return - let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], imethName, eenvinner, 1+argVals.Length, None, bodyR, sequel) - let ilParams = (ilArgTys,argVals) ||> List.map2 (fun ty v -> mkILParamNamed(v.LogicalName, ty)) - mkILNonGenericVirtualMethod(imethName, ILMemberAccess.Public, ilParams, mkILReturn ilRetTy, MethodBody.IL (notlazy ilCode)) ] + [ + for thisVals, argVals, interfaceTy, imethName, bodyR in methods do + let eenvinner = eenvinner |> AddStorageForLocalVals g [ (moveNextThisVar, Arg 0) ] + let m = bodyR.Range + + let implementedMeth = + match + InfoReader.TryFindIntrinsicMethInfo + infoReader + m + AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere + imethName + interfaceTy + with + | [ meth ] when meth.IsInstance -> meth + | _ -> error (InternalError(sprintf "expected method %s not found" imethName, m)) + + let argTys = implementedMeth.GetParamTypes(cenv.amap, m, []) |> List.concat + let retTy = implementedMeth.GetCompiledReturnType(cenv.amap, m, []) + let ilRetTy = GenReturnType cenv m eenvinner.tyenv retTy + let ilArgTys = argTys |> GenTypes cenv m eenvinner.tyenv + + if ilArgTys.Length <> argVals.Length then + error ( + InternalError( + sprintf "expected method arg count of %d, got %d for method %s" argVals.Length ilArgTys.Length imethName, + m + ) + ) + + let eenvinner = + eenvinner + |> AddStorageForLocalVals g (thisVals |> List.map (fun v -> (v.Deref, Arg 0))) + + let eenvinner = + eenvinner + |> AddStorageForLocalVals g (argVals |> List.mapi (fun i v -> v, Arg(i + 1))) + + let sequel = if retTy.IsNone then discardAndReturnVoid else Return + + let ilCode = + CodeGenMethodForExpr cenv cgbuf.mgbuf ([], imethName, eenvinner, 1 + argVals.Length, None, bodyR, sequel) + + let ilParams = + (ilArgTys, argVals) + ||> List.map2 (fun ty v -> mkILParamNamed (v.LogicalName, ty)) + + mkILNonGenericVirtualMethod (imethName, ILMemberAccess.Public, ilParams, mkILReturn ilRetTy, MethodBody.IL(notlazy ilCode)) + ] let mimpls = - [ for (_thisVals, _argVals, interfaceTy, imethName, bodyR), mdef in (List.zip methods mdefs) do - let m = bodyR.Range - let implementedMeth = - match InfoReader.TryFindIntrinsicMethInfo infoReader m AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere imethName interfaceTy with - | [meth] when meth.IsInstance -> meth - | _ -> error(InternalError(sprintf "expected method %s not found" imethName, m)) - - let slotsig = implementedMeth.GetSlotSig(amap, m) - let ilOverridesSpec = GenOverridesSpec cenv eenvinner slotsig m - let ilOverrideBy = mkILInstanceMethSpecInTy(ilCloTy, imethName, mdef.ParameterTypes, mdef.Return.Type, []) - { Overrides = ilOverridesSpec - OverrideBy = ilOverrideBy } ] + [ + for (_thisVals, _argVals, interfaceTy, imethName, bodyR), mdef in (List.zip methods mdefs) do + let m = bodyR.Range + + let implementedMeth = + match + InfoReader.TryFindIntrinsicMethInfo + infoReader + m + AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere + imethName + interfaceTy + with + | [ meth ] when meth.IsInstance -> meth + | _ -> error (InternalError(sprintf "expected method %s not found" imethName, m)) + + let slotsig = implementedMeth.GetSlotSig(amap, m) + let ilOverridesSpec = GenOverridesSpec cenv eenvinner slotsig m + + let ilOverrideBy = + mkILInstanceMethSpecInTy (ilCloTy, imethName, mdef.ParameterTypes, mdef.Return.Type, []) + + { + Overrides = ilOverridesSpec + OverrideBy = ilOverrideBy + } + ] let fdefs = [ // Fields copied from the template struct - for templateFld in infoReader.GetRecordOrClassFieldsOfType (None, AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere, m, templateStructTy) do - // Suppress the "ResumptionDynamicInfo" from generated state machines - if templateFld.LogicalName <> "ResumptionDynamicInfo" then - let access = ComputeMemberAccess false - let fty = GenType cenv m eenvinner.tyenv templateFld.FieldType - let fdef = - ILFieldDef(name = templateFld.LogicalName, fieldType = fty, attributes = enum 0, data = None, literalValue = None, offset = None, marshal = None, customAttrs = mkILCustomAttrs []) - .WithAccess(access) - .WithStatic(false) - yield fdef - - // Fields for captured variables - for ilCloFreeVar in ilCloFreeVars do - let access = ComputeMemberAccess false - let fdef = - ILFieldDef(name = ilCloFreeVar.fvName, fieldType = ilCloFreeVar.fvType, attributes = enum 0, - data = None, literalValue = None, offset = None, marshal = None, customAttrs = mkILCustomAttrs []) - .WithAccess(access) - .WithStatic(false) - yield fdef ] + for templateFld in + infoReader.GetRecordOrClassFieldsOfType( + None, + AccessibilityLogic.AccessorDomain.AccessibleFromSomewhere, + m, + templateStructTy + ) do + // Suppress the "ResumptionDynamicInfo" from generated state machines + if templateFld.LogicalName <> "ResumptionDynamicInfo" then + let access = ComputeMemberAccess false + let fty = GenType cenv m eenvinner.tyenv templateFld.FieldType + + let fdef = + ILFieldDef( + name = templateFld.LogicalName, + fieldType = fty, + attributes = enum 0, + data = None, + literalValue = None, + offset = None, + marshal = None, + customAttrs = mkILCustomAttrs [] + ) + .WithAccess(access) + .WithStatic(false) + + yield fdef + + // Fields for captured variables + for ilCloFreeVar in ilCloFreeVars do + let access = ComputeMemberAccess false + + let fdef = + ILFieldDef( + name = ilCloFreeVar.fvName, + fieldType = ilCloFreeVar.fvType, + attributes = enum 0, + data = None, + literalValue = None, + offset = None, + marshal = None, + customAttrs = mkILCustomAttrs [] + ) + .WithAccess(access) + .WithStatic(false) + + yield fdef + ] let cloTypeDef = - ILTypeDef(name = ilCloTypeRef.Name, - layout = ILTypeDefLayout.Auto, - attributes = enum 0, - genericParams = ilCloGenericFormals, - customAttrs = mkILCustomAttrs([ g.CompilerGeneratedAttribute; mkCompilationMappingAttr g (int SourceConstructFlags.Closure) ]), - fields = mkILFields fdefs, - events= emptyILEvents, - properties = emptyILProperties, - methods= mkILMethods mdefs, - methodImpls = mkILMethodImpls mimpls, - nestedTypes = emptyILTypeDefs, - implements = ilInterfaceTys, - extends = Some super, - isKnownToBeAttribute = false, - securityDecls = emptyILSecurityDecls) + ILTypeDef( + name = ilCloTypeRef.Name, + layout = ILTypeDefLayout.Auto, + attributes = enum 0, + genericParams = ilCloGenericFormals, + customAttrs = + mkILCustomAttrs ( + [ + g.CompilerGeneratedAttribute + mkCompilationMappingAttr g (int SourceConstructFlags.Closure) + ] + ), + fields = mkILFields fdefs, + events = emptyILEvents, + properties = emptyILProperties, + methods = mkILMethods mdefs, + methodImpls = mkILMethodImpls mimpls, + nestedTypes = emptyILTypeDefs, + implements = ilInterfaceTys, + extends = Some super, + isKnownToBeAttribute = false, + securityDecls = emptyILSecurityDecls + ) .WithSealed(true) .WithSpecialName(true) .WithAccess(ComputeTypeAccess ilCloTypeRef true) @@ -4925,41 +6119,63 @@ and GenStructStateMachine cenv cgbuf eenvouter (res: LoweredStateMachine) sequel cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) CountClosure() + LocalScope "machine" cgbuf (fun scopeMarks -> - let eenvouter = AddTemplateReplacement eenvouter (templateTyconRef, ilCloTypeRef, cloinfo.cloFreeTyvars, templateTypeInst) + let eenvouter = + AddTemplateReplacement eenvouter (templateTyconRef, ilCloTypeRef, cloinfo.cloFreeTyvars, templateTypeInst) + let ilMachineAddrTy = ILType.Byref ilCloTy // The local for the state machine - let locIdx, realloc, _ = AllocLocal cenv cgbuf eenvouter true (g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("machine", m), ilCloTy, false) scopeMarks + let locIdx, realloc, _ = + AllocLocal + cenv + cgbuf + eenvouter + true + (g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName("machine", m), ilCloTy, false) + scopeMarks // The local for the state machine address - let locIdx2, _realloc2, _ = AllocLocal cenv cgbuf eenvouter true (g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName (afterCodeThisVar.DisplayName, m), ilMachineAddrTy, false) scopeMarks - let eenvouter = eenvouter |> AddStorageForLocalVals g [(afterCodeThisVar, Local (locIdx2, realloc, None)) ] - - // Zero-initialize the machine + let locIdx2, _realloc2, _ = + AllocLocal + cenv + cgbuf + eenvouter + true + (g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName(afterCodeThisVar.DisplayName, m), + ilMachineAddrTy, + false) + scopeMarks + + let eenvouter = + eenvouter + |> AddStorageForLocalVals g [ (afterCodeThisVar, Local(locIdx2, realloc, None)) ] + + // Zero-initialize the machine EmitInitLocal cgbuf ilCloTy locIdx // Initialize the address-of-machine local - CG.EmitInstr cgbuf (pop 0) (Push [ ilMachineAddrTy ]) (I_ldloca (uint16 locIdx) ) - CG.EmitInstr cgbuf (pop 1) (Push [ ]) (I_stloc (uint16 locIdx2) ) + CG.EmitInstr cgbuf (pop 0) (Push [ ilMachineAddrTy ]) (I_ldloca(uint16 locIdx)) + CG.EmitInstr cgbuf (pop 1) (Push []) (I_stloc(uint16 locIdx2)) // Initialize the closure variables for fv, ilv in Seq.zip cloFreeVars cloinfo.ilCloAllFreeVars do if stateVarsSet.Contains fv then // zero-initialize the state var - if realloc then - CG.EmitInstr cgbuf (pop 0) (Push [ ilMachineAddrTy ]) (I_ldloc (uint16 locIdx2) ) + if realloc then + CG.EmitInstr cgbuf (pop 0) (Push [ ilMachineAddrTy ]) (I_ldloc(uint16 locIdx2)) GenDefaultValue cenv cgbuf eenvouter (fv.Type, m) - CG.EmitInstr cgbuf (pop 2) (Push [ ]) (mkNormalStfld (mkILFieldSpecInTy (ilCloTy, ilv.fvName, ilv.fvType))) + CG.EmitInstr cgbuf (pop 2) (Push []) (mkNormalStfld (mkILFieldSpecInTy (ilCloTy, ilv.fvName, ilv.fvType))) else // initialize the captured var - CG.EmitInstr cgbuf (pop 0) (Push [ ilMachineAddrTy ]) (I_ldloc (uint16 locIdx2) ) + CG.EmitInstr cgbuf (pop 0) (Push [ ilMachineAddrTy ]) (I_ldloc(uint16 locIdx2)) GenGetLocalVal cenv cgbuf eenvouter m fv None - CG.EmitInstr cgbuf (pop 2) (Push [ ]) (mkNormalStfld (mkILFieldSpecInTy (ilCloTy, ilv.fvName, ilv.fvType))) + CG.EmitInstr cgbuf (pop 2) (Push []) (mkNormalStfld (mkILFieldSpecInTy (ilCloTy, ilv.fvName, ilv.fvType))) - // Generate the start expression + // Generate the start expression GenExpr cenv cgbuf eenvouter afterCodeBody sequel - + ) and GenObjectExpr cenv cgbuf eenvouter objExpr (baseType, baseValOpt, basecall, overrides, interfaceImpls, m) sequel = @@ -4969,7 +6185,8 @@ and GenObjectExpr cenv cgbuf eenvouter objExpr (baseType, baseValOpt, basecall, // // Note, the 'let' bindings for the stateVars have already been transformed to 'set' expressions, and thus the stateVars are now // free variables of the expression. - let cloinfo, _, eenvinner = GetIlxClosureInfo cenv m ILBoxity.AsObject false false [] eenvouter objExpr + let cloinfo, _, eenvinner = + GetIlxClosureInfo cenv m ILBoxity.AsObject false false [] eenvouter objExpr let ilCloLambdas = cloinfo.ilCloLambdas let cloName = cloinfo.cloName @@ -4984,57 +6201,115 @@ and GenObjectExpr cenv cgbuf eenvouter objExpr (baseType, baseValOpt, basecall, let eenvinner = bindBaseOrThisVarOpt cenv eenvinner baseValOpt - let ilCtorBody = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], cloName, eenvinner, 1, None, basecall, discardAndReturnVoid) + let ilCtorBody = + CodeGenMethodForExpr cenv cgbuf.mgbuf ([], cloName, eenvinner, 1, None, basecall, discardAndReturnVoid) let genMethodAndOptionalMethodImpl tmethod useMethodImpl = - [ for (useMethodImpl, methodImplGeneratorFunction, methTyparsOfOverridingMethod), mdef in GenObjectMethod cenv eenvinner cgbuf useMethodImpl tmethod do - let mimpl = (if useMethodImpl then Some(methodImplGeneratorFunction (ilTyForOverriding, methTyparsOfOverridingMethod)) else None) - yield (mimpl, mdef) ] + [ + for (useMethodImpl, methodImplGeneratorFunction, methTyparsOfOverridingMethod), mdef in + GenObjectMethod cenv eenvinner cgbuf useMethodImpl tmethod do + let mimpl = + (if useMethodImpl then + Some(methodImplGeneratorFunction (ilTyForOverriding, methTyparsOfOverridingMethod)) + else + None) + + yield (mimpl, mdef) + ] let mimpls, mdefs = - [ for ov in overrides do - yield! genMethodAndOptionalMethodImpl ov (isInterfaceTy g baseType) - for _, tmethods in interfaceImpls do - for tmethod in tmethods do - yield! genMethodAndOptionalMethodImpl tmethod true ] + [ + for ov in overrides do + yield! genMethodAndOptionalMethodImpl ov (isInterfaceTy g baseType) + for _, tmethods in interfaceImpls do + for tmethod in tmethods do + yield! genMethodAndOptionalMethodImpl tmethod true + ] |> List.unzip let mimpls = mimpls |> List.choose id // choose the ones that actually have method impls - let interfaceTys = interfaceImpls |> List.map (fst >> GenType cenv m eenvinner.tyenv) + let interfaceTys = + interfaceImpls |> List.map (fst >> GenType cenv m eenvinner.tyenv) + + let super = + (if isInterfaceTy g baseType then + g.ilg.typ_Object + else + ilCloRetTy) - let super = (if isInterfaceTy g baseType then g.ilg.typ_Object else ilCloRetTy) - let interfaceTys = interfaceTys @ (if isInterfaceTy g baseType then [ilCloRetTy] else []) - let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, ilCloGenericFormals, [], ilCloAllFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, super, interfaceTys, Some cloinfo.cloSpec) + let interfaceTys = + interfaceTys @ (if isInterfaceTy g baseType then [ ilCloRetTy ] else []) + + let cloTypeDefs = + GenClosureTypeDefs + cenv + (ilCloTypeRef, + ilCloGenericFormals, + [], + ilCloAllFreeVars, + ilCloLambdas, + ilCtorBody, + mdefs, + mimpls, + super, + interfaceTys, + Some cloinfo.cloSpec) for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) CountClosure() GenWitnessArgsFromWitnessInfos cenv cgbuf eenvouter m cloinfo.cloWitnessInfos + for fv in cloinfo.cloFreeVars do - GenGetLocalVal cenv cgbuf eenvouter m fv None - - CG.EmitInstr cgbuf (pop ilCloAllFreeVars.Length) (Push [ EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv ilCloLambdas]) (I_newobj (cloSpec.Constructor, None)) + GenGetLocalVal cenv cgbuf eenvouter m fv None + + CG.EmitInstr + cgbuf + (pop ilCloAllFreeVars.Length) + (Push [ EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv ilCloLambdas ]) + (I_newobj(cloSpec.Constructor, None)) + GenSequel cenv eenvouter.cloc cgbuf sequel and GenSequenceExpr - cenv - (cgbuf: CodeGenBuffer) - eenvouter - (nextEnumeratorValRef: ValRef, pcvref: ValRef, currvref: ValRef, stateVars, generateNextExpr, closeExpr, checkCloseExpr: Expr, seqElemTy, m) sequel = + cenv + (cgbuf: CodeGenBuffer) + eenvouter + (nextEnumeratorValRef: ValRef, + pcvref: ValRef, + currvref: ValRef, + stateVars, + generateNextExpr, + closeExpr, + checkCloseExpr: Expr, + seqElemTy, + m) + sequel + = let g = cenv.g let stateVars = [ pcvref; currvref ] @ stateVars - let stateVarsSet = stateVars |> List.map (fun vref -> vref.Deref) |> Zset.ofList valOrder + + let stateVarsSet = + stateVars |> List.map (fun vref -> vref.Deref) |> Zset.ofList valOrder // pretend that the state variables are bound let eenvouter = - eenvouter |> AddStorageForLocalVals g (stateVars |> List.map (fun v -> v.Deref, Local(0, false, None))) + eenvouter + |> AddStorageForLocalVals g (stateVars |> List.map (fun v -> v.Deref, Local(0, false, None))) // Get the free variables. Make a lambda to pretend that the 'nextEnumeratorValRef' is bound (it is an argument to GenerateNext) let (cloFreeTyvars, cloWitnessInfos, cloFreeVars, ilCloTypeRef: ILTypeRef, ilCloAllFreeVars, eenvinner) = - GetIlxClosureFreeVars cenv m [] ILBoxity.AsObject eenvouter [] (mkLambda m nextEnumeratorValRef.Deref (generateNextExpr, g.int32_ty)) + GetIlxClosureFreeVars + cenv + m + [] + ILBoxity.AsObject + eenvouter + [] + (mkLambda m nextEnumeratorValRef.Deref (generateNextExpr, g.int32_ty)) let ilCloSeqElemTy = GenType cenv m eenvinner.tyenv seqElemTy let cloRetTy = mkSeqTy g seqElemTy @@ -5042,59 +6317,123 @@ and GenSequenceExpr let ilCloRetTyOuter = GenType cenv m eenvouter.tyenv cloRetTy let ilCloEnumeratorTy = GenType cenv m eenvinner.tyenv (mkIEnumeratorTy g seqElemTy) let ilCloEnumerableTy = GenType cenv m eenvinner.tyenv (mkSeqTy g seqElemTy) - let ilCloBaseTy = GenType cenv m eenvinner.tyenv (g.mk_GeneratedSequenceBase_ty seqElemTy) + + let ilCloBaseTy = + GenType cenv m eenvinner.tyenv (g.mk_GeneratedSequenceBase_ty seqElemTy) + let ilCloGenericParams = GenGenericParams cenv eenvinner cloFreeTyvars // Create a new closure class with a single "MoveNext" method that implements the iterator. let ilCloTyInner = mkILFormalBoxedTy ilCloTypeRef ilCloGenericParams let ilCloLambdas = Lambdas_return ilCloRetTyInner let cloref = IlxClosureRef(ilCloTypeRef, ilCloLambdas, ilCloAllFreeVars) - let ilxCloSpec = IlxClosureSpec.Create(cloref, GenGenericArgs m eenvouter.tyenv cloFreeTyvars, false) - let formalClospec = IlxClosureSpec.Create(cloref, mkILFormalGenericArgs 0 ilCloGenericParams, false) + + let ilxCloSpec = + IlxClosureSpec.Create(cloref, GenGenericArgs m eenvouter.tyenv cloFreeTyvars, false) + + let formalClospec = + IlxClosureSpec.Create(cloref, mkILFormalGenericArgs 0 ilCloGenericParams, false) let getFreshMethod = let _, mbody = - CodeGenMethod cenv cgbuf.mgbuf - ([], "GetFreshEnumerator", eenvinner, 1, None, + CodeGenMethod + cenv + cgbuf.mgbuf + ([], + "GetFreshEnumerator", + eenvinner, + 1, + None, (fun cgbuf eenv -> - GenWitnessArgsFromWitnessInfos cenv cgbuf eenv m cloWitnessInfos - for fv in cloFreeVars do - // State variables always get zero-initialized - if stateVarsSet.Contains fv then - GenDefaultValue cenv cgbuf eenv (fv.Type, m) - else - GenGetLocalVal cenv cgbuf eenv m fv None - CG.EmitInstr cgbuf (pop ilCloAllFreeVars.Length) (Push [ilCloRetTyInner]) (I_newobj (formalClospec.Constructor, None)) - GenSequel cenv eenv.cloc cgbuf Return), + GenWitnessArgsFromWitnessInfos cenv cgbuf eenv m cloWitnessInfos + + for fv in cloFreeVars do + // State variables always get zero-initialized + if stateVarsSet.Contains fv then + GenDefaultValue cenv cgbuf eenv (fv.Type, m) + else + GenGetLocalVal cenv cgbuf eenv m fv None + + CG.EmitInstr cgbuf (pop ilCloAllFreeVars.Length) (Push [ ilCloRetTyInner ]) (I_newobj(formalClospec.Constructor, None)) + GenSequel cenv eenv.cloc cgbuf Return), m) - mkILNonGenericVirtualMethod("GetFreshEnumerator", ILMemberAccess.Public, [], mkILReturn ilCloEnumeratorTy, MethodBody.IL (lazy mbody)) + + mkILNonGenericVirtualMethod ( + "GetFreshEnumerator", + ILMemberAccess.Public, + [], + mkILReturn ilCloEnumeratorTy, + MethodBody.IL(lazy mbody) + ) |> AddNonUserCompilerGeneratedAttribs g let closeMethod = - let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "Close", eenvinner, 1, None, closeExpr, discardAndReturnVoid) - mkILNonGenericVirtualMethod("Close", ILMemberAccess.Public, [], mkILReturn ILType.Void, MethodBody.IL (lazy ilCode)) + let ilCode = + CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "Close", eenvinner, 1, None, closeExpr, discardAndReturnVoid) + + mkILNonGenericVirtualMethod ("Close", ILMemberAccess.Public, [], mkILReturn ILType.Void, MethodBody.IL(lazy ilCode)) let checkCloseMethod = - let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "get_CheckClose", eenvinner, 1, None, checkCloseExpr, Return) - mkILNonGenericVirtualMethod("get_CheckClose", ILMemberAccess.Public, [], mkILReturn g.ilg.typ_Bool, MethodBody.IL (lazy ilCode)) + let ilCode = + CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "get_CheckClose", eenvinner, 1, None, checkCloseExpr, Return) + + mkILNonGenericVirtualMethod ("get_CheckClose", ILMemberAccess.Public, [], mkILReturn g.ilg.typ_Bool, MethodBody.IL(lazy ilCode)) let generateNextMethod = // the 'next enumerator' byref arg is at arg position 1 - let eenvinner = eenvinner |> AddStorageForLocalVals g [ (nextEnumeratorValRef.Deref, Arg 1) ] - let ilParams = [mkILParamNamed("next", ILType.Byref ilCloEnumerableTy)] + let eenvinner = + eenvinner |> AddStorageForLocalVals g [ (nextEnumeratorValRef.Deref, Arg 1) ] + + let ilParams = [ mkILParamNamed ("next", ILType.Byref ilCloEnumerableTy) ] let ilReturn = mkILReturn g.ilg.typ_Int32 - let ilCode = MethodBody.IL (lazy (CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "GenerateNext", eenvinner, 2, None, generateNextExpr, Return))) - mkILNonGenericVirtualMethod("GenerateNext", ILMemberAccess.Public, ilParams, ilReturn, ilCode) + + let ilCode = + MethodBody.IL(lazy (CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "GenerateNext", eenvinner, 2, None, generateNextExpr, Return))) + + mkILNonGenericVirtualMethod ("GenerateNext", ILMemberAccess.Public, ilParams, ilReturn, ilCode) let lastGeneratedMethod = - let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "get_LastGenerated", eenvinner, 1, None, exprForValRef m currvref, Return) - mkILNonGenericVirtualMethod("get_LastGenerated", ILMemberAccess.Public, [], mkILReturn ilCloSeqElemTy, MethodBody.IL (lazy ilCode)) + let ilCode = + CodeGenMethodForExpr cenv cgbuf.mgbuf ([], "get_LastGenerated", eenvinner, 1, None, exprForValRef m currvref, Return) + + mkILNonGenericVirtualMethod ("get_LastGenerated", ILMemberAccess.Public, [], mkILReturn ilCloSeqElemTy, MethodBody.IL(lazy ilCode)) |> AddNonUserCompilerGeneratedAttribs g - let ilCtorBody = mkILSimpleStorageCtor(Some ilCloBaseTy.TypeSpec, ilCloTyInner, [], [], ILMemberAccess.Assembly, None, eenvouter.imports).MethodBody + let ilCtorBody = + mkILSimpleStorageCtor( + Some ilCloBaseTy.TypeSpec, + ilCloTyInner, + [], + [], + ILMemberAccess.Assembly, + None, + eenvouter.imports + ) + .MethodBody + + let cloMethods = + [ + generateNextMethod + closeMethod + checkCloseMethod + lastGeneratedMethod + getFreshMethod + ] - let cloMethods = [generateNextMethod; closeMethod; checkCloseMethod; lastGeneratedMethod; getFreshMethod] - let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, ilCloGenericParams, [], ilCloAllFreeVars, ilCloLambdas, ilCtorBody, cloMethods, [], ilCloBaseTy, [], Some ilxCloSpec) + let cloTypeDefs = + GenClosureTypeDefs + cenv + (ilCloTypeRef, + ilCloGenericParams, + [], + ilCloAllFreeVars, + ilCloLambdas, + ilCtorBody, + cloMethods, + [], + ilCloBaseTy, + [], + Some ilxCloSpec) for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) @@ -5102,74 +6441,113 @@ and GenSequenceExpr CountClosure() GenWitnessArgsFromWitnessInfos cenv cgbuf eenvouter m cloWitnessInfos + for fv in cloFreeVars do - // State variables always get zero-initialized - if stateVarsSet.Contains fv then - GenDefaultValue cenv cgbuf eenvouter (fv.Type, m) - else - GenGetLocalVal cenv cgbuf eenvouter m fv None + // State variables always get zero-initialized + if stateVarsSet.Contains fv then + GenDefaultValue cenv cgbuf eenvouter (fv.Type, m) + else + GenGetLocalVal cenv cgbuf eenvouter m fv None - CG.EmitInstr cgbuf (pop ilCloAllFreeVars.Length) (Push [ilCloRetTyOuter]) (I_newobj (ilxCloSpec.Constructor, None)) + CG.EmitInstr cgbuf (pop ilCloAllFreeVars.Length) (Push [ ilCloRetTyOuter ]) (I_newobj(ilxCloSpec.Constructor, None)) GenSequel cenv eenvouter.cloc cgbuf sequel /// 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) = - let g = cenv.g - let cloInfo = - { cloFreeVars=ilCloAllFreeVars - cloStructure=ilCloLambdas - cloCode=notlazy ilCtorBody - cloUseStaticField = (match cloSpec with None -> false | Some cloSpec -> cloSpec.UseStaticField) - } - - let mdefs, fdefs = - if cloInfo.cloUseStaticField then - let cloSpec = cloSpec.Value - let cloTy = mkILFormalBoxedTy cloSpec.TypeRef (mkILFormalTypars cloSpec.GenericArgs) - let fspec = mkILFieldSpec (cloSpec.GetStaticFieldSpec().FieldRef, cloTy) - let ctorSpec = mkILMethSpecForMethRefInTy (cloSpec.Constructor.MethodRef, cloTy, []) - let ilInstrs = [ I_newobj (ctorSpec, None); mkNormalStsfld fspec ] - let ilCode = mkILMethodBody (true, [], 8, nonBranchingInstrsToCode ilInstrs, None, None) - let cctor = mkILClassCtor (MethodBody.IL (notlazy ilCode)) - let ilFieldDef = mkILStaticField(fspec.Name, fspec.FormalType, None, None, ILMemberAccess.Assembly).WithInitOnly(true) - (cctor :: mdefs), [ ilFieldDef ] - else - mdefs, [] - - let tdef = - ILTypeDef(name = tref.Name, - layout = ILTypeDefLayout.Auto, - attributes = enum 0, - genericParams = ilGenParams, - customAttrs = mkILCustomAttrs(attrs @ [mkCompilationMappingAttr g (int SourceConstructFlags.Closure) ]), - fields = mkILFields fdefs, - events= emptyILEvents, - properties = emptyILProperties, - methods= mkILMethods mdefs, - methodImpls= mkILMethodImpls mimpls, - nestedTypes=emptyILTypeDefs, - implements = ilIntfTys, - extends= Some ext, - isKnownToBeAttribute=false, - securityDecls= emptyILSecurityDecls) - .WithSealed(true) - .WithSerializable(true) - .WithSpecialName(true) - .WithAccess(ComputeTypeAccess tref true) - .WithLayout(ILTypeDefLayout.Auto) - .WithEncoding(ILDefaultPInvokeEncoding.Auto) - .WithInitSemantics(ILTypeInit.BeforeField) - - let tdefs = EraseClosures.convIlxClosureDef cenv.ilxPubCloEnv tref.Enclosing tdef cloInfo - tdefs - -and GenStaticDelegateClosureTypeDefs cenv (tref: ILTypeRef, ilGenParams, attrs, ilCloAllFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, ext, ilIntfTys, staticCloInfo) = - let tdefs = GenClosureTypeDefs cenv (tref, ilGenParams, attrs, ilCloAllFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, ext, ilIntfTys, staticCloInfo) +and GenClosureTypeDefs + cenv + (tref: ILTypeRef, + ilGenParams, + attrs, + ilCloAllFreeVars, + ilCloLambdas, + ilCtorBody, + mdefs, + mimpls, + ext, + ilIntfTys, + cloSpec: IlxClosureSpec option) + = + let g = cenv.g + + let cloInfo = + { + cloFreeVars = ilCloAllFreeVars + cloStructure = ilCloLambdas + cloCode = notlazy ilCtorBody + cloUseStaticField = + (match cloSpec with + | None -> false + | Some cloSpec -> cloSpec.UseStaticField) + } + + let mdefs, fdefs = + if cloInfo.cloUseStaticField then + let cloSpec = cloSpec.Value + let cloTy = mkILFormalBoxedTy cloSpec.TypeRef (mkILFormalTypars cloSpec.GenericArgs) + let fspec = mkILFieldSpec (cloSpec.GetStaticFieldSpec().FieldRef, cloTy) + let ctorSpec = mkILMethSpecForMethRefInTy (cloSpec.Constructor.MethodRef, cloTy, []) + let ilInstrs = [ I_newobj(ctorSpec, None); mkNormalStsfld fspec ] + + let ilCode = + mkILMethodBody (true, [], 8, nonBranchingInstrsToCode ilInstrs, None, None) + + let cctor = mkILClassCtor (MethodBody.IL(notlazy ilCode)) + + let ilFieldDef = + mkILStaticField(fspec.Name, fspec.FormalType, None, None, ILMemberAccess.Assembly) + .WithInitOnly(true) + + (cctor :: mdefs), [ ilFieldDef ] + else + mdefs, [] + + let tdef = + ILTypeDef( + name = tref.Name, + layout = ILTypeDefLayout.Auto, + attributes = enum 0, + genericParams = ilGenParams, + customAttrs = mkILCustomAttrs (attrs @ [ mkCompilationMappingAttr g (int SourceConstructFlags.Closure) ]), + fields = mkILFields fdefs, + events = emptyILEvents, + properties = emptyILProperties, + methods = mkILMethods mdefs, + methodImpls = mkILMethodImpls mimpls, + nestedTypes = emptyILTypeDefs, + implements = ilIntfTys, + extends = Some ext, + isKnownToBeAttribute = false, + securityDecls = emptyILSecurityDecls + ) + .WithSealed(true) + .WithSerializable(true) + .WithSpecialName(true) + .WithAccess(ComputeTypeAccess tref true) + .WithLayout(ILTypeDefLayout.Auto) + .WithEncoding(ILDefaultPInvokeEncoding.Auto) + .WithInitSemantics(ILTypeInit.BeforeField) + + let tdefs = + EraseClosures.convIlxClosureDef cenv.ilxPubCloEnv tref.Enclosing tdef cloInfo + + tdefs + +and GenStaticDelegateClosureTypeDefs + cenv + (tref: ILTypeRef, ilGenParams, attrs, ilCloAllFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, ext, ilIntfTys, staticCloInfo) + = + let tdefs = + GenClosureTypeDefs + cenv + (tref, ilGenParams, attrs, ilCloAllFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, ext, ilIntfTys, staticCloInfo) // Apply the abstract attribute, turning the sealed class into abstract sealed (i.e. static class). // 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)))) + tdefs + |> List.map (fun td -> + 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) @@ -5180,9 +6558,14 @@ and GenGenericArgs m (tyenv: TypeReprEnv) tps = /// Generate a local type function contract class and implementation and GenClosureAsLocalTypeFunction cenv (cgbuf: CodeGenBuffer) eenv thisVars expr m = let g = cenv.g - let cloinfo, body, eenvinner = GetIlxClosureInfo cenv m ILBoxity.AsObject true true thisVars eenv expr + + let cloinfo, body, eenvinner = + GetIlxClosureInfo cenv m ILBoxity.AsObject true true thisVars eenv expr + let ilCloTypeRef = cloinfo.cloSpec.TypeRef - let entryPointInfo = thisVars |> List.map (fun v -> (v, BranchCallClosure cloinfo.cloArityInfo)) + + let entryPointInfo = + thisVars |> List.map (fun v -> (v, BranchCallClosure cloinfo.cloArityInfo)) // Now generate the actual closure implementation w.r.t. eenvinner let directTypars, ilDirectWitnessParams, _directWitnessInfos, eenvinner = AddDirectTyparWitnessParams cenv eenvinner cloinfo m @@ -5193,25 +6576,76 @@ and GenClosureAsLocalTypeFunction cenv (cgbuf: CodeGenBuffer) eenv thisVars expr let ilCloFormalReturnTy, ilCloLambdas = let rec strip lambdas = match lambdas with - | Lambdas_forall(_, r) -> strip r + | Lambdas_forall (_, r) -> strip r | Lambdas_return returnTy -> returnTy, lambdas | _ -> failwith "AdjustNamedLocalTypeFuncIlxClosureInfo: local functions can currently only be type functions" + strip cloinfo.ilCloLambdas - let ilCloBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (entryPointInfo, cloinfo.cloName, eenvinner, 1, None, body, Return) - let ilCtorBody = mkILMethodBody (true, [], 8, nonBranchingInstrsToCode (mkCallBaseConstructor(g.ilg.typ_Object, [])), None, eenv.imports) - let cloMethods = [ mkILGenericVirtualMethod("DirectInvoke", ILMemberAccess.Assembly, ilDirectGenericParams, ilDirectWitnessParams, mkILReturn ilCloFormalReturnTy, MethodBody.IL(lazy ilCloBody)) ] + let ilCloBody = + CodeGenMethodForExpr cenv cgbuf.mgbuf (entryPointInfo, cloinfo.cloName, eenvinner, 1, None, body, Return) + + let ilCtorBody = + mkILMethodBody (true, [], 8, nonBranchingInstrsToCode (mkCallBaseConstructor (g.ilg.typ_Object, [])), None, eenv.imports) + + let cloMethods = + [ + mkILGenericVirtualMethod ( + "DirectInvoke", + ILMemberAccess.Assembly, + ilDirectGenericParams, + ilDirectWitnessParams, + mkILReturn ilCloFormalReturnTy, + MethodBody.IL(lazy ilCloBody) + ) + ] + + let cloTypeDefs = + GenClosureTypeDefs + cenv + (ilCloTypeRef, + cloinfo.cloILGenericParams, + [], + cloinfo.ilCloAllFreeVars, + ilCloLambdas, + ilCtorBody, + cloMethods, + [], + g.ilg.typ_Object, + [], + Some cloinfo.cloSpec) - let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, cloinfo.cloILGenericParams, [], cloinfo.ilCloAllFreeVars, ilCloLambdas, ilCtorBody, cloMethods, [], g.ilg.typ_Object, [], Some cloinfo.cloSpec) cloinfo, ilCloTypeRef, cloTypeDefs and GenClosureAsFirstClassFunction cenv (cgbuf: CodeGenBuffer) eenv thisVars m expr = let g = cenv.g - let cloinfo, body, eenvinner = GetIlxClosureInfo cenv m ILBoxity.AsObject false true thisVars eenv expr - let entryPointInfo = thisVars |> List.map (fun v -> (v, BranchCallClosure (cloinfo.cloArityInfo))) + + let cloinfo, body, eenvinner = + GetIlxClosureInfo cenv m ILBoxity.AsObject false true thisVars eenv expr + + let entryPointInfo = + thisVars |> List.map (fun v -> (v, BranchCallClosure(cloinfo.cloArityInfo))) + let ilCloTypeRef = cloinfo.cloSpec.TypeRef - let ilCloBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (entryPointInfo, cloinfo.cloName, eenvinner, 1, None, body, Return) - let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, cloinfo.cloILGenericParams, [], cloinfo.ilCloAllFreeVars, cloinfo.ilCloLambdas, ilCloBody, [], [], g.ilg.typ_Object, [], Some cloinfo.cloSpec) + + let ilCloBody = + CodeGenMethodForExpr cenv cgbuf.mgbuf (entryPointInfo, cloinfo.cloName, eenvinner, 1, None, body, Return) + + let cloTypeDefs = + GenClosureTypeDefs + cenv + (ilCloTypeRef, + cloinfo.cloILGenericParams, + [], + cloinfo.ilCloAllFreeVars, + cloinfo.ilCloLambdas, + ilCloBody, + [], + [], + g.ilg.typ_Object, + [], + Some cloinfo.cloSpec) + cloinfo, ilCloTypeRef, cloTypeDefs /// Generate the closure class for a function @@ -5227,44 +6661,50 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc thisVars e GenClosureAsFirstClassFunction cenv cgbuf eenv thisVars m expr CountClosure() + for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) + cloinfo, m | _ -> failwith "GenLambda: not a lambda" and GenClosureAlloc cenv (cgbuf: CodeGenBuffer) eenv (cloinfo, m) = CountClosure() + if cloinfo.cloSpec.UseStaticField then let fspec = cloinfo.cloSpec.GetStaticFieldSpec() - CG.EmitInstr cgbuf - (pop 0) - (Push [EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv cloinfo.ilCloLambdas]) - (mkNormalLdsfld fspec) + CG.EmitInstr cgbuf (pop 0) (Push [ EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv cloinfo.ilCloLambdas ]) (mkNormalLdsfld fspec) else GenWitnessArgsFromWitnessInfos cenv cgbuf eenv m cloinfo.cloWitnessInfos GenGetLocalVals cenv cgbuf eenv m cloinfo.cloFreeVars - CG.EmitInstr cgbuf + + CG.EmitInstr + cgbuf (pop cloinfo.ilCloAllFreeVars.Length) - (Push [EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv cloinfo.ilCloLambdas]) - (I_newobj (cloinfo.cloSpec.Constructor, None)) + (Push [ EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv cloinfo.ilCloLambdas ]) + (I_newobj(cloinfo.cloSpec.Constructor, None)) and GenLambda cenv cgbuf eenv isLocalTypeFunc thisVars expr sequel = let cloinfo, m = GenLambdaClosure cenv cgbuf eenv isLocalTypeFunc thisVars expr GenClosureAlloc cenv cgbuf eenv (cloinfo, m) GenSequel cenv eenv.cloc cgbuf sequel -and GenTypeOfVal cenv eenv (v: Val) = - GenType cenv v.Range eenv.tyenv v.Type +and GenTypeOfVal cenv eenv (v: Val) = GenType cenv v.Range eenv.tyenv v.Type and GenFreevar cenv m eenvouter tyenvinner (fv: Val) = let g = cenv.g - match StorageForVal cenv.g m fv eenvouter with + + match StorageForVal m fv eenvouter with // Local type functions - | Local(_, _, Some _) | Env(_, _, Some _) -> g.ilg.typ_Object + | Local (_, _, Some _) + | Env (_, _, Some _) -> g.ilg.typ_Object #if DEBUG // Check for things that should never make it into the free variable set. Only do this in debug for performance reasons - | StaticPropertyWithField _ | StaticProperty _ | Method _ | Null -> error(InternalError("GenFreevar: compiler error: unexpected unrealized value", fv.Range)) + | StaticPropertyWithField _ + | StaticProperty _ + | Method _ + | Null -> error (InternalError("GenFreevar: compiler error: unexpected unrealized value", fv.Range)) #endif | _ -> GenType cenv m tyenvinner fv.Type @@ -5273,7 +6713,9 @@ and GetIlxClosureFreeVars cenv m (thisVars: ValRef list) boxity eenvouter takenN // Choose a base name for the closure let basename = - let boundv = eenvouter.letBoundVars |> List.tryFind (fun v -> not v.IsCompilerGenerated) + let boundv = + eenvouter.letBoundVars |> List.tryFind (fun v -> not v.IsCompilerGenerated) + match boundv with | Some v -> v.CompiledName cenv.g.CompilerGlobalState | None -> "clo" @@ -5284,17 +6726,19 @@ and GetIlxClosureFreeVars cenv m (thisVars: ValRef list) boxity eenvouter takenN | Expr.Obj (uniq, _, _, _, _, _, _) | Expr.Lambda (uniq, _, _, _, _, _, _) | Expr.TyLambda (uniq, _, _, _, _) -> uniq - | _ -> newUnique() + | _ -> newUnique () // Choose a name for the closure let ilCloTypeRef = // FSharp 1.0 bug 3404: System.Reflection doesn't like '.' and '`' in type names let basenameSafeForUseAsTypename = CleanUpGeneratedTypeName basename let suffixmark = expr.Range + let cloName = // Ensure that we have an g.CompilerGlobalState - assert(g.CompilerGlobalState |> Option.isSome) + assert (g.CompilerGlobalState |> Option.isSome) g.CompilerGlobalState.Value.StableNameGenerator.GetUniqueCompilerGeneratedName(basenameSafeForUseAsTypename, suffixmark, uniq) + NestedTypeRefForCompLoc eenvouter.cloc cloName // Collect the free variables of the closure @@ -5304,20 +6748,25 @@ and GetIlxClosureFreeVars cenv m (thisVars: ValRef list) boxity eenvouter takenN // Also filter out the current value being bound, if any, as it is available from the "this" // pointer which gives the current closure itself. This is in the case e.g. let rec f = ... f ... let freeLocals = cloFreeVarResults.FreeLocals |> Zset.elements + let cloFreeVars = freeLocals |> List.filter (fun fv -> - (thisVars |> List.forall (fun v -> not (valRefEq g (mkLocalValRef fv) v))) && - (match StorageForVal cenv.g m fv eenvouter with - | StaticPropertyWithField _ | StaticProperty _ | Method _ | Null -> false - | _ -> true)) - - // Any closure using values represented as local type functions also captures the type variables captured - // by that local type function - let cloFreeTyvars = - (cloFreeVarResults.FreeTyvars, freeLocals) ||> List.fold (fun ftyvs fv -> - match StorageForVal cenv.g m fv eenvouter with - | Env (_, _, Some (moreFtyvs, _)) + (thisVars |> List.forall (fun v -> not (valRefEq g (mkLocalValRef fv) v))) + && (match StorageForVal m fv eenvouter with + | StaticPropertyWithField _ + | StaticProperty _ + | Method _ + | Null -> false + | _ -> true)) + + // Any closure using values represented as local type functions also captures the type variables captured + // by that local type function + let cloFreeTyvars = + (cloFreeVarResults.FreeTyvars, freeLocals) + ||> List.fold (fun ftyvs fv -> + match StorageForVal m fv eenvouter with + | Env (_, _, Some (moreFtyvs, _)) | Local (_, _, Some (moreFtyvs, _)) -> unionFreeTyvars ftyvs moreFtyvs | _ -> ftyvs) @@ -5332,11 +6781,14 @@ and GetIlxClosureFreeVars cenv m (thisVars: ValRef list) boxity eenvouter takenN // If generating a named closure, add the closure itself as a var, available via "arg0" . // The latter doesn't apply for the delegate implementation of closures. // Build the environment that is active inside the closure itself - let eenvinner = eenvinner |> AddStorageForLocalVals g (thisVars |> List.map (fun v -> (v.Deref, Arg 0))) + let eenvinner = + eenvinner + |> AddStorageForLocalVals g (thisVars |> List.map (fun v -> (v.Deref, Arg 0))) // Work out if the closure captures any witnesses. let cloWitnessInfos = let generateWitnesses = ComputeGenerateWitnesses g eenvinner + if generateWitnesses then // The 0 here represents that a closure doesn't reside within a generic class - there are no "enclosing class type parameters" to lop off. GetTraitWitnessInfosOfTypars g 0 cloFreeTyvars @@ -5351,22 +6803,23 @@ and GetIlxClosureFreeVars cenv m (thisVars: ValRef list) boxity eenvouter takenN let eenvinner = eenvinner |> AddStorageForLocalWitnesses ilCloWitnessStorage let ilCloFreeVars, ilCloFreeVarStorage = - let names = - cloFreeVars - |> List.map nameOfVal - |> ChooseFreeVarNames takenNames + let names = cloFreeVars |> List.map nameOfVal |> ChooseFreeVarNames takenNames (cloFreeVars, names) ||> List.map2 (fun fv nm -> let localCloInfo = - match StorageForVal g m fv eenvouter with - | Local(_, _, localCloInfo) - | Env(_, _, localCloInfo) -> localCloInfo + match StorageForVal m fv eenvouter with + | Local (_, _, localCloInfo) + | Env (_, _, localCloInfo) -> localCloInfo | _ -> None - let ilFv = mkILFreeVar (nm, fv.IsCompilerGenerated, GenFreevar cenv m eenvouter eenvinner.tyenv fv) + + let ilFv = + mkILFreeVar (nm, fv.IsCompilerGenerated, GenFreevar cenv m eenvouter eenvinner.tyenv fv) + let storage = let ilField = mkILFieldSpecInTy (ilCloTyInner, ilFv.fvName, ilFv.fvType) Env(ilCloTyInner, ilField, localCloInfo) + ilFv, (fv, storage)) |> List.unzip @@ -5379,25 +6832,26 @@ and GetIlxClosureFreeVars cenv m (thisVars: ValRef list) boxity eenvouter takenN and GetIlxClosureInfo cenv m boxity isLocalTypeFunc canUseStaticField thisVars eenvouter expr = let g = cenv.g + let returnTy = - match expr with - | Expr.Lambda (_, _, _, _, _, _, returnTy) | Expr.TyLambda (_, _, _, _, returnTy) -> returnTy - | _ -> tyOfExpr g expr + match expr with + | Expr.Lambda (_, _, _, _, _, _, returnTy) + | Expr.TyLambda (_, _, _, _, returnTy) -> returnTy + | _ -> tyOfExpr g expr // Determine the structure of the closure. We do this before analyzing free variables to // determine the taken argument names. let tvsl, vs, body, returnTy = let rec getCallStructure tvacc vacc (e, ety) = match e with - | Expr.TyLambda (_, tvs, body, _m, bty) -> - getCallStructure ((DropErasedTypars tvs) :: tvacc) vacc (body, bty) + | Expr.TyLambda (_, tvs, body, _m, bty) -> getCallStructure ((DropErasedTypars tvs) :: tvacc) vacc (body, bty) | Expr.Lambda (_, _, _, vs, body, _, bty) when not isLocalTypeFunc -> // Transform a lambda taking untupled arguments into one // taking only a single tupled argument if necessary. REVIEW: do this earlier let tupledv, body = MultiLambdaToTupledLambda g vs body getCallStructure tvacc (tupledv :: vacc) (body, bty) - | _ -> - (List.rev tvacc, List.rev vacc, e, ety) + | _ -> (List.rev tvacc, List.rev vacc, e, ety) + getCallStructure [] [] (expr, returnTy) let takenNames = vs |> List.map (fun v -> v.CompiledName g.CompilerGlobalState) @@ -5412,14 +6866,20 @@ and GetIlxClosureInfo cenv m boxity isLocalTypeFunc canUseStaticField thisVars e | tvs :: rest, _ -> let eenv = AddTyparsToEnv tvs eenv let l, eenv = getClosureArgs eenv numArgs rest vs - let lambdas = (tvs, l) ||> List.foldBack (fun tv sofar -> Lambdas_forall(GenGenericParam cenv eenv tv, sofar)) + + let lambdas = + (tvs, l) + ||> List.foldBack (fun tv sofar -> Lambdas_forall(GenGenericParam cenv eenv tv, sofar)) + lambdas, eenv | [], v :: rest -> let nm = v.CompiledName g.CompilerGlobalState + let l, eenv = let eenv = AddStorageForVal g (v, notlazy (Arg numArgs)) eenv - getClosureArgs eenv (numArgs+1) [] rest - let lambdas = Lambdas_lambda (mkILParamNamed(nm, GenTypeOfVal cenv eenv v), l) + getClosureArgs eenv (numArgs + 1) [] rest + + let lambdas = Lambdas_lambda(mkILParamNamed (nm, GenTypeOfVal cenv eenv v), l) lambdas, eenv | _ -> let returnTy' = GenType cenv m eenv.tyenv returnTy @@ -5440,26 +6900,31 @@ and GetIlxClosureInfo cenv m boxity isLocalTypeFunc canUseStaticField thisVars e let useStaticField = canUseStaticField && (ilCloAllFreeVars.Length = 0) - let ilxCloSpec = IlxClosureSpec.Create(IlxClosureRef(ilCloTypeRef, ilCloLambdas, ilCloAllFreeVars), ilCloGenericActuals, useStaticField) + let ilxCloSpec = + IlxClosureSpec.Create(IlxClosureRef(ilCloTypeRef, ilCloLambdas, ilCloAllFreeVars), ilCloGenericActuals, useStaticField) let cloinfo = - { cloExpr=expr - cloName=ilCloTypeRef.Name - cloArityInfo =narginfo - ilCloLambdas=ilCloLambdas - ilCloAllFreeVars = ilCloAllFreeVars - ilCloFormalReturnTy = ilCloReturnTy - cloSpec = ilxCloSpec - cloILGenericParams = ilCloGenericFormals - cloFreeVars=cloFreeVars - cloFreeTyvars=cloFreeTyvars - cloWitnessInfos = cloWitnessInfos } + { + cloExpr = expr + cloName = ilCloTypeRef.Name + cloArityInfo = narginfo + ilCloLambdas = ilCloLambdas + ilCloAllFreeVars = ilCloAllFreeVars + ilCloFormalReturnTy = ilCloReturnTy + cloSpec = ilxCloSpec + cloILGenericParams = ilCloGenericFormals + cloFreeVars = cloFreeVars + cloFreeTyvars = cloFreeTyvars + cloWitnessInfos = cloWitnessInfos + } + cloinfo, body, eenvinner /// Generate a new delegate construction including a closure class if necessary. This is a lot like generating function closures /// and object expression closures, and most of the code is shared. -and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod(TSlotSig(_, delegateTy, _, _, _, _) as slotsig, _attribs, methTyparsOfOverridingMethod, tmvs, body, _), m) sequel = +and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod (slotsig, _attribs, methTyparsOfOverridingMethod, tmvs, body, _), m) sequel = let g = cenv.g + let (TSlotSig (_, delegateTy, _, _, _, _)) = slotsig // Get the instantiation of the delegate type let ilCtxtDelTy = GenType cenv m eenvouter.tyenv delegateTy @@ -5471,19 +6936,21 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod(TSlotSig(_, delega if isILAppTy g delegateTy then let tcref = tcrefOfAppTy g delegateTy let tdef = tcref.ILTyconRawMetadata + match tdef.Methods.FindByName ".ctor" with - | [ctorMDef] -> + | [ ctorMDef ] -> match ctorMDef.Parameters with - | [ _;p2 ] -> (p2.Type.TypeSpec.Name = "System.UIntPtr") + | [ _; p2 ] -> (p2.Type.TypeSpec.Name = "System.UIntPtr") | _ -> false | _ -> false else false - with _ -> + with _ -> false // Work out the free type variables for the morphing thunk let takenNames = List.map nameOfVal tmvs + let cloFreeTyvars, cloWitnessInfos, cloFreeVars, ilDelegeeTypeRef, ilCloAllFreeVars, eenvinner = GetIlxClosureFreeVars cenv m [] ILBoxity.AsObject eenvouter takenNames expr @@ -5500,58 +6967,116 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod(TSlotSig(_, delega let envForDelegeeUnderTypars = AddTyparsToEnv methTyparsOfOverridingMethod eenvinner let numthis = if useStaticClosure then 0 else 1 - let tmvs, body = BindUnitVars g (tmvs, List.replicate (List.concat slotsig.FormalParams).Length ValReprInfo.unnamedTopArg1, body) + + let tmvs, body = + BindUnitVars g (tmvs, List.replicate (List.concat slotsig.FormalParams).Length ValReprInfo.unnamedTopArg1, body) // The slot sig contains a formal instantiation. When creating delegates we're only // interested in the actual instantiation since we don't have to emit a method impl. - let ilDelegeeParams, ilDelegeeRet = GenActualSlotsig m cenv envForDelegeeUnderTypars slotsig methTyparsOfOverridingMethod tmvs + let ilDelegeeParams, ilDelegeeRet = + GenActualSlotsig m cenv envForDelegeeUnderTypars slotsig methTyparsOfOverridingMethod tmvs + + let envForDelegeeMeth = + AddStorageForLocalVals g (List.mapi (fun i v -> (v, Arg(i + numthis))) tmvs) envForDelegeeUnderTypars + + let ilMethodBody = + CodeGenMethodForExpr + cenv + cgbuf.mgbuf + ([], + delegeeMethName, + envForDelegeeMeth, + 1, + None, + body, + (if slotSigHasVoidReturnTy slotsig then + discardAndReturnVoid + else + Return)) - let envForDelegeeMeth = AddStorageForLocalVals g (List.mapi (fun i v -> (v, Arg (i+numthis))) tmvs) envForDelegeeUnderTypars - - let ilMethodBody = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], delegeeMethName, envForDelegeeMeth, 1, None, body, (if slotSigHasVoidReturnTy slotsig then discardAndReturnVoid else Return)) let delegeeInvokeMeth = - (if useStaticClosure then mkILNonGenericStaticMethod else mkILNonGenericInstanceMethod) - (delegeeMethName, - ILMemberAccess.Assembly, - ilDelegeeParams, - ilDelegeeRet, - MethodBody.IL(lazy ilMethodBody)) - let delegeeCtorMeth = mkILSimpleStorageCtor(Some g.ilg.typ_Object.TypeSpec, ilDelegeeTyInner, [], [], ILMemberAccess.Assembly, None, eenvouter.imports) + (if useStaticClosure then + mkILNonGenericStaticMethod + else + mkILNonGenericInstanceMethod) + ( + delegeeMethName, + ILMemberAccess.Assembly, + ilDelegeeParams, + ilDelegeeRet, + MethodBody.IL(lazy ilMethodBody) + ) + + let delegeeCtorMeth = + mkILSimpleStorageCtor (Some g.ilg.typ_Object.TypeSpec, ilDelegeeTyInner, [], [], ILMemberAccess.Assembly, None, eenvouter.imports) + let ilCtorBody = delegeeCtorMeth.MethodBody let ilCloLambdas = Lambdas_return ilCtxtDelTy + let cloTypeDefs = - (if useStaticClosure then GenStaticDelegateClosureTypeDefs else GenClosureTypeDefs) - cenv (ilDelegeeTypeRef, ilDelegeeGenericParams, [], ilCloAllFreeVars, ilCloLambdas, ilCtorBody, [delegeeInvokeMeth], [], g.ilg.typ_Object, [], None) + (if useStaticClosure then + GenStaticDelegateClosureTypeDefs + else + GenClosureTypeDefs) + cenv + (ilDelegeeTypeRef, + ilDelegeeGenericParams, + [], + ilCloAllFreeVars, + ilCloLambdas, + ilCtorBody, + [ delegeeInvokeMeth ], + [], + g.ilg.typ_Object, + [], + None) + for cloTypeDef in cloTypeDefs do cgbuf.mgbuf.AddTypeDef(ilDelegeeTypeRef, cloTypeDef, false, false, None) + CountClosure() // Push the constructor for the delegee let ctxtGenericArgsForDelegee = GenGenericArgs m eenvouter.tyenv cloFreeTyvars + if useStaticClosure then GenUnit cenv eenvouter m cgbuf else - let ilxCloSpec = IlxClosureSpec.Create(IlxClosureRef(ilDelegeeTypeRef, ilCloLambdas, ilCloAllFreeVars), ctxtGenericArgsForDelegee, false) + let ilxCloSpec = + IlxClosureSpec.Create(IlxClosureRef(ilDelegeeTypeRef, ilCloLambdas, ilCloAllFreeVars), ctxtGenericArgsForDelegee, false) GenWitnessArgsFromWitnessInfos cenv cgbuf eenvouter m cloWitnessInfos GenGetLocalVals cenv cgbuf eenvouter m cloFreeVars - CG.EmitInstr cgbuf (pop ilCloAllFreeVars.Length) (Push [EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv ilCloLambdas]) (I_newobj (ilxCloSpec.Constructor, None)) + CG.EmitInstr + cgbuf + (pop ilCloAllFreeVars.Length) + (Push [ EraseClosures.mkTyOfLambdas cenv.ilxPubCloEnv ilCloLambdas ]) + (I_newobj(ilxCloSpec.Constructor, None)) // Push the function pointer to the Invoke method of the delegee let ilDelegeeTyOuter = mkILBoxedTy ilDelegeeTypeRef ctxtGenericArgsForDelegee + let ilDelegeeInvokeMethOuter = - (if useStaticClosure then mkILNonGenericStaticMethSpecInTy else mkILNonGenericInstanceMethSpecInTy) - (ilDelegeeTyOuter, - "Invoke", - typesOfILParams ilDelegeeParams, - ilDelegeeRet.Type) - CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_IntPtr]) (I_ldftn ilDelegeeInvokeMethOuter) + (if useStaticClosure then + mkILNonGenericStaticMethSpecInTy + else + mkILNonGenericInstanceMethSpecInTy) + ( + ilDelegeeTyOuter, + "Invoke", + typesOfILParams ilDelegeeParams, + ilDelegeeRet.Type + ) + + CG.EmitInstr cgbuf (pop 0) (Push [ g.ilg.typ_IntPtr ]) (I_ldftn ilDelegeeInvokeMethOuter) // Instantiate the delegate - let ilDelegeeCtorMethOuter = mkCtorMethSpecForDelegate g.ilg (ilCtxtDelTy, useUIntPtrForDelegateCtor) - CG.EmitInstr cgbuf (pop 2) (Push [ilCtxtDelTy]) (I_newobj(ilDelegeeCtorMethOuter, None)) + let ilDelegeeCtorMethOuter = + mkCtorMethSpecForDelegate g.ilg (ilCtxtDelTy, useUIntPtrForDelegateCtor) + + CG.EmitInstr cgbuf (pop 2) (Push [ ilCtxtDelTy ]) (I_newobj(ilDelegeeCtorMethOuter, None)) GenSequel cenv eenvouter.cloc cgbuf sequel /// Generate statically-resolved conditionals used for type-directed optimizations. @@ -5572,10 +7097,12 @@ and GenStaticOptimization cenv cgbuf eenv (constraints, e2, e3, _m) sequel = let e = let generateWitnesses = ComputeGenerateWitnesses cenv.g eenv + if DecideStaticOptimizations cenv.g constraints generateWitnesses = StaticOptimizationAnswer.Yes then e2 else e3 + GenExpr cenv cgbuf eenv e sequel //------------------------------------------------------------------------- @@ -5585,7 +7112,10 @@ and GenStaticOptimization cenv cgbuf eenv (constraints, e2, e3, _m) sequel = and IsSequelImmediate sequel = match sequel with (* All of these can be done at the end of each branch - we don't need a real join point *) - | Return | ReturnVoid | Br _ | LeaveHandler _ -> true + | Return + | ReturnVoid + | Br _ + | LeaveHandler _ -> true | DiscardThen sequel -> IsSequelImmediate sequel | _ -> false @@ -5603,15 +7133,17 @@ and GenJoinPoint cenv cgbuf pos eenv ty m sequel = sequel, afterJoin, stackAfterJoin, Continue // We end scopes at the join point, if any - | EndLocalScope(sq, mark) -> - let sequelNow, afterJoin, stackAfterJoin, sequelAfterJoin = GenJoinPoint cenv cgbuf pos eenv ty m sq + | EndLocalScope (sq, mark) -> + let sequelNow, afterJoin, stackAfterJoin, sequelAfterJoin = + GenJoinPoint cenv cgbuf pos eenv ty m sq + sequelNow, afterJoin, stackAfterJoin, EndLocalScope(sequelAfterJoin, mark) // If something non-trivial happens after a discard then generate a join point, but first discard the value (often this means we won't generate it at all) | DiscardThen sequel -> let stackAfterJoin = cgbuf.GetCurrentStack() let afterJoin = CG.GenerateDelayMark cgbuf (pos + "_join") - DiscardThen (Br afterJoin), afterJoin, stackAfterJoin, sequel + DiscardThen(Br afterJoin), afterJoin, stackAfterJoin, sequel // The others (e.g. Continue, LeaveFilter and CmpThenBrOrContinue) can't be done at the end of each branch. We must create a join point. | _ -> @@ -5623,98 +7155,152 @@ and GenJoinPoint cenv cgbuf pos eenv ty m sequel = // Accumulate the decision graph as we go and GenDecisionTreeAndTargets cenv cgbuf stackAtTargets eenv tree targets sequel contf = - let targetCounts = accTargetsOfDecisionTree tree [] |> List.countBy id |> Dictionary.ofList + let targetCounts = + accTargetsOfDecisionTree tree [] |> List.countBy id |> Dictionary.ofList + let targetNext = ref 0 // used to make sure we generate the targets in-order, postponing if necessary - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv tree targets (targetNext, targetCounts) (IntMap.empty()) sequel (fun targetInfos -> - let sortedTargetInfos = - targetInfos - |> Seq.sortBy (fun (KeyValue(targetIdx, _)) -> targetIdx) - |> Seq.filter (fun (KeyValue(_, (_, isTargetPostponed))) -> isTargetPostponed) - |> Seq.map (fun (KeyValue(_, (targetInfo, _))) -> targetInfo) - |> List.ofSeq - GenPostponedDecisionTreeTargets cenv cgbuf sortedTargetInfos stackAtTargets sequel contf - ) + + GenDecisionTreeAndTargetsInner + cenv + cgbuf + None + stackAtTargets + eenv + tree + targets + (targetNext, targetCounts) + (IntMap.empty ()) + sequel + (fun targetInfos -> + let sortedTargetInfos = + targetInfos + |> Seq.sortBy (fun (KeyValue (targetIdx, _)) -> targetIdx) + |> Seq.filter (fun (KeyValue (_, (_, isTargetPostponed))) -> isTargetPostponed) + |> Seq.map (fun (KeyValue (_, (targetInfo, _))) -> targetInfo) + |> List.ofSeq + + GenPostponedDecisionTreeTargets cenv cgbuf sortedTargetInfos stackAtTargets sequel contf) and GenPostponedDecisionTreeTargets cenv cgbuf targetInfos stackAtTargets sequel contf = match targetInfos with | [] -> contf Fake | targetInfo :: rest -> - let eenvAtTarget, exprAtTarget, sequelAtTarget = GenDecisionTreeTarget cenv cgbuf stackAtTargets targetInfo sequel + let eenvAtTarget, exprAtTarget, sequelAtTarget = + GenDecisionTreeTarget cenv cgbuf stackAtTargets targetInfo sequel + GenLinearExpr cenv cgbuf eenvAtTarget exprAtTarget sequelAtTarget true (fun Fake -> - GenPostponedDecisionTreeTargets cenv cgbuf rest stackAtTargets sequel contf - ) + GenPostponedDecisionTreeTargets cenv cgbuf rest stackAtTargets sequel contf) /// When inplabOpt is None, we are assuming a branch or fallthrough to the current code location /// /// When inplabOpt is "Some inplab", we are assuming an existing branch to "inplab" and can optionally /// set inplab to point to another location if no codegen is required. -and GenDecisionTreeAndTargetsInner cenv cgbuf inplabOpt stackAtTargets eenv tree targets targetCounts targetInfos sequel (contf: Zmap<_,_> -> FakeUnit) = - CG.SetStack cgbuf stackAtTargets // Set the expected initial stack. +and GenDecisionTreeAndTargetsInner + cenv + cgbuf + inplabOpt + stackAtTargets + eenv + tree + targets + targetCounts + targetInfos + sequel + (contf: Zmap<_, _> -> FakeUnit) + = + CG.SetStack cgbuf stackAtTargets // Set the expected initial stack. + match tree with - | TDBind(bind, rest) -> - cgbuf.SetMarkToHereIfNecessary inplabOpt - let startMark, endMark as scopeMarks = StartDelayedLocalScope "dtreeBind" cgbuf - let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind - GenDebugPointForBind cenv cgbuf bind - GenBindingAfterDebugPoint cenv cgbuf eenv bind false (Some startMark) - - // We don't get the scope marks quite right for dtree-bound variables. This is because - // we effectively lose an EndLocalScope for all dtrees that go to the same target - // So we just pretend that the variable goes out of scope here. - CG.SetMarkToHere cgbuf endMark - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv rest targets targetCounts targetInfos sequel contf - - | TDSuccess(es, targetIdx) -> - let targetInfos, genTargetInfoOpt = GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targets targetCounts targetInfos sequel + | TDBind (bind, rest) -> + cgbuf.SetMarkToHereIfNecessary inplabOpt + let startMark, endMark as scopeMarks = StartDelayedLocalScope "dtreeBind" cgbuf + let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind + GenDebugPointForBind cenv cgbuf bind + GenBindingAfterDebugPoint cenv cgbuf eenv bind false (Some startMark) + + // We don't get the scope marks quite right for dtree-bound variables. This is because + // we effectively lose an EndLocalScope for all dtrees that go to the same target + // So we just pretend that the variable goes out of scope here. + CG.SetMarkToHere cgbuf endMark + GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv rest targets targetCounts targetInfos sequel contf + + | TDSuccess (es, targetIdx) -> + let targetInfos, genTargetInfoOpt = + GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targets targetCounts targetInfos sequel + match genTargetInfoOpt with | Some (eenvAtTarget, exprAtTarget, sequelAtTarget) -> GenLinearExpr cenv cgbuf eenvAtTarget exprAtTarget sequelAtTarget true (fun Fake -> contf targetInfos) - | _ -> - contf targetInfos + | _ -> contf targetInfos - | TDSwitch(e, cases, dflt, m) -> + | TDSwitch (e, cases, dflt, m) -> GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases dflt m targets targetCounts targetInfos sequel contf -and GetTarget (targets:_[]) n = - if n >= targets.Length then failwith "GetTarget: target not found in decision tree" +and GetTarget (targets: _[]) n = + if n >= targets.Length then + failwith "GetTarget: target not found in decision tree" + targets[n] /// Generate a success node of a decision tree, binding the variables and going to the target /// If inplabOpt is present, this label must get set to the first logical place to execute. /// For example, if no variables get bound this can just be set to jump straight to the target. -and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targets (targetNext: int ref, targetCounts: Dictionary) targetInfos sequel = - let (TTarget(vs, successExpr, stateVarFlagsOpt)) = GetTarget targets targetIdx +and GenDecisionTreeSuccess + cenv + cgbuf + inplabOpt + stackAtTargets + eenv + es + targetIdx + targets + (targetNext: int ref, targetCounts: Dictionary) + targetInfos + sequel + = + let (TTarget (vs, successExpr, stateVarFlagsOpt)) = GetTarget targets targetIdx + match IntMap.tryFind targetIdx targetInfos with | Some (targetInfo, isTargetPostponed) -> - let (targetMarkBeforeBinds, targetMarkAfterBinds: Mark, eenvAtTarget, _, _, _, _, _, _) = targetInfo + let (targetMarkBeforeBinds, targetMarkAfterBinds: Mark, eenvAtTarget, _, _, _, _, _, _) = + targetInfo // We have encountered this target before. See if we should generate it now let targetCount = targetCounts[targetIdx] - let generateTargetNow = isTargetPostponed && cenv.options.localOptimizationsEnabled && targetCount = 1 && targetNext.Value = targetIdx + + let generateTargetNow = + isTargetPostponed + && cenv.options.localOptimizationsEnabled + && targetCount = 1 + && targetNext.Value = targetIdx + targetCounts[targetIdx] <- targetCount - 1 // If not binding anything we can go directly to the targetMarkBeforeBinds point // This is useful to avoid lots of branches e.g. in match A | B | C -> e // In this case each case will just go straight to "e" if isNil vs then - cgbuf.SetMarkOrEmitBranchIfNecessary (inplabOpt, targetMarkBeforeBinds) + cgbuf.SetMarkOrEmitBranchIfNecessary(inplabOpt, targetMarkBeforeBinds) else cgbuf.SetMarkToHereIfNecessary inplabOpt cgbuf.EmitStartOfHiddenCode() - (vs, es) ||> List.iter2 (fun v e -> + (vs, es) + ||> List.iter2 (fun v e -> - GetStoreValCtxt cenv cgbuf eenvAtTarget v + GetStoreValCtxt cgbuf eenvAtTarget v // Emit the expression GenBindingRhs cenv cgbuf eenv v e) - vs |> List.rev |> List.iter (fun v -> + vs + |> List.rev + |> List.iter (fun v -> // Store the results - GenStoreVal cenv cgbuf eenvAtTarget v.Range v) + GenStoreVal cgbuf eenvAtTarget v.Range v) CG.EmitInstr cgbuf (pop 0) Push0 (I_br targetMarkAfterBinds.CodeLabel) - + let genTargetInfoOpt = if generateTargetNow then // Fenerate the targets in-order only @@ -5725,7 +7311,10 @@ and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx // Update the targetInfos let isTargetStillPostponed = isTargetPostponed && not generateTargetNow - let targetInfos = IntMap.add targetIdx (targetInfo, isTargetStillPostponed) targetInfos + + let targetInfos = + IntMap.add targetIdx (targetInfo, isTargetStillPostponed) targetInfos + targetInfos, genTargetInfoOpt | None -> @@ -5737,24 +7326,29 @@ and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx let startMark, endMark as scopeMarks = StartDelayedLocalScope "targetBinds" cgbuf // Allocate storage for variables (except those lifted to be state machine variables) - let binds = - match stateVarFlagsOpt with + let binds = + match stateVarFlagsOpt with | None -> mkInvisibleBinds vs es - | Some stateVarFlags -> - (vs, es, stateVarFlags) - |||> List.zip3 - |> List.choose (fun (v, e, isStateVar) -> if isStateVar then None else Some (mkInvisibleBind v e)) + | Some stateVarFlags -> + (vs, es, stateVarFlags) + |||> List.zip3 + |> List.choose (fun (v, e, isStateVar) -> if isStateVar then None else Some(mkInvisibleBind v e)) let eenvAtTarget = AllocStorageForBinds cenv cgbuf scopeMarks eenv binds - let targetInfo = (targetMarkBeforeBinds, targetMarkAfterBinds, eenvAtTarget, successExpr, vs, es, stateVarFlagsOpt, startMark, endMark) + let targetInfo = + (targetMarkBeforeBinds, targetMarkAfterBinds, eenvAtTarget, successExpr, vs, es, stateVarFlagsOpt, startMark, endMark) let targetCount = targetCounts[targetIdx] // In debug mode, postpone all decision tree targets to after the switching. - // In release mode, if a target is the target of multiple incoming success nodes, postpone it to avoid + // In release mode, if a target is the target of multiple incoming success nodes, postpone it to avoid // making any backward branches - let generateTargetNow = cenv.options.localOptimizationsEnabled && targetCount = 1 && targetNext.Value = targetIdx + let generateTargetNow = + cenv.options.localOptimizationsEnabled + && targetCount = 1 + && targetNext.Value = targetIdx + targetCounts[targetIdx] <- targetCount - 1 let genTargetInfoOpt = @@ -5766,7 +7360,7 @@ and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx Some(GenDecisionTreeTarget cenv cgbuf stackAtTargets targetInfo sequel) else // Here we are postponing the generation of the target. - cgbuf.SetMarkOrEmitBranchIfNecessary (inplabOpt, targetMarkBeforeBinds) + cgbuf.SetMarkOrEmitBranchIfNecessary(inplabOpt, targetMarkBeforeBinds) None let isTargetPostponed = not generateTargetNow @@ -5774,7 +7368,9 @@ and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targetInfos, genTargetInfoOpt and GenDecisionTreeTarget cenv cgbuf stackAtTargets targetInfo sequel = - let targetMarkBeforeBinds, targetMarkAfterBinds, eenvAtTarget, successExpr, vs, es, stateVarFlagsOpt, startMark, endMark = targetInfo + let targetMarkBeforeBinds, targetMarkAfterBinds, eenvAtTarget, successExpr, vs, es, stateVarFlagsOpt, startMark, endMark = + targetInfo + CG.SetMarkToHere cgbuf targetMarkBeforeBinds cgbuf.EmitStartOfHiddenCode() @@ -5786,93 +7382,207 @@ and GenDecisionTreeTarget cenv cgbuf stackAtTargets targetInfo sequel = CG.SetStack cgbuf stackAtTargets (eenvAtTarget, successExpr, (EndLocalScope(sequel, endMark))) -and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defaultTargetOpt switchm targets targetCounts targetInfos sequel contf = +and GenDecisionTreeSwitch + cenv + cgbuf + inplabOpt + stackAtTargets + eenv + e + cases + defaultTargetOpt + switchm + targets + targetCounts + targetInfos + sequel + contf + = let g = cenv.g let m = e.Range cgbuf.SetMarkToHereIfNecessary inplabOpt cgbuf.EmitStartOfHiddenCode() + match cases with - // optimize a test against a boolean value, i.e. the all-important if-then-else - | TCase(DecisionTreeTest.Const(Const.Bool b), successTree) :: _ -> - let failureTree = (match defaultTargetOpt with None -> cases.Tail.Head.CaseTree | Some d -> d) - GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e None false eenv (if b then successTree else failureTree) (if b then failureTree else successTree) targets targetCounts targetInfos sequel contf - - // Optimize a single test for a union case to an "isdata" test - much - // more efficient code, and this case occurs in the generated equality testers where perf is important - | TCase(DecisionTreeTest.UnionCase(c, tyargs), successTree) :: rest when rest.Length = (match defaultTargetOpt with None -> 1 | Some _ -> 0) -> + // optimize a test against a boolean value, i.e. the all-important if-then-else + | TCase (DecisionTreeTest.Const (Const.Bool b), successTree) :: _ -> + let failureTree = + (match defaultTargetOpt with + | None -> cases.Tail.Head.CaseTree + | Some d -> d) + + GenDecisionTreeTest + cenv + eenv.cloc + cgbuf + stackAtTargets + e + None + false + eenv + (if b then successTree else failureTree) + (if b then failureTree else successTree) + targets + targetCounts + targetInfos + sequel + contf + + // Optimize a single test for a union case to an "isdata" test - much + // more efficient code, and this case occurs in the generated equality testers where perf is important + | TCase (DecisionTreeTest.UnionCase (c, tyargs), successTree) :: rest when + rest.Length = (match defaultTargetOpt with + | None -> 1 + | Some _ -> 0) + -> let failureTree = match defaultTargetOpt with | None -> rest.Head.CaseTree | Some tg -> tg + let cuspec = GenUnionSpec cenv m eenv.tyenv c.TyconRef tyargs let idx = c.Index let avoidHelpers = entityRefInThisAssembly g.compilingFSharpCore c.TyconRef - let tester = (Some (pop 1, Push [g.ilg.typ_Bool], Choice1Of2 (avoidHelpers, cuspec, idx))) - GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e tester false eenv successTree failureTree targets targetCounts targetInfos sequel contf - - // Use GenDecisionTreeTest to generate a single test for null (when no box required) where the success - // is going to the immediate first node in the tree - | TCase(DecisionTreeTest.IsNull _, (TDSuccess([], 0) as successTree)) :: rest - when rest.Length = (match defaultTargetOpt with None -> 1 | Some _ -> 0) - && not (isTyparTy g (tyOfExpr g e)) -> + + let tester = + (Some(pop 1, Push [ g.ilg.typ_Bool ], Choice1Of2(avoidHelpers, cuspec, idx))) + + GenDecisionTreeTest + cenv + eenv.cloc + cgbuf + stackAtTargets + e + tester + false + eenv + successTree + failureTree + targets + targetCounts + targetInfos + sequel + contf + + // Use GenDecisionTreeTest to generate a single test for null (when no box required) where the success + // is going to the immediate first node in the tree + | TCase (DecisionTreeTest.IsNull _, (TDSuccess ([], 0) as successTree)) :: rest when + rest.Length = (match defaultTargetOpt with + | None -> 1 + | Some _ -> 0) + && not (isTyparTy g (tyOfExpr g e)) + -> let failureTree = match defaultTargetOpt with | None -> rest.Head.CaseTree | Some tg -> tg - GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e None true eenv successTree failureTree targets targetCounts targetInfos sequel contf - | _ -> + GenDecisionTreeTest + cenv + eenv.cloc + cgbuf + stackAtTargets + e + None + true + eenv + successTree + failureTree + targets + targetCounts + targetInfos + sequel + contf + + | _ -> let caseLabels = List.map (fun _ -> CG.GenerateDelayMark cgbuf "switch_case") cases let firstDiscrim = cases.Head.Discriminator + match firstDiscrim with // Iterated tests, e.g. exception constructors, nulltests, typetests and active patterns. // These should always have one positive and one negative branch | DecisionTreeTest.ArrayLength _ | DecisionTreeTest.IsInst _ | DecisionTreeTest.IsNull - | DecisionTreeTest.Const(Const.Zero) -> - if not (isSingleton cases) || Option.isNone defaultTargetOpt then failwith "internal error: GenDecisionTreeSwitch: DecisionTreeTest.IsInst/isnull/query" + | DecisionTreeTest.Const (Const.Zero) -> + if not (isSingleton cases) || Option.isNone defaultTargetOpt then + failwith "internal error: GenDecisionTreeSwitch: DecisionTreeTest.IsInst/isnull/query" + let bi = - match firstDiscrim with - | DecisionTreeTest.Const(Const.Zero) -> - GenExpr cenv cgbuf eenv e Continue - BI_brfalse - | DecisionTreeTest.IsNull -> - GenExpr cenv cgbuf eenv e Continue - let srcTy = tyOfExpr g e - if isTyparTy g srcTy then - let ilFromTy = GenType cenv m eenv.tyenv srcTy - CG.EmitInstr cgbuf (pop 1) (Push [g.ilg.typ_Object]) (I_box ilFromTy) - BI_brfalse - | DecisionTreeTest.IsInst (_srcty, tgty) -> - let e = mkCallTypeTest g m tgty e - GenExpr cenv cgbuf eenv e Continue - BI_brtrue - | _ -> failwith "internal error: GenDecisionTreeSwitch" - CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp (bi, (List.head caseLabels).CodeLabel)) - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets targetCounts targetInfos sequel caseLabels cases contf + match firstDiscrim with + | DecisionTreeTest.Const (Const.Zero) -> + GenExpr cenv cgbuf eenv e Continue + BI_brfalse + | DecisionTreeTest.IsNull -> + GenExpr cenv cgbuf eenv e Continue + let srcTy = tyOfExpr g e + + if isTyparTy g srcTy then + let ilFromTy = GenType cenv m eenv.tyenv srcTy + CG.EmitInstr cgbuf (pop 1) (Push [ g.ilg.typ_Object ]) (I_box ilFromTy) + + BI_brfalse + | DecisionTreeTest.IsInst (_srcTy, tgtTy) -> + let e = mkCallTypeTest g m tgtTy e + GenExpr cenv cgbuf eenv e Continue + BI_brtrue + | _ -> failwith "internal error: GenDecisionTreeSwitch" + + CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp(bi, (List.head caseLabels).CodeLabel)) + + GenDecisionTreeCases + cenv + cgbuf + stackAtTargets + eenv + defaultTargetOpt + targets + targetCounts + targetInfos + sequel + caseLabels + cases + contf | DecisionTreeTest.ActivePatternCase _ -> - error(InternalError("internal error in codegen: DecisionTreeTest.ActivePatternCase", switchm)) + error (InternalError("internal error in codegen: DecisionTreeTest.ActivePatternCase", switchm)) | DecisionTreeTest.UnionCase (hdc, tyargs) -> GenExpr cenv cgbuf eenv e Continue let cuspec = GenUnionSpec cenv m eenv.tyenv hdc.TyconRef tyargs + let dests = - if cases.Length <> caseLabels.Length then failwith "internal error: DecisionTreeTest.UnionCase" - (cases, caseLabels) ||> List.map2 (fun case label -> - match case with - | TCase(DecisionTreeTest.UnionCase (c, _), _) -> (c.Index, label.CodeLabel) - | _ -> failwith "error: mixed constructor/const test?") + if cases.Length <> caseLabels.Length then + failwith "internal error: DecisionTreeTest.UnionCase" + + (cases, caseLabels) + ||> List.map2 (fun case label -> + match case with + | TCase (DecisionTreeTest.UnionCase (c, _), _) -> (c.Index, label.CodeLabel) + | _ -> failwith "error: mixed constructor/const test?") let avoidHelpers = entityRefInThisAssembly g.compilingFSharpCore hdc.TyconRef EraseUnions.emitDataSwitch g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec, dests) - CG.EmitInstrs cgbuf (pop 1) Push0 [ ] // push/pop to match the line above - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets targetCounts targetInfos sequel caseLabels cases contf + CG.EmitInstrs cgbuf (pop 1) Push0 [] // push/pop to match the line above + + GenDecisionTreeCases + cenv + cgbuf + stackAtTargets + eenv + defaultTargetOpt + targets + targetCounts + targetInfos + sequel + caseLabels + cases + contf | DecisionTreeTest.Const c -> GenExpr cenv cgbuf eenv e Continue + match c with | Const.Bool _ -> failwith "should have been done earlier" | Const.SByte _ @@ -5882,92 +7592,185 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau | Const.UInt16 _ | Const.UInt32 _ | Const.Char _ -> - if List.length cases <> List.length caseLabels then failwith "internal error: " + if List.length cases <> List.length caseLabels then + failwith "internal error: " + let dests = - (cases, caseLabels) ||> List.map2 (fun case label -> - let i = - match case.Discriminator with - DecisionTreeTest.Const c2 -> - match c2 with - | Const.SByte i -> int32 i - | Const.Int16 i -> int32 i - | Const.Int32 i -> i - | Const.Byte i -> int32 i - | Const.UInt16 i -> int32 i - | Const.UInt32 i -> int32 i - | Const.Char c -> int32 c + (cases, caseLabels) + ||> List.map2 (fun case label -> + let i = + match case.Discriminator with + | DecisionTreeTest.Const c2 -> + match c2 with + | Const.SByte i -> int32 i + | Const.Int16 i -> int32 i + | Const.Int32 i -> i + | Const.Byte i -> int32 i + | Const.UInt16 i -> int32 i + | Const.UInt32 i -> int32 i + | Const.Char c -> int32 c + | _ -> failwith "internal error: badly formed const test" + | _ -> failwith "internal error: badly formed const test" - | _ -> failwith "internal error: badly formed const test" - (i, label.CodeLabel)) - let mn = List.foldBack (fst >> Operators.min) dests (fst(List.head dests)) - let mx = List.foldBack (fst >> Operators.max) dests (fst(List.head dests)) + (i, label.CodeLabel)) + + let mn = List.foldBack (fst >> Operators.min) dests (fst (List.head dests)) + let mx = List.foldBack (fst >> Operators.max) dests (fst (List.head dests)) // Check if it's worth using a switch // REVIEW: this is using switches even for single integer matches! if mx - mn = (List.length dests - 1) then let destinationLabels = dests |> List.sortBy fst |> List.map snd + if mn <> 0 then - CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Int32]) (mkLdcInt32 mn) - CG.EmitInstr cgbuf (pop 1) Push0 AI_sub + CG.EmitInstr cgbuf (pop 0) (Push [ g.ilg.typ_Int32 ]) (mkLdcInt32 mn) + CG.EmitInstr cgbuf (pop 1) Push0 AI_sub + CG.EmitInstr cgbuf (pop 1) Push0 (I_switch destinationLabels) else - error(InternalError("non-dense integer matches not implemented in codegen - these should have been removed by the pattern match compiler", switchm)) - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets targetCounts targetInfos sequel caseLabels cases contf - | _ -> error(InternalError("these matches should never be needed", switchm)) - - | DecisionTreeTest.Error m -> - error(InternalError("Trying to compile error recovery branch", m)) - -and GenDecisionTreeCases cenv cgbuf stackAtTargets eenv defaultTargetOpt targets targetCounts targetInfos sequel caseLabels cases (contf: Zmap<_,_> -> FakeUnit) = + error ( + InternalError( + "non-dense integer matches not implemented in codegen - these should have been removed by the pattern match compiler", + switchm + ) + ) + + GenDecisionTreeCases + cenv + cgbuf + stackAtTargets + eenv + defaultTargetOpt + targets + targetCounts + targetInfos + sequel + caseLabels + cases + contf + | _ -> error (InternalError("these matches should never be needed", switchm)) + + | DecisionTreeTest.Error m -> error (InternalError("Trying to compile error recovery branch", m)) + +and GenDecisionTreeCases + cenv + cgbuf + stackAtTargets + eenv + defaultTargetOpt + targets + targetCounts + targetInfos + sequel + caseLabels + cases + (contf: Zmap<_, _> -> FakeUnit) + = match defaultTargetOpt with | Some defaultTarget -> - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv defaultTarget targets targetCounts targetInfos sequel (fun targetInfos -> - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv None targets targetCounts targetInfos sequel caseLabels cases contf - ) + GenDecisionTreeAndTargetsInner + cenv + cgbuf + None + stackAtTargets + eenv + defaultTarget + targets + targetCounts + targetInfos + sequel + (fun targetInfos -> + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv None targets targetCounts targetInfos sequel caseLabels cases contf) | None -> match caseLabels, cases with - | caseLabel :: caseLabelsTail, TCase(_, caseTree) :: casesTail -> - GenDecisionTreeAndTargetsInner cenv cgbuf (Some caseLabel) stackAtTargets eenv caseTree targets targetCounts targetInfos sequel (fun targetInfos -> - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv None targets targetCounts targetInfos sequel caseLabelsTail casesTail contf - ) - | _ -> - contf targetInfos + | caseLabel :: caseLabelsTail, TCase (_, caseTree) :: casesTail -> + GenDecisionTreeAndTargetsInner + cenv + cgbuf + (Some caseLabel) + stackAtTargets + eenv + caseTree + targets + targetCounts + targetInfos + sequel + (fun targetInfos -> + GenDecisionTreeCases + cenv + cgbuf + stackAtTargets + eenv + None + targets + targetCounts + targetInfos + sequel + caseLabelsTail + casesTail + contf) + | _ -> contf targetInfos // Used for the peephole optimization below -and (|BoolExpr|_|) = function Expr.Const (Const.Bool b1, _, _) -> Some b1 | _ -> None +and (|BoolExpr|_|) = + function + | Expr.Const (Const.Bool b1, _, _) -> Some b1 + | _ -> None -and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester isNullTest eenv successTree failureTree targets targetCounts targetInfos sequel contf = +and GenDecisionTreeTest + cenv + cloc + cgbuf + stackAtTargets + e + tester + isNullTest + eenv + successTree + failureTree + targets + targetCounts + targetInfos + sequel + contf + = let g = cenv.g + match successTree, failureTree with // Peephole: if generating a boolean value or its negation then just leave it on the stack // This comes up in the generated equality functions. REVIEW: do this as a peephole optimization elsewhere - | TDSuccess(es1, n1), - TDSuccess(es2, n2) when - not isNullTest && - isNil es1 && isNil es2 && - (match GetTarget targets n1, GetTarget targets n2 with - | TTarget(_, BoolExpr b1, _), TTarget(_, BoolExpr b2, _) -> b1 = not b2 - | _ -> false) -> - - match GetTarget targets n1, GetTarget targets n2 with - - | TTarget(_, BoolExpr b1, _), _ -> - GenExpr cenv cgbuf eenv e Continue - match tester with - | Some (pops, pushes, i) -> - match i with - | Choice1Of2 (avoidHelpers, cuspec, idx) -> CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData g.ilg (avoidHelpers, cuspec, idx)) - | Choice2Of2 i -> CG.EmitInstr cgbuf pops pushes i - | _ -> () - if not b1 then - CG.EmitInstr cgbuf (pop 0) (Push [g.ilg.typ_Bool]) (mkLdcInt32 0) - CG.EmitInstr cgbuf (pop 1) Push0 AI_ceq - GenSequel cenv cloc cgbuf sequel - contf targetInfos - - | _ -> failwith "internal error: GenDecisionTreeTest during bool elim" + | TDSuccess (es1, n1), TDSuccess (es2, n2) when + not isNullTest + && isNil es1 + && isNil es2 + && (match GetTarget targets n1, GetTarget targets n2 with + | TTarget (_, BoolExpr b1, _), TTarget (_, BoolExpr b2, _) -> b1 = not b2 + | _ -> false) + -> + + match GetTarget targets n1, GetTarget targets n2 with + + | TTarget (_, BoolExpr b1, _), _ -> + GenExpr cenv cgbuf eenv e Continue + + match tester with + | Some (pops, pushes, i) -> + match i with + | Choice1Of2 (avoidHelpers, cuspec, idx) -> + CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData g.ilg (avoidHelpers, cuspec, idx)) + | Choice2Of2 i -> CG.EmitInstr cgbuf pops pushes i + | _ -> () + + if not b1 then + CG.EmitInstr cgbuf (pop 0) (Push [ g.ilg.typ_Bool ]) (mkLdcInt32 0) + CG.EmitInstr cgbuf (pop 1) Push0 AI_ceq + + GenSequel cenv cloc cgbuf sequel + contf targetInfos + + | _ -> failwith "internal error: GenDecisionTreeTest during bool elim" | _ -> match tester with @@ -5980,15 +7783,39 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester isNullTest eenv // If so, emit the failure logic, then came back and do the success target, then // do any postponed failure target. match successTree, failureTree with - | TDSuccess _, (TDBind _ | TDSwitch _) -> - + | TDSuccess _, + (TDBind _ + | TDSwitch _) -> + // OK, there is more logic in the decision tree on the failure branch let success = CG.GenerateDelayMark cgbuf "testSuccess" let testForSuccess = if isNullTest then BI_brfalse else BI_brtrue - GenExpr cenv cgbuf eenv e (CmpThenBrOrContinue(pop 1, [ I_brcmp (testForSuccess, success.CodeLabel) ])) - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv failureTree targets targetCounts targetInfos sequel (fun targetInfos -> - GenDecisionTreeAndTargetsInner cenv cgbuf (Some success) stackAtTargets eenv successTree targets targetCounts targetInfos sequel contf - ) + GenExpr cenv cgbuf eenv e (CmpThenBrOrContinue(pop 1, [ I_brcmp(testForSuccess, success.CodeLabel) ])) + + GenDecisionTreeAndTargetsInner + cenv + cgbuf + None + stackAtTargets + eenv + failureTree + targets + targetCounts + targetInfos + sequel + (fun targetInfos -> + GenDecisionTreeAndTargetsInner + cenv + cgbuf + (Some success) + stackAtTargets + eenv + successTree + targets + targetCounts + targetInfos + sequel + contf) | _ -> @@ -5997,50 +7824,124 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester isNullTest eenv // logic first. let failure = CG.GenerateDelayMark cgbuf "testFailure" let testForFailure = if isNullTest then BI_brtrue else BI_brfalse - GenExpr cenv cgbuf eenv e (CmpThenBrOrContinue(pop 1, [ I_brcmp (testForFailure, failure.CodeLabel) ])) - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv successTree targets targetCounts targetInfos sequel (fun targetInfos -> - GenDecisionTreeAndTargetsInner cenv cgbuf (Some failure) stackAtTargets eenv failureTree targets targetCounts targetInfos sequel contf - ) + GenExpr cenv cgbuf eenv e (CmpThenBrOrContinue(pop 1, [ I_brcmp(testForFailure, failure.CodeLabel) ])) + + GenDecisionTreeAndTargetsInner + cenv + cgbuf + None + stackAtTargets + eenv + successTree + targets + targetCounts + targetInfos + sequel + (fun targetInfos -> + GenDecisionTreeAndTargetsInner + cenv + cgbuf + (Some failure) + stackAtTargets + eenv + failureTree + targets + targetCounts + targetInfos + sequel + contf) // Turn 'isdata' tests that branch into EI_brisdata tests | Some (_, _, Choice1Of2 (avoidHelpers, cuspec, idx)) -> let failure = CG.GenerateDelayMark cgbuf "testFailure" - GenExpr cenv cgbuf eenv e (CmpThenBrOrContinue(pop 1, EraseUnions.mkBrIsData g.ilg false (avoidHelpers, cuspec, idx, failure.CodeLabel))) - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv successTree targets targetCounts targetInfos sequel (fun targetInfos -> - GenDecisionTreeAndTargetsInner cenv cgbuf (Some failure) stackAtTargets eenv failureTree targets targetCounts targetInfos sequel contf - ) + GenExpr + cenv + cgbuf + eenv + e + (CmpThenBrOrContinue(pop 1, EraseUnions.mkBrIsData g.ilg false (avoidHelpers, cuspec, idx, failure.CodeLabel))) + + GenDecisionTreeAndTargetsInner + cenv + cgbuf + None + stackAtTargets + eenv + successTree + targets + targetCounts + targetInfos + sequel + (fun targetInfos -> + GenDecisionTreeAndTargetsInner + cenv + cgbuf + (Some failure) + stackAtTargets + eenv + failureTree + targets + targetCounts + targetInfos + sequel + contf) | Some (pops, pushes, i) -> let failure = CG.GenerateDelayMark cgbuf "testFailure" GenExpr cenv cgbuf eenv e Continue + match i with - | Choice1Of2 (avoidHelpers, cuspec, idx) -> CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData g.ilg (avoidHelpers, cuspec, idx)) + | Choice1Of2 (avoidHelpers, cuspec, idx) -> + CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData g.ilg (avoidHelpers, cuspec, idx)) | Choice2Of2 i -> CG.EmitInstr cgbuf pops pushes i - CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp (BI_brfalse, failure.CodeLabel)) - GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv successTree targets targetCounts targetInfos sequel (fun targetInfos -> - GenDecisionTreeAndTargetsInner cenv cgbuf (Some failure) stackAtTargets eenv failureTree targets targetCounts targetInfos sequel contf - ) + CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp(BI_brfalse, failure.CodeLabel)) + + GenDecisionTreeAndTargetsInner + cenv + cgbuf + None + stackAtTargets + eenv + successTree + targets + targetCounts + targetInfos + sequel + (fun targetInfos -> + GenDecisionTreeAndTargetsInner + cenv + cgbuf + (Some failure) + stackAtTargets + eenv + failureTree + targets + targetCounts + targetInfos + sequel + contf) /// Generate fixups for letrec bindings and GenLetRecFixup cenv cgbuf eenv (ilxCloSpec: IlxClosureSpec, e, ilField: ILFieldSpec, e2, _m) = GenExpr cenv cgbuf eenv e Continue CG.EmitInstr cgbuf (pop 0) Push0 (I_castclass ilxCloSpec.ILType) GenExpr cenv cgbuf eenv e2 Continue - CG.EmitInstr cgbuf (pop 2) Push0 (mkNormalStfld (mkILFieldSpec(ilField.FieldRef, ilxCloSpec.ILType))) + CG.EmitInstr cgbuf (pop 2) Push0 (mkNormalStfld (mkILFieldSpec (ilField.FieldRef, ilxCloSpec.ILType))) /// Generate letrec bindings and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = - + // 'let rec' bindings are always considered to be in loops, that is each may have backward branches for the // tailcalls back to the entry point. This means we don't rely on zero-init of mutable locals let eenv = SetIsInLoop true eenv // Fix up recursion for non-toplevel recursive bindings let bindsPossiblyRequiringFixup = - allBinds |> List.filter (fun b -> - match (StorageForVal cenv.g m b.Var eenv) with + allBinds + |> List.filter (fun b -> + match (StorageForVal m b.Var eenv) with | StaticProperty _ | Method _ // Note: Recursive data stored in static fields may require fixups e.g. let x = C(x) @@ -6050,44 +7951,84 @@ and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = let computeFixupsForOneRecursiveVar boundv forwardReferenceSet (fixups: _ ref) thisVars access set e = match e with - | Expr.Lambda _ | Expr.TyLambda _ | Expr.Obj _ -> - let isLocalTypeFunc = Option.isSome thisVars && (IsNamedLocalTypeFuncVal cenv.g (Option.get thisVars) e) - let thisVars = (match e with Expr.Obj _ -> [] | _ when isLocalTypeFunc -> [] | _ -> Option.map mkLocalValRef thisVars |> Option.toList) - let canUseStaticField = (match e with Expr.Obj _ -> false | _ -> true) - let clo, _, eenvclo = GetIlxClosureInfo cenv m ILBoxity.AsObject isLocalTypeFunc canUseStaticField thisVars {eenv with letBoundVars=(mkLocalValRef boundv) :: eenv.letBoundVars} e + | Expr.Lambda _ + | Expr.TyLambda _ + | Expr.Obj _ -> + let isLocalTypeFunc = + Option.isSome thisVars + && (IsNamedLocalTypeFuncVal cenv.g (Option.get thisVars) e) + + let thisVars = + (match e with + | Expr.Obj _ -> [] + | _ when isLocalTypeFunc -> [] + | _ -> Option.map mkLocalValRef thisVars |> Option.toList) + + let canUseStaticField = + (match e with + | Expr.Obj _ -> false + | _ -> true) + + let clo, _, eenvclo = + GetIlxClosureInfo + cenv + m + ILBoxity.AsObject + isLocalTypeFunc + canUseStaticField + thisVars + { eenv with + letBoundVars = (mkLocalValRef boundv) :: eenv.letBoundVars + } + e + for fv in clo.cloFreeVars do if Zset.contains fv forwardReferenceSet then - match StorageForVal cenv.g m fv eenvclo with + match StorageForVal m fv eenvclo with | Env (_, ilField, _) -> - let fixup = (boundv, fv, (fun () -> GenLetRecFixup cenv cgbuf eenv (clo.cloSpec, access, ilField, exprForVal m fv, m))) + let fixup = + (boundv, fv, (fun () -> GenLetRecFixup cenv cgbuf eenv (clo.cloSpec, access, ilField, exprForVal m fv, m))) + fixups.Value <- fixup :: fixups.Value | _ -> error (InternalError("GenLetRec: " + fv.LogicalName + " was not in the environment", m)) | Expr.Val (vref, _, _) -> let fv = vref.Deref let needsFixup = Zset.contains fv forwardReferenceSet + if needsFixup then let fixup = (boundv, fv, (fun () -> GenExpr cenv cgbuf eenv (set e) discard)) fixups.Value <- fixup :: fixups.Value | _ -> failwith "compute real fixup vars" - let fixups = ref [] - let recursiveVars = Zset.addList (bindsPossiblyRequiringFixup |> List.map (fun v -> v.Var)) (Zset.empty valOrder) + + let recursiveVars = + Zset.addList (bindsPossiblyRequiringFixup |> List.map (fun v -> v.Var)) (Zset.empty valOrder) + let _ = - (recursiveVars, bindsPossiblyRequiringFixup) ||> List.fold (fun forwardReferenceSet (bind: Binding) -> + (recursiveVars, bindsPossiblyRequiringFixup) + ||> List.fold (fun forwardReferenceSet (bind: Binding) -> // Compute fixups - bind.Expr |> IterateRecursiveFixups cenv.g (Some bind.Var) - (computeFixupsForOneRecursiveVar bind.Var forwardReferenceSet fixups) - (exprForVal m bind.Var, - (fun _ -> failwith ("internal error: should never need to set non-delayed recursive val: " + bind.Var.LogicalName))) + bind.Expr + |> IterateRecursiveFixups + cenv.g + (Some bind.Var) + (computeFixupsForOneRecursiveVar bind.Var forwardReferenceSet fixups) + (exprForVal m bind.Var, + (fun _ -> + failwith ( + "internal error: should never need to set non-delayed recursive val: " + + bind.Var.LogicalName + ))) // Record the variable as defined let forwardReferenceSet = Zset.remove bind.Var forwardReferenceSet forwardReferenceSet) // Generate the actual bindings let _ = - (recursiveVars, allBinds) ||> List.fold (fun forwardReferenceSet (bind: Binding) -> + (recursiveVars, allBinds) + ||> List.fold (fun forwardReferenceSet (bind: Binding) -> GenBinding cenv cgbuf eenv bind false // Record the variable as defined @@ -6095,15 +8036,18 @@ and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = // Execute and discard any fixups that can now be committed let newFixups = - fixups.Value |> List.filter (fun (boundv, fv, action) -> + fixups.Value + |> List.filter (fun (boundv, fv, action) -> if (Zset.contains boundv forwardReferenceSet || Zset.contains fv forwardReferenceSet) then true else - action() + action () false) + fixups.Value <- newFixups forwardReferenceSet) + () and GenLetRec cenv cgbuf eenv (binds, body, m) sequel = @@ -6126,21 +8070,33 @@ and GenBinding cenv cgbuf eenv (bind: Binding) (isStateVar: bool) = and ComputeMemberAccessRestrictedBySig eenv vspec = let isHidden = - IsHiddenVal eenv.sigToImplRemapInfo vspec || // anything hidden by a signature gets assembly visibility - not vspec.IsMemberOrModuleBinding || // anything that's not a module or member binding gets assembly visibility - vspec.IsIncrClassGeneratedMember // compiler generated members for class function 'let' bindings get assembly visibility + // Anything hidden by a signature gets assembly visibility + IsHiddenVal eenv.sigToImplRemapInfo vspec + || + // Anything that's not a module or member binding gets assembly visibility + not vspec.IsMemberOrModuleBinding + || + // Compiler generated members for class function 'let' bindings get assembly visibility + vspec.IsIncrClassGeneratedMember + ComputeMemberAccess isHidden and ComputeMethodAccessRestrictedBySig eenv vspec = let isHidden = - IsHiddenVal eenv.sigToImplRemapInfo vspec || // anything hidden by a signature gets assembly visibility - not vspec.IsMemberOrModuleBinding || // anything that's not a module or member binding gets assembly visibility - vspec.IsIncrClassGeneratedMember // compiler generated members for class function 'let' bindings get assembly visibility + // Anything hidden by a signature gets assembly visibility + IsHiddenVal eenv.sigToImplRemapInfo vspec + || + // Anything that's not a module or member binding gets assembly visibility + not vspec.IsMemberOrModuleBinding + || + // Compiler generated members for class function 'let' bindings get assembly visibility + vspec.IsIncrClassGeneratedMember + ComputeMemberAccess isHidden and GenBindingAfterDebugPoint cenv cgbuf eenv bind isStateVar startMarkOpt = let g = cenv.g - let (TBind(vspec, rhsExpr, _)) = bind + let (TBind (vspec, rhsExpr, _)) = bind // Record the closed reflection definition if publishing // There is no real reason we're doing this so late in the day @@ -6149,39 +8105,57 @@ and GenBindingAfterDebugPoint cenv cgbuf eenv bind isStateVar startMarkOpt = | _ -> () let eenv = - if isStateVar then eenv - else { eenv with letBoundVars = (mkLocalValRef vspec) :: eenv.letBoundVars; - initLocals = eenv.initLocals && (match vspec.ApparentEnclosingEntity with Parent ref -> not (HasFSharpAttribute g g.attrib_SkipLocalsInitAttribute ref.Attribs) | _ -> true) } + if isStateVar then + eenv + else + { eenv with + letBoundVars = (mkLocalValRef vspec) :: eenv.letBoundVars + initLocals = + eenv.initLocals + && (match vspec.ApparentEnclosingEntity with + | Parent ref -> not (HasFSharpAttribute g g.attrib_SkipLocalsInitAttribute ref.Attribs) + | _ -> true) + } let access = ComputeMethodAccessRestrictedBySig eenv vspec // Workaround for .NET and Visual Studio restriction w.r.t debugger type proxys // Mark internal constructors in internal classes as public. let access = - if access = ILMemberAccess.Assembly && vspec.IsConstructor && IsHiddenTycon eenv.sigToImplRemapInfo vspec.MemberApparentEntity.Deref then + if + access = ILMemberAccess.Assembly + && vspec.IsConstructor + && IsHiddenTycon eenv.sigToImplRemapInfo vspec.MemberApparentEntity.Deref + then ILMemberAccess.Public else access let m = vspec.Range - match StorageForVal cenv.g m vspec eenv with + match StorageForVal m vspec eenv with | Null -> GenExpr cenv cgbuf eenv rhsExpr discard CommitStartScope cgbuf startMarkOpt // The initialization code for static 'let' and 'do' bindings gets compiled into the initialization .cctor for the whole file - | _ when vspec.IsClassConstructor && isNil vspec.TopValDeclaringEntity.TyparsNoRange && not isStateVar -> - let tps, _, _, _, cctorBody, _ = IteratedAdjustArityOfLambda g cenv.amap vspec.ValReprInfo.Value rhsExpr + | _ when + vspec.IsClassConstructor + && isNil vspec.TopValDeclaringEntity.TyparsNoRange + && not isStateVar + -> + let tps, _, _, _, cctorBody, _ = + IteratedAdjustArityOfLambda g cenv.amap vspec.ValReprInfo.Value rhsExpr + let eenv = EnvForTypars tps eenv CommitStartScope cgbuf startMarkOpt GenExpr cenv cgbuf eenv cctorBody discard - - | Method (topValInfo, _, mspec, mspecW, _, ctps, mtps, curriedArgInfos, paramInfos, witnessInfos, argTys, retInfo) when not isStateVar -> + + | Method (valReprInfo, _, mspec, mspecW, _, ctps, mtps, curriedArgInfos, paramInfos, witnessInfos, argTys, retInfo) when not isStateVar -> let methLambdaTypars, methLambdaCtorThisValOpt, methLambdaBaseValOpt, methLambdaCurriedVars, methLambdaBody, methLambdaBodyTy = - IteratedAdjustArityOfLambda g cenv.amap topValInfo rhsExpr + IteratedAdjustArityOfLambda g cenv.amap valReprInfo rhsExpr let methLambdaVars = List.concat methLambdaCurriedVars @@ -6189,35 +8163,87 @@ and GenBindingAfterDebugPoint cenv cgbuf eenv bind isStateVar startMarkOpt = let hasWitnessEntry = cenv.g.generateWitnesses && not witnessInfos.IsEmpty - GenMethodForBinding cenv cgbuf.mgbuf eenv (vspec, mspec, hasWitnessEntry, false, access, ctps, mtps, [], curriedArgInfos, paramInfos, argTys, retInfo, topValInfo, methLambdaCtorThisValOpt, methLambdaBaseValOpt, methLambdaTypars, methLambdaVars, methLambdaBody, methLambdaBodyTy) + GenMethodForBinding + cenv + cgbuf.mgbuf + eenv + (vspec, + mspec, + hasWitnessEntry, + false, + access, + ctps, + mtps, + [], + curriedArgInfos, + paramInfos, + argTys, + retInfo, + valReprInfo, + methLambdaCtorThisValOpt, + methLambdaBaseValOpt, + methLambdaTypars, + methLambdaVars, + methLambdaBody, + methLambdaBodyTy) // If generating witnesses, then generate the second entry point with additional arguments. // Take a copy of the expression to ensure generated names are unique. if hasWitnessEntry then let copyOfLambdaBody = copyExpr cenv.g CloneAll methLambdaBody - GenMethodForBinding cenv cgbuf.mgbuf eenv (vspec, mspecW, hasWitnessEntry, true, access, ctps, mtps, witnessInfos, curriedArgInfos, paramInfos, argTys, retInfo, topValInfo, methLambdaCtorThisValOpt, methLambdaBaseValOpt, methLambdaTypars, methLambdaVars, copyOfLambdaBody, methLambdaBodyTy) + + GenMethodForBinding + cenv + cgbuf.mgbuf + eenv + (vspec, + mspecW, + hasWitnessEntry, + true, + access, + ctps, + mtps, + witnessInfos, + curriedArgInfos, + paramInfos, + argTys, + retInfo, + valReprInfo, + methLambdaCtorThisValOpt, + methLambdaBaseValOpt, + methLambdaTypars, + methLambdaVars, + copyOfLambdaBody, + methLambdaBodyTy) | StaticProperty (ilGetterMethSpec, optShadowLocal) when not isStateVar -> let ilAttribs = GenAttrs cenv eenv vspec.Attribs let ilTy = ilGetterMethSpec.FormalReturnType + let ilPropDef = - ILPropertyDef(name = ChopPropertyName ilGetterMethSpec.Name, - attributes = PropertyAttributes.None, - setMethod = None, - getMethod = Some ilGetterMethSpec.MethodRef, - callingConv = ILThisConvention.Static, - propertyType = ilTy, - init = None, - args = [], - customAttrs = mkILCustomAttrs ilAttribs) + ILPropertyDef( + name = ChopPropertyName ilGetterMethSpec.Name, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some ilGetterMethSpec.MethodRef, + callingConv = ILThisConvention.Static, + propertyType = ilTy, + init = None, + args = [], + customAttrs = mkILCustomAttrs ilAttribs + ) cgbuf.mgbuf.AddOrMergePropertyDef(ilGetterMethSpec.MethodRef.DeclaringTypeRef, ilPropDef, m) let ilMethodDef = - let ilCode = CodeGenMethodForExpr cenv cgbuf.mgbuf ([], ilGetterMethSpec.Name, eenv, 0, None, rhsExpr, Return) + let ilCode = + CodeGenMethodForExpr cenv cgbuf.mgbuf ([], ilGetterMethSpec.Name, eenv, 0, None, rhsExpr, Return) + let ilMethodBody = MethodBody.IL(lazy ilCode) - (mkILStaticMethod ([], ilGetterMethSpec.Name, access, [], mkILReturn ilTy, ilMethodBody)).WithSpecialName + + (mkILStaticMethod ([], ilGetterMethSpec.Name, access, [], mkILReturn ilTy, ilMethodBody)) + .WithSpecialName |> AddNonUserCompilerGeneratedAttribs g CountMethodDef() @@ -6229,40 +8255,60 @@ and GenBindingAfterDebugPoint cenv cgbuf eenv bind isStateVar startMarkOpt = | NoShadowLocal -> () | ShadowLocal (startMark, storage) -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call (Normalcall, ilGetterMethSpec, None)) + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (I_call(Normalcall, ilGetterMethSpec, None)) GenSetStorage m cgbuf storage cgbuf.SetMarkToHere startMark - | StaticPropertyWithField (fspec, vref, hasLiteralAttr, ilTyForProperty, ilPropName, fty, ilGetterMethRef, ilSetterMethRef, optShadowLocal) -> + | StaticPropertyWithField (fspec, + vref, + hasLiteralAttr, + ilTyForProperty, + ilPropName, + fty, + ilGetterMethRef, + ilSetterMethRef, + optShadowLocal) -> let mut = vspec.IsMutable - let canTarget(targets, goal: System.AttributeTargets) = + let canTarget (targets, goal: System.AttributeTargets) = match targets with | None -> true - | Some tgts -> 0 <> int(tgts &&& goal) + | Some tgts -> 0 <> int (tgts &&& goal) /// Generate a static field definition... let ilFieldDefs = - let access = ComputeMemberAccess (not hasLiteralAttr || IsHiddenVal eenv.sigToImplRemapInfo vspec) + let access = + ComputeMemberAccess(not hasLiteralAttr || IsHiddenVal eenv.sigToImplRemapInfo vspec) + let ilFieldDef = mkILStaticField (fspec.Name, fty, None, None, access) + let ilFieldDef = match vref.LiteralValue with - | Some konst -> ilFieldDef.WithLiteralDefaultValue( Some (GenFieldInit m konst) ) + | Some konst -> ilFieldDef.WithLiteralDefaultValue(Some(GenFieldInit m konst)) | None -> ilFieldDef let ilFieldDef = let isClassInitializer = (cgbuf.MethodName = ".cctor") - ilFieldDef.WithInitOnly(not (mut || cenv.options.isInteractiveItExpr || not isClassInitializer || hasLiteralAttr)) + + ilFieldDef.WithInitOnly( + not ( + mut + || cenv.options.isInteractiveItExpr + || not isClassInitializer + || hasLiteralAttr + ) + ) let ilAttribs = if not hasLiteralAttr then vspec.Attribs - |> List.filter (fun (Attrib(_, _, _, _, _, targets, _)) -> canTarget(targets, System.AttributeTargets.Field)) + |> List.filter (fun (Attrib (_, _, _, _, _, targets, _)) -> canTarget (targets, System.AttributeTargets.Field)) |> GenAttrs cenv eenv // backing field only gets attributes that target fields else - GenAttrs cenv eenv vspec.Attribs // literals have no property, so preserve all the attributes on the field itself + GenAttrs cenv eenv vspec.Attribs // literals have no property, so preserve all the attributes on the field itself - let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs (ilAttribs @ [ g.DebuggerBrowsableNeverAttribute ])) + let ilFieldDef = + ilFieldDef.With(customAttrs = mkILCustomAttrs (ilAttribs @ [ g.DebuggerBrowsableNeverAttribute ])) [ (fspec.DeclaringTypeRef, ilFieldDef) ] @@ -6276,68 +8322,101 @@ and GenBindingAfterDebugPoint cenv cgbuf eenv bind isStateVar startMarkOpt = if hasLiteralAttr then match optShadowLocal with | NoShadowLocal -> () - | ShadowLocal (startMark, _storage) -> - cgbuf.SetMarkToHere startMark + | ShadowLocal (startMark, _storage) -> cgbuf.SetMarkToHere startMark else let ilAttribs = vspec.Attribs - |> List.filter (fun (Attrib(_, _, _, _, _, targets, _)) -> canTarget(targets, System.AttributeTargets.Property)) + |> List.filter (fun (Attrib (_, _, _, _, _, targets, _)) -> canTarget (targets, System.AttributeTargets.Property)) |> GenAttrs cenv eenv // property only gets attributes that target properties + let ilPropDef = - ILPropertyDef(name=ilPropName, - attributes = PropertyAttributes.None, - setMethod=(if mut || cenv.options.isInteractiveItExpr then Some ilSetterMethRef else None), - getMethod=Some ilGetterMethRef, - callingConv=ILThisConvention.Static, - propertyType=fty, - init=None, - args = [], - customAttrs=mkILCustomAttrs (ilAttribs @ [mkCompilationMappingAttr g (int SourceConstructFlags.Value)])) + ILPropertyDef( + name = ilPropName, + attributes = PropertyAttributes.None, + setMethod = + (if mut || cenv.options.isInteractiveItExpr then + Some ilSetterMethRef + else + None), + getMethod = Some ilGetterMethRef, + callingConv = ILThisConvention.Static, + propertyType = fty, + init = None, + args = [], + customAttrs = mkILCustomAttrs (ilAttribs @ [ mkCompilationMappingAttr g (int SourceConstructFlags.Value) ]) + ) + cgbuf.mgbuf.AddOrMergePropertyDef(ilTypeRefForProperty, ilPropDef, m) let getterMethod = - let body = mkMethodBody(true, [], 2, nonBranchingInstrsToCode [ mkNormalLdsfld fspec ], None, eenv.imports) - mkILStaticMethod([], ilGetterMethRef.Name, access, [], mkILReturn fty, body).WithSpecialName + let body = + mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkNormalLdsfld fspec ], None, eenv.imports) + + mkILStaticMethod( + [], + ilGetterMethRef.Name, + access, + [], + mkILReturn fty, + body + ) + .WithSpecialName cgbuf.mgbuf.AddMethodDef(ilTypeRefForProperty, getterMethod) if mut || cenv.options.isInteractiveItExpr then - let body = mkMethodBody(true, [], 2, nonBranchingInstrsToCode [ mkLdarg0;mkNormalStsfld fspec], None, eenv.imports) + let body = + mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkLdarg0; mkNormalStsfld fspec ], None, eenv.imports) + let setterMethod = - mkILStaticMethod([], ilSetterMethRef.Name, access, [mkILParamNamed("value", fty)], mkILReturn ILType.Void, body).WithSpecialName + mkILStaticMethod( + [], + ilSetterMethRef.Name, + access, + [ mkILParamNamed ("value", fty) ], + mkILReturn ILType.Void, + body + ) + .WithSpecialName + cgbuf.mgbuf.AddMethodDef(ilTypeRefForProperty, setterMethod) GenBindingRhs cenv cgbuf eenv vspec rhsExpr CommitStartScope cgbuf startMarkOpt match optShadowLocal with - | NoShadowLocal -> - EmitSetStaticField cgbuf fspec + | NoShadowLocal -> EmitSetStaticField cgbuf fspec | ShadowLocal (startMark, storage) -> - CG.EmitInstr cgbuf (pop 0) (Push [fty]) AI_dup + CG.EmitInstr cgbuf (pop 0) (Push [ fty ]) AI_dup EmitSetStaticField cgbuf fspec GenSetStorage m cgbuf storage cgbuf.SetMarkToHere startMark | _ -> - let storage = StorageForVal cenv.g m vspec eenv + let storage = StorageForVal m vspec eenv + match storage, rhsExpr with // locals are zero-init, no need to initialize them, except if you are in a loop and the local is mutable. | Local (_, realloc, _), Expr.Const (Const.Zero, _, _) when not realloc && not (eenv.isInLoop && vspec.IsMutable) -> CommitStartScope cgbuf startMarkOpt | _ -> - GetStoreValCtxt cenv cgbuf eenv vspec + GetStoreValCtxt cgbuf eenv vspec GenBindingRhs cenv cgbuf eenv vspec rhsExpr CommitStartScope cgbuf startMarkOpt - GenStoreVal cenv cgbuf eenv vspec.Range vspec + GenStoreVal cgbuf eenv vspec.Range vspec -and GetStoreValCtxt cenv cgbuf eenv (vspec: Val) = +and GetStoreValCtxt cgbuf eenv (vspec: Val) = // Emit the ldarg0 if needed - match StorageForVal cenv.g vspec.Range vspec eenv with + match StorageForVal vspec.Range vspec eenv with | Env (ilCloTy, _, _) -> - let ilCloAddrTy = if ilCloTy.Boxity = ILBoxity.AsValue then ILType.Byref ilCloTy else ilCloTy - CG.EmitInstr cgbuf (pop 0) (Push [ilCloAddrTy]) mkLdarg0 + let ilCloAddrTy = + if ilCloTy.Boxity = ILBoxity.AsValue then + ILType.Byref ilCloTy + else + ilCloTy + + CG.EmitInstr cgbuf (pop 0) (Push [ ilCloAddrTy ]) mkLdarg0 | _ -> () //------------------------------------------------------------------------- @@ -6347,6 +8426,7 @@ and GetStoreValCtxt cenv cgbuf eenv (vspec: Val) = /// Generate encoding P/Invoke and COM marshalling information and GenMarshal cenv attribs = let g = cenv.g + let otherAttribs = // For IlReflect backend, we rely on Reflection.Emit API to emit the pseudo-custom attributes // correctly, so we do not filter them out. @@ -6354,11 +8434,13 @@ and GenMarshal cenv attribs = match cenv.options.ilxBackend with | IlReflectBackend -> attribs | IlWriteBackend -> - attribs |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_MarshalAsAttribute >> not) + attribs + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_MarshalAsAttribute >> not) match TryFindFSharpAttributeOpt g g.attrib_MarshalAsAttribute attribs with - | Some (Attrib(_, _, [ AttribInt32Arg unmanagedType ], namedArgs, _, _, m)) -> + | Some (Attrib (_, _, [ AttribInt32Arg unmanagedType ], namedArgs, _, _, m)) -> let decoder = AttributeDecoder namedArgs + let rec decodeUnmanagedType unmanagedType = // enumeration values for System.Runtime.InteropServices.UnmanagedType taken from mscorlib.il match unmanagedType with @@ -6380,7 +8462,7 @@ and GenMarshal cenv attribs = | 0x14 -> ILNativeType.LPSTR | 0x15 -> ILNativeType.LPWSTR | 0x16 -> ILNativeType.LPTSTR - | 0x17 -> ILNativeType.FixedSysString (decoder.FindInt32 "SizeConst" 0x0) + | 0x17 -> ILNativeType.FixedSysString(decoder.FindInt32 "SizeConst" 0x0) | 0x19 -> ILNativeType.IUnknown | 0x1A -> ILNativeType.IDispatch | 0x1B -> ILNativeType.Struct @@ -6431,13 +8513,22 @@ and GenMarshal cenv attribs = | 0x48 -> ILNativeVariant.CLSID | 0x14 -> ILNativeVariant.Int64 | _ -> ILNativeVariant.Empty + let safeArrayUserDefinedSubType = // the argument is a System.Type obj, but it's written to MD as a UTF8 string match decoder.FindTypeName "SafeArrayUserDefinedSubType" "" with | "" -> None - | res -> if (safeArraySubType = ILNativeVariant.IDispatch) || (safeArraySubType = ILNativeVariant.IUnknown) then Some res else None + | res -> + if + (safeArraySubType = ILNativeVariant.IDispatch) + || (safeArraySubType = ILNativeVariant.IUnknown) + then + Some res + else + None + ILNativeType.SafeArray(safeArraySubType, safeArrayUserDefinedSubType) - | 0x1E -> ILNativeType.FixedArray (decoder.FindInt32 "SizeConst" 0x0) + | 0x1E -> ILNativeType.FixedArray(decoder.FindInt32 "SizeConst" 0x0) | 0x1F -> ILNativeType.Int | 0x20 -> ILNativeType.UInt | 0x22 -> ILNativeType.ByValStr @@ -6447,26 +8538,28 @@ and GenMarshal cenv attribs = | 0x26 -> ILNativeType.Method | 0x28 -> ILNativeType.AsAny | 0x2A -> - let sizeParamIndex = + let sizeParamIndex = match decoder.FindInt16 "SizeParamIndex" -1s with | -1s -> None - | res -> Some (int res, None) - let arraySubType = + | res -> Some(int res, None) + + let arraySubType = match decoder.FindInt32 "ArraySubType" -1 with | -1 -> None - | res -> Some (decodeUnmanagedType res) - ILNativeType.Array(arraySubType, sizeParamIndex) + | res -> Some(decodeUnmanagedType res) + + ILNativeType.Array(arraySubType, sizeParamIndex) | 0x2B -> ILNativeType.LPSTRUCT - | 0x2C -> - error(Error(FSComp.SR.ilCustomMarshallersCannotBeUsedInFSharp(), m)) - (* ILNativeType.Custom of bytes * string * string * bytes (* GUID, nativeTypeName, custMarshallerName, cookieString *) *) - //ILNativeType.Error + | 0x2C -> error (Error(FSComp.SR.ilCustomMarshallersCannotBeUsedInFSharp (), m)) + (* ILNativeType.Custom of bytes * string * string * bytes (* GUID, nativeTypeName, custMarshallerName, cookieString *) *) + //ILNativeType.Error | 0x2D -> ILNativeType.Error | 0x30 -> ILNativeType.LPUTF8STR | _ -> ILNativeType.Empty + Some(decodeUnmanagedType unmanagedType), otherAttribs - | Some (Attrib(_, _, _, _, _, _, m)) -> - errorR(Error(FSComp.SR.ilMarshalAsAttributeCannotBeDecoded(), m)) + | Some (Attrib (_, _, _, _, _, _, m)) -> + errorR (Error(FSComp.SR.ilMarshalAsAttributeCannotBeDecoded (), m)) None, attribs | _ -> // No MarshalAs detected @@ -6475,12 +8568,18 @@ and GenMarshal cenv attribs = /// Generate special attributes on an IL parameter and GenParamAttribs cenv paramTy attribs = let g = cenv.g - let inFlag = HasFSharpAttribute g g.attrib_InAttribute attribs || isInByrefTy g paramTy - let outFlag = HasFSharpAttribute g g.attrib_OutAttribute attribs || isOutByrefTy g paramTy + + let inFlag = + HasFSharpAttribute g g.attrib_InAttribute attribs || isInByrefTy g paramTy + + let outFlag = + HasFSharpAttribute g g.attrib_OutAttribute attribs || isOutByrefTy g paramTy + let optionalFlag = HasFSharpAttributeOpt g g.attrib_OptionalAttribute attribs - let defaultValue = TryFindFSharpAttributeOpt g g.attrib_DefaultParameterValueAttribute attribs - |> Option.bind OptionalArgInfo.FieldInitForDefaultParameterValueAttrib + let defaultValue = + TryFindFSharpAttributeOpt g g.attrib_DefaultParameterValueAttribute attribs + |> Option.bind OptionalArgInfo.FieldInitForDefaultParameterValueAttrib // Return the filtered attributes. Do not generate In, Out, Optional or DefaultParameterValue attributes // as custom attributes in the code - they are implicit from the IL bits for these let attribs = @@ -6494,7 +8593,16 @@ and GenParamAttribs cenv paramTy attribs = inFlag, outFlag, optionalFlag, defaultValue, Marshal, attribs /// Generate IL parameters -and GenParams (cenv: cenv) eenv m (mspec: ILMethodSpec) witnessInfos (argInfos: ArgReprInfo list) methArgTys (implValsOpt: Val list option) = +and GenParams + (cenv: cenv) + eenv + m + (mspec: ILMethodSpec) + witnessInfos + (argInfos: ArgReprInfo list) + methArgTys + (implValsOpt: Val list option) + = let g = cenv.g let ilWitnessParams = GenWitnessParams cenv eenv m witnessInfos let ilArgTys = mspec.FormalArgTypes |> List.skip witnessInfos.Length @@ -6508,23 +8616,22 @@ and GenParams (cenv: cenv) eenv m (mspec: ILMethodSpec) witnessInfos (argInfos: let ilArgTysAndInfoAndVals = match implValsOpt with - | Some implVals when (implVals.Length = ilArgTys.Length) -> - List.map2 (fun x y -> x, Some y) ilArgTysAndInfos implVals - | _ -> - List.map (fun x -> x, None) ilArgTysAndInfos + | Some implVals when (implVals.Length = ilArgTys.Length) -> List.map2 (fun x y -> x, Some y) ilArgTysAndInfos implVals + | _ -> List.map (fun x -> x, None) ilArgTysAndInfos let ilParams, _ = (Set.empty, List.zip methArgTys ilArgTysAndInfoAndVals) ||> List.mapFold (fun takenNames (methodArgTy, ((ilArgTy, topArgInfo), implValOpt)) -> - let inFlag, outFlag, optionalFlag, defaultParamValue, Marshal, attribs = GenParamAttribs cenv methodArgTy topArgInfo.Attribs + let inFlag, outFlag, optionalFlag, defaultParamValue, Marshal, attribs = + GenParamAttribs cenv methodArgTy topArgInfo.Attribs let idOpt = match topArgInfo.Name with | Some v -> Some v | None -> - match implValOpt with - | Some v -> Some v.Id - | None -> None + match implValOpt with + | Some v -> Some v.Id + | None -> None let nmOpt, takenNames = match idOpt with @@ -6532,32 +8639,33 @@ and GenParams (cenv: cenv) eenv m (mspec: ILMethodSpec) witnessInfos (argInfos: let nm = if takenNames.Contains(id.idText) then // Ensure that we have an g.CompilerGlobalState - assert(g.CompilerGlobalState |> Option.isSome) - g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName (id.idText, id.idRange) + assert (g.CompilerGlobalState |> Option.isSome) + g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName(id.idText, id.idRange) else id.idText - Some nm, takenNames.Add(nm) - | None -> - None, takenNames + Some nm, takenNames.Add(nm) + | None -> None, takenNames let ilAttribs = GenAttrs cenv eenv attribs let ilAttribs = match GenReadOnlyAttributeIfNecessary g methodArgTy with - | Some attr -> ilAttribs @ [attr] + | Some attr -> ilAttribs @ [ attr ] | None -> ilAttribs - let param : ILParameter = - { Name = nmOpt - Type = ilArgTy - Default = defaultParamValue - Marshal = Marshal - IsIn = inFlag - IsOut = outFlag - IsOptional = optionalFlag - CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs ilAttribs) - MetadataIndex = NoMetadataIdx } + let param: ILParameter = + { + Name = nmOpt + Type = ilArgTy + Default = defaultParamValue + Marshal = Marshal + IsIn = inFlag + IsOut = outFlag + IsOptional = optionalFlag + CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs ilAttribs) + MetadataIndex = NoMetadataIdx + } param, takenNames) @@ -6572,30 +8680,49 @@ and GenReturnInfo cenv eenv returnTy ilRetTy (retInfo: ArgReprInfo) : ILReturn = match returnTy with | Some retTy -> match GenReadOnlyAttributeIfNecessary cenv.g retTy with - | Some attr -> ilAttribs @ [attr] + | Some attr -> ilAttribs @ [ attr ] | None -> ilAttribs - | _ -> - ilAttribs + | _ -> ilAttribs let ilAttrs = mkILCustomAttrs ilAttribs - { Type=ilRetTy - Marshal=marshal - CustomAttrsStored= storeILCustomAttrs ilAttrs - MetadataIndex = NoMetadataIdx } + + { + Type = ilRetTy + Marshal = marshal + CustomAttrsStored = storeILCustomAttrs ilAttrs + MetadataIndex = NoMetadataIdx + } /// Generate an IL property for a member and GenPropertyForMethodDef compileAsInstance tref mdef (v: Val) (memberInfo: ValMemberInfo) ilArgTys ilPropTy ilAttrs compiledName = - let name = match compiledName with | Some n -> n | _ -> v.PropertyName in (* chop "get_" *) - - ILPropertyDef(name = name, - attributes = PropertyAttributes.None, - setMethod = (if memberInfo.MemberFlags.MemberKind= SynMemberKind.PropertySet then Some(mkRefToILMethod(tref, mdef)) else None), - getMethod = (if memberInfo.MemberFlags.MemberKind= SynMemberKind.PropertyGet then Some(mkRefToILMethod(tref, mdef)) else None), - callingConv = (if compileAsInstance then ILThisConvention.Instance else ILThisConvention.Static), - propertyType = ilPropTy, - init = None, - args = ilArgTys, - customAttrs = ilAttrs) + let name = + match compiledName with + | Some n -> n + | _ -> v.PropertyName in (* chop "get_" *) + + ILPropertyDef( + name = name, + attributes = PropertyAttributes.None, + setMethod = + (if memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertySet then + Some(mkRefToILMethod (tref, mdef)) + else + None), + getMethod = + (if memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGet then + Some(mkRefToILMethod (tref, mdef)) + else + None), + callingConv = + (if compileAsInstance then + ILThisConvention.Instance + else + ILThisConvention.Static), + propertyType = ilPropTy, + init = None, + args = ilArgTys, + customAttrs = ilAttrs + ) /// Generate an ILEventDef for a [] member and GenEventForProperty cenv eenvForMeth (mspec: ILMethodSpec) (v: Val) ilAttrsThatGoOnPrimaryItem m returnTy = @@ -6603,43 +8730,53 @@ and GenEventForProperty cenv eenvForMeth (mspec: ILMethodSpec) (v: Val) ilAttrsT let delegateTy = FindDelegateTypeOfPropertyEvent cenv.g cenv.amap evname m returnTy let ilDelegateTy = GenType cenv m eenvForMeth.tyenv delegateTy let ilThisTy = mspec.DeclaringType - let addMethRef = mkILMethRef (ilThisTy.TypeRef, mspec.CallingConv, "add_" + evname, 0, [ilDelegateTy], ILType.Void) - let removeMethRef = mkILMethRef (ilThisTy.TypeRef, mspec.CallingConv, "remove_" + evname, 0, [ilDelegateTy], ILType.Void) - ILEventDef(eventType = Some ilDelegateTy, - name= evname, - attributes = EventAttributes.None, - addMethod = addMethRef, - removeMethod = removeMethRef, - fireMethod= None, - otherMethods= [], - customAttrs = mkILCustomAttrs ilAttrsThatGoOnPrimaryItem) + + let addMethRef = + mkILMethRef (ilThisTy.TypeRef, mspec.CallingConv, "add_" + evname, 0, [ ilDelegateTy ], ILType.Void) + + let removeMethRef = + mkILMethRef (ilThisTy.TypeRef, mspec.CallingConv, "remove_" + evname, 0, [ ilDelegateTy ], ILType.Void) + + ILEventDef( + eventType = Some ilDelegateTy, + name = evname, + attributes = EventAttributes.None, + addMethod = addMethRef, + removeMethod = removeMethRef, + fireMethod = None, + otherMethods = [], + customAttrs = mkILCustomAttrs ilAttrsThatGoOnPrimaryItem + ) and ComputeMethodImplNameFixupForMemberBinding cenv (v: Val) = - if isNil v.ImplementedSlotSigs then - None - else - let slotsig = v.ImplementedSlotSigs |> List.last - let useMethodImpl = ComputeUseMethodImpl cenv.g v - let nameOfOverridingMethod = GenNameOfOverridingMethod cenv (useMethodImpl, slotsig) - Some nameOfOverridingMethod + if isNil v.ImplementedSlotSigs then + None + else + let slotsig = v.ImplementedSlotSigs |> List.last + let useMethodImpl = ComputeUseMethodImpl cenv.g v + let nameOfOverridingMethod = GenNameOfOverridingMethod cenv (useMethodImpl, slotsig) + Some nameOfOverridingMethod and ComputeFlagFixupsForMemberBinding cenv (v: Val) = - [ let useMethodImpl = ComputeUseMethodImpl cenv.g v + [ + let useMethodImpl = ComputeUseMethodImpl cenv.g v - if useMethodImpl then - fixupMethodImplFlags - else - fixupVirtualSlotFlags + if useMethodImpl then + fixupMethodImplFlags + else + fixupVirtualSlotFlags - match ComputeMethodImplNameFixupForMemberBinding cenv v with - | Some nm -> renameMethodDef nm - | None -> () ] + match ComputeMethodImplNameFixupForMemberBinding cenv v with + | Some nm -> renameMethodDef nm + | None -> () + ] and ComputeMethodImplAttribs cenv (_v: Val) attrs = let g = cenv.g + let implflags = match TryFindFSharpAttribute g g.attrib_MethodImplAttribute attrs with - | Some (Attrib(_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags + | Some (Attrib (_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags | _ -> 0x0 let hasPreserveSigAttr = @@ -6664,25 +8801,49 @@ and ComputeMethodImplAttribs cenv (_v: Val) attrs = hasPreserveSigImplFlag, hasSynchronizedImplFlag, hasNoInliningImplFlag, hasAggressiveInliningImplFlag, attrs and GenMethodForBinding - cenv mgbuf eenv - (v: Val, mspec, hasWitnessEntry, generateWitnessArgs, access, ctps, mtps, witnessInfos, curriedArgInfos, paramInfos, argTys, retInfo, topValInfo, - ctorThisValOpt, baseValOpt, methLambdaTypars, methLambdaVars, methLambdaBody, returnTy) = + cenv + mgbuf + eenv + (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 // If a method has a witness-passing version of the code, then suppress // the generation of any witness in the non-witness passing version of the code - let eenv = { eenv with suppressWitnesses = hasWitnessEntry && not generateWitnessArgs } + let eenv = + { eenv with + suppressWitnesses = hasWitnessEntry && not generateWitnessArgs + } let selfMethodVars, nonSelfMethodVars, compileAsInstance = match v.MemberInfo with | Some _ when ValSpecIsCompiledAsInstance g v -> match methLambdaVars with - | [] -> error(InternalError("Internal error: empty argument list for instance method", v.Range)) - | h :: t -> [h], t, true + | [] -> error (InternalError("Internal error: empty argument list for instance method", v.Range)) + | h :: t -> [ h ], t, true | _ -> [], methLambdaVars, false - let nonUnitNonSelfMethodVars, body = BindUnitVars cenv.g (nonSelfMethodVars, paramInfos, methLambdaBody) + let nonUnitNonSelfMethodVars, body = + BindUnitVars cenv.g (nonSelfMethodVars, paramInfos, methLambdaBody) let eenv = bindBaseOrThisVarOpt cenv eenv ctorThisValOpt let eenv = bindBaseOrThisVarOpt cenv eenv baseValOpt @@ -6710,16 +8871,46 @@ and GenMethodForBinding let eenvForMeth = eenvUnderMethLambdaTypars let numArgsUsed = 0 let numArgsUsed = numArgsUsed + (if isCtor then 1 else 0) - let eenvForMeth = eenvForMeth |> AddStorageForLocalVals cenv.g (selfMethodVars |> List.mapi (fun i v -> (v, Arg (numArgsUsed+i)))) + + let eenvForMeth = + eenvForMeth + |> AddStorageForLocalVals cenv.g (selfMethodVars |> List.mapi (fun i v -> (v, Arg(numArgsUsed + i)))) + let numArgsUsed = numArgsUsed + selfMethodVars.Length - let eenvForMeth = eenvForMeth |> AddStorageForLocalWitnesses (methLambdaWitnessInfos |> List.mapi (fun i w -> (w, Arg (numArgsUsed+i)))) + + let eenvForMeth = + eenvForMeth + |> AddStorageForLocalWitnesses(methLambdaWitnessInfos |> List.mapi (fun i w -> (w, Arg(numArgsUsed + i)))) + let numArgsUsed = numArgsUsed + methLambdaWitnessInfos.Length - let eenvForMeth = eenvForMeth |> AddStorageForLocalVals cenv.g (List.mapi (fun i v -> (v, Arg (numArgsUsed+i))) nonUnitNonSelfMethodVars) - let eenvForMeth = if eenvForMeth.initLocals && HasFSharpAttribute g g.attrib_SkipLocalsInitAttribute v.Attribs then { eenvForMeth with initLocals = false } else eenvForMeth + + let eenvForMeth = + eenvForMeth + |> AddStorageForLocalVals cenv.g (List.mapi (fun i v -> (v, Arg(numArgsUsed + i))) nonUnitNonSelfMethodVars) + + let eenvForMeth = + if + eenvForMeth.initLocals + && HasFSharpAttribute g g.attrib_SkipLocalsInitAttribute v.Attribs + then + { eenvForMeth with initLocals = false } + else + eenvForMeth + eenvForMeth let tailCallInfo = - [(mkLocalValRef v, BranchCallMethod (topValInfo.AritiesOfArgs, curriedArgInfos, methLambdaTypars, selfMethodVars.Length, methLambdaWitnessInfos.Length, nonUnitNonSelfMethodVars.Length))] + [ + (mkLocalValRef v, + BranchCallMethod( + valReprInfo.AritiesOfArgs, + curriedArgInfos, + methLambdaTypars, + selfMethodVars.Length, + methLambdaWitnessInfos.Length, + nonUnitNonSelfMethodVars.Length + )) + ] // Discard the result on a 'void' return type. For a constructor just return 'void' let sequel = @@ -6730,34 +8921,44 @@ and GenMethodForBinding // Now generate the code. let hasPreserveSigNamedArg, ilMethodBody, hasDllImport = match TryFindFSharpAttributeOpt g g.attrib_DllImportAttribute v.Attribs with - | Some (Attrib(_, _, [ AttribStringArg dll ], namedArgs, _, _, m)) -> - if not (isNil methLambdaTypars) then error(Error(FSComp.SR.ilSignatureForExternalFunctionContainsTypeParameters(), m)) - let hasPreserveSigNamedArg, mbody = GenPInvokeMethod (v.CompiledName g.CompilerGlobalState, dll, namedArgs) + | Some (Attrib (_, _, [ AttribStringArg dll ], namedArgs, _, _, m)) -> + if not (isNil methLambdaTypars) then + error (Error(FSComp.SR.ilSignatureForExternalFunctionContainsTypeParameters (), m)) + + let hasPreserveSigNamedArg, mbody = + GenPInvokeMethod(v.CompiledName g.CompilerGlobalState, dll, namedArgs) + hasPreserveSigNamedArg, mbody, true - | Some (Attrib(_, _, _, _, _, _, m)) -> - error(Error(FSComp.SR.ilDllImportAttributeCouldNotBeDecoded(), m)) + | Some (Attrib (_, _, _, _, _, _, m)) -> error (Error(FSComp.SR.ilDllImportAttributeCouldNotBeDecoded (), m)) | _ -> // Replace the body of ValInline.PseudoVal "must inline" methods with a 'throw' // For witness-passing methods, don't do this if `isLegacy` flag specified // on the attribute. Older compilers let bodyExpr = - let attr = TryFindFSharpBoolAttributeAssumeFalse cenv.g cenv.g.attrib_NoDynamicInvocationAttribute v.Attribs - if (not generateWitnessArgs && attr.IsSome) || - (generateWitnessArgs && attr = Some false) then - let exnArg = mkString cenv.g m (FSComp.SR.ilDynamicInvocationNotSupported(v.CompiledName g.CompilerGlobalState)) + let attr = + TryFindFSharpBoolAttributeAssumeFalse cenv.g cenv.g.attrib_NoDynamicInvocationAttribute v.Attribs + + if + (not generateWitnessArgs && attr.IsSome) + || (generateWitnessArgs && attr = Some false) + then + let exnArg = + mkString cenv.g m (FSComp.SR.ilDynamicInvocationNotSupported (v.CompiledName g.CompilerGlobalState)) + let exnExpr = MakeNotSupportedExnExpr cenv eenv (exnArg, m) mkThrow m returnTy exnExpr else body let selfValOpt = - match selfMethodVars with - | [h] -> Some h + match selfMethodVars with + | [ h ] -> Some h | _ -> None - let ilCodeLazy = CodeGenMethodForExpr cenv mgbuf (tailCallInfo, mspec.Name, eenvForMeth, 0, selfValOpt, bodyExpr, sequel) + let ilCodeLazy = + CodeGenMethodForExpr cenv mgbuf (tailCallInfo, mspec.Name, eenvForMeth, 0, selfValOpt, bodyExpr, sequel) // This is the main code generation for most methods false, MethodBody.IL(notlazy ilCodeLazy), false @@ -6765,64 +8966,92 @@ and GenMethodForBinding // Do not generate DllImport attributes into the code - they are implicit from the P/Invoke let attrs = v.Attribs - |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_DllImportAttribute >> not) - |> List.filter (IsMatchingFSharpAttribute g g.attrib_CompiledNameAttribute >> not) + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_DllImportAttribute >> not) + |> List.filter (IsMatchingFSharpAttribute g g.attrib_CompiledNameAttribute >> not) let attrsAppliedToGetterOrSetter, attrs = - List.partition (fun (Attrib(_, _, _, _, isAppliedToGetterOrSetter, _, _)) -> isAppliedToGetterOrSetter) attrs + List.partition (fun (Attrib (_, _, _, _, isAppliedToGetterOrSetter, _, _)) -> isAppliedToGetterOrSetter) attrs let sourceNameAttribs, compiledName = - match v.Attribs |> List.tryFind (IsMatchingFSharpAttribute g g.attrib_CompiledNameAttribute) with - | Some (Attrib(_, _, [ AttribStringArg b ], _, _, _, _)) -> [ mkCompilationSourceNameAttr g v.LogicalName ], Some b + match + v.Attribs + |> List.tryFind (IsMatchingFSharpAttribute g g.attrib_CompiledNameAttribute) + with + | Some (Attrib (_, _, [ AttribStringArg b ], _, _, _, _)) -> [ mkCompilationSourceNameAttr g v.LogicalName ], Some b | _ -> [], None // check if the hasPreserveSigNamedArg and hasSynchronizedImplFlag implementation flags have been specified - let hasPreserveSigImplFlag, hasSynchronizedImplFlag, hasNoInliningFlag, hasAggressiveInliningImplFlag, attrs = ComputeMethodImplAttribs cenv v attrs + let hasPreserveSigImplFlag, hasSynchronizedImplFlag, hasNoInliningFlag, hasAggressiveInliningImplFlag, attrs = + ComputeMethodImplAttribs cenv v attrs - let securityAttributes, attrs = attrs |> List.partition (fun a -> IsSecurityAttribute g cenv.amap cenv.casApplied a m) + let securityAttributes, attrs = + attrs + |> List.partition (fun a -> IsSecurityAttribute g cenv.amap cenv.casApplied a m) let permissionSets = CreatePermissionSets cenv eenv securityAttributes - let secDecls = if List.isEmpty securityAttributes then emptyILSecurityDecls else mkILSecurityDecls permissionSets + let secDecls = + if List.isEmpty securityAttributes then + emptyILSecurityDecls + else + mkILSecurityDecls permissionSets // Do not push the attributes to the method for events and properties - let ilAttrsCompilerGenerated = if v.IsCompilerGenerated then [ g.CompilerGeneratedAttribute ] else [] + let ilAttrsCompilerGenerated = + if v.IsCompilerGenerated then + [ g.CompilerGeneratedAttribute ] + else + [] let ilAttrsThatGoOnPrimaryItem = - [ yield! GenAttrs cenv eenv attrs - yield! GenCompilationArgumentCountsAttr cenv v - - match v.MemberInfo with - | Some memberInfo when - memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGet || - memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertySet || - memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGetSet -> - match GenReadOnlyAttributeIfNecessary g returnTy with Some ilAttr -> ilAttr | _ -> () - | _ -> () ] + [ + yield! GenAttrs cenv eenv attrs + yield! GenCompilationArgumentCountsAttr cenv v + + match v.MemberInfo with + | Some memberInfo when + memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGet + || memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertySet + || memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGetSet + -> + match GenReadOnlyAttributeIfNecessary g returnTy with + | Some ilAttr -> ilAttr + | _ -> () + | _ -> () + ] let ilTypars = GenGenericParams cenv eenvUnderMethLambdaTypars methLambdaTypars - let ilParams = GenParams cenv eenvUnderMethTypeTypars m mspec witnessInfos paramInfos argTys (Some nonUnitNonSelfMethodVars) - let ilReturn = GenReturnInfo cenv eenvUnderMethTypeTypars (Some returnTy) mspec.FormalReturnType retInfo + + let ilParams = + GenParams cenv eenvUnderMethTypeTypars m mspec witnessInfos paramInfos argTys (Some nonUnitNonSelfMethodVars) + + let ilReturn = + GenReturnInfo cenv eenvUnderMethTypeTypars (Some returnTy) mspec.FormalReturnType retInfo + let methName = mspec.Name let tref = mspec.MethodRef.DeclaringTypeRef match v.MemberInfo with // don't generate unimplemented abstracts | Some memberInfo when memberInfo.MemberFlags.IsDispatchSlot && not memberInfo.IsImplemented -> - // skipping unimplemented abstract method - () + // skipping unimplemented abstract method + () // compiling CLIEvent properties - | Some memberInfo - when not v.IsExtensionMember && - (match memberInfo.MemberFlags.MemberKind with - | SynMemberKind.PropertySet | SynMemberKind.PropertyGet -> CompileAsEvent cenv.g v.Attribs - | _ -> false) -> + | Some memberInfo when + not v.IsExtensionMember + && (match memberInfo.MemberFlags.MemberKind with + | SynMemberKind.PropertySet + | SynMemberKind.PropertyGet -> CompileAsEvent cenv.g v.Attribs + | _ -> false) + -> let useMethodImpl = - if compileAsInstance && - ((memberInfo.MemberFlags.IsDispatchSlot && memberInfo.IsImplemented) || - memberInfo.MemberFlags.IsOverrideOrExplicitImpl) then + if + compileAsInstance + && ((memberInfo.MemberFlags.IsDispatchSlot && memberInfo.IsImplemented) + || memberInfo.MemberFlags.IsOverrideOrExplicitImpl) + then let useMethodImpl = ComputeUseMethodImpl cenv.g v @@ -6841,175 +9070,245 @@ and GenMethodForBinding // Instead emit the pseudo-property as an event. // on't do this if it's a private method impl. if not useMethodImpl then - let edef = GenEventForProperty cenv eenvForMeth mspec v ilAttrsThatGoOnPrimaryItem m returnTy + let edef = + GenEventForProperty cenv eenvForMeth mspec v ilAttrsThatGoOnPrimaryItem m returnTy + mgbuf.AddEventDef(tref, edef) | _ -> - let mdef = - match v.MemberInfo with - | Some memberInfo when not v.IsExtensionMember -> - - let ilMethTypars = ilTypars |> List.skip mspec.DeclaringType.GenericArgs.Length - if memberInfo.MemberFlags.MemberKind = SynMemberKind.Constructor then - assert (isNil ilMethTypars) - let mdef = mkILCtor (access, ilParams, ilMethodBody) - let mdef = mdef.With(customAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) - mdef - - elif memberInfo.MemberFlags.MemberKind = SynMemberKind.ClassConstructor then - assert (isNil ilMethTypars) - let mdef = mkILClassCtor ilMethodBody - let mdef = mdef.With(customAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) - mdef - - // Generate virtual/override methods + method-impl information if needed - else - let mdef = - if not compileAsInstance then - mkILStaticMethod (ilMethTypars, mspec.Name, access, ilParams, ilReturn, ilMethodBody) - - elif (memberInfo.MemberFlags.IsDispatchSlot && memberInfo.IsImplemented) || - memberInfo.MemberFlags.IsOverrideOrExplicitImpl then - - let flagFixups = ComputeFlagFixupsForMemberBinding cenv v - let mdef = mkILGenericVirtualMethod (mspec.Name, ILMemberAccess.Public, ilMethTypars, ilParams, ilReturn, ilMethodBody) - let mdef = List.fold (fun mdef f -> f mdef) mdef flagFixups - - // fixup can potentially change name of reflected definition that was already recorded - patch it if necessary - mgbuf.ReplaceNameOfReflectedDefinition(v, mdef.Name) - mdef - else - mkILGenericNonVirtualMethod (mspec.Name, access, ilMethTypars, ilParams, ilReturn, ilMethodBody) - - let isAbstract = - memberInfo.MemberFlags.IsDispatchSlot && - let tcref = v.MemberApparentEntity - not tcref.Deref.IsFSharpDelegateTycon - - let mdef = - if mdef.IsVirtual then - mdef.WithFinal(memberInfo.MemberFlags.IsFinal).WithAbstract(isAbstract) - else mdef - - match memberInfo.MemberFlags.MemberKind with - - | SynMemberKind.PropertySet | SynMemberKind.PropertyGet -> - if not (isNil ilMethTypars) then - error(InternalError("A property may not be more generic than the enclosing type - constrain the polymorphism in the expression", v.Range)) - - // Check if we're compiling the property as a .NET event - assert not (CompileAsEvent cenv.g v.Attribs) - - // Emit the property, but not if its a private method impl - if mdef.Access <> ILMemberAccess.Private then - let vtyp = ReturnTypeOfPropertyVal g v - let ilPropTy = GenType cenv m eenvUnderMethTypeTypars.tyenv vtyp - let ilPropTy = GenReadOnlyModReqIfNecessary g vtyp ilPropTy - let ilArgTys = v |> ArgInfosOfPropertyVal g |> List.map fst |> GenTypes cenv m eenvUnderMethTypeTypars.tyenv - let ilPropDef = GenPropertyForMethodDef compileAsInstance tref mdef v memberInfo ilArgTys ilPropTy (mkILCustomAttrs ilAttrsThatGoOnPrimaryItem) compiledName - mgbuf.AddOrMergePropertyDef(tref, ilPropDef, m) - - // Add the special name flag for all properties - let mdef = mdef.WithSpecialName.With(customAttrs= mkILCustomAttrs ((GenAttrs cenv eenv attrsAppliedToGetterOrSetter) @ sourceNameAttribs @ ilAttrsCompilerGenerated)) - mdef - - | _ -> - let mdef = mdef.With(customAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) - mdef + let mdef = + match v.MemberInfo with + | Some memberInfo when not v.IsExtensionMember -> - | _ -> - let mdef = mkILStaticMethod (ilTypars, methName, access, ilParams, ilReturn, ilMethodBody) - - // For extension properties, also emit attrsAppliedToGetterOrSetter on the getter or setter method - let ilAttrs = - match v.MemberInfo with - | Some memberInfo when v.IsExtensionMember -> - match memberInfo.MemberFlags.MemberKind with - | SynMemberKind.PropertySet | SynMemberKind.PropertyGet -> ilAttrsThatGoOnPrimaryItem @ GenAttrs cenv eenv attrsAppliedToGetterOrSetter - | _ -> ilAttrsThatGoOnPrimaryItem - | _ -> ilAttrsThatGoOnPrimaryItem - - let ilCustomAttrs = mkILCustomAttrs (ilAttrs @ sourceNameAttribs @ ilAttrsCompilerGenerated) - let mdef = mdef.With(customAttrs= ilCustomAttrs) - mdef + let ilMethTypars = ilTypars |> List.skip mspec.DeclaringType.GenericArgs.Length - // Does the function have an explicit [] attribute? - let isExplicitEntryPoint = HasFSharpAttribute g g.attrib_EntryPointAttribute attrs - - let mdef = - mdef - .WithSecurity(not (List.isEmpty securityAttributes)) - .WithPInvoke(hasDllImport) - .WithPreserveSig(hasPreserveSigImplFlag || hasPreserveSigNamedArg) - .WithSynchronized(hasSynchronizedImplFlag) - .WithNoInlining(hasNoInliningFlag) - .WithAggressiveInlining(hasAggressiveInliningImplFlag) - .With(isEntryPoint=isExplicitEntryPoint, securityDecls=secDecls) - - let mdef = - if // operator names - mdef.Name.StartsWithOrdinal("op_") || - // active pattern names - mdef.Name.StartsWithOrdinal("|") || - // event add/remove method - v.val_flags.IsGeneratedEventVal then - mdef.WithSpecialName - else + if memberInfo.MemberFlags.MemberKind = SynMemberKind.Constructor then + assert (isNil ilMethTypars) + let mdef = mkILCtor (access, ilParams, ilMethodBody) + + let mdef = + mdef.With(customAttrs = mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) + + mdef + + elif memberInfo.MemberFlags.MemberKind = SynMemberKind.ClassConstructor then + assert (isNil ilMethTypars) + let mdef = mkILClassCtor ilMethodBody + + let mdef = + mdef.With(customAttrs = mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) + + mdef + + // Generate virtual/override methods + method-impl information if needed + else + let mdef = + if not compileAsInstance then + mkILStaticMethod (ilMethTypars, mspec.Name, access, ilParams, ilReturn, ilMethodBody) + + elif + (memberInfo.MemberFlags.IsDispatchSlot && memberInfo.IsImplemented) + || memberInfo.MemberFlags.IsOverrideOrExplicitImpl + then + + let flagFixups = ComputeFlagFixupsForMemberBinding cenv v + + let mdef = + mkILGenericVirtualMethod (mspec.Name, ILMemberAccess.Public, ilMethTypars, ilParams, ilReturn, ilMethodBody) + + let mdef = List.fold (fun mdef f -> f mdef) mdef flagFixups + + // fixup can potentially change name of reflected definition that was already recorded - patch it if necessary + mgbuf.ReplaceNameOfReflectedDefinition(v, mdef.Name) + mdef + else + mkILGenericNonVirtualMethod (mspec.Name, access, ilMethTypars, ilParams, ilReturn, ilMethodBody) + + let isAbstract = + memberInfo.MemberFlags.IsDispatchSlot + && let tcref = v.MemberApparentEntity in + not tcref.Deref.IsFSharpDelegateTycon + + let mdef = + if mdef.IsVirtual then + mdef.WithFinal(memberInfo.MemberFlags.IsFinal).WithAbstract(isAbstract) + else + mdef + + match memberInfo.MemberFlags.MemberKind with + + | SynMemberKind.PropertySet + | SynMemberKind.PropertyGet -> + if not (isNil ilMethTypars) then + error ( + InternalError( + "A property may not be more generic than the enclosing type - constrain the polymorphism in the expression", + v.Range + ) + ) + + // Check if we're compiling the property as a .NET event + assert not (CompileAsEvent cenv.g v.Attribs) + + // Emit the property, but not if it's a private method impl + if mdef.Access <> ILMemberAccess.Private then + let vtyp = ReturnTypeOfPropertyVal g v + let ilPropTy = GenType cenv m eenvUnderMethTypeTypars.tyenv vtyp + let ilPropTy = GenReadOnlyModReqIfNecessary g vtyp ilPropTy + + let ilArgTys = + v + |> ArgInfosOfPropertyVal g + |> List.map fst + |> GenTypes cenv m eenvUnderMethTypeTypars.tyenv + + let ilPropDef = + GenPropertyForMethodDef + compileAsInstance + tref + mdef + v + memberInfo + ilArgTys + ilPropTy + (mkILCustomAttrs ilAttrsThatGoOnPrimaryItem) + compiledName + + mgbuf.AddOrMergePropertyDef(tref, ilPropDef, m) + + // Add the special name flag for all properties + let mdef = + mdef.WithSpecialName.With( + customAttrs = + mkILCustomAttrs ( + (GenAttrs cenv eenv attrsAppliedToGetterOrSetter) + @ sourceNameAttribs @ ilAttrsCompilerGenerated + ) + ) + + mdef + + | _ -> + let mdef = + mdef.With( + customAttrs = mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated) + ) + + mdef + + | _ -> + let mdef = + mkILStaticMethod (ilTypars, methName, access, ilParams, ilReturn, ilMethodBody) + + // For extension properties, also emit attrsAppliedToGetterOrSetter on the getter or setter method + let ilAttrs = + match v.MemberInfo with + | Some memberInfo when v.IsExtensionMember -> + match memberInfo.MemberFlags.MemberKind with + | SynMemberKind.PropertySet + | SynMemberKind.PropertyGet -> ilAttrsThatGoOnPrimaryItem @ GenAttrs cenv eenv attrsAppliedToGetterOrSetter + | _ -> ilAttrsThatGoOnPrimaryItem + | _ -> ilAttrsThatGoOnPrimaryItem + + let ilCustomAttrs = + mkILCustomAttrs (ilAttrs @ sourceNameAttribs @ ilAttrsCompilerGenerated) + + let mdef = mdef.With(customAttrs = ilCustomAttrs) + mdef + + // Does the function have an explicit [] attribute? + let isExplicitEntryPoint = HasFSharpAttribute g g.attrib_EntryPointAttribute attrs + + let mdef = mdef - CountMethodDef() - mgbuf.AddMethodDef(tref, mdef) + .WithSecurity(not (List.isEmpty securityAttributes)) + .WithPInvoke(hasDllImport) + .WithPreserveSig(hasPreserveSigImplFlag || hasPreserveSigNamedArg) + .WithSynchronized(hasSynchronizedImplFlag) + .WithNoInlining(hasNoInliningFlag) + .WithAggressiveInlining(hasAggressiveInliningImplFlag) + .With(isEntryPoint = isExplicitEntryPoint, securityDecls = secDecls) + + let mdef = + if // operator names + mdef.Name.StartsWithOrdinal("op_") + || + // active pattern names + mdef.Name.StartsWithOrdinal("|") + || + // event add/remove method + v.val_flags.IsGeneratedEventVal + then + mdef.WithSpecialName + else + mdef + + CountMethodDef() + mgbuf.AddMethodDef(tref, mdef) and GenPInvokeMethod (nm, dll, namedArgs) = let decoder = AttributeDecoder namedArgs let hasPreserveSigNamedArg = decoder.FindBool "PreserveSig" true + hasPreserveSigNamedArg, - let pinvoke = - { Where=mkSimpleModRef dll - Name=decoder.FindString "EntryPoint" nm - CallingConv= - match decoder.FindInt32 "CallingConvention" 0 with - | 1 -> PInvokeCallingConvention.WinApi - | 2 -> PInvokeCallingConvention.Cdecl - | 3 -> PInvokeCallingConvention.Stdcall - | 4 -> PInvokeCallingConvention.Thiscall - | 5 -> PInvokeCallingConvention.Fastcall - | _ -> PInvokeCallingConvention.WinApi - CharEncoding= - match decoder.FindInt32 "CharSet" 0 with - | 1 -> PInvokeCharEncoding.None - | 2 -> PInvokeCharEncoding.Ansi - | 3 -> PInvokeCharEncoding.Unicode - | 4 -> PInvokeCharEncoding.Auto - | _ -> PInvokeCharEncoding.None - NoMangle= decoder.FindBool "ExactSpelling" false - LastError= decoder.FindBool "SetLastError" false - ThrowOnUnmappableChar= if (decoder.FindBool "ThrowOnUnmappableChar" false) then PInvokeThrowOnUnmappableChar.Enabled else PInvokeThrowOnUnmappableChar.UseAssembly - CharBestFit=if (decoder.FindBool "BestFitMapping" false) then PInvokeCharBestFit.Enabled else PInvokeCharBestFit.UseAssembly } : PInvokeMethod + let pinvoke: PInvokeMethod = + { + Where = mkSimpleModRef dll + Name = decoder.FindString "EntryPoint" nm + CallingConv = + match decoder.FindInt32 "CallingConvention" 0 with + | 1 -> PInvokeCallingConvention.WinApi + | 2 -> PInvokeCallingConvention.Cdecl + | 3 -> PInvokeCallingConvention.Stdcall + | 4 -> PInvokeCallingConvention.Thiscall + | 5 -> PInvokeCallingConvention.Fastcall + | _ -> PInvokeCallingConvention.WinApi + CharEncoding = + match decoder.FindInt32 "CharSet" 0 with + | 1 -> PInvokeCharEncoding.None + | 2 -> PInvokeCharEncoding.Ansi + | 3 -> PInvokeCharEncoding.Unicode + | 4 -> PInvokeCharEncoding.Auto + | _ -> PInvokeCharEncoding.None + NoMangle = decoder.FindBool "ExactSpelling" false + LastError = decoder.FindBool "SetLastError" false + ThrowOnUnmappableChar = + if (decoder.FindBool "ThrowOnUnmappableChar" false) then + PInvokeThrowOnUnmappableChar.Enabled + else + PInvokeThrowOnUnmappableChar.UseAssembly + CharBestFit = + if (decoder.FindBool "BestFitMapping" false) then + PInvokeCharBestFit.Enabled + else + PInvokeCharBestFit.UseAssembly + } + MethodBody.PInvoke(lazy pinvoke) - + and GenBindings cenv cgbuf eenv binds stateVarFlagsOpt = - match stateVarFlagsOpt with - | None -> - binds |> List.iter (fun bind -> GenBinding cenv cgbuf eenv bind false) - | Some stateVarFlags -> - (binds, stateVarFlags) ||> List.iter2 (fun bind isStateVar -> GenBinding cenv cgbuf eenv bind isStateVar) + match stateVarFlagsOpt with + | None -> binds |> List.iter (fun bind -> GenBinding cenv cgbuf eenv bind false) + | Some stateVarFlags -> + (binds, stateVarFlags) + ||> List.iter2 (fun bind isStateVar -> GenBinding cenv cgbuf eenv bind isStateVar) //------------------------------------------------------------------------- // Generate locals and other storage of values //------------------------------------------------------------------------- and GenSetVal cenv cgbuf eenv (vref, e, m) sequel = - let storage = StorageForValRef cenv.g m vref eenv - GetStoreValCtxt cenv cgbuf eenv vref.Deref + let storage = StorageForValRef m vref eenv + GetStoreValCtxt cgbuf eenv vref.Deref GenExpr cenv cgbuf eenv e Continue GenSetStorage vref.Range cgbuf storage GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel and GenGetValRefAndSequel cenv cgbuf eenv m (v: ValRef) storeSequel = let ty = v.Type - GenGetStorageAndSequel cenv cgbuf eenv m (ty, GenType cenv m eenv.tyenv ty) (StorageForValRef cenv.g m v eenv) storeSequel + GenGetStorageAndSequel cenv cgbuf eenv m (ty, GenType cenv m eenv.tyenv ty) (StorageForValRef m v eenv) storeSequel and GenGetVal cenv cgbuf eenv (v: ValRef, m) sequel = GenGetValRefAndSequel cenv cgbuf eenv m v None @@ -7017,56 +9316,59 @@ and GenGetVal cenv cgbuf eenv (v: ValRef, m) sequel = and GenBindingRhs cenv cgbuf eenv (vspec: Val) expr = let g = cenv.g + match expr with - | Expr.TyLambda _ | Expr.Lambda _ -> + | Expr.TyLambda _ + | Expr.Lambda _ -> - match IsLocalErasedTyLambda g eenv vspec expr with - | Some body -> - GenExpr cenv cgbuf eenv body Continue + match IsLocalErasedTyLambda eenv vspec expr with + | Some body -> GenExpr cenv cgbuf eenv body Continue | None -> let isLocalTypeFunc = IsNamedLocalTypeFuncVal g vspec expr let thisVars = if isLocalTypeFunc then [] else [ mkLocalValRef vspec ] GenLambda cenv cgbuf eenv isLocalTypeFunc thisVars expr Continue - | _ -> - GenExpr cenv cgbuf eenv expr Continue + | _ -> GenExpr cenv cgbuf eenv expr Continue and CommitStartScope cgbuf startMarkOpt = match startMarkOpt with | None -> () | Some startMark -> cgbuf.SetMarkToHere startMark -and EmitInitLocal cgbuf ty idx = CG.EmitInstrs cgbuf (pop 0) Push0 [I_ldloca (uint16 idx); (I_initobj ty) ] +and EmitInitLocal cgbuf ty idx = + CG.EmitInstrs cgbuf (pop 0) Push0 [ I_ldloca(uint16 idx); (I_initobj ty) ] -and EmitSetLocal cgbuf idx = CG.EmitInstr cgbuf (pop 1) Push0 (mkStloc (uint16 idx)) +and EmitSetLocal cgbuf idx = + CG.EmitInstr cgbuf (pop 1) Push0 (mkStloc (uint16 idx)) -and EmitGetLocal cgbuf ty idx = CG.EmitInstr cgbuf (pop 0) (Push [ty]) (mkLdloc (uint16 idx)) +and EmitGetLocal cgbuf ty idx = + CG.EmitInstr cgbuf (pop 0) (Push [ ty ]) (mkLdloc (uint16 idx)) -and EmitSetStaticField cgbuf fspec = CG.EmitInstr cgbuf (pop 1) Push0 (mkNormalStsfld fspec) +and EmitSetStaticField cgbuf fspec = + CG.EmitInstr cgbuf (pop 1) Push0 (mkNormalStsfld fspec) -and EmitGetStaticFieldAddr cgbuf ty fspec = CG.EmitInstr cgbuf (pop 0) (Push [ty]) (I_ldsflda fspec) +and EmitGetStaticFieldAddr cgbuf ty fspec = + CG.EmitInstr cgbuf (pop 0) (Push [ ty ]) (I_ldsflda fspec) -and EmitGetStaticField cgbuf ty fspec = CG.EmitInstr cgbuf (pop 0) (Push [ty]) (mkNormalLdsfld fspec) +and EmitGetStaticField cgbuf ty fspec = + CG.EmitInstr cgbuf (pop 0) (Push [ ty ]) (mkNormalLdsfld fspec) and GenSetStorage m cgbuf storage = match storage with - | Local (idx, _, _) -> - EmitSetLocal cgbuf idx + | Local (idx, _, _) -> EmitSetLocal cgbuf idx | StaticPropertyWithField (_, _, hasLiteralAttr, ilContainerTy, _, _, _, ilSetterMethRef, _) -> - if hasLiteralAttr then errorR(Error(FSComp.SR.ilLiteralFieldsCannotBeSet(), m)) - CG.EmitInstr cgbuf (pop 1) Push0 (I_call(Normalcall, mkILMethSpecForMethRefInTy(ilSetterMethRef, ilContainerTy, []), None)) + if hasLiteralAttr then + errorR (Error(FSComp.SR.ilLiteralFieldsCannotBeSet (), m)) - | StaticProperty (ilGetterMethSpec, _) -> - error(Error(FSComp.SR.ilStaticMethodIsNotLambda(ilGetterMethSpec.Name), m)) + CG.EmitInstr cgbuf (pop 1) Push0 (I_call(Normalcall, mkILMethSpecForMethRefInTy (ilSetterMethRef, ilContainerTy, []), None)) - | Method (_, _, mspec, _, m, _, _, _, _, _, _, _) -> - error(Error(FSComp.SR.ilStaticMethodIsNotLambda(mspec.Name), m)) + | StaticProperty (ilGetterMethSpec, _) -> error (Error(FSComp.SR.ilStaticMethodIsNotLambda (ilGetterMethSpec.Name), m)) - | Null -> - CG.EmitInstr cgbuf (pop 1) Push0 AI_pop + | Method (_, _, mspec, _, m, _, _, _, _, _, _, _) -> error (Error(FSComp.SR.ilStaticMethodIsNotLambda (mspec.Name), m)) + + | Null -> CG.EmitInstr cgbuf (pop 1) Push0 AI_pop - | Arg _ -> - error(Error(FSComp.SR.ilMutableVariablesCannotEscapeMethod(), m)) + | Arg _ -> error (Error(FSComp.SR.ilMutableVariablesCannotEscapeMethod (), m)) | Env (_, ilField, _) -> // Note: ldarg0 has already been emitted in GenSetVal @@ -7074,23 +9376,29 @@ and GenSetStorage m cgbuf storage = and CommitGetStorageSequel cenv cgbuf eenv m ty localCloInfo storeSequel = match localCloInfo, storeSequel with - | Some (_, {contents =NamedLocalIlxClosureInfoGenerator _cloinfo}), _ -> - error(InternalError("Unexpected generator", m)) - - | Some (_, {contents =NamedLocalIlxClosureInfoGenerated cloinfo}), Some (tyargs, args, m, sequel) when not (isNil tyargs) -> + | Some (_, + { + contents = NamedLocalIlxClosureInfoGenerator _cloinfo + }), + _ -> error (InternalError("Unexpected generator", m)) + + | Some (_, + { + contents = NamedLocalIlxClosureInfoGenerated cloinfo + }), + Some (tyargs, args, m, sequel) when not (isNil tyargs) -> let actualRetTy = GenNamedLocalTyFuncCall cenv cgbuf eenv ty cloinfo tyargs m - CommitGetStorageSequel cenv cgbuf eenv m actualRetTy None (Some ([], args, m, sequel)) + CommitGetStorageSequel cenv cgbuf eenv m actualRetTy None (Some([], args, m, sequel)) | _, None -> () - | _, Some ([], [], _, sequel) -> - GenSequel cenv eenv.cloc cgbuf sequel + | _, Some ([], [], _, sequel) -> GenSequel cenv eenv.cloc cgbuf sequel - | _, Some (tyargs, args, m, sequel) -> - GenCurriedArgsAndIndirectCall cenv cgbuf eenv (ty, tyargs, args, m) sequel + | _, Some (tyargs, args, m, sequel) -> GenCurriedArgsAndIndirectCall cenv cgbuf eenv (ty, tyargs, args, m) sequel and GenGetStorageAndSequel (cenv: cenv) cgbuf eenv m (ty, ilTy) storage storeSequel = let g = cenv.g + match storage with | Local (idx, _, localCloInfo) -> EmitGetLocal cgbuf ilTy idx @@ -7101,14 +9409,19 @@ and GenGetStorageAndSequel (cenv: cenv) cgbuf eenv m (ty, ilTy) storage storeSeq if hasLiteralAttr then EmitGetStaticField cgbuf ilTy fspec else - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call(Normalcall, mkILMethSpecForMethRefInTy (ilGetterMethRef, ilContainerTy, []), None)) + CG.EmitInstr + cgbuf + (pop 0) + (Push [ ilTy ]) + (I_call(Normalcall, mkILMethSpecForMethRefInTy (ilGetterMethRef, ilContainerTy, []), None)) + CommitGetStorageSequel cenv cgbuf eenv m ty None storeSequel | StaticProperty (ilGetterMethSpec, _) -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call (Normalcall, ilGetterMethSpec, None)) + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (I_call(Normalcall, ilGetterMethSpec, None)) CommitGetStorageSequel cenv cgbuf eenv m ty None storeSequel - | Method (topValInfo, vref, _, _, _, _, _, _, _, _, _, _) -> + | Method (valReprInfo, vref, _, _, _, _, _, _, _, _, _, _) -> // Get a toplevel value as a first-class value. // We generate a lambda expression and that simply calls // the toplevel method. However we optimize the case where we are @@ -7116,60 +9429,75 @@ and GenGetStorageAndSequel (cenv: cenv) cgbuf eenv m (ty, ilTy) storage storeSeq // First build a lambda expression for the saturated use of the toplevel value... // REVIEW: we should NOT be doing this in the backend... - let expr, exprTy = AdjustValForExpectedArity g m vref NormalValUse topValInfo + let expr, exprTy = AdjustValForExpectedArity g m vref NormalValUse valReprInfo // Then reduce out any arguments (i.e. apply the sequel immediately if we can...) match storeSequel with - | None -> - GenLambda cenv cgbuf eenv false [] expr Continue + | None -> GenLambda cenv cgbuf eenv false [] expr Continue | Some (tyargs', args, m, sequel) -> let specializedExpr = - if isNil args && isNil tyargs' then failwith ("non-lambda at use of method " + vref.LogicalName) - MakeApplicationAndBetaReduce cenv.g (expr, exprTy, [tyargs'], args, m) + if isNil args && isNil tyargs' then + failwith ("non-lambda at use of method " + vref.LogicalName) + + MakeApplicationAndBetaReduce cenv.g (expr, exprTy, [ tyargs' ], args, m) + GenExpr cenv cgbuf eenv specializedExpr sequel | Null -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) AI_ldnull + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) AI_ldnull CommitGetStorageSequel cenv cgbuf eenv m ty None storeSequel | Arg i -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (mkLdarg (uint16 i)) + CG.EmitInstr cgbuf (pop 0) (Push [ ilTy ]) (mkLdarg (uint16 i)) CommitGetStorageSequel cenv cgbuf eenv m ty None storeSequel | Env (_, ilField, localCloInfo) -> - CG.EmitInstrs cgbuf (pop 0) (Push [ilTy]) [ mkLdarg0; mkNormalLdfld ilField ] + CG.EmitInstrs cgbuf (pop 0) (Push [ ilTy ]) [ mkLdarg0; mkNormalLdfld ilField ] CommitGetStorageSequel cenv cgbuf eenv m ty localCloInfo storeSequel and GenGetLocalVals cenv cgbuf eenvouter m fvs = List.iter (fun v -> GenGetLocalVal cenv cgbuf eenvouter m v None) fvs and GenGetLocalVal cenv cgbuf eenv m (vspec: Val) storeSequel = - GenGetStorageAndSequel cenv cgbuf eenv m (vspec.Type, GenTypeOfVal cenv eenv vspec) (StorageForVal cenv.g m vspec eenv) storeSequel + GenGetStorageAndSequel cenv cgbuf eenv m (vspec.Type, GenTypeOfVal cenv eenv vspec) (StorageForVal m vspec eenv) storeSequel and GenGetLocalVRef cenv cgbuf eenv m (vref: ValRef) storeSequel = - GenGetStorageAndSequel cenv cgbuf eenv m (vref.Type, GenTypeOfVal cenv eenv vref.Deref) (StorageForValRef cenv.g m vref eenv) storeSequel + GenGetStorageAndSequel cenv cgbuf eenv m (vref.Type, GenTypeOfVal cenv eenv vref.Deref) (StorageForValRef m vref eenv) storeSequel -and GenStoreVal cenv cgbuf eenv m (vspec: Val) = - GenSetStorage vspec.Range cgbuf (StorageForVal cenv.g m vspec eenv) +and GenStoreVal cgbuf eenv m (vspec: Val) = + GenSetStorage vspec.Range cgbuf (StorageForVal m vspec eenv) /// Allocate IL locals and AllocLocal cenv cgbuf eenv compgen (v, ty, isFixed) (scopeMarks: Mark * Mark) : int * _ * _ = - // The debug range for the local - let ranges = if compgen then [] else [(v, scopeMarks)] - // Get an index for the local - let j, realloc = + // The debug range for the local + let ranges = if compgen then [] else [ (v, scopeMarks) ] + // Get an index for the local + let j, realloc = if cenv.options.localOptimizationsEnabled then - cgbuf.ReallocLocal((fun i (_, ty', isFixed') -> not isFixed' && not isFixed && not (IntMap.mem i eenv.liveLocals) && (ty = ty')), ranges, ty, isFixed) + cgbuf.ReallocLocal( + (fun i (_, ty2, isFixed2) -> not isFixed2 && not isFixed && not (IntMap.mem i eenv.liveLocals) && (ty = ty2)), + ranges, + ty, + isFixed + ) else cgbuf.AllocLocal(ranges, ty, isFixed), false - j, realloc, { eenv with liveLocals = IntMap.add j () eenv.liveLocals } + + j, + realloc, + { eenv with + liveLocals = IntMap.add j () eenv.liveLocals + } /// Decide storage for local value and if necessary allocate an ILLocal for it and AllocLocalVal cenv cgbuf v eenv repr scopeMarks = let g = cenv.g + let repr, eenv = let ty = v.Type - if isUnitTy g ty && not v.IsMutable then Null, eenv + + if isUnitTy g ty && not v.IsMutable then + Null, eenv else match repr with | Some repr when IsNamedLocalTypeFuncVal g v repr -> @@ -7177,22 +9505,43 @@ and AllocLocalVal cenv cgbuf v eenv repr scopeMarks = // known, named, non-escaping type functions let cloinfoGenerate eenv = let eenvinner = - {eenv with - letBoundVars=(mkLocalValRef v) :: eenv.letBoundVars} - let cloinfo, _, _ = GetIlxClosureInfo cenv v.Range ILBoxity.AsObject true true [] eenvinner repr + { eenv with + letBoundVars = (mkLocalValRef v) :: eenv.letBoundVars + } + + let cloinfo, _, _ = + GetIlxClosureInfo cenv v.Range ILBoxity.AsObject true true [] eenvinner repr + cloinfo - let idx, realloc, eenv = AllocLocal cenv cgbuf eenv v.IsCompilerGenerated (v.CompiledName g.CompilerGlobalState, g.ilg.typ_Object, false) scopeMarks - Local (idx, realloc, Some(ftyvs, ref (NamedLocalIlxClosureInfoGenerator cloinfoGenerate))), eenv + let idx, realloc, eenv = + AllocLocal + cenv + cgbuf + eenv + v.IsCompilerGenerated + (v.CompiledName g.CompilerGlobalState, g.ilg.typ_Object, false) + scopeMarks + + Local(idx, realloc, Some(ftyvs, ref (NamedLocalIlxClosureInfoGenerator cloinfoGenerate))), eenv | _ -> // normal local - let idx, realloc, eenv = AllocLocal cenv cgbuf eenv v.IsCompilerGenerated (v.CompiledName g.CompilerGlobalState, GenTypeOfVal cenv eenv v, v.IsFixed) scopeMarks - Local (idx, realloc, None), eenv + let idx, realloc, eenv = + AllocLocal + cenv + cgbuf + eenv + v.IsCompilerGenerated + (v.CompiledName g.CompilerGlobalState, GenTypeOfVal cenv eenv v, v.IsFixed) + scopeMarks + + Local(idx, realloc, None), eenv + let eenv = AddStorageForVal g (v, notlazy repr) eenv repr, eenv and AllocStorageForBind cenv cgbuf scopeMarks eenv bind = - AllocStorageForBinds cenv cgbuf scopeMarks eenv [bind] + AllocStorageForBinds cenv cgbuf scopeMarks eenv [ bind ] and AllocStorageForBinds cenv cgbuf scopeMarks eenv binds = // phase 1 - decide representations - most are very simple. @@ -7200,39 +9549,38 @@ and AllocStorageForBinds cenv cgbuf scopeMarks eenv binds = // Phase 2 - run the cloinfo generators for NamedLocalClosure values against the environment recording the // representation choices. - reps |> List.iter (fun reprOpt -> - match reprOpt with - | Some repr -> - match repr with - | Local(_, _, Some (_, g)) - | Env(_, _, Some (_, g)) -> - match g.Value with - | NamedLocalIlxClosureInfoGenerator f -> - g.Value <- NamedLocalIlxClosureInfoGenerated (f eenv) - | NamedLocalIlxClosureInfoGenerated _ -> - () - | _ -> () - | _ -> ()) + reps + |> List.iter (fun reprOpt -> + match reprOpt with + | Some repr -> + match repr with + | Local (_, _, Some (_, g)) + | Env (_, _, Some (_, g)) -> + match g.Value with + | NamedLocalIlxClosureInfoGenerator f -> g.Value <- NamedLocalIlxClosureInfoGenerated(f eenv) + | NamedLocalIlxClosureInfoGenerated _ -> () + | _ -> () + | _ -> ()) eenv -and AllocValForBind cenv cgbuf (scopeMarks: Mark * Mark) eenv (TBind(v, repr, _)) = +and AllocValForBind cenv cgbuf (scopeMarks: Mark * Mark) eenv (TBind (v, repr, _)) = match v.ValReprInfo with | None -> let repr, eenv = AllocLocalVal cenv cgbuf v eenv (Some repr) scopeMarks Some repr, eenv - | Some _ -> - None, AllocTopValWithinExpr cenv cgbuf (snd scopeMarks) eenv.cloc v eenv + | Some _ -> None, AllocTopValWithinExpr cenv cgbuf (snd scopeMarks) eenv.cloc v eenv and AllocTopValWithinExpr cenv cgbuf endMark cloc v eenv = let g = cenv.g // decide whether to use a shadow local or not let useShadowLocal = - cenv.options.generateDebugSymbols && - not cenv.options.localOptimizationsEnabled && - not v.IsCompilerGenerated && - not v.IsMutable && + cenv.options.generateDebugSymbols + && not cenv.options.localOptimizationsEnabled + && not v.IsCompilerGenerated + && not v.IsMutable + && // Don't use shadow locals for things like functions which are not compiled as static values/properties IsCompiledAsStaticProperty g v @@ -7240,7 +9588,7 @@ and AllocTopValWithinExpr cenv cgbuf endMark cloc v eenv = if useShadowLocal then let startMark = CG.GenerateDelayMark cgbuf ("start_" + v.LogicalName) let storage, eenv = AllocLocalVal cenv cgbuf v eenv None (startMark, endMark) - ShadowLocal (startMark, storage), eenv + ShadowLocal(startMark, storage), eenv else NoShadowLocal, eenv @@ -7255,13 +9603,24 @@ and AllocTopValWithinExpr cenv cgbuf endMark cloc v eenv = /// - and because IL requires empty stack following a forward br (jump). and EmitSaveStack cenv cgbuf eenv m scopeMarks = let savedStack = (cgbuf.GetCurrentStack()) + let savedStackLocals, eenvinner = - (eenv, savedStack) ||> List.mapFold (fun eenv ty -> + (eenv, savedStack) + ||> List.mapFold (fun eenv ty -> let idx, _realloc, eenv = // Ensure that we have an g.CompilerGlobalState - assert(cenv.g.CompilerGlobalState |> Option.isSome) - AllocLocal cenv cgbuf eenv true (cenv.g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName ("spill", m), ty, false) scopeMarks + assert (cenv.g.CompilerGlobalState |> Option.isSome) + + AllocLocal + cenv + cgbuf + eenv + true + (cenv.g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName("spill", m), ty, false) + scopeMarks + idx, eenv) + List.iter (EmitSetLocal cgbuf) savedStackLocals cgbuf.AssertEmptyStack() (savedStack, savedStackLocals), eenvinner (* need to return, it marks locals "live" *) @@ -7276,12 +9635,10 @@ and EmitRestoreStack cgbuf (savedStack, savedStackLocals) = //------------------------------------------------------------------------- and GenAttribArg amap g eenv x (ilArgTy: ILType) = - let exprL expr = exprL g expr match stripDebugPoints x, ilArgTy with // Detect 'null' used for an array argument - | Expr.Const (Const.Zero, _, _), ILType.Array _ -> - ILAttribElem.Null + | Expr.Const (Const.Zero, _, _), ILType.Array _ -> ILAttribElem.Null // Detect standard constants | Expr.Const (c, m, _), _ -> @@ -7291,12 +9648,12 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = match c with | Const.Bool b -> ILAttribElem.Bool b | Const.Int32 i when isobj || tynm = "System.Int32" -> ILAttribElem.Int32 i - | Const.Int32 i when tynm = "System.SByte" -> ILAttribElem.SByte (sbyte i) - | Const.Int32 i when tynm = "System.Int16" -> ILAttribElem.Int16 (int16 i) - | Const.Int32 i when tynm = "System.Byte" -> ILAttribElem.Byte (byte i) - | Const.Int32 i when tynm = "System.UInt16" ->ILAttribElem.UInt16 (uint16 i) - | Const.Int32 i when tynm = "System.UInt32" ->ILAttribElem.UInt32 (uint32 i) - | Const.Int32 i when tynm = "System.UInt64" ->ILAttribElem.UInt64 (uint64 (int64 i)) + | Const.Int32 i when tynm = "System.SByte" -> ILAttribElem.SByte(sbyte i) + | Const.Int32 i when tynm = "System.Int16" -> ILAttribElem.Int16(int16 i) + | Const.Int32 i when tynm = "System.Byte" -> ILAttribElem.Byte(byte i) + | Const.Int32 i when tynm = "System.UInt16" -> ILAttribElem.UInt16(uint16 i) + | Const.Int32 i when tynm = "System.UInt32" -> ILAttribElem.UInt32(uint32 i) + | Const.Int32 i when tynm = "System.UInt64" -> ILAttribElem.UInt64(uint64 (int64 i)) | Const.SByte i -> ILAttribElem.SByte i | Const.Int16 i -> ILAttribElem.Int16 i | Const.Int32 i -> ILAttribElem.Int32 i @@ -7311,67 +9668,69 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = | Const.Zero when isobj -> ILAttribElem.Null | Const.Zero when tynm = "System.String" -> ILAttribElem.String None | Const.Zero when tynm = "System.Type" -> ILAttribElem.Type None - | Const.String i when isobj || tynm = "System.String" -> ILAttribElem.String (Some i) - | _ -> error (InternalError ( "The type '" + tynm + "' may not be used as a custom attribute value", m)) + | Const.String i when isobj || tynm = "System.String" -> ILAttribElem.String(Some i) + | _ -> error (InternalError("The type '" + tynm + "' may not be used as a custom attribute value", m)) // Detect '[| ... |]' nodes - | Expr.Op (TOp.Array, [elemTy], args, m), _ -> + | Expr.Op (TOp.Array, [ elemTy ], args, m), _ -> let ilElemTy = GenType amap m eenv.tyenv elemTy - ILAttribElem.Array (ilElemTy, List.map (fun arg -> GenAttribArg amap g eenv arg ilElemTy) args) + ILAttribElem.Array(ilElemTy, List.map (fun arg -> GenAttribArg amap g eenv arg ilElemTy) args) // Detect 'typeof' calls - | TypeOfExpr g ty, _ -> - ILAttribElem.Type (Some (GenType amap x.Range eenv.tyenv ty)) + | TypeOfExpr g ty, _ -> ILAttribElem.Type(Some(GenType amap x.Range eenv.tyenv ty)) // Detect 'typedefof' calls - | TypeDefOfExpr g ty, _ -> - ILAttribElem.TypeRef (Some (GenType amap x.Range eenv.tyenv ty).TypeRef) + | TypeDefOfExpr g ty, _ -> ILAttribElem.TypeRef(Some (GenType amap x.Range eenv.tyenv ty).TypeRef) // Ignore upcasts - | Expr.Op (TOp.Coerce, _, [arg2], _), _ -> - GenAttribArg amap g eenv arg2 ilArgTy + | Expr.Op (TOp.Coerce, _, [ arg2 ], _), _ -> GenAttribArg amap g eenv arg2 ilArgTy // Detect explicit enum values - | EnumExpr g arg1, _ -> - GenAttribArg amap g eenv arg1 ilArgTy - + | EnumExpr g arg1, _ -> GenAttribArg amap g eenv arg1 ilArgTy // Detect bitwise or of attribute flags: one case of constant folding (a more general treatment is needed) | AttribBitwiseOrExpr g (arg1, arg2), _ -> let v1 = GenAttribArg amap g eenv arg1 ilArgTy let v2 = GenAttribArg amap g eenv arg2 ilArgTy + match v1, v2 with - | ILAttribElem.SByte i1, ILAttribElem.SByte i2 -> ILAttribElem.SByte (i1 ||| i2) - | ILAttribElem.Int16 i1, ILAttribElem.Int16 i2-> ILAttribElem.Int16 (i1 ||| i2) - | ILAttribElem.Int32 i1, ILAttribElem.Int32 i2-> ILAttribElem.Int32 (i1 ||| i2) - | ILAttribElem.Int64 i1, ILAttribElem.Int64 i2-> ILAttribElem.Int64 (i1 ||| i2) - | ILAttribElem.Byte i1, ILAttribElem.Byte i2-> ILAttribElem.Byte (i1 ||| i2) - | ILAttribElem.UInt16 i1, ILAttribElem.UInt16 i2-> ILAttribElem.UInt16 (i1 ||| i2) - | ILAttribElem.UInt32 i1, ILAttribElem.UInt32 i2-> ILAttribElem.UInt32 (i1 ||| i2) - | ILAttribElem.UInt64 i1, ILAttribElem.UInt64 i2-> ILAttribElem.UInt64 (i1 ||| i2) - | _ -> error (InternalError ("invalid custom attribute value (not a valid constant): " + showL (exprL x), x.Range)) + | ILAttribElem.SByte i1, ILAttribElem.SByte i2 -> ILAttribElem.SByte(i1 ||| i2) + | ILAttribElem.Int16 i1, ILAttribElem.Int16 i2 -> ILAttribElem.Int16(i1 ||| i2) + | ILAttribElem.Int32 i1, ILAttribElem.Int32 i2 -> ILAttribElem.Int32(i1 ||| i2) + | ILAttribElem.Int64 i1, ILAttribElem.Int64 i2 -> ILAttribElem.Int64(i1 ||| i2) + | ILAttribElem.Byte i1, ILAttribElem.Byte i2 -> ILAttribElem.Byte(i1 ||| i2) + | ILAttribElem.UInt16 i1, ILAttribElem.UInt16 i2 -> ILAttribElem.UInt16(i1 ||| i2) + | ILAttribElem.UInt32 i1, ILAttribElem.UInt32 i2 -> ILAttribElem.UInt32(i1 ||| i2) + | ILAttribElem.UInt64 i1, ILAttribElem.UInt64 i2 -> ILAttribElem.UInt64(i1 ||| i2) + | _ -> error (InternalError("invalid custom attribute value (not a valid constant): " + showL (exprL x), x.Range)) // Other expressions are not valid custom attribute values - | _ -> - error (InternalError ("invalid custom attribute value (not a constant): " + showL (exprL x), x.Range)) - + | _ -> error (InternalError("invalid custom attribute value (not a constant): " + showL (exprL x), x.Range)) -and GenAttr cenv g eenv (Attrib(_, k, args, props, _, _, _)) = +and GenAttr cenv g eenv (Attrib (_, k, args, props, _, _, _)) = let props = - props |> List.map (fun (AttribNamedArg(s, ty, fld, AttribExpr(_, expr))) -> + props + |> List.map (fun (AttribNamedArg (s, ty, fld, AttribExpr (_, expr))) -> let m = expr.Range let ilTy = GenType cenv m eenv.tyenv ty let cval = GenAttribArg cenv g eenv expr ilTy (s, ilTy, fld, cval)) + let mspec = match k with - | ILAttrib mref -> mkILMethSpec(mref, AsObject, [], []) + | ILAttrib mref -> mkILMethSpec (mref, AsObject, [], []) | FSAttrib vref -> - assert vref.IsMember - let mspec, _, _, _, _, _, _, _, _, _ = GetMethodSpecForMemberVal cenv (Option.get vref.MemberInfo) vref - mspec - let ilArgs = List.map2 (fun (AttribExpr(_, vexpr)) ty -> GenAttribArg cenv g eenv vexpr ty) args mspec.FormalArgTypes + assert vref.IsMember + + let mspec, _, _, _, _, _, _, _, _, _ = + GetMethodSpecForMemberVal cenv (Option.get vref.MemberInfo) vref + + mspec + + let ilArgs = + List.map2 (fun (AttribExpr (_, vexpr)) ty -> GenAttribArg cenv g eenv vexpr ty) args mspec.FormalArgTypes + mkILCustomAttribMethRef (mspec, ilArgs, props) and GenAttrs cenv eenv attrs = @@ -7379,28 +9738,44 @@ and GenAttrs cenv eenv attrs = and GenCompilationArgumentCountsAttr cenv (v: Val) = let g = cenv.g - [ match v.ValReprInfo with - | Some tvi when v.IsMemberOrModuleBinding -> - let arities = if ValSpecIsCompiledAsInstance g v then List.tail tvi.AritiesOfArgs else tvi.AritiesOfArgs - if arities.Length > 1 then - yield mkCompilationArgumentCountsAttr g arities - | _ -> - () ] + + [ + match v.ValReprInfo with + | Some tvi when v.IsMemberOrModuleBinding -> + let arities = + if ValSpecIsCompiledAsInstance g v then + List.tail tvi.AritiesOfArgs + else + tvi.AritiesOfArgs + + if arities.Length > 1 then + yield mkCompilationArgumentCountsAttr g arities + | _ -> () + ] // Create a permission set for a list of security attributes and CreatePermissionSets cenv eenv (securityAttributes: Attrib list) = let g = cenv.g - [for Attrib(tcref, _, actions, _, _, _, _) as attr in securityAttributes do - let action = match actions with | [AttribInt32Arg act] -> act | _ -> failwith "internal error: unrecognized security action" - let secaction = (List.assoc action (Lazy.force ILSecurityActionRevMap)) - let tref = tcref.CompiledRepresentationForNamedType - let ilattr = GenAttr cenv g eenv attr - let _, ilNamedArgs = - match TryDecodeILAttribute tref (mkILCustomAttrs [ilattr]) with - | Some(ae, na) -> ae, na - | _ -> [], [] - let setArgs = ilNamedArgs |> List.map (fun (n, ilt, _, ilae) -> (n, ilt, ilae)) - yield mkPermissionSet (secaction, [(tref, setArgs)])] + + [ + for Attrib (tcref, _, actions, _, _, _, _) as attr in securityAttributes do + let action = + match actions with + | [ AttribInt32Arg act ] -> act + | _ -> failwith "internal error: unrecognized security action" + + let secaction = (List.assoc action (Lazy.force ILSecurityActionRevMap)) + let tref = tcref.CompiledRepresentationForNamedType + let ilattr = GenAttr cenv g eenv attr + + let _, ilNamedArgs = + match TryDecodeILAttribute tref (mkILCustomAttrs [ ilattr ]) with + | Some (ae, na) -> ae, na + | _ -> [], [] + + let setArgs = ilNamedArgs |> List.map (fun (n, ilt, _, ilae) -> (n, ilt, ilae)) + yield mkPermissionSet (secaction, [ (tref, setArgs) ]) + ] //-------------------------------------------------------------------------- // Generate the set of modules for an assembly, and the declarations in each module @@ -7410,21 +9785,34 @@ and CreatePermissionSets cenv eenv (securityAttributes: Attrib list) = and GenTypeDefForCompLoc (cenv, eenv, mgbuf: AssemblyBuilder, cloc, hidden, attribs, initTrigger, eliminateIfEmpty, addAtEnd) = let g = cenv.g let tref = TypeRefForCompLoc cloc + let tdef = - mkILSimpleClass g.ilg - (tref.Name, - ComputeTypeAccess tref hidden, - emptyILMethods, - emptyILFields, - emptyILTypeDefs, - emptyILProperties, - emptyILEvents, - mkILCustomAttrs - (GenAttrs cenv eenv attribs @ - (if List.contains tref.Name [TypeNameForImplicitMainMethod cloc; TypeNameForInitClass cloc; TypeNameForPrivateImplementationDetails cloc] - then [ ] - else [mkCompilationMappingAttr g (int SourceConstructFlags.Module)])), - initTrigger) + mkILSimpleClass + g.ilg + (tref.Name, + ComputeTypeAccess tref hidden, + emptyILMethods, + emptyILFields, + emptyILTypeDefs, + emptyILProperties, + emptyILEvents, + mkILCustomAttrs ( + GenAttrs cenv eenv attribs + @ (if + List.contains + tref.Name + [ + TypeNameForImplicitMainMethod cloc + TypeNameForInitClass cloc + TypeNameForPrivateImplementationDetails cloc + ] + then + [] + else + [ mkCompilationMappingAttr g (int SourceConstructFlags.Module) ]) + ), + initTrigger) + let tdef = tdef.WithSealed(true).WithAbstract(true) mgbuf.AddTypeDef(tref, tdef, eliminateIfEmpty, addAtEnd, None) @@ -7434,18 +9822,23 @@ and GenImplFileContents cenv cgbuf qname lazyInitInfo eenv mty def = // rather than incrementally as we step through the initializations in the module. This is a little unfortunate // but stems from the way we add module values all at once before we generate the module itself. LocalScope "module" cgbuf (fun (_, endMark) -> - let sigToImplRemapInfo = ComputeRemappingFromImplementationToSignature cenv.g def mty + let sigToImplRemapInfo = + ComputeRemappingFromImplementationToSignature cenv.g def mty + let eenv = AddSignatureRemapInfo "defs" sigToImplRemapInfo eenv // Allocate all the values, including any shadow locals for static fields - let eenv = AddBindingsForModuleContents (AllocTopValWithinExpr cenv cgbuf endMark) eenv.cloc eenv def + let eenv = + AddBindingsForModuleContents (AllocTopValWithinExpr cenv cgbuf endMark) eenv.cloc eenv def + let _eenvEnd = GenModuleOrNamespaceContents cenv cgbuf qname lazyInitInfo eenv def ()) and GenModuleOrNamespaceContents cenv (cgbuf: CodeGenBuffer) qname lazyInitInfo eenv x = match x with - | TMDefRec(_isRec, opens, tycons, mbinds, m) -> + | TMDefRec (_isRec, opens, tycons, mbinds, m) -> let eenvinner = AddDebugImportsToEnv cenv eenv opens + for tc in tycons do if tc.IsFSharpException then GenExnDef cenv cgbuf.mgbuf eenvinner m tc @@ -7453,17 +9846,26 @@ and GenModuleOrNamespaceContents cenv (cgbuf: CodeGenBuffer) qname lazyInitInfo GenTypeDef cenv cgbuf.mgbuf lazyInitInfo eenvinner m tc // Generate chunks of non-nested bindings together to allow recursive fixups. - let mutable bindsRemaining = mbinds + let mutable bindsRemaining = mbinds + while not bindsRemaining.IsEmpty do - match bindsRemaining with - | ModuleOrNamespaceBinding.Binding _ :: _ -> + match bindsRemaining with + | ModuleOrNamespaceBinding.Binding _ :: _ -> let recBinds = bindsRemaining - |> List.takeWhile (function ModuleOrNamespaceBinding.Binding _ -> true | _ -> false) - |> List.map (function ModuleOrNamespaceBinding.Binding recBind -> recBind | _ -> failwith "GenModuleOrNamespaceContents - unexpected") + |> List.takeWhile (function + | ModuleOrNamespaceBinding.Binding _ -> true + | _ -> false) + |> List.map (function + | ModuleOrNamespaceBinding.Binding recBind -> recBind + | _ -> failwith "GenModuleOrNamespaceContents - unexpected") + let otherBinds = bindsRemaining - |> List.skipWhile (function ModuleOrNamespaceBinding.Binding _ -> true | _ -> false) + |> List.skipWhile (function + | ModuleOrNamespaceBinding.Binding _ -> true + | _ -> false) + GenLetRecBindings cenv cgbuf eenv (recBinds, m) bindsRemaining <- otherBinds | (ModuleOrNamespaceBinding.Module _ as mbind) :: rest -> @@ -7473,61 +9875,92 @@ and GenModuleOrNamespaceContents cenv (cgbuf: CodeGenBuffer) qname lazyInitInfo eenvinner - | TMDefLet(bind, _) -> - GenBindings cenv cgbuf eenv [bind] None + | TMDefLet (bind, _) -> + GenBindings cenv cgbuf eenv [ bind ] None eenv | TMDefOpens openDecls -> let eenvinner = AddDebugImportsToEnv cenv eenv openDecls eenvinner - | TMDefDo(e, _) -> + | TMDefDo (e, _) -> GenExpr cenv cgbuf eenv e discard eenv | TMDefs mdefs -> - (eenv, mdefs) ||> List.fold (GenModuleOrNamespaceContents cenv cgbuf qname lazyInitInfo) + (eenv, mdefs) + ||> List.fold (GenModuleOrNamespaceContents cenv cgbuf qname lazyInitInfo) // Generate a module binding and GenModuleBinding cenv (cgbuf: CodeGenBuffer) (qname: QualifiedNameOfFile) lazyInitInfo eenv m x = - match x with - | ModuleOrNamespaceBinding.Binding bind -> - GenLetRecBindings cenv cgbuf eenv ([bind], m) - - | ModuleOrNamespaceBinding.Module (mspec, mdef) -> - let hidden = IsHiddenTycon eenv.sigToImplRemapInfo mspec - - let eenvinner = - if mspec.IsNamespace then eenv else - { eenv with cloc = CompLocForFixedModule cenv.options.fragName qname.Text mspec; initLocals = eenv.initLocals && not (HasFSharpAttribute cenv.g cenv.g.attrib_SkipLocalsInitAttribute mspec.Attribs) } - - // Create the class to hold the contents of this module. No class needed if - // we're compiling it as a namespace. - // - // Most module static fields go into the "InitClass" static class. - // However mutable static fields go into the class for the module itself. - // So this static class ends up with a .cctor if it has mutable fields. - // - if not mspec.IsNamespace then - // The use of ILTypeInit.OnAny prevents the execution of the cctor before the - // "main" method in the case where the "main" method is implicit. - let staticClassTrigger = (* if eenv.isFinalFile then *) ILTypeInit.OnAny (* else ILTypeInit.BeforeField *) - - GenTypeDefForCompLoc (cenv, eenvinner, cgbuf.mgbuf, eenvinner.cloc, hidden, mspec.Attribs, staticClassTrigger, false, (* atEnd= *) true) + match x with + | ModuleOrNamespaceBinding.Binding bind -> GenLetRecBindings cenv cgbuf eenv ([ bind ], m) - // Generate the declarations in the module and its initialization code - let _envAtEnd = GenModuleOrNamespaceContents cenv cgbuf qname lazyInitInfo eenvinner mdef + | ModuleOrNamespaceBinding.Module (mspec, mdef) -> + let hidden = IsHiddenTycon eenv.sigToImplRemapInfo mspec - // If the module has a .cctor for some mutable fields, we need to ensure that when - // those fields are "touched" the InitClass .cctor is forced. The InitClass .cctor will - // then fill in the value of the mutable fields. - if not mspec.IsNamespace && (cgbuf.mgbuf.GetCurrentFields(TypeRefForCompLoc eenvinner.cloc) |> Seq.isEmpty |> not) then - GenForceWholeFileInitializationAsPartOfCCtor cenv cgbuf.mgbuf lazyInitInfo (TypeRefForCompLoc eenvinner.cloc) eenv.imports mspec.Range + let eenvinner = + if mspec.IsNamespace then + eenv + else + { eenv with + cloc = CompLocForFixedModule cenv.options.fragName qname.Text mspec + initLocals = + eenv.initLocals + && not (HasFSharpAttribute cenv.g cenv.g.attrib_SkipLocalsInitAttribute mspec.Attribs) + } + + // Create the class to hold the contents of this module. No class needed if + // we're compiling it as a namespace. + // + // Most module static fields go into the "InitClass" static class. + // However mutable static fields go into the class for the module itself. + // So this static class ends up with a .cctor if it has mutable fields. + // + if not mspec.IsNamespace then + // The use of ILTypeInit.OnAny prevents the execution of the cctor before the + // "main" method in the case where the "main" method is implicit. + let staticClassTrigger = (* if eenv.isFinalFile then *) + ILTypeInit.OnAny (* else ILTypeInit.BeforeField *) + + GenTypeDefForCompLoc( + cenv, + eenvinner, + cgbuf.mgbuf, + eenvinner.cloc, + hidden, + mspec.Attribs, + staticClassTrigger, + false (* atEnd= *) , + true + ) + // Generate the declarations in the module and its initialization code + let _envAtEnd = + GenModuleOrNamespaceContents cenv cgbuf qname lazyInitInfo eenvinner mdef + + // If the module has a .cctor for some mutable fields, we need to ensure that when + // those fields are "touched" the InitClass .cctor is forced. The InitClass .cctor will + // then fill in the value of the mutable fields. + if + not mspec.IsNamespace + && (cgbuf.mgbuf.GetCurrentFields(TypeRefForCompLoc eenvinner.cloc) + |> Seq.isEmpty + |> not) + then + GenForceWholeFileInitializationAsPartOfCCtor + cenv + cgbuf.mgbuf + lazyInitInfo + (TypeRefForCompLoc eenvinner.cloc) + eenv.imports + mspec.Range /// Generate the namespace fragments in a single file and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: CheckedImplFileAfterOptimization) = - let (CheckedImplFile (qname, _, signature, contents, hasExplicitEntryPoint, isScript, anonRecdTypes, _)) = implFile.ImplFile + let (CheckedImplFile (qname, _, signature, contents, hasExplicitEntryPoint, isScript, anonRecdTypes, _)) = + implFile.ImplFile + let optimizeDuringCodeGen = implFile.OptimizeDuringCodeGen let g = cenv.g let m = qname.Range @@ -7536,7 +9969,13 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke for anonInfo in anonRecdTypes.Values do mgbuf.GenerateAnonType((fun ilThisTy -> GenToStringMethod cenv eenv ilThisTy m), anonInfo) - let eenv = {eenv with cloc = { eenv.cloc with TopImplQualifiedName = qname.Text } } + let eenv = + { eenv with + cloc = + { eenv.cloc with + TopImplQualifiedName = qname.Text + } + } cenv.optimizeDuringCodeGen <- optimizeDuringCodeGen @@ -7546,25 +9985,28 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke let initClassCompLoc = CompLocForInitClass eenv.cloc let initClassTy = mkILTyForCompLoc initClassCompLoc - let initClassTrigger = (* if isFinalFile then *) ILTypeInit.OnAny (* else ILTypeInit.BeforeField *) + let initClassTrigger = (* if isFinalFile then *) + ILTypeInit.OnAny (* else ILTypeInit.BeforeField *) let eenv = { eenv with cloc = initClassCompLoc isFinalFile = isFinalFile - someTypeInThisAssembly = initClassTy } + someTypeInThisAssembly = initClassTy + } // Create the class to hold the initialization code and static fields for this file. // internal static class $ {} // Put it at the end since that gives an approximation of dependency order (to aid FSI.EXE's code generator - see FSharp 1.0 5548) - GenTypeDefForCompLoc (cenv, eenv, mgbuf, initClassCompLoc, useHiddenInitCode, [], initClassTrigger, false, (*atEnd=*)true) + GenTypeDefForCompLoc(cenv, eenv, mgbuf, initClassCompLoc, useHiddenInitCode, [], initClassTrigger, false, true) // lazyInitInfo is an accumulator of functions which add the forced initialization of the storage module to // - mutable fields in public modules // - static "let" bindings in types // These functions only get executed/committed if we actually end up producing some code for the .cctor for the storage module. // The existence of .cctors adds costs to execution, so this is a half-sensible attempt to avoid adding them when possible. - let lazyInitInfo = ResizeArray ILInstr list -> ILInstr list -> unit>() + let lazyInitInfo = + ResizeArray ILInstr list -> ILInstr list -> unit>() // codegen .cctor/main for outer module let clocCcu = CompLocForCcu cenv.viewCcu @@ -7581,11 +10023,18 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke // topInstrs is ILInstr[] and contains the abstract IL for this file's top-level actions. topCode is the ILMethodBody for that same code. let topInstrs, topCode = - CodeGenMethod cenv mgbuf - ([], methodName, eenv, 0, None, + CodeGenMethod + cenv + mgbuf + ([], + methodName, + eenv, + 0, + None, (fun cgbuf eenv -> - GenImplFileContents cenv cgbuf qname lazyInitInfo eenv signature contents - CG.EmitInstr cgbuf (pop 0) Push0 I_ret), m) + GenImplFileContents cenv cgbuf qname lazyInitInfo eenv signature contents + CG.EmitInstr cgbuf (pop 0) Push0 I_ret), + m) // The code generation for the initialization is now complete and the IL code is in topCode. // Make a .cctor and/or main method to contain the code. This initializes all modules. @@ -7613,12 +10062,21 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke // Final file, explicit entry point: place the code in a .cctor, and add code to main that forces the .cctor (if topCode has initialization effect). | Some tref -> if doesSomething then - lazyInitInfo.Add (fun fspec feefee seqpt -> + lazyInitInfo.Add(fun fspec feefee seqpt -> // This adds the explicit init of the .cctor to the explicit entry point main method let ilDebugRange = GenPossibleILDebugRange cenv m - mgbuf.AddExplicitInitToSpecificMethodDef((fun md -> md.IsEntryPoint), tref, fspec, ilDebugRange, eenv.imports, feefee, seqpt)) - let cctorMethDef = mkILClassCtor (MethodBody.IL (lazy topCode)) + mgbuf.AddExplicitInitToSpecificMethodDef( + (fun md -> md.IsEntryPoint), + tref, + fspec, + ilDebugRange, + eenv.imports, + feefee, + seqpt + )) + + let cctorMethDef = mkILClassCtor (MethodBody.IL(lazy topCode)) mgbuf.AddMethodDef(initClassTy.TypeRef, cctorMethDef) // Final file, implicit entry point. We generate no .cctor. @@ -7627,23 +10085,31 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke // } | None -> let ilAttrs = mkILCustomAttrs (GenAttrs cenv eenv mainInfo) + if not cenv.options.isInteractive && not doesSomething then let errorM = m.EndRange - warning (Error(FSComp.SR.ilMainModuleEmpty(), errorM)) + warning (Error(FSComp.SR.ilMainModuleEmpty (), errorM)) // generate main@ let ilMainMethodDef = - let mdef = mkILNonGenericStaticMethod(mainMethName, ILMemberAccess.Public, [], mkILReturn ILType.Void, MethodBody.IL (lazy topCode)) - mdef.With(isEntryPoint= true, customAttrs = ilAttrs) + let mdef = + mkILNonGenericStaticMethod ( + mainMethName, + ILMemberAccess.Public, + [], + mkILReturn ILType.Void, + MethodBody.IL(lazy topCode) + ) - mgbuf.AddMethodDef(initClassTy.TypeRef, ilMainMethodDef) + mdef.With(isEntryPoint = true, customAttrs = ilAttrs) + mgbuf.AddMethodDef(initClassTy.TypeRef, ilMainMethodDef) // Library file: generate an optional .cctor if topCode has initialization effect | None -> if doesSomething then // Add the cctor - let cctorMethDef = mkILClassCtor (MethodBody.IL (lazy topCode)) + let cctorMethDef = mkILClassCtor (MethodBody.IL(lazy topCode)) mgbuf.AddMethodDef(initClassTy.TypeRef, cctorMethDef) // Commit the directed initializations @@ -7652,12 +10118,13 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke // Why do this for the final file? // There is no need to do this for a final file with an implicit entry point. For an explicit entry point in lazyInitInfo. let initFieldName = CompilerGeneratedName "init" + let ilFieldDef = mkILStaticField (initFieldName, g.ilg.typ_Int32, None, None, ComputeMemberAccess true) |> g.AddFieldNeverAttributes |> g.AddFieldGeneratedAttributes - let fspec = mkILFieldSpecInTy (initClassTy, initFieldName, cenv. g.ilg.typ_Int32) + let fspec = mkILFieldSpecInTy (initClassTy, initFieldName, cenv.g.ilg.typ_Int32) CountStaticFieldDef() mgbuf.AddFieldDef(initClassTy.TypeRef, ilFieldDef) @@ -7672,7 +10139,9 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke // uses the constructs exported from this module. // We add the module type all over again. Note no shadow locals for static fields needed here since they are only relevant to the main/.cctor let eenvafter = - let allocVal = ComputeAndAddStorageForLocalTopVal (cenv, g, cenv.intraAssemblyInfo, cenv.options.isInteractive, NoShadowLocal) + let allocVal = + ComputeAndAddStorageForLocalTopVal(cenv, g, cenv.intraAssemblyInfo, cenv.options.isInteractive, NoShadowLocal) + AddBindingsForLocalModuleType allocVal clocCcu eenv signature eenvafter @@ -7680,55 +10149,66 @@ and GenImplFile cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (implFile: Checke and GenForceWholeFileInitializationAsPartOfCCtor cenv (mgbuf: AssemblyBuilder) (lazyInitInfo: ResizeArray<_>) tref imports m = // Authoring a .cctor with effects forces the cctor for the 'initialization' module by doing a dummy store & load of a field // Doing both a store and load keeps FxCop happier because it thinks the field is useful - lazyInitInfo.Add (fun fspec feefee seqpt -> + lazyInitInfo.Add(fun fspec feefee seqpt -> let ilDebugRange = GenPossibleILDebugRange cenv m mgbuf.AddExplicitInitToSpecificMethodDef((fun md -> md.Name = ".cctor"), tref, fspec, ilDebugRange, imports, feefee, seqpt)) - /// Generate an Equals method. and GenEqualsOverrideCallingIComparable cenv (tcref: TyconRef, ilThisTy, _ilThatTy) = let g = cenv.g - let mspec = mkILNonGenericInstanceMethSpecInTy (g.iltyp_IComparable, "CompareTo", [g.ilg.typ_Object], g.ilg.typ_Int32) + + let mspec = + mkILNonGenericInstanceMethSpecInTy (g.iltyp_IComparable, "CompareTo", [ g.ilg.typ_Object ], g.ilg.typ_Int32) let ilInstrs = - [ mkLdarg0 - mkLdarg 1us - if tcref.IsStructOrEnumTycon then - I_callconstraint ( Normalcall, ilThisTy, mspec, None) - else - I_callvirt ( Normalcall, mspec, None) - mkLdcInt32 0 - AI_ceq ] - - let ilMethodBody = mkMethodBody(true, [], 2, nonBranchingInstrsToCode ilInstrs, None, None) - - mkILNonGenericVirtualMethod - ("Equals", ILMemberAccess.Public, - [mkILParamNamed ("obj", g.ilg.typ_Object)], - mkILReturn g.ilg.typ_Bool, - ilMethodBody) + [ + mkLdarg0 + mkLdarg 1us + if tcref.IsStructOrEnumTycon then + I_callconstraint(Normalcall, ilThisTy, mspec, None) + else + I_callvirt(Normalcall, mspec, None) + mkLdcInt32 0 + AI_ceq + ] + + let ilMethodBody = + mkMethodBody (true, [], 2, nonBranchingInstrsToCode ilInstrs, None, None) + + mkILNonGenericVirtualMethod ( + "Equals", + ILMemberAccess.Public, + [ mkILParamNamed ("obj", g.ilg.typ_Object) ], + mkILReturn g.ilg.typ_Bool, + ilMethodBody + ) |> AddNonUserCompilerGeneratedAttribs g and GenFieldInit m c = match c with | ConstToILFieldInit fieldInit -> fieldInit - | _ -> error(Error(FSComp.SR.ilTypeCannotBeUsedForLiteralField(), m)) + | _ -> error (Error(FSComp.SR.ilTypeCannotBeUsedForLiteralField (), m)) and GenWitnessParams cenv eenv m (witnessInfos: TraitWitnessInfos) = - ((Set.empty, 0), witnessInfos) ||> List.mapFold (fun (used,i) witnessInfo -> + ((Set.empty, 0), witnessInfos) + ||> List.mapFold (fun (used, i) witnessInfo -> let ty = GenWitnessTy cenv.g witnessInfo let nm = String.uncapitalize witnessInfo.MemberName let nm = if used.Contains nm then nm + string i else nm - let ilParam = - { Name=Some nm - Type= GenType cenv m eenv.tyenv ty - Default=None - Marshal=None - IsIn=false - IsOut=false - IsOptional=false - CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs []) - MetadataIndex = NoMetadataIdx }: ILParameter + + let ilParam: ILParameter = + { + Name = Some nm + Type = GenType cenv m eenv.tyenv ty + Default = None + Marshal = None + IsIn = false + IsOut = false + IsOptional = false + CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs []) + MetadataIndex = NoMetadataIdx + } + ilParam, (used.Add nm, i + 1)) |> fst @@ -7738,66 +10218,101 @@ and GenAbstractBinding cenv eenv tref (vref: ValRef) = let m = vref.Range let memberInfo = Option.get vref.MemberInfo let attribs = vref.Attribs - let hasPreserveSigImplFlag, hasSynchronizedImplFlag, hasNoInliningFlag, hasAggressiveInliningImplFlag, attribs = ComputeMethodImplAttribs cenv vref.Deref attribs + + let hasPreserveSigImplFlag, hasSynchronizedImplFlag, hasNoInliningFlag, hasAggressiveInliningImplFlag, attribs = + ComputeMethodImplAttribs cenv vref.Deref attribs + if memberInfo.MemberFlags.IsDispatchSlot && not memberInfo.IsImplemented then let mspec, _mspecW, ctps, mtps, _curriedArgInfos, argInfos, retInfo, witnessInfos, methArgTys, returnTy = GetMethodSpecForMemberVal cenv memberInfo vref let ilAttrs = - [ yield! GenAttrs cenv eenv attribs - yield! GenCompilationArgumentCountsAttr cenv vref.Deref - - match vref.MemberInfo, returnTy with - | Some memberInfo, Some returnTy when - memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGet || - memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertySet || - memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGetSet -> - match GenReadOnlyAttributeIfNecessary g returnTy with Some ilAttr -> ilAttr | _ -> () - | _ -> () ] + [ + yield! GenAttrs cenv eenv attribs + yield! GenCompilationArgumentCountsAttr cenv vref.Deref + + match vref.MemberInfo, returnTy with + | Some memberInfo, Some returnTy when + memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGet + || memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertySet + || memberInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGetSet + -> + match GenReadOnlyAttributeIfNecessary g returnTy with + | Some ilAttr -> ilAttr + | _ -> () + | _ -> () + ] assert witnessInfos.IsEmpty - let eenvForMeth = EnvForTypars (ctps@mtps) eenv + let eenvForMeth = EnvForTypars (ctps @ mtps) eenv let ilMethTypars = GenGenericParams cenv eenvForMeth mtps - let ilReturn = GenReturnInfo cenv eenvForMeth returnTy mspec.FormalReturnType retInfo + + let ilReturn = + GenReturnInfo cenv eenvForMeth returnTy mspec.FormalReturnType retInfo + let ilParams = GenParams cenv eenvForMeth m mspec [] argInfos methArgTys None let compileAsInstance = ValRefIsCompiledAsInstanceMember g vref - let mdef = mkILGenericVirtualMethod (vref.CompiledName g.CompilerGlobalState, ILMemberAccess.Public, ilMethTypars, ilParams, ilReturn, MethodBody.Abstract) + + let mdef = + mkILGenericVirtualMethod ( + vref.CompiledName g.CompilerGlobalState, + ILMemberAccess.Public, + ilMethTypars, + ilParams, + ilReturn, + MethodBody.Abstract + ) let mdef = fixupVirtualSlotFlags mdef + let mdef = if mdef.IsVirtual then - mdef.WithFinal(memberInfo.MemberFlags.IsFinal).WithAbstract(memberInfo.MemberFlags.IsDispatchSlot) - else mdef + mdef + .WithFinal(memberInfo.MemberFlags.IsFinal) + .WithAbstract(memberInfo.MemberFlags.IsDispatchSlot) + else + mdef + let mdef = - mdef.WithPreserveSig(hasPreserveSigImplFlag) - .WithSynchronized(hasSynchronizedImplFlag) - .WithNoInlining(hasNoInliningFlag) - .WithAggressiveInlining(hasAggressiveInliningImplFlag) + mdef + .WithPreserveSig(hasPreserveSigImplFlag) + .WithSynchronized(hasSynchronizedImplFlag) + .WithNoInlining(hasNoInliningFlag) + .WithAggressiveInlining(hasAggressiveInliningImplFlag) match memberInfo.MemberFlags.MemberKind with | SynMemberKind.ClassConstructor | SynMemberKind.Constructor | SynMemberKind.Member -> - let mdef = mdef.With(customAttrs= mkILCustomAttrs ilAttrs) - [mdef], [], [] - | SynMemberKind.PropertyGetSet -> error(Error(FSComp.SR.ilUnexpectedGetSetAnnotation(), m)) - | SynMemberKind.PropertySet | SynMemberKind.PropertyGet -> - let v = vref.Deref - let vtyp = ReturnTypeOfPropertyVal g v - if CompileAsEvent g attribs then - - let edef = GenEventForProperty cenv eenvForMeth mspec v ilAttrs m vtyp - [], [], [edef] - else - let ilPropDef = - let ilPropTy = GenType cenv m eenvForMeth.tyenv vtyp - let ilPropTy = GenReadOnlyModReqIfNecessary g vtyp ilPropTy - let ilArgTys = v |> ArgInfosOfPropertyVal g |> List.map fst |> GenTypes cenv m eenvForMeth.tyenv - GenPropertyForMethodDef compileAsInstance tref mdef v memberInfo ilArgTys ilPropTy (mkILCustomAttrs ilAttrs) None - let mdef = mdef.WithSpecialName - [mdef], [ilPropDef], [] + let mdef = mdef.With(customAttrs = mkILCustomAttrs ilAttrs) + [ mdef ], [], [] + | SynMemberKind.PropertyGetSet -> error (Error(FSComp.SR.ilUnexpectedGetSetAnnotation (), m)) + | SynMemberKind.PropertySet + | SynMemberKind.PropertyGet -> + let v = vref.Deref + let vtyp = ReturnTypeOfPropertyVal g v + + if CompileAsEvent g attribs then + + let edef = GenEventForProperty cenv eenvForMeth mspec v ilAttrs m vtyp + [], [], [ edef ] + else + let ilPropDef = + let ilPropTy = GenType cenv m eenvForMeth.tyenv vtyp + let ilPropTy = GenReadOnlyModReqIfNecessary g vtyp ilPropTy + + let ilArgTys = + v + |> ArgInfosOfPropertyVal g + |> List.map fst + |> GenTypes cenv m eenvForMeth.tyenv + + GenPropertyForMethodDef compileAsInstance tref mdef v memberInfo ilArgTys ilPropTy (mkILCustomAttrs ilAttrs) None + + let mdef = mdef.WithSpecialName + [ mdef ], [ ilPropDef ], [] else [], [], [] @@ -7807,682 +10322,968 @@ and GenToStringMethod cenv eenv ilThisTy m = /// Generate a ToString/get_Message method that calls 'sprintf "%A"' and GenPrintingMethod cenv eenv methName ilThisTy m = - let g = cenv.g - [ if not g.useReflectionFreeCodeGen then - match (eenv.valsInScope.TryFind g.sprintf_vref.Deref, - eenv.valsInScope.TryFind g.new_format_vref.Deref) with - | Some(Lazy(Method(_, _, sprintfMethSpec, _, _, _, _, _, _, _, _, _))), Some(Lazy(Method(_, _, newFormatMethSpec, _, _, _, _, _, _, _, _, _))) -> - // The type returned by the 'sprintf' call - let funcTy = EraseClosures.mkILFuncTy cenv.ilxPubCloEnv ilThisTy g.ilg.typ_String - - // Give the instantiation of the printf format object, i.e. a Format`5 object compatible with StringFormat - let newFormatMethSpec = - mkILMethSpec(newFormatMethSpec.MethodRef, AsObject, - [ // 'T -> string' - funcTy - // rest follow from 'StringFormat' - GenUnitTy cenv eenv m - g.ilg.typ_String - g.ilg.typ_String - ilThisTy], []) - - // Instantiate with our own type - let sprintfMethSpec = mkILMethSpec(sprintfMethSpec.MethodRef, AsObject, [], [funcTy]) - - // Here's the body of the method. Call printf, then invoke the function it returns - let callInstrs = EraseClosures.mkCallFunc cenv.ilxPubCloEnv (fun _ -> 0us) eenv.tyenv.Count Normalcall (Apps_app(ilThisTy, Apps_done g.ilg.typ_String)) - - let ilInstrs = - [ // load the hardwired format string - I_ldstr "%+A" - // make the printf format object - mkNormalNewobj newFormatMethSpec - // call sprintf - mkNormalCall sprintfMethSpec - // call the function returned by sprintf - mkLdarg0 - if ilThisTy.Boxity = ILBoxity.AsValue then - mkNormalLdobj ilThisTy - yield! callInstrs ] - - let ilMethodBody = mkMethodBody (true, [], 2, nonBranchingInstrsToCode ilInstrs, None, eenv.imports) - - let mdef = mkILNonGenericVirtualMethod (methName, ILMemberAccess.Public, [], mkILReturn g.ilg.typ_String, ilMethodBody) - let mdef = mdef.With(customAttrs = mkILCustomAttrs [ g.CompilerGeneratedAttribute ]) - yield mdef - | _ -> () ] + let g = cenv.g + [ if not g.useReflectionFreeCodeGen then + match (eenv.valsInScope.TryFind g.sprintf_vref.Deref, eenv.valsInScope.TryFind g.new_format_vref.Deref) with + | Some (Lazy (Method (_, _, sprintfMethSpec, _, _, _, _, _, _, _, _, _))), + Some (Lazy (Method (_, _, newFormatMethSpec, _, _, _, _, _, _, _, _, _))) -> + // The type returned by the 'sprintf' call + let funcTy = EraseClosures.mkILFuncTy cenv.ilxPubCloEnv ilThisTy g.ilg.typ_String + + // Give the instantiation of the printf format object, i.e. a Format`5 object compatible with StringFormat + let newFormatMethSpec = + mkILMethSpec ( + newFormatMethSpec.MethodRef, + AsObject, + [ // 'T -> string' + funcTy + // rest follow from 'StringFormat' + GenUnitTy cenv eenv m + g.ilg.typ_String + g.ilg.typ_String + ilThisTy + ], + [] + ) + + // Instantiate with our own type + let sprintfMethSpec = + mkILMethSpec (sprintfMethSpec.MethodRef, AsObject, [], [ funcTy ]) + + // Here's the body of the method. Call printf, then invoke the function it returns + let callInstrs = + EraseClosures.mkCallFunc + cenv.ilxPubCloEnv + (fun _ -> 0us) + eenv.tyenv.Count + Normalcall + (Apps_app(ilThisTy, Apps_done g.ilg.typ_String)) + + let ilInstrs = + [ // load the hardwired format string + I_ldstr "%+A" + // make the printf format object + mkNormalNewobj newFormatMethSpec + // call sprintf + mkNormalCall sprintfMethSpec + // call the function returned by sprintf + mkLdarg0 + if ilThisTy.Boxity = ILBoxity.AsValue then + mkNormalLdobj ilThisTy + yield! callInstrs + ] + + let ilMethodBody = + mkMethodBody (true, [], 2, nonBranchingInstrsToCode ilInstrs, None, eenv.imports) + + let mdef = + mkILNonGenericVirtualMethod (methName, ILMemberAccess.Public, [], mkILReturn g.ilg.typ_String, ilMethodBody) + + let mdef = mdef.With(customAttrs = mkILCustomAttrs [ g.CompilerGeneratedAttribute ]) + yield mdef + | _ -> () + ] and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let g = cenv.g let tcref = mkLocalTyconRef tycon - if tycon.IsTypeAbbrev then () else - match tycon.TypeReprInfo with + + if tycon.IsTypeAbbrev then + () + else + match tycon.TypeReprInfo with #if !NO_TYPEPROVIDERS - | TProvidedNamespaceRepr _ - | TProvidedTypeRepr _ + | TProvidedNamespaceRepr _ + | TProvidedTypeRepr _ #endif - | TNoRepr - | TAsmRepr _ - | TILObjectRepr _ - | TMeasureableRepr _ -> () - | TFSharpObjectRepr _ - | TFSharpRecdRepr _ - | TFSharpUnionRepr _ -> - let eenvinner = EnvForTycon tycon eenv - let thisTy = generalizedTyconRef g tcref - - let ilThisTy = GenType cenv m eenvinner.tyenv thisTy - let tref = ilThisTy.TypeRef - let ilGenParams = GenGenericParams cenv eenvinner tycon.TyparsNoRange - let ilIntfTys = tycon.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv m eenvinner.tyenv) - let ilTypeName = tref.Name - - let hidden = IsHiddenTycon eenv.sigToImplRemapInfo tycon - let hiddenRepr = hidden || IsHiddenTyconRepr eenv.sigToImplRemapInfo tycon - let access = ComputeTypeAccess tref hidden - - // The implicit augmentation doesn't actually create CompareTo(object) or Object.Equals - // So we do it here. - // - // Note you only have to implement 'System.IComparable' to customize structural comparison AND equality on F# types - // See also FinalTypeDefinitionChecksAtEndOfInferenceScope in tc.fs - // - // Generate an Equals method implemented via IComparable if the type EXPLICITLY implements IComparable. - // HOWEVER, if the type doesn't override Object.Equals already. - let augmentOverrideMethodDefs = - - (if Option.isNone tycon.GeneratedCompareToValues && - Option.isNone tycon.GeneratedHashAndEqualsValues && - tycon.HasInterface g g.mk_IComparable_ty && - not (tycon.HasOverride g "Equals" [g.obj_ty]) && - not tycon.IsFSharpInterfaceTycon - then - [ GenEqualsOverrideCallingIComparable cenv (tcref, ilThisTy, ilThisTy) ] - else []) - - // Generate the interface slots and abstract slots. - let abstractMethodDefs, abstractPropDefs, abstractEventDefs = - if tycon.IsFSharpDelegateTycon then - [], [], [] - else - // sort by order of declaration - // REVIEW: this should be based off tcaug_adhoc_list, which is in declaration order - tycon.MembersOfFSharpTyconSorted - |> List.sortWith (fun v1 v2 -> rangeOrder.Compare(v1.DefinitionRange, v2.DefinitionRange)) - |> List.map (GenAbstractBinding cenv eenv tref) - |> List.unzip3 - |> mapTriple (List.concat, List.concat, List.concat) + | TNoRepr + | TAsmRepr _ + | TILObjectRepr _ + | TMeasureableRepr _ -> () + | TFSharpObjectRepr _ + | TFSharpRecdRepr _ + | TFSharpUnionRepr _ -> + let eenvinner = EnvForTycon tycon eenv + let thisTy = generalizedTyconRef g tcref + + let ilThisTy = GenType cenv m eenvinner.tyenv thisTy + let tref = ilThisTy.TypeRef + let ilGenParams = GenGenericParams cenv eenvinner tycon.TyparsNoRange + + let ilIntfTys = + tycon.ImmediateInterfaceTypesOfFSharpTycon + |> List.map (GenType cenv m eenvinner.tyenv) + + let ilTypeName = tref.Name + + let hidden = IsHiddenTycon eenv.sigToImplRemapInfo tycon + let hiddenRepr = hidden || IsHiddenTyconRepr eenv.sigToImplRemapInfo tycon + let access = ComputeTypeAccess tref hidden + + // The implicit augmentation doesn't actually create CompareTo(object) or Object.Equals + // So we do it here. + // + // Note you only have to implement 'System.IComparable' to customize structural comparison AND equality on F# types + // See also FinalTypeDefinitionChecksAtEndOfInferenceScope in tc.fs + // + // Generate an Equals method implemented via IComparable if the type EXPLICITLY implements IComparable. + // HOWEVER, if the type doesn't override Object.Equals already. + let augmentOverrideMethodDefs = + + (if + Option.isNone tycon.GeneratedCompareToValues + && Option.isNone tycon.GeneratedHashAndEqualsValues + && tycon.HasInterface g g.mk_IComparable_ty + && not (tycon.HasOverride g "Equals" [ g.obj_ty ]) + && not tycon.IsFSharpInterfaceTycon + then + [ GenEqualsOverrideCallingIComparable cenv (tcref, ilThisTy, ilThisTy) ] + else + []) + + // Generate the interface slots and abstract slots. + let abstractMethodDefs, abstractPropDefs, abstractEventDefs = + if tycon.IsFSharpDelegateTycon then + [], [], [] + else + // sort by order of declaration + // REVIEW: this should be based off tcaug_adhoc_list, which is in declaration order + tycon.MembersOfFSharpTyconSorted + |> List.sortWith (fun v1 v2 -> rangeOrder.Compare(v1.DefinitionRange, v2.DefinitionRange)) + |> List.map (GenAbstractBinding cenv eenv tref) + |> List.unzip3 + |> mapTriple (List.concat, List.concat, List.concat) + let abstractPropDefs = abstractPropDefs |> MergePropertyDefs m + let isAbstract = isAbstractTycon tycon - let abstractPropDefs = abstractPropDefs |> MergePropertyDefs m - let isAbstract = isAbstractTycon tycon + // Generate all the method impls showing how various abstract slots and interface slots get implemented + // REVIEW: no method impl generated for IStructuralHash or ICompare + let methodImpls = + [ + for vref in tycon.MembersOfFSharpTyconByName |> NameMultiMap.range do + assert vref.IsMember + let memberInfo = vref.MemberInfo.Value - // Generate all the method impls showing how various abstract slots and interface slots get implemented - // REVIEW: no method impl generated for IStructuralHash or ICompare - let methodImpls = - [ for vref in tycon.MembersOfFSharpTyconByName |> NameMultiMap.range do - assert vref.IsMember - let memberInfo = vref.MemberInfo.Value - if memberInfo.MemberFlags.IsOverrideOrExplicitImpl && not (CompileAsEvent g vref.Attribs) then + if + memberInfo.MemberFlags.IsOverrideOrExplicitImpl + && not (CompileAsEvent g vref.Attribs) + then - for slotsig in memberInfo.ImplementedSlotSigs do + for slotsig in memberInfo.ImplementedSlotSigs do - if isInterfaceTy g slotsig.ImplementedType then + if isInterfaceTy g slotsig.DeclaringType then - match vref.ValReprInfo with - | Some _ -> + match vref.ValReprInfo with + | Some _ -> - let memberParentTypars, memberMethodTypars = - match PartitionValRefTypars g vref with - | Some(_, memberParentTypars, memberMethodTypars, _, _) -> memberParentTypars, memberMethodTypars - | None -> [], [] + let memberParentTypars, memberMethodTypars = + match PartitionValRefTypars g vref with + | Some (_, memberParentTypars, memberMethodTypars, _, _) -> + memberParentTypars, memberMethodTypars + | None -> [], [] - let useMethodImpl = true - let eenvUnderTypars = EnvForTypars memberParentTypars eenv - let _, methodImplGenerator = GenMethodImpl cenv eenvUnderTypars (useMethodImpl, slotsig) m - if useMethodImpl then - yield methodImplGenerator (ilThisTy, memberMethodTypars) + let useMethodImpl = true + let eenvUnderTypars = EnvForTypars memberParentTypars eenv - | _ -> () ] + let _, methodImplGenerator = + GenMethodImpl cenv eenvUnderTypars (useMethodImpl, slotsig) m - // Try to add a DefaultMemberAttribute for the 'Item' property - let defaultMemberAttrs = - // REVIEW: this should be based off tcaug_adhoc_list, which is in declaration order - tycon.MembersOfFSharpTyconSorted - |> List.tryPick (fun vref -> - let name = vref.DisplayName - match vref.MemberInfo with - | None -> None - | Some memberInfo -> - match name, memberInfo.MemberFlags.MemberKind with - | ("Item" | "op_IndexedLookup"), (SynMemberKind.PropertyGet | SynMemberKind.PropertySet) when not (isNil (ArgInfosOfPropertyVal g vref.Deref)) -> - Some( mkILCustomAttribute (g.FindSysILTypeRef "System.Reflection.DefaultMemberAttribute", [g.ilg.typ_String], [ILAttribElem.String(Some name)], []) ) - | _ -> None) - |> Option.toList - - let tyconRepr = tycon.TypeReprInfo - - // DebugDisplayAttribute gets copied to the subtypes generated as part of DU compilation - let debugDisplayAttrs, normalAttrs = tycon.Attribs |> List.partition (IsMatchingFSharpAttribute g g.attrib_DebuggerDisplayAttribute) - let securityAttrs, normalAttrs = normalAttrs |> List.partition (fun a -> IsSecurityAttribute g cenv.amap cenv.casApplied a m) - let generateDebugDisplayAttribute = - not g.useReflectionFreeCodeGen && - not g.compilingFSharpCore && - tycon.IsUnionTycon && - isNil debugDisplayAttrs - - let generateDebugProxies = - not (tyconRefEq g tcref g.unit_tcr_canon) && - not (HasFSharpAttribute g g.attrib_DebuggerTypeProxyAttribute tycon.Attribs) - - let permissionSets = CreatePermissionSets cenv eenv securityAttrs - let secDecls = if List.isEmpty securityAttrs then emptyILSecurityDecls else mkILSecurityDecls permissionSets - - let ilDebugDisplayAttributes = - [ yield! GenAttrs cenv eenv debugDisplayAttrs - if generateDebugDisplayAttribute then - yield g.mkDebuggerDisplayAttribute ("{" + debugDisplayMethodName + "(),nq}") ] - - let ilCustomAttrs = - [ yield! defaultMemberAttrs - yield! normalAttrs - |> List.filter (IsMatchingFSharpAttribute g g.attrib_StructLayoutAttribute >> not) - |> GenAttrs cenv eenv - yield! ilDebugDisplayAttributes ] - - let reprAccess = ComputeMemberAccess hiddenRepr - - - let ilTypeDefKind = - match tyconRepr with - | TFSharpObjectRepr o -> - match o.fsobjmodel_kind with - | TFSharpClass -> ILTypeDefKind.Class - | TFSharpStruct -> ILTypeDefKind.ValueType - | TFSharpInterface -> ILTypeDefKind.Interface - | TFSharpEnum -> ILTypeDefKind.Enum - | TFSharpDelegate _ -> ILTypeDefKind.Delegate - | TFSharpRecdRepr _ - | TFSharpUnionRepr _ when tycon.IsStructOrEnumTycon -> ILTypeDefKind.ValueType - | _ -> ILTypeDefKind.Class - - let requiresExtraField = - let isEmptyStruct = - (match ilTypeDefKind with ILTypeDefKind.ValueType -> true | _ -> false) && - // All structs are sequential by default - // Structs with no instance fields get size 1, pack 0 - tycon.AllFieldsArray |> Array.forall (fun f -> f.IsStatic) - - isEmptyStruct && cenv.options.workAroundReflectionEmitBugs && not tycon.TyparsNoRange.IsEmpty - - // Compute a bunch of useful things for each field - let isCLIMutable = (TryFindFSharpBoolAttribute g g.attrib_CLIMutableAttribute tycon.Attribs = Some true) - let fieldSummaries = - - [ for fspec in tycon.AllFieldsArray do - - let useGenuineField = useGenuineField tycon fspec - - // The property (or genuine IL field) is hidden in these circumstances: - // - secret fields apart from "__value" fields for enums - // - the representation of the type is hidden - // - the F# field is hidden by a signature or private declaration - let isPropHidden = - // Enums always have public cases irrespective of Enum Visibility - if tycon.IsEnumTycon then false - else - (fspec.IsCompilerGenerated || hiddenRepr || - IsHiddenRecdField eenv.sigToImplRemapInfo (tcref.MakeNestedRecdFieldRef fspec)) - let ilType = GenType cenv m eenvinner.tyenv fspec.FormalType - let ilFieldName = ComputeFieldName tycon fspec + if useMethodImpl then + yield methodImplGenerator (ilThisTy, memberMethodTypars) - yield (useGenuineField, ilFieldName, fspec.IsMutable, fspec.IsStatic, fspec.PropertyAttribs, ilType, isPropHidden, fspec) ] + | _ -> () + ] - // Generate the IL fields - let ilFieldDefs = - [ for useGenuineField, ilFieldName, isFSharpMutable, isStatic, _, ilPropType, isPropHidden, fspec in fieldSummaries do - - let ilFieldOffset = - match TryFindFSharpAttribute g g.attrib_FieldOffsetAttribute fspec.FieldAttribs with - | Some (Attrib(_, _, [ AttribInt32Arg fieldOffset ], _, _, _, _)) -> - Some fieldOffset - | Some attrib -> - errorR(Error(FSComp.SR.ilFieldOffsetAttributeCouldNotBeDecoded(), attrib.Range)) - None - | _ -> - None - - let attribs = - [ // If using a field then all the attributes go on the field - // See also FSharp 1.0 Bug 4727: once we start compiling them as real mutable fields, you should not be able to target both "property" for "val mutable" fields in classes - - if useGenuineField then yield! fspec.PropertyAttribs - yield! fspec.FieldAttribs ] - - - let ilNotSerialized = HasFSharpAttributeOpt g g.attrib_NonSerializedAttribute attribs - - let fattribs = - attribs - // Do not generate FieldOffset as a true CLI custom attribute, since it is implied by other corresponding CLI metadata - |> List.filter (IsMatchingFSharpAttribute g g.attrib_FieldOffsetAttribute >> not) - // Do not generate NonSerialized as a true CLI custom attribute, since it is implied by other corresponding CLI metadata - |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_NonSerializedAttribute >> not) - - let ilFieldMarshal, fattribs = GenMarshal cenv fattribs - - // The IL field is hidden if the property/field is hidden OR we're using a property - // AND the field is not mutable (because we can take the address of a mutable field). - // Otherwise fields are always accessed via their property getters/setters - // - // Additionally, don't hide fields for multiemit in F# Interactive - let isFieldHidden = - isPropHidden || - (not useGenuineField && - not isFSharpMutable && - not (cenv.options.isInteractive && cenv.options.fsiMultiAssemblyEmit)) - - let extraAttribs = - match tyconRepr with - | TFSharpRecdRepr _ when not useGenuineField -> [ g.DebuggerBrowsableNeverAttribute ] // hide fields in records in debug display - | _ -> [] // don't hide fields in classes in debug display - - let access = ComputeMemberAccess isFieldHidden - - let literalValue = Option.map (GenFieldInit m) fspec.LiteralValue - - let fdef = - ILFieldDef(name = ilFieldName, - fieldType = ilPropType, - attributes = enum 0, - data = None, - literalValue = None, - offset = ilFieldOffset, - marshal = None, - customAttrs = mkILCustomAttrs (GenAttrs cenv eenv fattribs @ extraAttribs)) - .WithAccess(access) - .WithStatic(isStatic) - .WithSpecialName(ilFieldName="value__" && tycon.IsEnumTycon) - .WithNotSerialized(ilNotSerialized) - .WithLiteralDefaultValue(literalValue) - .WithFieldMarshal(ilFieldMarshal) - yield fdef - - if requiresExtraField then - yield mkILInstanceField("__dummy", g.ilg.typ_Int32, None, ILMemberAccess.Assembly) ] - - // Generate property definitions for the fields compiled as properties - let ilPropertyDefsForFields = - [ for i, (useGenuineField, _, isFSharpMutable, isStatic, propAttribs, ilPropType, _, fspec) in Seq.indexed fieldSummaries do - if not useGenuineField then - let ilCallingConv = if isStatic then ILCallingConv.Static else ILCallingConv.Instance - let ilPropName = fspec.LogicalName - let ilHasSetter = isCLIMutable || isFSharpMutable - let ilFieldAttrs = GenAttrs cenv eenv propAttribs @ [mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i] - yield - ILPropertyDef(name= ilPropName, - attributes= PropertyAttributes.None, - setMethod= (if ilHasSetter then Some(mkILMethRef(tref, ilCallingConv, "set_" + ilPropName, 0, [ilPropType], ILType.Void)) else None), - getMethod= Some(mkILMethRef(tref, ilCallingConv, "get_" + ilPropName, 0, [], ilPropType)), - callingConv= ilCallingConv.ThisConv, - propertyType= ilPropType, - init= None, - args= [], - customAttrs = mkILCustomAttrs ilFieldAttrs) ] - - let methodDefs = - [ // Generate property getter methods for those fields that have properties - for useGenuineField, ilFieldName, _, isStatic, _, ilPropType, isPropHidden, fspec in fieldSummaries do - if not useGenuineField then - let ilPropName = fspec.LogicalName - let ilMethName = "get_" + ilPropName - let access = ComputeMemberAccess isPropHidden - yield mkLdfldMethodDef (ilMethName, access, isStatic, ilThisTy, ilFieldName, ilPropType) - - // Generate property setter methods for the mutable fields - for useGenuineField, ilFieldName, isFSharpMutable, isStatic, _, ilPropType, isPropHidden, fspec in fieldSummaries do - let ilHasSetter = (isCLIMutable || isFSharpMutable) && not useGenuineField - if ilHasSetter then - let ilPropName = fspec.LogicalName - let ilFieldSpec = mkILFieldSpecInTy(ilThisTy, ilFieldName, ilPropType) - let ilMethName = "set_" + ilPropName - let ilParams = [mkILParamNamed("value", ilPropType)] - let ilReturn = mkILReturn ILType.Void - let iLAccess = ComputeMemberAccess isPropHidden - let ilMethodDef = - if isStatic then - let ilMethodBody = mkMethodBody(true, [], 2, nonBranchingInstrsToCode [ mkLdarg0;mkNormalStsfld ilFieldSpec], None, eenv.imports) - mkILNonGenericStaticMethod (ilMethName, iLAccess, ilParams, ilReturn, ilMethodBody) - else - let ilMethodBody = mkMethodBody(true, [], 2, nonBranchingInstrsToCode [ mkLdarg0;mkLdarg 1us;mkNormalStfld ilFieldSpec], None, eenv.imports) - mkILNonGenericInstanceMethod (ilMethName, iLAccess, ilParams, ilReturn, ilMethodBody) - yield ilMethodDef.WithSpecialName - - if generateDebugDisplayAttribute then - let (|Lazy|) (x: Lazy<_>) = x.Force() - match (eenv.valsInScope.TryFind g.sprintf_vref.Deref, - eenv.valsInScope.TryFind g.new_format_vref.Deref) with - | Some(Lazy(Method(_, _, sprintfMethSpec, _, _, _, _, _, _, _, _, _))), Some(Lazy(Method(_, _, newFormatMethSpec, _, _, _, _, _, _, _, _, _))) -> - // The type returned by the 'sprintf' call - let funcTy = EraseClosures.mkILFuncTy cenv.ilxPubCloEnv ilThisTy g.ilg.typ_String - // Give the instantiation of the printf format object, i.e. a Format`5 object compatible with StringFormat - let newFormatMethSpec = mkILMethSpec(newFormatMethSpec.MethodRef, AsObject, - [// 'T -> string' - funcTy - // rest follow from 'StringFormat' - GenUnitTy cenv eenv m - g.ilg.typ_String - g.ilg.typ_String - g.ilg.typ_String], []) - // Instantiate with our own type - let sprintfMethSpec = mkILMethSpec(sprintfMethSpec.MethodRef, AsObject, [], [funcTy]) - - // Here's the body of the method. Call printf, then invoke the function it returns - let callInstrs = EraseClosures.mkCallFunc cenv.ilxPubCloEnv (fun _ -> 0us) eenv.tyenv.Count Normalcall (Apps_app(ilThisTy, Apps_done g.ilg.typ_String)) - - let ilInstrs = - [ // load the hardwired format string - I_ldstr "%+0.8A" - // make the printf format object - mkNormalNewobj newFormatMethSpec - // call sprintf - mkNormalCall sprintfMethSpec - // call the function returned by sprintf - mkLdarg0 - if ilThisTy.Boxity = ILBoxity.AsValue then - mkNormalLdobj ilThisTy - yield! callInstrs ] - - let ilMethodBody = mkMethodBody (true, [], 2, nonBranchingInstrsToCode ilInstrs, None, eenv.imports) - - let ilMethodDef = mkILNonGenericInstanceMethod (debugDisplayMethodName, ILMemberAccess.Assembly, [], mkILReturn g.ilg.typ_Object, ilMethodBody) - yield ilMethodDef.WithSpecialName |> AddNonUserCompilerGeneratedAttribs g - | None, _ -> - //printfn "sprintf not found" - () - | _, None -> - //printfn "new format not found" - () - | _ -> - //printfn "neither found, or non-method" - () - - // Build record constructors and the funky methods that go with records and delegate types. - // Constructors and delegate methods have the same access as the representation - match tyconRepr with - | TFSharpRecdRepr _ when not tycon.IsEnumTycon -> - // No constructor for enum types - // Otherwise find all the non-static, non zero-init fields and build a constructor - let relevantFields = - fieldSummaries - |> List.filter (fun (_, _, _, isStatic, _, _, _, fspec) -> not isStatic && not fspec.IsZeroInit) - - let fieldNamesAndTypes = - relevantFields - |> List.map (fun (_, ilFieldName, _, _, _, ilPropType, _, fspec) -> (fspec.LogicalName, ilFieldName, ilPropType)) - - let isStructRecord = tycon.IsStructRecordOrUnionTycon - - // No type spec if the record is a value type - let spec = if isStructRecord then None else Some(g.ilg.typ_Object.TypeSpec) - let ilMethodDef = mkILSimpleStorageCtorWithParamNames(spec, ilThisTy, [], ChooseParamNames fieldNamesAndTypes, reprAccess, None, eenv.imports) - - yield ilMethodDef - // FSharp 1.0 bug 1988: Explicitly setting the ComVisible(true) attribute on an F# type causes an F# record to be emitted in a way that enables mutation for COM interop scenarios - // FSharp 3.0 feature: adding CLIMutable to a record type causes emit of default constructor, and all fields get property setters - // Records that are value types do not create a default constructor with CLIMutable or ComVisible - if not isStructRecord && (isCLIMutable || (TryFindFSharpBoolAttribute g g.attrib_ComVisibleAttribute tycon.Attribs = Some true)) then - yield mkILSimpleStorageCtor(Some g.ilg.typ_Object.TypeSpec, ilThisTy, [], [], reprAccess, None, eenv.imports) - - if not (tycon.HasMember g "ToString" []) then - yield! GenToStringMethod cenv eenv ilThisTy m - - | TFSharpObjectRepr r when tycon.IsFSharpDelegateTycon -> - - // Build all the methods that go with a delegate type - match r.fsobjmodel_kind with - | TFSharpDelegate slotSig -> - - let parameters, ret = - // When "type delegateTy = delegate of unit -> returnTy", - // suppress the unit arg from delegate .Invoke vslot. - let (TSlotSig(nm, ty, ctps, mtps, paraml, returnTy)) = slotSig - let paraml = - match paraml with - | [[tsp]] when isUnitTy g tsp.Type -> [] (* suppress unit arg *) - | paraml -> paraml - GenActualSlotsig m cenv eenvinner (TSlotSig(nm, ty, ctps, mtps, paraml, returnTy)) [] [] - - yield! mkILDelegateMethods reprAccess g.ilg (g.iltyp_AsyncCallback, g.iltyp_IAsyncResult) (parameters, ret) - | _ -> - () - - | TFSharpUnionRepr _ when not (tycon.HasMember g "ToString" []) -> - yield! GenToStringMethod cenv eenv ilThisTy m - | _ -> () ] - - let ilMethods = methodDefs @ augmentOverrideMethodDefs @ abstractMethodDefs - let ilProperties = mkILProperties (ilPropertyDefsForFields @ abstractPropDefs) - let ilEvents = mkILEvents abstractEventDefs - let ilFields = mkILFields ilFieldDefs - - let tdef, tdefDiscards = - let isSerializable = (TryFindFSharpBoolAttribute g g.attrib_AutoSerializableAttribute tycon.Attribs <> Some false) - - match tycon.TypeReprInfo with - | TILObjectRepr _ -> - let tdef = tycon.ILTyconRawMetadata.WithAccess access - let tdef = tdef.With(customAttrs = mkILCustomAttrs ilCustomAttrs, genericParams = ilGenParams) - tdef, None - - | TFSharpRecdRepr _ | TFSharpObjectRepr _ as tyconRepr -> - let super = superOfTycon g tycon - let ilBaseTy = GenType cenv m eenvinner.tyenv super - - // Build a basic type definition - let isObjectType = (match tyconRepr with TFSharpObjectRepr _ -> true | _ -> false) - let ilAttrs = - ilCustomAttrs @ - [mkCompilationMappingAttr g - (int (if isObjectType - then SourceConstructFlags.ObjectType - elif hiddenRepr then SourceConstructFlags.RecordType ||| SourceConstructFlags.NonPublicRepresentation - else SourceConstructFlags.RecordType)) ] - - // For now, generic types always use ILTypeInit.BeforeField. This is because - // there appear to be some cases where ILTypeInit.OnAny causes problems for - // the .NET CLR when used in conjunction with generic classes in cross-DLL - // and NGEN scenarios. - // - // We don't apply this rule to the final file. This is because ALL classes with .cctors in - // the final file (which may in turn trigger the .cctor for the .EXE itself, which - // in turn calls the main() method) must have deterministic initialization - // that is not triggered prior to execution of the main() method. - // If this property doesn't hold then the .cctor can end up running - // before the main method even starts. - let typeDefTrigger = - if eenv.isFinalFile || tycon.TyparsNoRange.IsEmpty then - ILTypeInit.OnAny - else - ILTypeInit.BeforeField - - let isKnownToBeAttribute = ExistsSameHeadTypeInHierarchy g cenv.amap m super g.mk_Attribute_ty - - let tdef = mkILGenericClass (ilTypeName, access, ilGenParams, ilBaseTy, ilIntfTys, - mkILMethods ilMethods, ilFields, emptyILTypeDefs, ilProperties, ilEvents, mkILCustomAttrs ilAttrs, - typeDefTrigger) - - // Set some the extra entries in the definition - let isTheSealedAttribute = tyconRefEq g tcref g.attrib_SealedAttribute.TyconRef - - let tdef = - tdef.WithSealed(isSealedTy g thisTy || isTheSealedAttribute) - .WithSerializable(isSerializable) - .WithAbstract(isAbstract) - .WithImport(isComInteropTy g thisTy) - .With(methodImpls=mkILMethodImpls methodImpls, isKnownToBeAttribute=isKnownToBeAttribute) - - let tdLayout, tdEncoding = - match TryFindFSharpAttribute g g.attrib_StructLayoutAttribute tycon.Attribs with - | Some (Attrib(_, _, [ AttribInt32Arg layoutKind ], namedArgs, _, _, _)) -> - let decoder = AttributeDecoder namedArgs - let ilPack = decoder.FindInt32 "Pack" 0x0 - let ilSize = decoder.FindInt32 "Size" 0x0 - let tdEncoding = - match (decoder.FindInt32 "CharSet" 0x0) with - (* enumeration values for System.Runtime.InteropServices.CharSet taken from mscorlib.il *) - | 0x03 -> ILDefaultPInvokeEncoding.Unicode - | 0x04 -> ILDefaultPInvokeEncoding.Auto - | _ -> ILDefaultPInvokeEncoding.Ansi - let layoutInfo = - if ilPack = 0x0 && ilSize = 0x0 - then { Size=None; Pack=None } - else { Size = Some ilSize; Pack = Some (uint16 ilPack) } - let tdLayout = - match layoutKind with - (* enumeration values for System.Runtime.InteropServices.LayoutKind taken from mscorlib.il *) - | 0x0 -> ILTypeDefLayout.Sequential layoutInfo - | 0x2 -> ILTypeDefLayout.Explicit layoutInfo - | _ -> ILTypeDefLayout.Auto - tdLayout, tdEncoding - | Some (Attrib(_, _, _, _, _, _, m)) -> - errorR(Error(FSComp.SR.ilStructLayoutAttributeCouldNotBeDecoded(), m)) - ILTypeDefLayout.Auto, ILDefaultPInvokeEncoding.Ansi - - | _ when (match ilTypeDefKind with ILTypeDefKind.ValueType -> true | _ -> false) -> - - // All structs are sequential by default - // Structs with no instance fields get size 1, pack 0 - if tycon.AllFieldsArray |> Array.exists (fun f -> not f.IsStatic) || - // Reflection emit doesn't let us emit 'pack' and 'size' for generic structs. - // In that case we generate a dummy field instead - (cenv.options.workAroundReflectionEmitBugs && not tycon.TyparsNoRange.IsEmpty) - then - ILTypeDefLayout.Sequential { Size=None; Pack=None }, ILDefaultPInvokeEncoding.Ansi - else - ILTypeDefLayout.Sequential { Size=Some 1; Pack=Some 0us }, ILDefaultPInvokeEncoding.Ansi + // Try to add a DefaultMemberAttribute for the 'Item' property + let defaultMemberAttrs = + // REVIEW: this should be based off tcaug_adhoc_list, which is in declaration order + tycon.MembersOfFSharpTyconSorted + |> List.tryPick (fun vref -> + let name = vref.DisplayName + + match vref.MemberInfo with + | None -> None + | Some memberInfo -> + match name, memberInfo.MemberFlags.MemberKind with + | ("Item" + | "op_IndexedLookup"), + (SynMemberKind.PropertyGet + | SynMemberKind.PropertySet) when not (isNil (ArgInfosOfPropertyVal g vref.Deref)) -> + Some( + mkILCustomAttribute ( + g.FindSysILTypeRef "System.Reflection.DefaultMemberAttribute", + [ g.ilg.typ_String ], + [ ILAttribElem.String(Some name) ], + [] + ) + ) + | _ -> None) + |> Option.toList + + let tyconRepr = tycon.TypeReprInfo + + // DebugDisplayAttribute gets copied to the subtypes generated as part of DU compilation + let debugDisplayAttrs, normalAttrs = + tycon.Attribs + |> List.partition (IsMatchingFSharpAttribute g g.attrib_DebuggerDisplayAttribute) + + let securityAttrs, normalAttrs = + normalAttrs + |> List.partition (fun a -> IsSecurityAttribute g cenv.amap cenv.casApplied a m) + + let generateDebugDisplayAttribute = + not g.compilingFSharpCore && tycon.IsUnionTycon && isNil debugDisplayAttrs + + let generateDebugProxies = + not (tyconRefEq g tcref g.unit_tcr_canon) + && not (HasFSharpAttribute g g.attrib_DebuggerTypeProxyAttribute tycon.Attribs) + + let permissionSets = CreatePermissionSets cenv eenv securityAttrs + + let secDecls = + if List.isEmpty securityAttrs then + emptyILSecurityDecls + else + mkILSecurityDecls permissionSets + + let ilDebugDisplayAttributes = + [ + yield! GenAttrs cenv eenv debugDisplayAttrs + if generateDebugDisplayAttribute then + yield g.mkDebuggerDisplayAttribute ("{" + debugDisplayMethodName + "(),nq}") + ] + + let ilCustomAttrs = + [ + yield! defaultMemberAttrs + yield! + normalAttrs + |> List.filter (IsMatchingFSharpAttribute g g.attrib_StructLayoutAttribute >> not) + |> GenAttrs cenv eenv + yield! ilDebugDisplayAttributes + ] + + let reprAccess = ComputeMemberAccess hiddenRepr + + // DebugDisplayAttribute gets copied to the subtypes generated as part of DU compilation + let debugDisplayAttrs, normalAttrs = tycon.Attribs |> List.partition (IsMatchingFSharpAttribute g g.attrib_DebuggerDisplayAttribute) + let securityAttrs, normalAttrs = normalAttrs |> List.partition (fun a -> IsSecurityAttribute g cenv.amap cenv.casApplied a m) + let generateDebugDisplayAttribute = + not g.useReflectionFreeCodeGen && + not g.compilingFSharpCore && + tycon.IsUnionTycon && + isNil debugDisplayAttrs + + let ilTypeDefKind = + match tyconRepr with + | TFSharpObjectRepr o -> + match o.fsobjmodel_kind with + | TFSharpClass -> ILTypeDefKind.Class + | TFSharpStruct -> ILTypeDefKind.ValueType + | TFSharpInterface -> ILTypeDefKind.Interface + | TFSharpEnum -> ILTypeDefKind.Enum + | TFSharpDelegate _ -> ILTypeDefKind.Delegate + | TFSharpRecdRepr _ + | TFSharpUnionRepr _ when tycon.IsStructOrEnumTycon -> ILTypeDefKind.ValueType + | _ -> ILTypeDefKind.Class + + let requiresExtraField = + let isEmptyStruct = + (match ilTypeDefKind with + | ILTypeDefKind.ValueType -> true + | _ -> false) + && + // All structs are sequential by default + // Structs with no instance fields get size 1, pack 0 + tycon.AllFieldsArray |> Array.forall (fun f -> f.IsStatic) + + isEmptyStruct + && cenv.options.workAroundReflectionEmitBugs + && not tycon.TyparsNoRange.IsEmpty + + // Compute a bunch of useful things for each field + let isCLIMutable = + (TryFindFSharpBoolAttribute g g.attrib_CLIMutableAttribute tycon.Attribs = Some true) + + let fieldSummaries = + + [ + for fspec in tycon.AllFieldsArray do + + let useGenuineField = useGenuineField tycon fspec + + // The property (or genuine IL field) is hidden in these circumstances: + // - secret fields apart from "__value" fields for enums + // - the representation of the type is hidden + // - the F# field is hidden by a signature or private declaration + let isPropHidden = + // Enums always have public cases irrespective of Enum Visibility + if tycon.IsEnumTycon then + false + else + (fspec.IsCompilerGenerated + || hiddenRepr + || IsHiddenRecdField eenv.sigToImplRemapInfo (tcref.MakeNestedRecdFieldRef fspec)) + + let ilType = GenType cenv m eenvinner.tyenv fspec.FormalType + let ilFieldName = ComputeFieldName tycon fspec + + yield + (useGenuineField, + ilFieldName, + fspec.IsMutable, + fspec.IsStatic, + fspec.PropertyAttribs, + ilType, + isPropHidden, + fspec) + ] - | _ -> - ILTypeDefLayout.Auto, ILDefaultPInvokeEncoding.Ansi + // Generate the IL fields + let ilFieldDefs = + [ + for useGenuineField, ilFieldName, isFSharpMutable, isStatic, _, ilPropType, isPropHidden, fspec in fieldSummaries do + + let ilFieldOffset = + match TryFindFSharpAttribute g g.attrib_FieldOffsetAttribute fspec.FieldAttribs with + | Some (Attrib (_, _, [ AttribInt32Arg fieldOffset ], _, _, _, _)) -> Some fieldOffset + | Some attrib -> + errorR (Error(FSComp.SR.ilFieldOffsetAttributeCouldNotBeDecoded (), attrib.Range)) + None + | _ -> None + + let attribs = + [ // If using a field then all the attributes go on the field + // See also FSharp 1.0 Bug 4727: once we start compiling them as real mutable fields, you should not be able to target both "property" for "val mutable" fields in classes + + if useGenuineField then + yield! fspec.PropertyAttribs + yield! fspec.FieldAttribs + ] + + let ilNotSerialized = + HasFSharpAttributeOpt g g.attrib_NonSerializedAttribute attribs + + let fattribs = + attribs + // Do not generate FieldOffset as a true CLI custom attribute, since it is implied by other corresponding CLI metadata + |> List.filter (IsMatchingFSharpAttribute g g.attrib_FieldOffsetAttribute >> not) + // Do not generate NonSerialized as a true CLI custom attribute, since it is implied by other corresponding CLI metadata + |> List.filter (IsMatchingFSharpAttributeOpt g g.attrib_NonSerializedAttribute >> not) + + let ilFieldMarshal, fattribs = GenMarshal cenv fattribs + + // The IL field is hidden if the property/field is hidden OR we're using a property + // AND the field is not mutable (because we can take the address of a mutable field). + // Otherwise fields are always accessed via their property getters/setters + // + // Additionally, don't hide fields for multiemit in F# Interactive + let isFieldHidden = + isPropHidden + || (not useGenuineField + && not isFSharpMutable + && not (cenv.options.isInteractive && cenv.options.fsiMultiAssemblyEmit)) + + let extraAttribs = + match tyconRepr with + | TFSharpRecdRepr _ when not useGenuineField -> [ g.DebuggerBrowsableNeverAttribute ] // hide fields in records in debug display + | _ -> [] // don't hide fields in classes in debug display + + let access = ComputeMemberAccess isFieldHidden + + let literalValue = Option.map (GenFieldInit m) fspec.LiteralValue + + let fdef = + ILFieldDef( + name = ilFieldName, + fieldType = ilPropType, + attributes = enum 0, + data = None, + literalValue = None, + offset = ilFieldOffset, + marshal = None, + customAttrs = mkILCustomAttrs (GenAttrs cenv eenv fattribs @ extraAttribs) + ) + .WithAccess(access) + .WithStatic(isStatic) + .WithSpecialName(ilFieldName = "value__" && tycon.IsEnumTycon) + .WithNotSerialized(ilNotSerialized) + .WithLiteralDefaultValue(literalValue) + .WithFieldMarshal(ilFieldMarshal) + + yield fdef + + if requiresExtraField then + yield mkILInstanceField ("__dummy", g.ilg.typ_Int32, None, ILMemberAccess.Assembly) + ] - // if the type's layout is Explicit, ensure that each field has a valid offset - let validateExplicit (fdef: ILFieldDef) = - match fdef.Offset with - // Remove field suffix "@" for pretty printing - | None -> errorR(Error(FSComp.SR.ilFieldDoesNotHaveValidOffsetForStructureLayout(tdef.Name, fdef.Name.Replace("@", "")), (trimRangeToLine m))) + // Generate property definitions for the fields compiled as properties + let ilPropertyDefsForFields = + [ + for i, (useGenuineField, _, isFSharpMutable, isStatic, propAttribs, ilPropType, _, fspec) in Seq.indexed fieldSummaries do + if not useGenuineField then + let ilCallingConv = + if isStatic then + ILCallingConv.Static + else + ILCallingConv.Instance + + let ilPropName = fspec.LogicalName + let ilHasSetter = isCLIMutable || isFSharpMutable + + let ilFieldAttrs = + GenAttrs cenv eenv propAttribs + @ [ mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i ] + + yield + ILPropertyDef( + name = ilPropName, + attributes = PropertyAttributes.None, + setMethod = + (if ilHasSetter then + Some(mkILMethRef (tref, ilCallingConv, "set_" + ilPropName, 0, [ ilPropType ], ILType.Void)) + else + None), + getMethod = Some(mkILMethRef (tref, ilCallingConv, "get_" + ilPropName, 0, [], ilPropType)), + callingConv = ilCallingConv.ThisConv, + propertyType = ilPropType, + init = None, + args = [], + customAttrs = mkILCustomAttrs ilFieldAttrs + ) + ] + + let methodDefs = + [ // Generate property getter methods for those fields that have properties + for useGenuineField, ilFieldName, _, isStatic, _, ilPropType, isPropHidden, fspec in fieldSummaries do + if not useGenuineField then + let ilPropName = fspec.LogicalName + let ilMethName = "get_" + ilPropName + let access = ComputeMemberAccess isPropHidden + let isStruct = isStructTyconRef tcref + + let attrs = + if isStruct && not isStatic then + [ GenReadOnlyAttribute g ] + else + [] + + yield mkLdfldMethodDef (ilMethName, access, isStatic, ilThisTy, ilFieldName, ilPropType, attrs) + + // Generate property setter methods for the mutable fields + for useGenuineField, ilFieldName, isFSharpMutable, isStatic, _, ilPropType, isPropHidden, fspec in fieldSummaries do + let ilHasSetter = (isCLIMutable || isFSharpMutable) && not useGenuineField + + if ilHasSetter then + let ilPropName = fspec.LogicalName + let ilFieldSpec = mkILFieldSpecInTy (ilThisTy, ilFieldName, ilPropType) + let ilMethName = "set_" + ilPropName + let ilParams = [ mkILParamNamed ("value", ilPropType) ] + let ilReturn = mkILReturn ILType.Void + let iLAccess = ComputeMemberAccess isPropHidden + + let ilMethodDef = + if isStatic then + let ilMethodBody = + mkMethodBody ( + true, + [], + 2, + nonBranchingInstrsToCode [ mkLdarg0; mkNormalStsfld ilFieldSpec ], + None, + eenv.imports + ) + + mkILNonGenericStaticMethod (ilMethName, iLAccess, ilParams, ilReturn, ilMethodBody) + else + let ilMethodBody = + mkMethodBody ( + true, + [], + 2, + nonBranchingInstrsToCode [ mkLdarg0; mkLdarg 1us; mkNormalStfld ilFieldSpec ], + None, + eenv.imports + ) + + mkILNonGenericInstanceMethod (ilMethName, iLAccess, ilParams, ilReturn, ilMethodBody) + + yield ilMethodDef.WithSpecialName + + if generateDebugDisplayAttribute then + let (|Lazy|) (x: Lazy<_>) = x.Force() + + match (eenv.valsInScope.TryFind g.sprintf_vref.Deref, eenv.valsInScope.TryFind g.new_format_vref.Deref) with + | Some (Lazy (Method (_, _, sprintfMethSpec, _, _, _, _, _, _, _, _, _))), + Some (Lazy (Method (_, _, newFormatMethSpec, _, _, _, _, _, _, _, _, _))) -> + // The type returned by the 'sprintf' call + let funcTy = EraseClosures.mkILFuncTy cenv.ilxPubCloEnv ilThisTy g.ilg.typ_String + // Give the instantiation of the printf format object, i.e. a Format`5 object compatible with StringFormat + let newFormatMethSpec = + mkILMethSpec ( + newFormatMethSpec.MethodRef, + AsObject, + [ // 'T -> string' + funcTy + // rest follow from 'StringFormat' + GenUnitTy cenv eenv m + g.ilg.typ_String + g.ilg.typ_String + g.ilg.typ_String + ], + [] + ) + // Instantiate with our own type + let sprintfMethSpec = + mkILMethSpec (sprintfMethSpec.MethodRef, AsObject, [], [ funcTy ]) + + // Here's the body of the method. Call printf, then invoke the function it returns + let callInstrs = + EraseClosures.mkCallFunc + cenv.ilxPubCloEnv + (fun _ -> 0us) + eenv.tyenv.Count + Normalcall + (Apps_app(ilThisTy, Apps_done g.ilg.typ_String)) + + let ilInstrs = + [ // load the hardwired format string + I_ldstr "%+0.8A" + // make the printf format object + mkNormalNewobj newFormatMethSpec + // call sprintf + mkNormalCall sprintfMethSpec + // call the function returned by sprintf + mkLdarg0 + if ilThisTy.Boxity = ILBoxity.AsValue then + mkNormalLdobj ilThisTy + yield! callInstrs + ] + + let ilMethodBody = + mkMethodBody (true, [], 2, nonBranchingInstrsToCode ilInstrs, None, eenv.imports) + + let ilMethodDef = + mkILNonGenericInstanceMethod ( + debugDisplayMethodName, + ILMemberAccess.Assembly, + [], + mkILReturn g.ilg.typ_Object, + ilMethodBody + ) + + yield ilMethodDef.WithSpecialName |> AddNonUserCompilerGeneratedAttribs g + | None, _ -> + //printfn "sprintf not found" + () + | _, None -> + //printfn "new format not found" + () + | _ -> + //printfn "neither found, or non-method" + () + + // Build record constructors and the funky methods that go with records and delegate types. + // Constructors and delegate methods have the same access as the representation + match tyconRepr with + | TFSharpRecdRepr _ when not tycon.IsEnumTycon -> + // No constructor for enum types + // Otherwise find all the non-static, non zero-init fields and build a constructor + let relevantFields = + fieldSummaries + |> List.filter (fun (_, _, _, isStatic, _, _, _, fspec) -> not isStatic && not fspec.IsZeroInit) + + let fieldNamesAndTypes = + relevantFields + |> List.map (fun (_, ilFieldName, _, _, _, ilPropType, _, fspec) -> (fspec.LogicalName, ilFieldName, ilPropType)) + + let isStructRecord = tycon.IsStructRecordOrUnionTycon + + // No type spec if the record is a value type + let spec = + if isStructRecord then + None + else + Some(g.ilg.typ_Object.TypeSpec) + + let ilMethodDef = + mkILSimpleStorageCtorWithParamNames ( + spec, + ilThisTy, + [], + ChooseParamNames fieldNamesAndTypes, + reprAccess, + None, + eenv.imports + ) + + yield ilMethodDef + // FSharp 1.0 bug 1988: Explicitly setting the ComVisible(true) attribute on an F# type causes an F# record to be emitted in a way that enables mutation for COM interop scenarios + // FSharp 3.0 feature: adding CLIMutable to a record type causes emit of default constructor, and all fields get property setters + // Records that are value types do not create a default constructor with CLIMutable or ComVisible + if + not isStructRecord + && (isCLIMutable + || (TryFindFSharpBoolAttribute g g.attrib_ComVisibleAttribute tycon.Attribs = Some true)) + then + yield mkILSimpleStorageCtor (Some g.ilg.typ_Object.TypeSpec, ilThisTy, [], [], reprAccess, None, eenv.imports) + + if not (tycon.HasMember g "ToString" []) then + yield! GenToStringMethod cenv eenv ilThisTy m + + | TFSharpObjectRepr r when tycon.IsFSharpDelegateTycon -> + + // Build all the methods that go with a delegate type + match r.fsobjmodel_kind with + | TFSharpDelegate slotSig -> + + let parameters, ret = + // When "type delegateTy = delegate of unit -> returnTy", + // suppress the unit arg from delegate .Invoke vslot. + let (TSlotSig (nm, ty, ctps, mtps, paraml, returnTy)) = slotSig + + let paraml = + match paraml with + | [ [ tsp ] ] when isUnitTy g tsp.Type -> [] (* suppress unit arg *) + | paraml -> paraml + + GenActualSlotsig m cenv eenvinner (TSlotSig(nm, ty, ctps, mtps, paraml, returnTy)) [] [] + + yield! mkILDelegateMethods reprAccess g.ilg (g.iltyp_AsyncCallback, g.iltyp_IAsyncResult) (parameters, ret) + | _ -> () + + | TFSharpUnionRepr _ when not (tycon.HasMember g "ToString" []) -> yield! GenToStringMethod cenv eenv ilThisTy m | _ -> () - - // if the type's layout is Sequential, no offsets should be applied - let validateSequential (fdef: ILFieldDef) = - match fdef.Offset with - | Some _ -> errorR(Error(FSComp.SR.ilFieldHasOffsetForSequentialLayout(), (trimRangeToLine m))) + ] + + let ilMethods = methodDefs @ augmentOverrideMethodDefs @ abstractMethodDefs + let ilProperties = mkILProperties (ilPropertyDefsForFields @ abstractPropDefs) + let ilEvents = mkILEvents abstractEventDefs + let ilFields = mkILFields ilFieldDefs + + let tdef, tdefDiscards = + let isSerializable = + (TryFindFSharpBoolAttribute g g.attrib_AutoSerializableAttribute tycon.Attribs + <> Some false) + + match tycon.TypeReprInfo with + | TILObjectRepr _ -> + let tdef = tycon.ILTyconRawMetadata.WithAccess access + + let tdef = + tdef.With(customAttrs = mkILCustomAttrs ilCustomAttrs, genericParams = ilGenParams) + + tdef, None + + | TFSharpRecdRepr _ + | TFSharpObjectRepr _ as tyconRepr -> + let super = superOfTycon g tycon + let ilBaseTy = GenType cenv m eenvinner.tyenv super + + // Build a basic type definition + let isObjectType = + (match tyconRepr with + | TFSharpObjectRepr _ -> true + | _ -> false) + + let ilAttrs = + ilCustomAttrs + @ [ + mkCompilationMappingAttr + g + (int ( + if isObjectType then + SourceConstructFlags.ObjectType + elif hiddenRepr then + SourceConstructFlags.RecordType ||| SourceConstructFlags.NonPublicRepresentation + else + SourceConstructFlags.RecordType + )) + ] + + // For now, generic types always use ILTypeInit.BeforeField. This is because + // there appear to be some cases where ILTypeInit.OnAny causes problems for + // the .NET CLR when used in conjunction with generic classes in cross-DLL + // and NGEN scenarios. + // + // We don't apply this rule to the final file. This is because ALL classes with .cctors in + // the final file (which may in turn trigger the .cctor for the .EXE itself, which + // in turn calls the main() method) must have deterministic initialization + // that is not triggered prior to execution of the main() method. + // If this property doesn't hold then the .cctor can end up running + // before the main method even starts. + let typeDefTrigger = + if eenv.isFinalFile || tycon.TyparsNoRange.IsEmpty then + ILTypeInit.OnAny + else + ILTypeInit.BeforeField + + let isKnownToBeAttribute = + ExistsSameHeadTypeInHierarchy g cenv.amap m super g.mk_Attribute_ty + + let tdef = + mkILGenericClass ( + ilTypeName, + access, + ilGenParams, + ilBaseTy, + ilIntfTys, + mkILMethods ilMethods, + ilFields, + emptyILTypeDefs, + ilProperties, + ilEvents, + mkILCustomAttrs ilAttrs, + typeDefTrigger + ) + + // Set some the extra entries in the definition + let isTheSealedAttribute = tyconRefEq g tcref g.attrib_SealedAttribute.TyconRef + + let tdef = + tdef + .WithSealed(isSealedTy g thisTy || isTheSealedAttribute) + .WithSerializable(isSerializable) + .WithAbstract(isAbstract) + .WithImport(isComInteropTy g thisTy) + .With(methodImpls = mkILMethodImpls methodImpls, isKnownToBeAttribute = isKnownToBeAttribute) + + let tdLayout, tdEncoding = + match TryFindFSharpAttribute g g.attrib_StructLayoutAttribute tycon.Attribs with + | Some (Attrib (_, _, [ AttribInt32Arg layoutKind ], namedArgs, _, _, _)) -> + let decoder = AttributeDecoder namedArgs + let ilPack = decoder.FindInt32 "Pack" 0x0 + let ilSize = decoder.FindInt32 "Size" 0x0 + + let tdEncoding = + match (decoder.FindInt32 "CharSet" 0x0) with + (* enumeration values for System.Runtime.InteropServices.CharSet taken from mscorlib.il *) + | 0x03 -> ILDefaultPInvokeEncoding.Unicode + | 0x04 -> ILDefaultPInvokeEncoding.Auto + | _ -> ILDefaultPInvokeEncoding.Ansi + + let layoutInfo = + if ilPack = 0x0 && ilSize = 0x0 then + { Size = None; Pack = None } + else + { + Size = Some ilSize + Pack = Some(uint16 ilPack) + } + + let tdLayout = + match layoutKind with + (* enumeration values for System.Runtime.InteropServices.LayoutKind taken from mscorlib.il *) + | 0x0 -> ILTypeDefLayout.Sequential layoutInfo + | 0x2 -> ILTypeDefLayout.Explicit layoutInfo + | _ -> ILTypeDefLayout.Auto + + tdLayout, tdEncoding + | Some (Attrib (_, _, _, _, _, _, m)) -> + errorR (Error(FSComp.SR.ilStructLayoutAttributeCouldNotBeDecoded (), m)) + ILTypeDefLayout.Auto, ILDefaultPInvokeEncoding.Ansi + + | _ when + (match ilTypeDefKind with + | ILTypeDefKind.ValueType -> true + | _ -> false) + -> + + // All structs are sequential by default + // Structs with no instance fields get size 1, pack 0 + if + tycon.AllFieldsArray |> Array.exists (fun f -> not f.IsStatic) + || + // Reflection emit doesn't let us emit 'pack' and 'size' for generic structs. + // In that case we generate a dummy field instead + (cenv.options.workAroundReflectionEmitBugs && not tycon.TyparsNoRange.IsEmpty) + then + ILTypeDefLayout.Sequential { Size = None; Pack = None }, ILDefaultPInvokeEncoding.Ansi + else + ILTypeDefLayout.Sequential { Size = Some 1; Pack = Some 0us }, ILDefaultPInvokeEncoding.Ansi + + | _ -> ILTypeDefLayout.Auto, ILDefaultPInvokeEncoding.Ansi + + // if the type's layout is Explicit, ensure that each field has a valid offset + let validateExplicit (fdef: ILFieldDef) = + match fdef.Offset with + // Remove field suffix "@" for pretty printing + | None -> + errorR ( + Error( + FSComp.SR.ilFieldDoesNotHaveValidOffsetForStructureLayout (tdef.Name, fdef.Name.Replace("@", "")), + (trimRangeToLine m) + ) + ) + | _ -> () + + // if the type's layout is Sequential, no offsets should be applied + let validateSequential (fdef: ILFieldDef) = + match fdef.Offset with + | Some _ -> errorR (Error(FSComp.SR.ilFieldHasOffsetForSequentialLayout (), (trimRangeToLine m))) + | _ -> () + + match tdLayout with + | ILTypeDefLayout.Explicit _ -> List.iter validateExplicit ilFieldDefs + | ILTypeDefLayout.Sequential _ -> List.iter validateSequential ilFieldDefs | _ -> () - match tdLayout with - | ILTypeDefLayout.Explicit _ -> List.iter validateExplicit ilFieldDefs - | ILTypeDefLayout.Sequential _ -> List.iter validateSequential ilFieldDefs - | _ -> () - - let tdef = tdef.WithKind(ilTypeDefKind).WithLayout(tdLayout).WithEncoding(tdEncoding) - tdef, None - - | TFSharpUnionRepr _ -> - let alternatives = - tycon.UnionCasesArray |> Array.mapi (fun i ucspec -> - { altName=ucspec.CompiledName - altFields=GenUnionCaseRef cenv m eenvinner.tyenv i ucspec.RecdFieldsArray - altCustomAttrs= mkILCustomAttrs (GenAttrs cenv eenv ucspec.Attribs @ [mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.UnionCase) i]) }) - let cuinfo = - { UnionCasesAccessibility=reprAccess - IsNullPermitted=IsUnionTypeWithNullAsTrueValue g tycon - HelpersAccessibility=reprAccess - HasHelpers=ComputeUnionHasHelpers g tcref - GenerateDebugProxies= generateDebugProxies - DebugDisplayAttributes= ilDebugDisplayAttributes - UnionCases= alternatives - DebugPoint = None - DebugImports = eenv.imports } - - let layout = - if isStructTy g thisTy then - if (match ilTypeDefKind with ILTypeDefKind.ValueType -> true | _ -> false) then - // Structs with no instance fields get size 1, pack 0 - ILTypeDefLayout.Sequential { Size=Some 1; Pack=Some 0us } - else - ILTypeDefLayout.Sequential { Size=None; Pack=None } - else - ILTypeDefLayout.Auto - - let cattrs = - mkILCustomAttrs (ilCustomAttrs @ - [mkCompilationMappingAttr g - (int (if hiddenRepr - then SourceConstructFlags.SumType ||| SourceConstructFlags.NonPublicRepresentation - else SourceConstructFlags.SumType)) ]) - let tdef = - ILTypeDef(name = ilTypeName, - layout = layout, - attributes = enum 0, - genericParams = ilGenParams, - customAttrs = cattrs, - fields = ilFields, - events= ilEvents, - properties = ilProperties, - methods= mkILMethods ilMethods, - methodImpls= mkILMethodImpls methodImpls, - nestedTypes=emptyILTypeDefs, - implements = ilIntfTys, - extends= Some (if tycon.IsStructOrEnumTycon then g.iltyp_ValueType else g.ilg.typ_Object), - isKnownToBeAttribute=false, - securityDecls= emptyILSecurityDecls) - .WithLayout(layout) - .WithSerializable(isSerializable) - .WithSealed(true) - .WithEncoding(ILDefaultPInvokeEncoding.Auto) - .WithAccess(access) - .WithInitSemantics(ILTypeInit.BeforeField) - - let tdef2 = EraseUnions.mkClassUnionDef (g.AddMethodGeneratedAttributes, g.AddPropertyGeneratedAttributes, g.AddPropertyNeverAttributes, g.AddFieldGeneratedAttributes, g.AddFieldNeverAttributes, g.MkDebuggerTypeProxyAttribute) g.ilg tref tdef cuinfo - - // Discard the user-supplied (i.e. prim-type.fs) implementations of the get_Empty, get_IsEmpty, get_Value and get_None and Some methods. - // This is because we will replace their implementations by ones that load the unique - // private static field for lists etc. - // - // Also discard the F#-compiler supplied implementation of the Empty, IsEmpty, Value and None properties. - let tdefDiscards = - Some ((fun (md: ILMethodDef) -> - (cuinfo.HasHelpers = SpecialFSharpListHelpers && (md.Name = "get_Empty" || md.Name = "Cons" || md.Name = "get_IsEmpty")) || - (cuinfo.HasHelpers = SpecialFSharpOptionHelpers && (md.Name = "get_Value" || md.Name = "get_None" || md.Name = "Some"))), - - (fun (pd: ILPropertyDef) -> - (cuinfo.HasHelpers = SpecialFSharpListHelpers && (pd.Name = "Empty" || pd.Name = "IsEmpty" )) || - (cuinfo.HasHelpers = SpecialFSharpOptionHelpers && (pd.Name = "Value" || pd.Name = "None")))) - - tdef2, tdefDiscards - - | _ -> failwith "??" - - let tdef = tdef.WithHasSecurity(not (List.isEmpty securityAttrs)) - let tdef = tdef.With(securityDecls = secDecls) - mgbuf.AddTypeDef(tref, tdef, false, false, tdefDiscards) - - // If a non-generic type is written with "static let" and "static do" (i.e. it has a ".cctor") - // then the code for the .cctor is placed into .cctor for the backing static class for the file. - // It is not placed in its own .cctor as there is no feasible way for this to be given a coherent - // order in the sequential initialization of the file. - // - // In this case, the .cctor for this type must force the .cctor of the backing static class for the file. - if tycon.TyparsNoRange.IsEmpty && tycon.MembersOfFSharpTyconSorted |> List.exists (fun vref -> vref.Deref.IsClassConstructor) then - GenForceWholeFileInitializationAsPartOfCCtor cenv mgbuf lazyInitInfo tref eenv.imports m - - + let tdef = + tdef.WithKind(ilTypeDefKind).WithLayout(tdLayout).WithEncoding(tdEncoding) + + tdef, None + + | TFSharpUnionRepr _ -> + let alternatives = + tycon.UnionCasesArray + |> Array.mapi (fun i ucspec -> + { + altName = ucspec.CompiledName + altFields = GenUnionCaseRef cenv m eenvinner.tyenv i ucspec.RecdFieldsArray + altCustomAttrs = + mkILCustomAttrs ( + GenAttrs cenv eenv ucspec.Attribs + @ [ mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.UnionCase) i ] + ) + }) + + let cuinfo = + { + UnionCasesAccessibility = reprAccess + IsNullPermitted = IsUnionTypeWithNullAsTrueValue g tycon + HelpersAccessibility = reprAccess + HasHelpers = ComputeUnionHasHelpers g tcref + GenerateDebugProxies = generateDebugProxies + DebugDisplayAttributes = ilDebugDisplayAttributes + UnionCases = alternatives + DebugPoint = None + DebugImports = eenv.imports + } + + let layout = + if isStructTy g thisTy then + if + (match ilTypeDefKind with + | ILTypeDefKind.ValueType -> true + | _ -> false) + then + // Structs with no instance fields get size 1, pack 0 + ILTypeDefLayout.Sequential { Size = Some 1; Pack = Some 0us } + else + ILTypeDefLayout.Sequential { Size = None; Pack = None } + else + ILTypeDefLayout.Auto + + let cattrs = + mkILCustomAttrs ( + ilCustomAttrs + @ [ + mkCompilationMappingAttr + g + (int ( + if hiddenRepr then + SourceConstructFlags.SumType ||| SourceConstructFlags.NonPublicRepresentation + else + SourceConstructFlags.SumType + )) + ] + ) + + let tdef = + ILTypeDef( + name = ilTypeName, + layout = layout, + attributes = enum 0, + genericParams = ilGenParams, + customAttrs = cattrs, + fields = ilFields, + events = ilEvents, + properties = ilProperties, + methods = mkILMethods ilMethods, + methodImpls = mkILMethodImpls methodImpls, + nestedTypes = emptyILTypeDefs, + implements = ilIntfTys, + extends = + Some( + if tycon.IsStructOrEnumTycon then + g.iltyp_ValueType + else + g.ilg.typ_Object + ), + isKnownToBeAttribute = false, + securityDecls = emptyILSecurityDecls + ) + .WithLayout(layout) + .WithSerializable(isSerializable) + .WithSealed(true) + .WithEncoding(ILDefaultPInvokeEncoding.Auto) + .WithAccess(access) + .WithInitSemantics(ILTypeInit.BeforeField) + + let tdef2 = + EraseUnions.mkClassUnionDef + (g.AddMethodGeneratedAttributes, + g.AddPropertyGeneratedAttributes, + g.AddPropertyNeverAttributes, + g.AddFieldGeneratedAttributes, + g.AddFieldNeverAttributes, + g.MkDebuggerTypeProxyAttribute) + g.ilg + tref + tdef + cuinfo + + // Discard the user-supplied (i.e. prim-type.fs) implementations of the get_Empty, get_IsEmpty, get_Value and get_None and Some methods. + // This is because we will replace their implementations by ones that load the unique + // private static field for lists etc. + // + // Also discard the F#-compiler supplied implementation of the Empty, IsEmpty, Value and None properties. + let tdefDiscards = + Some( + (fun (md: ILMethodDef) -> + (cuinfo.HasHelpers = SpecialFSharpListHelpers + && (md.Name = "get_Empty" || md.Name = "Cons" || md.Name = "get_IsEmpty")) + || (cuinfo.HasHelpers = SpecialFSharpOptionHelpers + && (md.Name = "get_Value" || md.Name = "get_None" || md.Name = "Some"))), + + (fun (pd: ILPropertyDef) -> + (cuinfo.HasHelpers = SpecialFSharpListHelpers + && (pd.Name = "Empty" || pd.Name = "IsEmpty")) + || (cuinfo.HasHelpers = SpecialFSharpOptionHelpers + && (pd.Name = "Value" || pd.Name = "None"))) + ) + + tdef2, tdefDiscards + + | _ -> failwith "??" + + let tdef = tdef.WithHasSecurity(not (List.isEmpty securityAttrs)) + let tdef = tdef.With(securityDecls = secDecls) + mgbuf.AddTypeDef(tref, tdef, false, false, tdefDiscards) + + // If a non-generic type is written with "static let" and "static do" (i.e. it has a ".cctor") + // then the code for the .cctor is placed into .cctor for the backing static class for the file. + // It is not placed in its own .cctor as there is no feasible way for this to be given a coherent + // order in the sequential initialization of the file. + // + // In this case, the .cctor for this type must force the .cctor of the backing static class for the file. + if + tycon.TyparsNoRange.IsEmpty + && tycon.MembersOfFSharpTyconSorted + |> List.exists (fun vref -> vref.Deref.IsClassConstructor) + then + GenForceWholeFileInitializationAsPartOfCCtor cenv mgbuf lazyInitInfo tref eenv.imports m /// Generate the type for an F# exception declaration. and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = let g = cenv.g let exncref = mkLocalEntityRef exnc + match exnc.ExceptionInfo with - | TExnAbbrevRepr _ | TExnAsmRepr _ | TExnNone -> () + | TExnAbbrevRepr _ + | TExnAsmRepr _ + | TExnNone -> () | TExnFresh _ -> let ilThisTy = GenExnType cenv m eenv.tyenv exncref let tref = ilThisTy.TypeRef @@ -8492,92 +11293,132 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = let fspecs = exnc.TrueInstanceFieldsAsList let ilMethodDefsForProperties, ilFieldDefs, ilPropertyDefs, fieldNamesAndTypes = - [ for i, fld in Seq.indexed fspecs do - let ilPropName = fld.LogicalName - let ilPropType = GenType cenv m eenv.tyenv fld.FormalType - let ilMethName = "get_" + fld.LogicalName - let ilFieldName = ComputeFieldName exnc fld - let ilMethodDef = mkLdfldMethodDef (ilMethName, reprAccess, false, ilThisTy, ilFieldName, ilPropType) - let ilFieldDef = mkILInstanceField(ilFieldName, ilPropType, None, ILMemberAccess.Assembly) - let ilPropDef = - ILPropertyDef(name = ilPropName, - attributes = PropertyAttributes.None, - setMethod = None, - getMethod = Some(mkILMethRef(tref, ILCallingConv.Instance, ilMethName, 0, [], ilPropType)), - callingConv = ILThisConvention.Instance, - propertyType = ilPropType, - init = None, - args = [], - customAttrs=mkILCustomAttrs (GenAttrs cenv eenv fld.PropertyAttribs @ [mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i])) - yield (ilMethodDef, ilFieldDef, ilPropDef, (ilPropName, ilFieldName, ilPropType)) ] - |> List.unzip4 + [ + for i, fld in Seq.indexed fspecs do + let ilPropName = fld.LogicalName + let ilPropType = GenType cenv m eenv.tyenv fld.FormalType + let ilMethName = "get_" + fld.LogicalName + let ilFieldName = ComputeFieldName exnc fld + + let ilMethodDef = + mkLdfldMethodDef (ilMethName, reprAccess, false, ilThisTy, ilFieldName, ilPropType, []) + + let ilFieldDef = + mkILInstanceField (ilFieldName, ilPropType, None, ILMemberAccess.Assembly) + + let ilPropDef = + ILPropertyDef( + name = ilPropName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some(mkILMethRef (tref, ILCallingConv.Instance, ilMethName, 0, [], ilPropType)), + callingConv = ILThisConvention.Instance, + propertyType = ilPropType, + init = None, + args = [], + customAttrs = + mkILCustomAttrs ( + GenAttrs cenv eenv fld.PropertyAttribs + @ [ mkCompilationMappingAttrWithSeqNum g (int SourceConstructFlags.Field) i ] + ) + ) + + yield (ilMethodDef, ilFieldDef, ilPropDef, (ilPropName, ilFieldName, ilPropType)) + ] + |> List.unzip4 let ilCtorDef = - mkILSimpleStorageCtorWithParamNames(Some g.iltyp_Exception.TypeSpec, ilThisTy, [], ChooseParamNames fieldNamesAndTypes, reprAccess, None, eenv.imports) + mkILSimpleStorageCtorWithParamNames ( + Some g.iltyp_Exception.TypeSpec, + ilThisTy, + [], + ChooseParamNames fieldNamesAndTypes, + reprAccess, + None, + eenv.imports + ) // In compiled code, all exception types get a parameterless constructor for use with XML serialization // This does default-initialization of all fields let ilCtorDefNoArgs = if not (isNil fieldNamesAndTypes) then - [ mkILSimpleStorageCtor(Some g.iltyp_Exception.TypeSpec, ilThisTy, [], [], reprAccess, None, eenv.imports) ] + [ + mkILSimpleStorageCtor (Some g.iltyp_Exception.TypeSpec, ilThisTy, [], [], reprAccess, None, eenv.imports) + ] else [] let serializationRelatedMembers = - // do not emit serialization related members if target framework lacks SerializationInfo or StreamingContext - match g.iltyp_SerializationInfo, g.iltyp_StreamingContext with - | Some serializationInfoType, Some streamingContextType -> - - let ilInstrsForSerialization = - [ mkLdarg0 - mkLdarg 1us - mkLdarg 2us - mkNormalCall (mkILCtorMethSpecForTy (g.iltyp_Exception, [serializationInfoType; streamingContextType])) ] - |> nonBranchingInstrsToCode - - let ilCtorDefForSerialization = - mkILCtor(ILMemberAccess.Family, - [mkILParamNamed("info", serializationInfoType);mkILParamNamed("context", streamingContextType)], - mkMethodBody (false, [], 8, ilInstrsForSerialization, None, eenv.imports)) - - [ilCtorDefForSerialization] - | _ -> [] + // do not emit serialization related members if target framework lacks SerializationInfo or StreamingContext + match g.iltyp_SerializationInfo, g.iltyp_StreamingContext with + | Some serializationInfoType, Some streamingContextType -> + + let ilInstrsForSerialization = + [ + mkLdarg0 + mkLdarg 1us + mkLdarg 2us + mkNormalCall (mkILCtorMethSpecForTy (g.iltyp_Exception, [ serializationInfoType; streamingContextType ])) + ] + |> nonBranchingInstrsToCode + + let ilCtorDefForSerialization = + mkILCtor ( + ILMemberAccess.Family, + [ + mkILParamNamed ("info", serializationInfoType) + mkILParamNamed ("context", streamingContextType) + ], + mkMethodBody (false, [], 8, ilInstrsForSerialization, None, eenv.imports) + ) + + [ ilCtorDefForSerialization ] + | _ -> [] let ilTypeName = tref.Name let ilMethodDefs = - [ ilCtorDef - yield! ilCtorDefNoArgs - yield! serializationRelatedMembers - yield! ilMethodDefsForProperties - - if cenv.g.langVersion.SupportsFeature(LanguageFeature.BetterExceptionPrinting) && - not (exnc.HasMember g "get_Message" []) && - not (exnc.HasMember g "Message" []) then - yield! GenPrintingMethod cenv eenv "get_Message" ilThisTy m ] - - let interfaces = exnc.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv m eenv.tyenv) + [ + ilCtorDef + yield! ilCtorDefNoArgs + yield! serializationRelatedMembers + yield! ilMethodDefsForProperties + + if + cenv.g.langVersion.SupportsFeature(LanguageFeature.BetterExceptionPrinting) + && not (exnc.HasMember g "get_Message" []) + && not (exnc.HasMember g "Message" []) + then + yield! GenPrintingMethod cenv eenv "get_Message" ilThisTy m + ] + + let interfaces = + exnc.ImmediateInterfaceTypesOfFSharpTycon + |> List.map (GenType cenv m eenv.tyenv) let tdef = - mkILGenericClass - (ilTypeName, access, [], g.iltyp_Exception, - interfaces, - mkILMethods ilMethodDefs, - mkILFields ilFieldDefs, - emptyILTypeDefs, - mkILProperties ilPropertyDefs, - emptyILEvents, - mkILCustomAttrs [mkCompilationMappingAttr g (int SourceConstructFlags.Exception)], - ILTypeInit.BeforeField) + mkILGenericClass ( + ilTypeName, + access, + [], + g.iltyp_Exception, + interfaces, + mkILMethods ilMethodDefs, + mkILFields ilFieldDefs, + emptyILTypeDefs, + mkILProperties ilPropertyDefs, + emptyILEvents, + mkILCustomAttrs [ mkCompilationMappingAttr g (int SourceConstructFlags.Exception) ], + ILTypeInit.BeforeField + ) let tdef = tdef.WithSerializable(true) mgbuf.AddTypeDef(tref, tdef, false, false, None) - let CodegenAssembly cenv eenv mgbuf implFiles = match List.tryFrontAndBack implFiles with | None -> () - | Some (firstImplFiles, lastImplFile) -> + | Some (firstImplFiles, lastImplFile) -> let eenv = List.fold (GenImplFile cenv mgbuf None) eenv firstImplFiles let eenv = GenImplFile cenv mgbuf cenv.options.mainMethodInfo eenv lastImplFile @@ -8587,14 +11428,27 @@ let CodegenAssembly cenv eenv mgbuf implFiles = //printfn "#extraBindings = %d" extraBindings.Length if not (isNil extraBindings) then let mexpr = TMDefs [ for b in extraBindings -> TMDefLet(b, range0) ] + let _emptyTopInstrs, _emptyTopCode = - CodeGenMethod cenv mgbuf ([], "unused", eenv, 0, None, (fun cgbuf eenv -> - let lazyInitInfo = ResizeArray() - let qname = QualifiedNameOfFile(mkSynId range0 "unused") - LocalScope "module" cgbuf (fun (_, endMark) -> - let eenv = AddBindingsForModuleContents (AllocTopValWithinExpr cenv cgbuf endMark) eenv.cloc eenv mexpr - let _eenvEnv = GenModuleOrNamespaceContents cenv cgbuf qname lazyInitInfo eenv mexpr - ())), range0) + CodeGenMethod + cenv + mgbuf + ([], + "unused", + eenv, + 0, + None, + (fun cgbuf eenv -> + let lazyInitInfo = ResizeArray() + let qname = QualifiedNameOfFile(mkSynId range0 "unused") + + LocalScope "module" cgbuf (fun (_, endMark) -> + let eenv = + AddBindingsForModuleContents (AllocTopValWithinExpr cenv cgbuf endMark) eenv.cloc eenv mexpr + + let _eenvEnv = GenModuleOrNamespaceContents cenv cgbuf qname lazyInitInfo eenv mexpr + ())), + range0) //printfn "#_emptyTopInstrs = %d" _emptyTopInstrs.Length () @@ -8607,32 +11461,35 @@ let CodegenAssembly cenv eenv mgbuf implFiles = let GetEmptyIlxGenEnv (g: TcGlobals) ccu = let thisCompLoc = CompLocForCcu ccu - { tyenv=TypeReprEnv.Empty - cloc = thisCompLoc - exitSequel = Return - valsInScope=ValMap<_>.Empty - witnessesInScope = EmptyTraitWitnessInfoHashMap g - suppressWitnesses = false - someTypeInThisAssembly= g.ilg.typ_Object // dummy value - isFinalFile = false - letBoundVars=[] - liveLocals=IntMap.empty() - innerVals = [] - sigToImplRemapInfo = [] (* "module remap info" *) - withinSEH = false - isInLoop = false - initLocals = true - imports = None + + { + tyenv = TypeReprEnv.Empty + cloc = thisCompLoc + exitSequel = Return + valsInScope = ValMap<_>.Empty + witnessesInScope = EmptyTraitWitnessInfoHashMap g + suppressWitnesses = false + someTypeInThisAssembly = g.ilg.typ_Object // dummy value + isFinalFile = false + letBoundVars = [] + liveLocals = IntMap.empty () + innerVals = [] + sigToImplRemapInfo = [] (* "module remap info" *) + withinSEH = false + isInLoop = false + initLocals = true + imports = None } type IlxGenResults = - { ilTypeDefs: ILTypeDef list - ilAssemAttrs: ILAttribute list - ilNetModuleAttrs: ILAttribute list - topAssemblyAttrs: Attribs - permissionSets: ILSecurityDecl list - quotationResourceInfo: (ILTypeRef list * byte[]) list } - + { + ilTypeDefs: ILTypeDef list + ilAssemAttrs: ILAttribute list + ilNetModuleAttrs: ILAttribute list + topAssemblyAttrs: Attribs + permissionSets: ILSecurityDecl list + quotationResourceInfo: (ILTypeRef list * byte[]) list + } let GenerateCode (cenv, anonTypeTable, eenv, CheckedAssemblyAfterOptimization implFiles, assemAttribs, moduleAttribs) = @@ -8641,15 +11498,30 @@ let GenerateCode (cenv, anonTypeTable, eenv, CheckedAssemblyAfterOptimization im // Generate the implementations into the mgbuf let mgbuf = AssemblyBuilder(cenv, anonTypeTable) - let eenv = { eenv with cloc = CompLocForFragment cenv.options.fragName cenv.viewCcu } + + let eenv = + { eenv with + cloc = CompLocForFragment cenv.options.fragName cenv.viewCcu + } // Generate the PrivateImplementationDetails type - GenTypeDefForCompLoc (cenv, eenv, mgbuf, CompLocForPrivateImplementationDetails eenv.cloc, useHiddenInitCode, [], ILTypeInit.BeforeField, true, (* atEnd= *) true) + GenTypeDefForCompLoc( + cenv, + eenv, + mgbuf, + CompLocForPrivateImplementationDetails eenv.cloc, + useHiddenInitCode, + [], + ILTypeInit.BeforeField, + true (* atEnd= *) , + true + ) // Generate the whole assembly CodegenAssembly cenv eenv mgbuf implFiles - let ilAssemAttrs = GenAttrs cenv eenv (assemAttribs |> List.filter (fun a -> not(IsAssemblyVersionAttribute g a))) + let ilAssemAttrs = + GenAttrs cenv eenv (assemAttribs |> List.filter (fun a -> not (IsAssemblyVersionAttribute g a))) let tdefs, reflectedDefinitions = mgbuf.Close() @@ -8658,23 +11530,34 @@ let GenerateCode (cenv, anonTypeTable, eenv, CheckedAssemblyAfterOptimization im match reflectedDefinitions with | [] -> [] | _ -> - let qscope = QuotationTranslator.QuotationGenerationScope.Create (g, cenv.amap, cenv.viewCcu, cenv.tcVal, QuotationTranslator.IsReflectedDefinition.Yes) + let qscope = + QuotationTranslator.QuotationGenerationScope.Create( + g, + cenv.amap, + cenv.viewCcu, + cenv.tcVal, + QuotationTranslator.IsReflectedDefinition.Yes + ) + let defns = - reflectedDefinitions |> List.choose (fun ((methName, v), e) -> + reflectedDefinitions + |> List.choose (fun ((methName, v), e) -> try - let mbaseR, astExpr = QuotationTranslator.ConvReflectedDefinition qscope methName v e + let mbaseR, astExpr = + QuotationTranslator.ConvReflectedDefinition qscope methName v e - Some(mbaseR, astExpr) - with - | QuotationTranslator.InvalidQuotedTerm e -> warning e; None) + Some(mbaseR, astExpr) + with QuotationTranslator.InvalidQuotedTerm e -> + warning e + None) let referencedTypeDefs, typeSplices, exprSplices = qscope.Close() for _typeSplice, m in typeSplices do - error(InternalError("A free type variable was detected in a reflected definition", m)) + error (InternalError("A free type variable was detected in a reflected definition", m)) for _exprSplice, m in exprSplices do - error(Error(FSComp.SR.ilReflectedDefinitionsCannotUseSliceOperator(), m)) + error (Error(FSComp.SR.ilReflectedDefinitionsCannotUseSliceOperator (), m)) let defnsResourceBytes = defns |> QuotationPickler.PickleDefns @@ -8683,17 +11566,21 @@ let GenerateCode (cenv, anonTypeTable, eenv, CheckedAssemblyAfterOptimization im let ilNetModuleAttrs = GenAttrs cenv eenv moduleAttribs let casApplied = Dictionary() - let securityAttrs, topAssemblyAttrs = assemAttribs |> List.partition (fun a -> IsSecurityAttribute g cenv.amap casApplied a rangeStartup) + + let securityAttrs, topAssemblyAttrs = + assemAttribs + |> List.partition (fun a -> IsSecurityAttribute g cenv.amap casApplied a rangeStartup) // remove any security attributes from the top-level assembly attribute list let permissionSets = CreatePermissionSets cenv eenv securityAttrs - { ilTypeDefs= tdefs - ilAssemAttrs = ilAssemAttrs - ilNetModuleAttrs = ilNetModuleAttrs - topAssemblyAttrs = topAssemblyAttrs - permissionSets = permissionSets - quotationResourceInfo = quotationResourceInfo } - + { + ilTypeDefs = tdefs + ilAssemAttrs = ilAssemAttrs + ilNetModuleAttrs = ilNetModuleAttrs + topAssemblyAttrs = topAssemblyAttrs + permissionSets = permissionSets + quotationResourceInfo = quotationResourceInfo + } //------------------------------------------------------------------------- // For printing values in fsi we want to lookup the value of given vrefs. @@ -8705,18 +11592,21 @@ open System /// The lookup* functions are the conversions available from ilreflect. type ExecutionContext = - { LookupTypeRef: ILTypeRef -> Type - LookupType: ILType -> Type } + { + LookupTypeRef: ILTypeRef -> Type + LookupType: ILType -> Type + } // A helper to generate a default value for any System.Type. I couldn't find a System.Reflection // method to do this. let defaultOf = let gminfo = - lazy - (match <@@ Unchecked.defaultof @@> with - | Quotations.Patterns.Call(_, minfo, _) -> minfo.GetGenericMethodDefinition() - | _ -> failwith "unexpected failure decoding quotation at ilxgen startup") - fun ty -> gminfo.Value.MakeGenericMethod([| ty |]).Invoke(null, [| |]) + lazy + (match <@@ Unchecked.defaultof @@> with + | Quotations.Patterns.Call (_, minfo, _) -> minfo.GetGenericMethodDefinition() + | _ -> failwith "unexpected failure decoding quotation at ilxgen startup") + + fun ty -> gminfo.Value.MakeGenericMethod([| ty |]).Invoke(null, [||]) /// Top-level val bindings are stored (for example) in static fields. /// In the FSI case, these fields are be created and initialised, so we can recover the object. @@ -8724,89 +11614,96 @@ let defaultOf = /// IlxGen converts (v: Tast.Val) to AbsIL data structures. /// Ilreflect converts from AbsIL data structures to emitted Type, FieldInfo, MethodInfo etc. let LookupGeneratedValue (cenv: cenv) (ctxt: ExecutionContext) eenv (v: Val) = - try - // Convert the v.Type into a System.Type according to ilxgen and ilreflect. - let objTyp() = - let ilTy = GenType cenv v.Range TypeReprEnv.Empty v.Type - ctxt.LookupType ilTy - // Lookup the compiled v value (as an object). - match StorageForVal cenv.g v.Range v eenv with - | StaticPropertyWithField (fspec, _, hasLiteralAttr, ilContainerTy, _, _, ilGetterMethRef, _, _) -> - let obj = - if hasLiteralAttr then - let staticTy = ctxt.LookupTypeRef fspec.DeclaringTypeRef - // Checked: This FieldInfo (FieldBuilder) supports GetValue(). - staticTy.GetField(fspec.Name).GetValue(null: obj) - else - let staticTy = ctxt.LookupTypeRef ilContainerTy.TypeRef - // We can't call .Invoke on the ILMethodRef's MethodInfo, - // because it is the MethodBuilder and that does not support Invoke. - // Rather, we look for the getter MethodInfo from the built type and .Invoke on that. - let methInfo = staticTy.GetMethod(ilGetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) - methInfo.Invoke(null, null) - Some (obj, objTyp()) - - | StaticProperty (ilGetterMethSpec, _) -> - let obj = - let staticTy = ctxt.LookupTypeRef ilGetterMethSpec.MethodRef.DeclaringTypeRef - // 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(ilGetterMethSpec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) - methInfo.Invoke(null, null) - Some (obj, objTyp()) - - | Null -> - Some (null, objTyp()) - | Local _ -> None - | Method _ -> None - | Arg _ -> None - | Env _ -> None - with e -> + try + // Convert the v.Type into a System.Type according to ilxgen and ilreflect. + let objTyp () = + let ilTy = GenType cenv v.Range TypeReprEnv.Empty v.Type + ctxt.LookupType ilTy + // Lookup the compiled v value (as an object). + match StorageForVal v.Range v eenv with + | StaticPropertyWithField (fspec, _, hasLiteralAttr, ilContainerTy, _, _, ilGetterMethRef, _, _) -> + let obj = + if hasLiteralAttr then + let staticTy = ctxt.LookupTypeRef fspec.DeclaringTypeRef + // Checked: This FieldInfo (FieldBuilder) supports GetValue(). + staticTy.GetField(fspec.Name).GetValue(null: obj) + else + let staticTy = ctxt.LookupTypeRef ilContainerTy.TypeRef + // We can't call .Invoke on the ILMethodRef's MethodInfo, + // because it is the MethodBuilder and that does not support Invoke. + // Rather, we look for the getter MethodInfo from the built type and .Invoke on that. + let methInfo = + staticTy.GetMethod(ilGetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) + + methInfo.Invoke(null, null) + + Some(obj, objTyp ()) + + | StaticProperty (ilGetterMethSpec, _) -> + let obj = + let staticTy = ctxt.LookupTypeRef ilGetterMethSpec.MethodRef.DeclaringTypeRef + // 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(ilGetterMethSpec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) + + methInfo.Invoke(null, null) + + Some(obj, objTyp ()) + + | Null -> Some(null, objTyp ()) + | Local _ -> None + | Method _ -> None + | Arg _ -> None + | Env _ -> None + with e -> #if DEBUG - printf "ilxGen.LookupGeneratedValue for v=%s caught exception:\n%A\n\n" v.LogicalName e + printf "ilxGen.LookupGeneratedValue for v=%s caught exception:\n%A\n\n" v.LogicalName e #endif - None + None // Invoke the set_Foo method for a declaration with a value. Used to create variables with values programatically in fsi.exe. -let SetGeneratedValue (ctxt: ExecutionContext) (g: TcGlobals) eenv isForced (v: Val) (value: obj) = - try - match StorageForVal g v.Range v eenv with - | StaticPropertyWithField (fspec, _, hasLiteralAttr, _, _, _, _f, ilSetterMethRef, _) -> - if not hasLiteralAttr && (v.IsMutable || isForced) then - if isForced then - let staticTy = ctxt.LookupTypeRef fspec.DeclaringTypeRef - - let fieldInfo = staticTy.GetField(fspec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) - fieldInfo.SetValue(null, value) - else - let staticTy = ctxt.LookupTypeRef ilSetterMethRef.DeclaringTypeRef +let SetGeneratedValue (ctxt: ExecutionContext) eenv isForced (v: Val) (value: obj) = + try + match StorageForVal v.Range v eenv with + | StaticPropertyWithField (fspec, _, hasLiteralAttr, _, _, _, _f, ilSetterMethRef, _) -> + if not hasLiteralAttr && (v.IsMutable || isForced) then + if isForced then + let staticTy = ctxt.LookupTypeRef fspec.DeclaringTypeRef + + let fieldInfo = + 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) - let methInfo = staticTy.GetMethod(ilSetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) - methInfo.Invoke (null, [| value |]) |> ignore - | _ -> () - with - e -> + methInfo.Invoke(null, [| value |]) |> ignore + | _ -> () + with e -> #if DEBUG - printf "ilxGen.SetGeneratedValue for v=%s caught exception:\n%A\n\n" v.LogicalName e + printf "ilxGen.SetGeneratedValue for v=%s caught exception:\n%A\n\n" v.LogicalName e #endif - () + () // Invoke the set_Foo method for a declaration with a default/null value. Used to release storage in fsi.exe -let ClearGeneratedValue (ctxt: ExecutionContext) (g: TcGlobals) eenv (v: Val) = - try - match StorageForVal g v.Range v eenv with - | StaticPropertyWithField (fspec, _, hasLiteralAttr, _, _, _, _ilGetterMethRef, _ilSetterMethRef, _) -> - if not hasLiteralAttr && v.IsMutable then - let ty = ctxt.LookupType fspec.ActualType - SetGeneratedValue ctxt g eenv false v (defaultOf ty) - | _ -> () - with - e -> +let ClearGeneratedValue (ctxt: ExecutionContext) eenv (v: Val) = + try + match StorageForVal v.Range v eenv with + | StaticPropertyWithField (fspec, _, hasLiteralAttr, _, _, _, _ilGetterMethRef, _ilSetterMethRef, _) -> + if not hasLiteralAttr && v.IsMutable then + let ty = ctxt.LookupType fspec.ActualType + SetGeneratedValue ctxt eenv false v (defaultOf ty) + | _ -> () + with e -> #if DEBUG - printf "ilxGen.ClearGeneratedValue for v=%s caught exception:\n%A\n\n" v.LogicalName e + printf "ilxGen.ClearGeneratedValue for v=%s caught exception:\n%A\n\n" v.LogicalName e #endif - () + () /// The published API from the ILX code generator type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: ConstraintSolver.TcValF, ccu: CcuThunk) = @@ -8815,22 +11712,34 @@ type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: Constrai let mutable ilxGenEnv = GetEmptyIlxGenEnv tcGlobals ccu let anonTypeTable = AnonTypeGenerationTable() // Dictionaries are safe here as they will only be used during the codegen stage - will happen on a single thread. - let intraAssemblyInfo = { StaticFieldInfo = Dictionary<_, _>(HashIdentity.Structural) } + let intraAssemblyInfo = + { + StaticFieldInfo = Dictionary<_, _>(HashIdentity.Structural) + } + let casApplied = Dictionary() let cenv = - { g = tcGlobals - ilxPubCloEnv = EraseClosures.newIlxPubCloEnv(tcGlobals.ilg, tcGlobals.AddMethodGeneratedAttributes, tcGlobals.AddFieldGeneratedAttributes, tcGlobals.AddFieldNeverAttributes) - tcVal = tcVal - viewCcu = ccu - ilUnitTy = None - namedDebugPointsForInlinedCode = Map.empty - amap = amap - casApplied = casApplied - intraAssemblyInfo = intraAssemblyInfo - optionsOpt = None - optimizeDuringCodeGen = (fun _flag expr -> expr) - stackGuard = StackGuard(IlxGenStackGuardDepth) } + { + g = tcGlobals + ilxPubCloEnv = + EraseClosures.newIlxPubCloEnv ( + tcGlobals.ilg, + tcGlobals.AddMethodGeneratedAttributes, + tcGlobals.AddFieldGeneratedAttributes, + tcGlobals.AddFieldNeverAttributes + ) + tcVal = tcVal + viewCcu = ccu + ilUnitTy = None + namedDebugPointsForInlinedCode = Map.empty + amap = amap + casApplied = casApplied + intraAssemblyInfo = intraAssemblyInfo + optionsOpt = None + optimizeDuringCodeGen = (fun _flag expr -> expr) + stackGuard = StackGuard(IlxGenStackGuardDepth) + } /// Register a set of referenced assemblies with the ILX code generator member _.AddExternalCcus ccus = @@ -8838,29 +11747,47 @@ type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: Constrai /// Register a fragment of the current assembly with the ILX code generator. If 'isIncrementalFragment' is true then the input /// is assumed to be a fragment 'typed' into FSI.EXE, otherwise the input is assumed to be the result of a '#load' - member _.AddIncrementalLocalAssemblyFragment (isIncrementalFragment, fragName, typedImplFiles) = - ilxGenEnv <- AddIncrementalLocalAssemblyFragmentToIlxGenEnv (cenv, isIncrementalFragment, tcGlobals, ccu, fragName, intraAssemblyInfo, ilxGenEnv, typedImplFiles) + member _.AddIncrementalLocalAssemblyFragment(isIncrementalFragment, fragName, typedImplFiles) = + ilxGenEnv <- + AddIncrementalLocalAssemblyFragmentToIlxGenEnv( + cenv, + isIncrementalFragment, + tcGlobals, + ccu, + fragName, + intraAssemblyInfo, + ilxGenEnv, + typedImplFiles + ) /// Generate ILX code for an assembly fragment - member _.GenerateCode (codeGenOpts, typedAssembly: CheckedAssemblyAfterOptimization, assemAttribs, moduleAttribs) = + member _.GenerateCode(codeGenOpts, typedAssembly: CheckedAssemblyAfterOptimization, assemAttribs, moduleAttribs) = let namedDebugPointsForInlinedCode = let (CheckedAssemblyAfterOptimization impls) = typedAssembly - [| for impl in impls do - let (CheckedImplFile(namedDebugPointsForInlinedCode=dps)) = impl.ImplFile - for KeyValue(k,v) in dps do - yield (k,v) |] - let cenv = { cenv with optionsOpt = Some codeGenOpts; namedDebugPointsForInlinedCode = Map.ofArray namedDebugPointsForInlinedCode } - GenerateCode (cenv, anonTypeTable, ilxGenEnv, typedAssembly, assemAttribs, moduleAttribs) + [| + for impl in impls do + let (CheckedImplFile (namedDebugPointsForInlinedCode = dps)) = impl.ImplFile + + for KeyValue (k, v) in dps do + yield (k, v) + |] + + let cenv = + { cenv with + optionsOpt = Some codeGenOpts + namedDebugPointsForInlinedCode = Map.ofArray namedDebugPointsForInlinedCode + } + + GenerateCode(cenv, anonTypeTable, ilxGenEnv, typedAssembly, assemAttribs, moduleAttribs) /// Invert the compilation of the given value and clear the storage of the value - member _.ClearGeneratedValue (ctxt, v) = - ClearGeneratedValue ctxt tcGlobals ilxGenEnv v + member _.ClearGeneratedValue(ctxt, v) = ClearGeneratedValue ctxt ilxGenEnv v /// Invert the compilation of the given value and set the storage of the value, even if it is immutable - member _.ForceSetGeneratedValue (ctxt, v, value: obj) = - SetGeneratedValue ctxt tcGlobals ilxGenEnv true v value + member _.ForceSetGeneratedValue(ctxt, v, value: obj) = + SetGeneratedValue ctxt ilxGenEnv true v value /// Invert the compilation of the given value and return its current dynamic value and its compiled System.Type - member _.LookupGeneratedValue (ctxt, v) = - LookupGeneratedValue cenv ctxt ilxGenEnv v \ No newline at end of file + member _.LookupGeneratedValue(ctxt, v) = + LookupGeneratedValue cenv ctxt ilxGenEnv v diff --git a/src/Compiler/DependencyManager/AssemblyResolveHandler.fs b/src/Compiler/DependencyManager/AssemblyResolveHandler.fs index 5f17c53a41a..327eb063201 100644 --- a/src/Compiler/DependencyManager/AssemblyResolveHandler.fs +++ b/src/Compiler/DependencyManager/AssemblyResolveHandler.fs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace FSharp.Compiler.DependencyManager @@ -12,88 +12,109 @@ open Internal.Utilities.FSharpEnvironment type AssemblyResolutionProbe = delegate of Unit -> seq /// Type that encapsulates AssemblyResolveHandler for managed packages -type AssemblyResolveHandlerCoreclr (assemblyProbingPaths: AssemblyResolutionProbe option) as this = - let assemblyLoadContextType: Type = Type.GetType("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader", false) +type AssemblyResolveHandlerCoreclr(assemblyProbingPaths: AssemblyResolutionProbe option) as this = + let loadContextType = + Type.GetType("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader", false) let loadFromAssemblyPathMethod = - assemblyLoadContextType.GetMethod("LoadFromAssemblyPath", [| typeof |]) + loadContextType.GetMethod("LoadFromAssemblyPath", [| typeof |]) - let eventInfo, handler, defaultAssemblyLoadContext = - let eventInfo = assemblyLoadContextType.GetEvent("Resolving") - let mi = - let gmi = this.GetType().GetMethod("ResolveAssemblyNetStandard", BindingFlags.Instance ||| BindingFlags.NonPublic) - gmi.MakeGenericMethod(assemblyLoadContextType) + let eventInfo = loadContextType.GetEvent("Resolving") - eventInfo, - Delegate.CreateDelegate(eventInfo.EventHandlerType, this, mi), - assemblyLoadContextType.GetProperty("Default", BindingFlags.Static ||| BindingFlags.Public).GetValue(null, null) + let handler, defaultAssemblyLoadContext = + let ti = typeof + + let gmi = + 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) + + del, prop do eventInfo.AddEventHandler(defaultAssemblyLoadContext, handler) - member _.ResolveAssemblyNetStandard (ctxt: 'T) (assemblyName: AssemblyName): Assembly = + member _.ResolveAssemblyNetStandard (ctxt: 'T) (assemblyName: AssemblyName) : Assembly = let loadAssembly path = loadFromAssemblyPathMethod.Invoke(ctxt, [| path |]) :?> Assembly let assemblyPaths = match assemblyProbingPaths with | None -> Seq.empty - | Some assemblyProbingPaths -> assemblyProbingPaths.Invoke() + | Some assemblyProbingPaths -> assemblyProbingPaths.Invoke() try // args.Name is a displayname formatted assembly version. // E.g: "System.IO.FileSystem, Version=4.1.1.0, Culture=en-US, PublicKeyToken=b03f5f7f11d50a3a" let simpleName = assemblyName.Name - let assemblyPathOpt = assemblyPaths |> Seq.tryFind(fun path -> Path.GetFileNameWithoutExtension(path) = simpleName) + + let assemblyPathOpt = + assemblyPaths + |> Seq.tryFind (fun path -> Path.GetFileNameWithoutExtension(path) = simpleName) + match assemblyPathOpt with | Some path -> loadAssembly path | None -> Unchecked.defaultof - with | _ -> Unchecked.defaultof + with _ -> + Unchecked.defaultof interface IDisposable with member _x.Dispose() = eventInfo.RemoveEventHandler(defaultAssemblyLoadContext, handler) /// Type that encapsulates AssemblyResolveHandler for managed packages -type AssemblyResolveHandlerDeskTop (assemblyProbingPaths: AssemblyResolutionProbe option) = +type AssemblyResolveHandlerDeskTop(assemblyProbingPaths: AssemblyResolutionProbe option) = - let resolveAssemblyNET (assemblyName: AssemblyName): Assembly = - - let loadAssembly assemblyPath = - Assembly.LoadFrom(assemblyPath) + let resolveAssemblyNET (assemblyName: AssemblyName) : Assembly = let assemblyPaths = match assemblyProbingPaths with | None -> Seq.empty - | Some assemblyProbingPaths -> assemblyProbingPaths.Invoke() + | Some assemblyProbingPaths -> assemblyProbingPaths.Invoke() try // args.Name is a displayname formatted assembly version. // E.g: "System.IO.FileSystem, Version=4.1.1.0, Culture=en-US, PublicKeyToken=b03f5f7f11d50a3a" let simpleName = assemblyName.Name - let assemblyPathOpt = assemblyPaths |> Seq.tryFind(fun path -> Path.GetFileNameWithoutExtension(path) = simpleName) + + let assemblyPathOpt = + assemblyPaths + |> Seq.tryFind (fun path -> Path.GetFileNameWithoutExtension(path) = simpleName) + match assemblyPathOpt with - | Some path -> loadAssembly path + | Some path -> Assembly.LoadFrom path | None -> Unchecked.defaultof - with | _ -> Unchecked.defaultof + with _ -> + Unchecked.defaultof + + let handler = + ResolveEventHandler(fun _ (args: ResolveEventArgs) -> resolveAssemblyNET (AssemblyName(args.Name))) - let handler = ResolveEventHandler(fun _ (args: ResolveEventArgs) -> resolveAssemblyNET (AssemblyName(args.Name))) - do AppDomain.CurrentDomain.add_AssemblyResolve(handler) + do AppDomain.CurrentDomain.add_AssemblyResolve (handler) interface IDisposable with member _x.Dispose() = - AppDomain.CurrentDomain.remove_AssemblyResolve(handler) + AppDomain.CurrentDomain.remove_AssemblyResolve (handler) type AssemblyResolveHandler internal (assemblyProbingPaths: AssemblyResolutionProbe option) = let handler = - if isRunningOnCoreClr then - new AssemblyResolveHandlerCoreclr(assemblyProbingPaths) :> IDisposable - else - new AssemblyResolveHandlerDeskTop(assemblyProbingPaths) :> IDisposable + assemblyProbingPaths |> Option.map (fun _ -> + if isRunningOnCoreClr then + new AssemblyResolveHandlerCoreclr(assemblyProbingPaths) :> IDisposable + else + new AssemblyResolveHandlerDeskTop(assemblyProbingPaths) :> IDisposable + ) - new (assemblyProbingPaths: AssemblyResolutionProbe) = new AssemblyResolveHandler(Option.ofObj assemblyProbingPaths) + new(assemblyProbingPaths: AssemblyResolutionProbe) = new AssemblyResolveHandler(Option.ofObj assemblyProbingPaths) interface IDisposable with - member _.Dispose() = handler.Dispose() + member _.Dispose() = + handler |> Option.iter (fun handler -> handler.Dispose()) diff --git a/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi b/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi index 8aaf62c4618..0fbb6c33535 100644 --- a/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi +++ b/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace FSharp.Compiler.DependencyManager diff --git a/src/Compiler/DependencyManager/DependencyProvider.fs b/src/Compiler/DependencyManager/DependencyProvider.fs index aeb5f43f3e8..257d2869937 100644 --- a/src/Compiler/DependencyManager/DependencyProvider.fs +++ b/src/Compiler/DependencyManager/DependencyProvider.fs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace FSharp.Compiler.DependencyManager @@ -16,24 +16,25 @@ module Option = /// Convert string into Option string where null and String.Empty result in None let ofString s = - if String.IsNullOrEmpty(s) then None - else Some(s) + if String.IsNullOrEmpty(s) then None else Some(s) [] module ReflectionHelper = let dependencyManagerPattern = "*DependencyManager*.dll" - let dependencyManagerAttributeName= "DependencyManagerAttribute" + let dependencyManagerAttributeName = "DependencyManagerAttribute" let resolveDependenciesMethodName = "ResolveDependencies" + let clearResultsCacheMethodName = "ClearResultsCache" + let namePropertyName = "Name" let keyPropertyName = "Key" let helpMessagesPropertyName = "HelpMessages" - let arrEmpty = Array.empty + let arrEmpty = [||] let seqEmpty = Seq.empty @@ -41,40 +42,46 @@ module ReflectionHelper = try CustomAttributeExtensions.GetCustomAttributes(theAssembly) |> Seq.exists (fun a -> a.GetType().Name = attributeName) - with | _ -> false + with _ -> + false let getAttributeNamed (theType: Type) attributeName = try theType.GetTypeInfo().GetCustomAttributes false |> Seq.tryFind (fun a -> a.GetType().Name = attributeName) - with | _ -> None + with _ -> + None - let getInstanceProperty<'treturn> (theType: Type) propertyName = + let getInstanceProperty<'T> (theType: Type) propertyName = try - let property = theType.GetProperty(propertyName, BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance, Unchecked.defaultof, typeof<'treturn>, Array.empty, Array.empty) + let instanceFlags = + BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance + + let property = + theType.GetProperty(propertyName, instanceFlags, null, typeof<'T>, [||], [||]) + if isNull property then None else let getMethod = property.GetGetMethod() + if not (isNull getMethod) && not getMethod.IsStatic then Some property else None - with | _ -> None + with _ -> + None - let getInstanceMethod<'treturn> (theType: Type) (parameterTypes: Type array) methodName = + let getInstanceMethod<'T> (theType: Type) (parameterTypes: Type[]) methodName = try let theMethod = theType.GetMethod(methodName, parameterTypes) - if isNull theMethod then - None - else - Some theMethod - with | _ -> None + if isNull theMethod then None else Some theMethod + with _ -> + None - let stripTieWrapper (e:Exception) = + let stripTieWrapper (e: Exception) = match e with - | :? TargetInvocationException as e-> - e.InnerException + | :? TargetInvocationException as e -> e.InnerException | _ -> e /// Indicate the type of error to report @@ -117,15 +124,26 @@ type IResolveDependenciesResult = /// #I @"c:\somepath\to\packages\1.1.1\ResolvedPackage" abstract Roots: seq - [] type IDependencyManagerProvider = abstract Name: string abstract Key: string abstract HelpMessages: string[] - abstract ResolveDependencies: scriptDir: string * mainScriptName: string * scriptName: string * scriptExt: string * packageManagerTextLines: (string * string) seq * tfm: string * rid: string * timeout: int-> IResolveDependenciesResult - -type ReflectionDependencyManagerProvider(theType: Type, + abstract ClearResultsCache: unit -> unit + abstract ResolveDependencies: + scriptDir: string * + mainScriptName: string * + scriptName: string * + scriptExt: string * + packageManagerTextLines: (string * string) seq * + tfm: string * + rid: string * + timeout: int -> + IResolveDependenciesResult + + type ReflectionDependencyManagerProvider + ( + theType: Type, nameProperty: PropertyInfo, keyProperty: PropertyInfo, helpMessagesProperty: PropertyInfo option, @@ -133,40 +151,180 @@ type ReflectionDependencyManagerProvider(theType: Type, resolveDepsEx: MethodInfo option, resolveDepsExWithTimeout: MethodInfo option, resolveDepsExWithScriptInfoAndTimeout: MethodInfo option, - outputDir: string option) = - let instance = Activator.CreateInstance(theType, [| outputDir :> obj |]) + clearResultCache: MethodInfo option, + outputDir: string option, + useResultsCache: bool + ) = + + let instance = + if not(isNull (theType.GetConstructor([|typeof; typeof|]))) then + Activator.CreateInstance(theType, [| outputDir :> obj; useResultsCache :> obj |]) + else + Activator.CreateInstance(theType, [| outputDir :> obj |]) + let nameProperty = nameProperty.GetValue >> string let keyProperty = keyProperty.GetValue >> string + let helpMessagesProperty = - let toStringArray(o:obj) = o :?> string[] + let toStringArray (o: obj) = o :?> string[] + match helpMessagesProperty with | Some helpMessagesProperty -> helpMessagesProperty.GetValue >> toStringArray - | None -> fun _ -> Array.empty + | None -> fun _ -> [||] - static member InstanceMaker (theType: Type, outputDir: string option) = + static member InstanceMaker(theType: Type, outputDir: string option, useResultsCache: bool) = match getAttributeNamed theType dependencyManagerAttributeName, getInstanceProperty theType namePropertyName, getInstanceProperty theType keyPropertyName, getInstanceProperty theType helpMessagesPropertyName - with + with | None, _, _, _ | _, None, _, _ | _, _, None, _ -> None | Some _, Some nameProperty, Some keyProperty, None -> - let resolveMethod = getInstanceMethod theType [| typeof; typeof; typeof; typeof; typeof |] resolveDependenciesMethodName - let resolveMethodEx = getInstanceMethod theType [| typeof; typeof<(string * string) seq>; typeof; typeof |] resolveDependenciesMethodName - let resolveMethodExWithTimeout = getInstanceMethod theType [| typeof; typeof<(string * string) seq>; typeof; typeof; typeof |] resolveDependenciesMethodName - let resolveDepsExWithScriptInfoAndTimeout = getInstanceMethod theType [| typeof; typeof; typeof; typeof<(string * string) seq>; typeof; typeof; typeof |] resolveDependenciesMethodName - Some (fun () -> ReflectionDependencyManagerProvider(theType, nameProperty, keyProperty, None, resolveMethod, resolveMethodEx, resolveMethodExWithTimeout, resolveDepsExWithScriptInfoAndTimeout,outputDir) :> IDependencyManagerProvider) + let resolveMethod = + getInstanceMethod + theType + [| + typeof + typeof + typeof + typeof> + typeof + |] + resolveDependenciesMethodName + + let resolveMethodEx = + getInstanceMethod + theType + [| + typeof + typeof<(string * string) seq> + typeof + typeof + |] + resolveDependenciesMethodName + + let resolveMethodExWithTimeout = + getInstanceMethod + theType + [| + typeof + typeof<(string * string) seq> + typeof + typeof + typeof + |] + resolveDependenciesMethodName + + let resolveDepsExWithScriptInfoAndTimeout = + getInstanceMethod + theType + [| + typeof + typeof + typeof + typeof<(string * string) seq> + typeof + typeof + typeof + |] + resolveDependenciesMethodName + + let clearResultsCacheMethod = + getInstanceMethod + theType [||] + clearResultsCacheMethodName + + Some(fun () -> + ReflectionDependencyManagerProvider( + theType, + nameProperty, + keyProperty, + None, + resolveMethod, + resolveMethodEx, + resolveMethodExWithTimeout, + resolveDepsExWithScriptInfoAndTimeout, + clearResultsCacheMethod, + outputDir, + useResultsCache + ) + :> IDependencyManagerProvider) + | Some _, Some nameProperty, Some keyProperty, Some helpMessagesProperty -> - let resolveMethod = getInstanceMethod theType [| typeof; typeof; typeof; typeof; typeof |] resolveDependenciesMethodName - let resolveMethodEx = getInstanceMethod theType [| typeof; typeof<(string * string) seq>; typeof; typeof |] resolveDependenciesMethodName - let resolveMethodExWithTimeout = getInstanceMethod theType [| typeof; typeof<(string * string) seq>; typeof; typeof; typeof; |] resolveDependenciesMethodName - let resolveDepsExWithScriptInfoAndTimeout = getInstanceMethod theType [| typeof; typeof; typeof; typeof<(string * string) seq>; typeof; typeof; typeof |] resolveDependenciesMethodName - Some (fun () -> ReflectionDependencyManagerProvider(theType, nameProperty, keyProperty, Some helpMessagesProperty, resolveMethod, resolveMethodEx, resolveMethodExWithTimeout, resolveDepsExWithScriptInfoAndTimeout, outputDir) :> IDependencyManagerProvider) - - static member MakeResultFromObject(result: obj) = { - new IResolveDependenciesResult with + let resolveMethod = + getInstanceMethod + theType + [| + typeof + typeof + typeof + typeof> + typeof + |] + resolveDependenciesMethodName + + let resolveMethodEx = + getInstanceMethod + theType + [| + typeof + typeof<(string * string) seq> + typeof + typeof + |] + resolveDependenciesMethodName + + let resolveMethodExWithTimeout = + getInstanceMethod + theType + [| + typeof + typeof<(string * string) seq> + typeof + typeof + typeof + |] + resolveDependenciesMethodName + + let resolveDepsExWithScriptInfoAndTimeout = + getInstanceMethod + theType + [| + typeof + typeof + typeof + typeof<(string * string) seq> + typeof + typeof + typeof + |] + resolveDependenciesMethodName + + let clearResultsCacheMethod = + getInstanceMethod + theType [||] + clearResultsCacheMethodName + + Some(fun () -> + ReflectionDependencyManagerProvider( + theType, + nameProperty, + keyProperty, + Some helpMessagesProperty, + resolveMethod, + resolveMethodEx, + resolveMethodExWithTimeout, + resolveDepsExWithScriptInfoAndTimeout, + clearResultsCacheMethod, + outputDir, + useResultsCache + ) + :> IDependencyManagerProvider) + + static member MakeResultFromObject(result: obj) = + { new IResolveDependenciesResult with /// Succeded? member _.Success = match getInstanceProperty (result.GetType()) "Success" with @@ -175,37 +333,45 @@ type ReflectionDependencyManagerProvider(theType: Type, /// The resolution output log member _.StdOut = - match getInstanceProperty (result.GetType()) "StdOut" with - | None -> Array.empty - | Some p -> p.GetValue(result) :?> string array + match getInstanceProperty (result.GetType()) "StdOut" with + | None -> [||] + | Some p -> p.GetValue(result) :?> string[] /// The resolution error log (* process stderror *) member _.StdError = - match getInstanceProperty (result.GetType()) "StdError" with - | None -> Array.empty - | Some p -> p.GetValue(result) :?> string array + match getInstanceProperty (result.GetType()) "StdError" with + | None -> [||] + | Some p -> p.GetValue(result) :?> string[] /// The resolution paths member _.Resolutions = - match getInstanceProperty (result.GetType()) "Resolutions" with + match getInstanceProperty> (result.GetType()) "Resolutions" with | None -> Seq.empty - | Some p -> p.GetValue(result) :?> string seq + | Some p -> p.GetValue(result) :?> seq /// The source code file paths member _.SourceFiles = - match getInstanceProperty (result.GetType()) "SourceFiles" with + match getInstanceProperty> (result.GetType()) "SourceFiles" with | None -> Seq.empty - | Some p -> p.GetValue(result) :?> string seq + | Some p -> p.GetValue(result) :?> seq /// The roots to package directories member _.Roots = - match getInstanceProperty (result.GetType()) "Roots" with + match getInstanceProperty> (result.GetType()) "Roots" with | None -> Seq.empty - | Some p -> p.GetValue(result) :?> string seq + | Some p -> p.GetValue(result) :?> seq } - static member MakeResultFromFields(success: bool, stdOut: string array, stdError: string array, resolutions: string seq, sourceFiles: string seq, roots: string seq) = { - new IResolveDependenciesResult with + static member MakeResultFromFields + ( + success: bool, + stdOut: string[], + stdError: string[], + resolutions: seq, + sourceFiles: seq, + roots: seq + ) = + { new IResolveDependenciesResult with /// Succeded? member _.Success = success @@ -225,7 +391,6 @@ type ReflectionDependencyManagerProvider(theType: Type, member _.Roots = roots } - interface IDependencyManagerProvider with /// Name of dependency Manager @@ -234,11 +399,28 @@ type ReflectionDependencyManagerProvider(theType: Type, /// Key of dependency Manager: used for #r "key: ... " E.g nuget member _.Key = instance |> keyProperty + /// Clear the dependency manager caches + member _.ClearResultsCache () = + match clearResultCache with + | Some clearResultsCache -> + clearResultsCache.Invoke(instance, [||]) |> ignore + | None -> () + /// Key of dependency Manager: used for #help member _.HelpMessages = instance |> helpMessagesProperty /// Resolve the dependencies for the given arguments - member _.ResolveDependencies(scriptDir, mainScriptName, scriptName, scriptExt, packageManagerTextLines, tfm, rid, timeout): IResolveDependenciesResult = + member _.ResolveDependencies + ( + scriptDir, + mainScriptName, + scriptName, + scriptExt, + packageManagerTextLines, + tfm, + rid, + timeout + ) : IResolveDependenciesResult = // The ResolveDependencies method, has two signatures, the original signaature 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) @@ -246,19 +428,29 @@ type ReflectionDependencyManagerProvider(theType: Type, // We use reflection to get the correct method and to determine what we got back. let method, arguments = if resolveDepsExWithScriptInfoAndTimeout.IsSome then - resolveDepsExWithScriptInfoAndTimeout, [| box scriptDir; box scriptName; box scriptExt; box packageManagerTextLines; box tfm; box rid; box timeout |] + resolveDepsExWithScriptInfoAndTimeout, + [| + box scriptDir + box scriptName + box scriptExt + box packageManagerTextLines + box tfm + box rid + box timeout + |] elif resolveDepsExWithTimeout.IsSome then resolveDepsExWithTimeout, [| box scriptExt; box packageManagerTextLines; box tfm; box rid; box timeout |] elif resolveDepsEx.IsSome then resolveDepsEx, [| box scriptExt; box packageManagerTextLines; box tfm; box rid |] elif resolveDeps.IsSome then - resolveDeps, [| box scriptDir - box mainScriptName - box scriptName - box (packageManagerTextLines - |> Seq.filter(fun (dv, _) -> dv = "r") - |> Seq.map snd) - box tfm |] + resolveDeps, + [| + box scriptDir + box mainScriptName + box scriptName + box (packageManagerTextLines |> Seq.filter (fun (dv, _) -> dv = "r") |> Seq.map snd) + box tfm + |] else None, [||] @@ -269,66 +461,75 @@ type ReflectionDependencyManagerProvider(theType: Type, // Verify the number of arguments returned in the tuple returned by resolvedependencies, it can be: // 1 - object with properties // 3 - (bool * string list * string list) - // Support legacy api return shape (bool, string seq, string seq) --- original paket packagemanager - if FSharpType.IsTuple (result.GetType()) then + // Support legacy api return shape (bool, seq, seq) --- original paket packagemanager + if FSharpType.IsTuple(result.GetType()) then // Verify the number of arguments returned in the tuple returned by resolvedependencies, it can be: // 3 - (bool * string list * string list) let success, sourceFiles, packageRoots = let tupleFields = result |> FSharpValue.GetTupleFields + match tupleFields |> Array.length with - | 3 -> tupleFields[0] :?> bool, tupleFields[1] :?> string list |> List.toSeq, tupleFields[2] :?> string list |> List.distinct |> List.toSeq + | 3 -> + tupleFields[0] :?> bool, + tupleFields[1] :?> string list |> List.toSeq, + tupleFields[2] :?> string list |> List.distinct |> List.toSeq | _ -> false, seqEmpty, seqEmpty - ReflectionDependencyManagerProvider.MakeResultFromFields(success, Array.empty, Array.empty, Seq.empty, sourceFiles, packageRoots) + + ReflectionDependencyManagerProvider.MakeResultFromFields(success, [||], [||], Seq.empty, sourceFiles, packageRoots) else ReflectionDependencyManagerProvider.MakeResultFromObject(result) - | None -> - ReflectionDependencyManagerProvider.MakeResultFromFields(false, Array.empty, Array.empty, Seq.empty, Seq.empty, Seq.empty) - + | None -> ReflectionDependencyManagerProvider.MakeResultFromFields(false, [||], [||], Seq.empty, Seq.empty, Seq.empty) /// Provides DependencyManagement functions. /// Class is IDisposable -type DependencyProvider internal (assemblyProbingPaths: AssemblyResolutionProbe option, nativeProbingRoots: NativeResolutionProbe option) = +type DependencyProvider internal (assemblyProbingPaths: AssemblyResolutionProbe option, nativeProbingRoots: NativeResolutionProbe option, useResultsCache: bool) = // Note: creating a NativeDllResolveHandler currently installs process-wide handlers let dllResolveHandler = new NativeDllResolveHandler(nativeProbingRoots) // Note: creating a AssemblyResolveHandler currently installs process-wide handlers - let assemblyResolveHandler = new AssemblyResolveHandler(assemblyProbingPaths) :> IDisposable + let assemblyResolveHandler = + new AssemblyResolveHandler(assemblyProbingPaths) :> IDisposable // Resolution Path = Location of FSharp.Compiler.Service.dll - let assemblySearchPaths = lazy ( - [ - let assemblyLocation = typeof.GetTypeInfo().Assembly.Location - yield Path.GetDirectoryName assemblyLocation - yield AppDomain.CurrentDomain.BaseDirectory - ]) + let assemblySearchPaths = + lazy + ([ + let assemblyLocation = + typeof.GetTypeInfo().Assembly.Location + + yield Path.GetDirectoryName assemblyLocation + yield AppDomain.CurrentDomain.BaseDirectory + ]) let enumerateDependencyManagerAssemblies compilerTools (reportError: ResolvingErrorReport) = getCompilerToolsDesignTimeAssemblyPaths compilerTools |> Seq.append (assemblySearchPaths.Force()) |> Seq.collect (fun path -> try - if Directory.Exists(path) then Directory.EnumerateFiles(path, dependencyManagerPattern) - else Seq.empty - with _ -> Seq.empty) - |> Seq.choose (fun path -> + if Directory.Exists(path) then + Directory.EnumerateFiles(path, dependencyManagerPattern) + else + Seq.empty + with _ -> + Seq.empty) + |> Seq.choose (fun path -> try Some(Assembly.LoadFrom path) - with - | e -> + with e -> let e = stripTieWrapper e - let n, m = FSComp.SR.couldNotLoadDependencyManagerExtension(path,e.Message) + let n, m = FSComp.SR.couldNotLoadDependencyManagerExtension (path, e.Message) reportError.Invoke(ErrorReportType.Warning, n, m) None) |> Seq.filter (fun a -> assemblyHasAttribute a dependencyManagerAttributeName) - let mutable registeredDependencyManagers: Map option= None + let mutable registeredDependencyManagers: Map option = + None - let RegisteredDependencyManagers (compilerTools: string seq) (outputDir: string option) (reportError: ResolvingErrorReport) = + let RegisteredDependencyManagers (compilerTools: seq) (outputDir: string option) (reportError: ResolvingErrorReport) = match registeredDependencyManagers with - | Some managers -> - managers + | Some managers -> managers | None -> let managers = let defaultProviders = [] @@ -336,7 +537,7 @@ type DependencyProvider internal (assemblyProbingPaths: AssemblyResolutionProbe let loadedProviders = enumerateDependencyManagerAssemblies compilerTools reportError |> Seq.collect (fun a -> a.GetTypes()) - |> Seq.choose (fun t -> ReflectionDependencyManagerProvider.InstanceMaker(t, outputDir)) + |> Seq.choose (fun t -> ReflectionDependencyManagerProvider.InstanceMaker(t, outputDir, useResultsCache)) |> Seq.map (fun maker -> maker ()) defaultProviders @@ -344,98 +545,165 @@ type DependencyProvider internal (assemblyProbingPaths: AssemblyResolutionProbe |> Seq.map (fun pm -> pm.Key, pm) |> Map.ofSeq - registeredDependencyManagers <- - if managers.Count > 0 then - Some managers - else - None + registeredDependencyManagers <- if managers.Count > 0 then Some managers else None managers - let cache = ConcurrentDictionary<_,Result>(HashIdentity.Structural) + let cache = + ConcurrentDictionary<_, Result>(HashIdentity.Structural) + + new(assemblyProbingPaths: AssemblyResolutionProbe, nativeProbingRoots: NativeResolutionProbe) = + new DependencyProvider(Some assemblyProbingPaths, Some nativeProbingRoots, true) + + new(assemblyProbingPaths: AssemblyResolutionProbe, nativeProbingRoots: NativeResolutionProbe, useResultsCache) = + new DependencyProvider(Some assemblyProbingPaths, Some nativeProbingRoots, useResultsCache) - new (assemblyProbingPaths: AssemblyResolutionProbe, nativeProbingRoots: NativeResolutionProbe) = new DependencyProvider(Some assemblyProbingPaths, Some nativeProbingRoots) + new(nativeProbingRoots: NativeResolutionProbe, useResultsCache) = + new DependencyProvider(None, Some nativeProbingRoots, useResultsCache) - new (nativeProbingRoots: NativeResolutionProbe) = new DependencyProvider(None, Some nativeProbingRoots) + new(nativeProbingRoots: NativeResolutionProbe) = + new DependencyProvider(None, Some nativeProbingRoots, true) - new () = new DependencyProvider(None, None) + new() = new DependencyProvider(None, None, true) /// Returns a formatted help messages for registered dependencymanagers for the host to present - member _.GetRegisteredDependencyManagerHelpText (compilerTools, outputDir, errorReport) = [| - let managers = RegisteredDependencyManagers compilerTools (Option.ofString outputDir) errorReport + member _.GetRegisteredDependencyManagerHelpText(compilerTools, outputDir, errorReport) = + [| + let managers = + RegisteredDependencyManagers compilerTools (Option.ofString outputDir) errorReport + for kvp in managers do let dm = kvp.Value yield! dm.HelpMessages |] + + /// Clear the DependencyManager results caches + member _.ClearResultsCache(compilerTools, outputDir, errorReport) = + let managers = + RegisteredDependencyManagers compilerTools (Option.ofString outputDir) errorReport + + for kvp in managers do + kvp.Value.ClearResultsCache() + /// Returns a formatted error message for the host to present - member _.CreatePackageManagerUnknownError (compilerTools: string seq, outputDir: string, packageManagerKey: string, reportError: ResolvingErrorReport) = - let registeredKeys = String.Join(", ", RegisteredDependencyManagers compilerTools (Option.ofString outputDir) reportError |> Seq.map (fun kv -> kv.Value.Key)) + member _.CreatePackageManagerUnknownError + ( + compilerTools: seq, + outputDir: string, + packageManagerKey: string, + reportError: ResolvingErrorReport + ) = + let registeredKeys = + String.Join( + ", ", + RegisteredDependencyManagers compilerTools (Option.ofString outputDir) reportError + |> Seq.map (fun kv -> kv.Value.Key) + ) + let searchPaths = assemblySearchPaths.Force() - FSComp.SR.packageManagerUnknown(packageManagerKey, String.Join(", ", searchPaths, compilerTools), registeredKeys) + FSComp.SR.packageManagerUnknown (packageManagerKey, String.Join(", ", searchPaths, compilerTools), registeredKeys) /// Fetch a dependencymanager that supports a specific key - member this.TryFindDependencyManagerInPath (compilerTools: string seq, outputDir: string, reportError: ResolvingErrorReport, path: string): string MaybeNull * IDependencyManagerProvider MaybeNull = + member this.TryFindDependencyManagerInPath + ( + compilerTools: seq, + outputDir: string, + reportError: ResolvingErrorReport, + path: string + ) : string MaybeNull * IDependencyManagerProvider MaybeNull = try if path.Contains ":" && not (Path.IsPathRooted path) then - let managers = RegisteredDependencyManagers compilerTools (Option.ofString outputDir) reportError + let managers = + RegisteredDependencyManagers compilerTools (Option.ofString outputDir) reportError - match managers |> Seq.tryFind (fun kv -> path.StartsWith(kv.Value.Key + ":" )) with + match managers |> Seq.tryFind (fun kv -> path.StartsWith(kv.Value.Key + ":")) with | None -> - let err, msg = this.CreatePackageManagerUnknownError(compilerTools, outputDir, path.Split(':').[0], reportError) + let err, msg = + this.CreatePackageManagerUnknownError(compilerTools, outputDir, path.Split(':').[0], reportError) + reportError.Invoke(ErrorReportType.Error, err, msg) null, null - | Some kv -> - path, kv.Value + | Some kv -> path, kv.Value else path, null - with - | e -> + with e -> let e = stripTieWrapper e - let err, msg = FSComp.SR.packageManagerError(e.Message) + let err, msg = FSComp.SR.packageManagerError (e.Message) reportError.Invoke(ErrorReportType.Error, err, msg) null, null /// Fetch a dependencymanager that supports a specific key - member _.TryFindDependencyManagerByKey (compilerTools: string seq, outputDir: string, reportError: ResolvingErrorReport, key: string): IDependencyManagerProvider MaybeNull = + member _.TryFindDependencyManagerByKey + ( + compilerTools: seq, + outputDir: string, + reportError: ResolvingErrorReport, + key: string + ) : IDependencyManagerProvider MaybeNull = try RegisteredDependencyManagers compilerTools (Option.ofString outputDir) reportError |> Map.tryFind key |> Option.toObj - with - | e -> + with e -> let e = stripTieWrapper e - let err, msg = FSComp.SR.packageManagerError(e.Message) + let err, msg = FSComp.SR.packageManagerError (e.Message) reportError.Invoke(ErrorReportType.Error, err, msg) null /// Resolve reference for a list of package manager lines - member _.Resolve (packageManager:IDependencyManagerProvider, - scriptExt: string, - packageManagerTextLines: (string * string) seq, - reportError: ResolvingErrorReport, - executionTfm: string, - []executionRid: string MaybeNull, - []implicitIncludeDir: string, - []mainScriptName: string, - []fileName: string, - []timeout: int): IResolveDependenciesResult = - - let key = (packageManager.Key, scriptExt, Seq.toArray packageManagerTextLines, executionTfm, executionRid, implicitIncludeDir, mainScriptName, fileName) - - let result = - cache.GetOrAdd(key, System.Func<_,_>(fun _ -> - try - let executionRid = - match executionRid with - | Null -> RidHelpers.platformRid - | NonNull executionRid -> executionRid - Ok (packageManager.ResolveDependencies(implicitIncludeDir, mainScriptName, fileName, scriptExt, packageManagerTextLines, executionTfm, executionRid, timeout)) - - with e -> - let e = stripTieWrapper e - Error (FSComp.SR.packageManagerError(e.Message)) - )) + member _.Resolve + ( + packageManager: IDependencyManagerProvider, + scriptExt: string, + packageManagerTextLines: (string * string) seq, + reportError: ResolvingErrorReport, + executionTfm: string, + [] executionRid: string MaybeNull, + [] implicitIncludeDir: string, + [] mainScriptName: string, + [] fileName: string, + [] timeout: int + ) : IResolveDependenciesResult = + + let key = + (packageManager.Key, + scriptExt, + Seq.toArray packageManagerTextLines, + executionTfm, + executionRid, + implicitIncludeDir, + mainScriptName, + fileName) + + let result = + cache.GetOrAdd( + key, + System.Func<_, _>(fun _ -> + try + let executionRid = + match executionRid with + | Null -> RidHelpers.platformRid + | NonNull executionRid -> executionRid + + Ok( + packageManager.ResolveDependencies( + implicitIncludeDir, + mainScriptName, + fileName, + scriptExt, + packageManagerTextLines, + executionTfm, + executionRid, + timeout + ) + ) + + with e -> + let e = stripTieWrapper e + Error(FSComp.SR.packageManagerError (e.Message))) + ) + match result with | Ok res -> dllResolveHandler.RefreshPathsInEnvironment(res.Roots) diff --git a/src/Compiler/DependencyManager/DependencyProvider.fsi b/src/Compiler/DependencyManager/DependencyProvider.fsi index 4a35606a812..a4c76e67b92 100644 --- a/src/Compiler/DependencyManager/DependencyProvider.fsi +++ b/src/Compiler/DependencyManager/DependencyProvider.fsi @@ -1,8 +1,9 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. // Helper members to integrate DependencyManagers into F# codebase namespace FSharp.Compiler.DependencyManager +open System open System.Runtime.InteropServices open Internal.Utilities.Library @@ -53,6 +54,9 @@ type IDependencyManagerProvider = /// The help messages for this dependency manager inster abstract HelpMessages: string[] + /// Clear the results cache + abstract ClearResultsCache: unit -> unit + /// Resolve the dependencies, for the given set of arguments, go find the .dll references, scripts and additional include values. abstract ResolveDependencies: scriptDir: string * @@ -80,7 +84,7 @@ type ResolvingErrorReport = delegate of ErrorReportType * int * string -> unit /// provided each time the TryFindDependencyManagerByKey and TryFindDependencyManagerInPath are /// executed, which are assumed to be invariant over the lifetime of the DependencyProvider. type DependencyProvider = - interface System.IDisposable + interface IDisposable /// Construct a new DependencyProvider with no dynamic load handlers (only for compilation/analysis) new: unit -> DependencyProvider @@ -88,12 +92,25 @@ type DependencyProvider = /// Construct a new DependencyProvider with only native resolution new: nativeProbingRoots: NativeResolutionProbe -> DependencyProvider + /// Construct a new DependencyProvider with only native resolution and specify caching + new: nativeProbingRoots: NativeResolutionProbe * useResultsCache: bool -> DependencyProvider + /// Construct a new DependencyProvider with managed and native resolution new: assemblyProbingPaths: AssemblyResolutionProbe * nativeProbingRoots: NativeResolutionProbe -> DependencyProvider + /// Construct a new DependencyProvider with managed and native resolution and specify caching + new: + assemblyProbingPaths: AssemblyResolutionProbe * + nativeProbingRoots: NativeResolutionProbe * + useResultsCache: bool -> + DependencyProvider + /// Returns a formatted help messages for registered dependencymanagers for the host to present member GetRegisteredDependencyManagerHelpText: string seq * string * ResolvingErrorReport -> string[] + /// Clear the DependencyManager results caches + member ClearResultsCache: string seq * string * ResolvingErrorReport -> unit + /// Returns a formatted error message for the host to present member CreatePackageManagerUnknownError: string seq * string * string * ResolvingErrorReport -> int * string diff --git a/src/Compiler/DependencyManager/NativeDllResolveHandler.fs b/src/Compiler/DependencyManager/NativeDllResolveHandler.fs index 7ed85eb4035..47d821bb33b 100644 --- a/src/Compiler/DependencyManager/NativeDllResolveHandler.fs +++ b/src/Compiler/DependencyManager/NativeDllResolveHandler.fs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace FSharp.Compiler.DependencyManager @@ -11,19 +11,68 @@ open Internal.Utilities open Internal.Utilities.FSharpEnvironment open FSharp.Compiler.IO + +type internal ProbingPathsStore() = + + let addedPaths = ConcurrentBag() + + static member AppendPathSeparator (p: string) = + let separator = string Path.PathSeparator + + if not (p.EndsWith(separator, StringComparison.OrdinalIgnoreCase)) then + p + separator + else + p + + static member RemoveProbeFromProcessPath probePath = + if not (String.IsNullOrWhiteSpace(probePath)) then + let probe = ProbingPathsStore.AppendPathSeparator probePath + let path = ProbingPathsStore.AppendPathSeparator (Environment.GetEnvironmentVariable("PATH")) + + if path.Contains(probe) then + Environment.SetEnvironmentVariable("PATH", path.Replace(probe, "")) + + member _.AddProbeToProcessPath probePath = + let probe = ProbingPathsStore.AppendPathSeparator probePath + let path = ProbingPathsStore.AppendPathSeparator (Environment.GetEnvironmentVariable("PATH")) + + if not (path.Contains(probe)) then + Environment.SetEnvironmentVariable("PATH", path + probe) + addedPaths.Add probe + + member this.RefreshPathsInEnvironment(roots) = + for probePath in roots do + this.AddProbeToProcessPath(probePath) + + member this.Dispose() = + let mutable probe: string = Unchecked.defaultof + while (addedPaths.TryTake(&probe)) do + ProbingPathsStore.RemoveProbeFromProcessPath(probe) + + interface IDisposable with + member _.Dispose() = + let mutable probe: string = Unchecked.defaultof + while (addedPaths.TryTake(&probe)) do + ProbingPathsStore.RemoveProbeFromProcessPath(probe) + /// Signature for Native library resolution probe callback /// host implements this, it's job is to return a list of package roots to probe. type NativeResolutionProbe = delegate of Unit -> seq /// Type that encapsulates Native library probing for managed packages -type NativeDllResolveHandlerCoreClr (nativeProbingRoots: NativeResolutionProbe option) = +type internal NativeDllResolveHandlerCoreClr(nativeProbingRoots: NativeResolutionProbe option) = + + let probingPaths = new ProbingPathsStore() let nativeLibraryTryLoad = - let nativeLibraryType: Type = Type.GetType("System.Runtime.InteropServices.NativeLibrary, System.Runtime.InteropServices", false) - nativeLibraryType.GetMethod("TryLoad", [| typeof; typeof.MakeByRefType() |]) + let nativeLibraryType: Type = + Type.GetType("System.Runtime.InteropServices.NativeLibrary, System.Runtime.InteropServices", false) + + nativeLibraryType.GetMethod("TryLoad", [| typeof; typeof.MakeByRefType () |]) let loadNativeLibrary path = - let arguments = [| path:>obj; IntPtr.Zero:>obj |] + let arguments = [| path :> obj; IntPtr.Zero :> obj |] + if nativeLibraryTryLoad.Invoke(null, arguments) :?> bool then arguments[1] :?> IntPtr else @@ -32,13 +81,20 @@ type NativeDllResolveHandlerCoreClr (nativeProbingRoots: NativeResolutionProbe o let probingFileNames (name: string) = // coreclr native library probing algorithm: https://github.com/dotnet/coreclr/blob/9773db1e7b1acb3ec75c9cc0e36bd62dcbacd6d5/src/System.Private.CoreLib/shared/System/Runtime/Loader/LibraryNameVariation.Unix.cs let isRooted = Path.IsPathRooted name - let useSuffix s = not (name.Contains(s + ".") || name.EndsWith(s)) // linux devs often append version # to libraries I.e mydll.so.5.3.2 - let usePrefix = name.IndexOf(Path.DirectorySeparatorChar) = -1 // If name has directory information no add no prefix - && name.IndexOf(Path.AltDirectorySeparatorChar) = -1 - && name.IndexOf(Path.PathSeparator) = -1 - && name.IndexOf(Path.VolumeSeparatorChar) = -1 + + let useSuffix s = + not (name.Contains(s + ".") || name.EndsWith(s)) // linux devs often append version # to libraries I.e mydll.so.5.3.2 + + let usePrefix = + name.IndexOf(Path.DirectorySeparatorChar) = -1 // If name has directory information no add no prefix + && name.IndexOf(Path.AltDirectorySeparatorChar) = -1 + && name.IndexOf(Path.PathSeparator) = -1 + && name.IndexOf(Path.VolumeSeparatorChar) = -1 + let prefix = [| "lib" |] - let suffix = [| + + let suffix = + [| if RuntimeInformation.IsOSPlatform(OSPlatform.Windows) then ".dll" ".exe" @@ -49,103 +105,85 @@ type NativeDllResolveHandlerCoreClr (nativeProbingRoots: NativeResolutionProbe o |] [| - yield name // Bare name + yield name // Bare name if not isRooted then for s in suffix do - if useSuffix s then // Suffix without prefix + if useSuffix s then // Suffix without prefix yield (sprintf "%s%s" name s) + if usePrefix then - for p in prefix do // Suffix with prefix + for p in prefix do // Suffix with prefix yield (sprintf "%s%s%s" p name s) elif usePrefix then - for p in prefix do // Prefix + for p in prefix do // Prefix yield (sprintf "%s%s" p name) |] - let resolveUnmanagedDll (_: Assembly) (name: string): IntPtr = + let resolveUnmanagedDll (_: Assembly) (name: string) : IntPtr = // Enumerate probing roots looking for a dll that matches the probing name in the probed locations let probeForNativeLibrary root rid name = // Look for name in root - probingFileNames name |> Array.tryPick(fun name -> + probingFileNames name + |> Array.tryPick (fun name -> let path = Path.Combine(root, "runtimes", rid, "native", name) - if FileSystem.FileExistsShim(path) then - Some path - else - None) + if FileSystem.FileExistsShim(path) then Some path else None) let probe = match nativeProbingRoots with | None -> None - | Some nativeProbingRoots -> + | Some nativeProbingRoots -> nativeProbingRoots.Invoke() - |> Seq.tryPick(fun root -> - probingFileNames name |> Seq.tryPick(fun name -> + |> Seq.tryPick (fun root -> + probingFileNames name + |> Seq.tryPick (fun name -> let path = Path.Combine(root, name) + if FileSystem.FileExistsShim(path) then Some path else - RidHelpers.probingRids |> Seq.tryPick(fun rid -> probeForNativeLibrary root rid name))) + RidHelpers.probingRids + |> Seq.tryPick (fun rid -> probeForNativeLibrary root rid name))) match probe with - | Some path -> loadNativeLibrary(path) + | Some path -> loadNativeLibrary (path) | None -> IntPtr.Zero // 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) + let assemblyLoadContextType: Type = + Type.GetType("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader", false) + let eventInfo, handler, defaultAssemblyLoadContext = 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) - interface IDisposable with - member _x.Dispose() = eventInfo.RemoveEventHandler(defaultAssemblyLoadContext, handler) - - -type NativeDllResolveHandler (nativeProbingRoots: NativeResolutionProbe option) = - - let handler: IDisposable option = - if isRunningOnCoreClr then - Some (new NativeDllResolveHandlerCoreClr(nativeProbingRoots) :> IDisposable) - else - None + member _.RefreshPathsInEnvironment(roots: string seq) = + probingPaths.RefreshPathsInEnvironment(roots) - let appendPathSeparator (p: string) = - let separator = string Path.PathSeparator - if not(p.EndsWith(separator, StringComparison.OrdinalIgnoreCase)) then - p + separator - else - p + member _.Dispose() = + eventInfo.RemoveEventHandler(defaultAssemblyLoadContext, handler) + probingPaths.Dispose() - let addedPaths = ConcurrentBag() + interface IDisposable with + member this.Dispose() = this.Dispose() - let addProbeToProcessPath probePath = - let probe = appendPathSeparator probePath - let path = appendPathSeparator (Environment.GetEnvironmentVariable("PATH")) - if not (path.Contains(probe)) then - Environment.SetEnvironmentVariable("PATH", path + probe) - addedPaths.Add probe +type NativeDllResolveHandler(nativeProbingRoots: NativeResolutionProbe option) = - let removeProbeFromProcessPath probePath = - if not(String.IsNullOrWhiteSpace(probePath)) then - let probe = appendPathSeparator probePath - let path = appendPathSeparator (Environment.GetEnvironmentVariable("PATH")) - if path.Contains(probe) then Environment.SetEnvironmentVariable("PATH", path.Replace(probe, "")) + let handler: NativeDllResolveHandlerCoreClr option = + nativeProbingRoots + |> Option.filter(fun _ -> isRunningOnCoreClr) + |> Option.map (fun _ -> new NativeDllResolveHandlerCoreClr(nativeProbingRoots)) - new (nativeProbingRoots: NativeResolutionProbe) = new NativeDllResolveHandler(Option.ofObj nativeProbingRoots) + new(nativeProbingRoots: NativeResolutionProbe) = new NativeDllResolveHandler(Option.ofObj nativeProbingRoots) member internal _.RefreshPathsInEnvironment(roots: string seq) = - for probePath in roots do - addProbeToProcessPath probePath + handler |> Option.iter (fun handler -> handler.RefreshPathsInEnvironment(roots)) interface IDisposable with member _.Dispose() = - match handler with - | None -> () - | Some handler -> handler.Dispose() - - let mutable probe:string = Unchecked.defaultof - while (addedPaths.TryTake(&probe)) do - removeProbeFromProcessPath probe + handler |> Option.iter (fun handler -> handler.Dispose()) diff --git a/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi b/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi index d9e4956d7fb..8bb2babae2a 100644 --- a/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi +++ b/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace FSharp.Compiler.DependencyManager diff --git a/src/Compiler/Driver/CompilerConfig.fs b/src/Compiler/Driver/CompilerConfig.fs index 0c629ca0e78..0360e83b050 100644 --- a/src/Compiler/Driver/CompilerConfig.fs +++ b/src/Compiler/Driver/CompilerConfig.fs @@ -417,6 +417,7 @@ type TcConfigBuilder = mutable subsystemVersion: int * int mutable useHighEntropyVA: bool mutable inputCodePage: int option + mutable clearResultsCache: bool mutable embedResources: string list mutable diagnosticsOptions: FSharpDiagnosticOptions mutable mlCompatibility: bool @@ -543,7 +544,7 @@ type TcConfigBuilder = // If true - the compiler will copy FSharp.Core.dll along the produced binaries mutable copyFSharpCore: CopyFSharpCoreFlag - /// When false FSI will lock referenced assemblies requiring process restart, false = disable Shadow Copy false (*default*) + /// When false FSI will lock referenced assemblies requiring process restart, false = disable Shadow Copy false, the default mutable shadowCopyReferences: bool mutable useSdkRefs: bool @@ -634,6 +635,7 @@ type TcConfigBuilder = diagnosticsOptions = FSharpDiagnosticOptions.Default embedResources = [] inputCodePage = None + clearResultsCache = false subsystemVersion = 4, 0 // per spec for 357994 useHighEntropyVA = false mlCompatibility = false @@ -861,7 +863,8 @@ type TcConfigBuilder = | None -> () | Some n -> // nowarn:62 turns on mlCompatibility, e.g. shows ML compat items in intellisense menus - if n = 62 then tcConfigB.mlCompatibility <- true + if n = 62 then + tcConfigB.mlCompatibility <- true tcConfigB.diagnosticsOptions <- { tcConfigB.diagnosticsOptions with @@ -875,7 +878,8 @@ type TcConfigBuilder = | None -> () | Some n -> // warnon 62 turns on mlCompatibility, e.g. shows ML compat items in intellisense menus - if n = 62 then tcConfigB.mlCompatibility <- false + if n = 62 then + tcConfigB.mlCompatibility <- false tcConfigB.diagnosticsOptions <- { tcConfigB.diagnosticsOptions with @@ -943,11 +947,10 @@ type TcConfigBuilder = if FileSystem.IsInvalidPathShim path then warning (Error(FSComp.SR.buildInvalidAssemblyName (path), m)) elif - not - ( - tcConfigB.referencedDLLs - |> List.exists (fun ar2 -> equals m ar2.Range && path = ar2.Text) - ) + not ( + tcConfigB.referencedDLLs + |> List.exists (fun ar2 -> equals m ar2.Range && path = ar2.Text) + ) then // NOTE: We keep same paths if range is different. let projectReference = tcConfigB.projectReferences @@ -1054,9 +1057,10 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = else None - match data.referencedDLLs - |> List.filter (fun assemblyReference -> assemblyReference.SimpleAssemblyNameIs libraryName) - with + match + data.referencedDLLs + |> List.filter (fun assemblyReference -> assemblyReference.SimpleAssemblyNameIs libraryName) + with | [] -> defaultCoreLibraryReference, None | [ r ] | r :: _ -> nameOfDll r @@ -1181,7 +1185,9 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = let frameworkRootVersion = Path.Combine(frameworkRoot, targetFrameworkVersionValue) yield frameworkRootVersion let facades = Path.Combine(frameworkRootVersion, "Facades") - if FileSystem.DirectoryExistsShim facades then yield facades + + if FileSystem.DirectoryExistsShim facades then + yield facades match data.FxResolver.GetFrameworkRefsPackDirectory() with | Some path when FileSystem.DirectoryExistsShim(path) -> yield path @@ -1221,6 +1227,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member _.subsystemVersion = data.subsystemVersion member _.useHighEntropyVA = data.useHighEntropyVA member _.inputCodePage = data.inputCodePage + member _.clearResultsCache = data.clearResultsCache member _.embedResources = data.embedResources member _.diagnosticsOptions = data.diagnosticsOptions member _.mlCompatibility = data.mlCompatibility diff --git a/src/Compiler/Driver/CompilerConfig.fsi b/src/Compiler/Driver/CompilerConfig.fsi index 843830a6d69..2dfb76b5596 100644 --- a/src/Compiler/Driver/CompilerConfig.fsi +++ b/src/Compiler/Driver/CompilerConfig.fsi @@ -255,6 +255,8 @@ type TcConfigBuilder = mutable inputCodePage: int option + mutable clearResultsCache: bool + mutable embedResources: string list mutable diagnosticsOptions: FSharpDiagnosticOptions @@ -568,6 +570,8 @@ type TcConfig = member inputCodePage: int option + member clearResultsCache: bool + member embedResources: string list member diagnosticsOptions: FSharpDiagnosticOptions diff --git a/src/Compiler/Driver/CompilerDiagnostics.fs b/src/Compiler/Driver/CompilerDiagnostics.fs index a26d232746f..056f2f19a78 100644 --- a/src/Compiler/Driver/CompilerDiagnostics.fs +++ b/src/Compiler/Driver/CompilerDiagnostics.fs @@ -17,6 +17,7 @@ open FSharp.Compiler open FSharp.Compiler.AttributeChecking open FSharp.Compiler.CheckExpressions open FSharp.Compiler.CheckDeclarations +open FSharp.Compiler.CheckIncrementalClasses open FSharp.Compiler.CompilerConfig open FSharp.Compiler.CompilerImports open FSharp.Compiler.ConstraintSolver @@ -123,6 +124,7 @@ let GetRangeOfDiagnostic (diagnostic: PhasedDiagnostic) = | LetRecCheckedAtRuntime m | UpperCaseIdentifierInPattern m | NotUpperCaseConstructor m + | NotUpperCaseConstructorWithoutRQA m | RecursiveUseCheckedAtRuntime (_, _, m) | LetRecEvaluatedOutOfOrder (_, _, _, m) | DiagnosticWithText (_, _, m) @@ -269,6 +271,7 @@ let GetDiagnosticNumber (diagnostic: PhasedDiagnostic) = | UseOfAddressOfOperator _ -> 51 | DefensiveCopyWarning _ -> 52 | NotUpperCaseConstructor _ -> 53 + | NotUpperCaseConstructorWithoutRQA _ -> 53 | TypeIsImplicitlyAbstract _ -> 54 // 55 cannot be reused | DeprecatedThreadStaticBindingWarning _ -> 56 @@ -434,6 +437,7 @@ let ErrorFromApplyingDefault2E () = Message("ErrorFromApplyingDefault2", "") let ErrorsFromAddingSubsumptionConstraintE () = Message("ErrorsFromAddingSubsumptionConstraint", "%s%s%s") let UpperCaseIdentifierInPatternE () = Message("UpperCaseIdentifierInPattern", "") let NotUpperCaseConstructorE () = Message("NotUpperCaseConstructor", "") +let NotUpperCaseConstructorWithoutRQAE () = Message("NotUpperCaseConstructorWithoutRQA", "") let FunctionExpectedE () = Message("FunctionExpected", "") let BakedInMemberConstraintNameE () = Message("BakedInMemberConstraintName", "%s") let BadEventTransformationE () = Message("BadEventTransformation", "") @@ -770,6 +774,8 @@ let OutputPhasedErrorR (os: StringBuilder) (diagnostic: PhasedDiagnostic) (canSu | NotUpperCaseConstructor _ -> os.AppendString(NotUpperCaseConstructorE().Format) + | NotUpperCaseConstructorWithoutRQA _ -> os.AppendString(NotUpperCaseConstructorWithoutRQAE().Format) + | ErrorFromAddingConstraint (_, e, _) -> OutputExceptionR os e #if !NO_TYPEPROVIDERS @@ -894,7 +900,8 @@ let OutputPhasedErrorR (os: StringBuilder) (diagnostic: PhasedDiagnostic) (canSu | ParameterlessStructCtor _ -> os.AppendString(ParameterlessStructCtorE().Format) - | InterfaceNotRevealed (denv, ity, _) -> os.AppendString(InterfaceNotRevealedE().Format(NicePrint.minimalStringOfType denv ity)) + | InterfaceNotRevealed (denv, intfTy, _) -> + os.AppendString(InterfaceNotRevealedE().Format(NicePrint.minimalStringOfType denv intfTy)) | NotAFunctionButIndexer (_, _, name, _, _, old) -> if old then @@ -1206,11 +1213,15 @@ let OutputPhasedErrorR (os: StringBuilder) (diagnostic: PhasedDiagnostic) (canSu if showParserStackOnParseError then printfn "parser stack:" - for rps in ctxt.ReducibleProductions do + let rps = + ctxt.ReducibleProductions + |> List.map (fun rps -> rps |> List.map (fun rp -> rp, Parser.prodIdxToNonTerminal rp)) + + for rps in rps do printfn " ----" //printfn " state %d" state - for rp in rps do - printfn " non-terminal %+A (idx %d): ... " (Parser.prodIdxToNonTerminal rp) rp + for rp, nonTerminalId in rps do + printfn $" non-terminal %+A{nonTerminalId} (idx {rp}): ... " #endif match ctxt.CurrentToken with @@ -1496,7 +1507,7 @@ let OutputPhasedErrorR (os: StringBuilder) (diagnostic: PhasedDiagnostic) (canSu |> List.exists (function | TType_app (maybeUnit, [], _) -> match maybeUnit.TypeAbbrev with - | Some ttype when isUnitTy g ttype -> true + | Some ty when isUnitTy g ty -> true | _ -> false | _ -> false) @@ -1668,7 +1679,8 @@ let OutputPhasedErrorR (os: StringBuilder) (diagnostic: PhasedDiagnostic) (canSu | Some (cex, false) -> os.AppendString(MatchIncomplete2E().Format cex) | Some (cex, true) -> os.AppendString(MatchIncomplete3E().Format cex) - if isComp then os.AppendString(MatchIncomplete4E().Format) + if isComp then + os.AppendString(MatchIncomplete4E().Format) | PatternMatchCompilation.EnumMatchIncomplete (isComp, cexOpt, _) -> os.AppendString(EnumMatchIncomplete1E().Format) @@ -1678,11 +1690,12 @@ let OutputPhasedErrorR (os: StringBuilder) (diagnostic: PhasedDiagnostic) (canSu | Some (cex, false) -> os.AppendString(MatchIncomplete2E().Format cex) | Some (cex, true) -> os.AppendString(MatchIncomplete3E().Format cex) - if isComp then os.AppendString(MatchIncomplete4E().Format) + if isComp then + os.AppendString(MatchIncomplete4E().Format) | PatternMatchCompilation.RuleNeverMatched _ -> os.AppendString(RuleNeverMatchedE().Format) - | ValNotMutable (_, valRef, _) -> os.AppendString(ValNotMutableE().Format(valRef.DisplayName)) + | ValNotMutable (_, vref, _) -> os.AppendString(ValNotMutableE().Format(vref.DisplayName)) | ValNotLocal _ -> os.AppendString(ValNotLocalE().Format) @@ -1690,7 +1703,9 @@ let OutputPhasedErrorR (os: StringBuilder) (diagnostic: PhasedDiagnostic) (canSu | ObsoleteWarning (s, _) -> os.AppendString(Obsolete1E().Format) - if s <> "" then os.AppendString(Obsolete2E().Format s) + + if s <> "" then + os.AppendString(Obsolete2E().Format s) | Experimental (s, _) -> os.AppendString(ExperimentalE().Format s) @@ -1985,7 +2000,8 @@ let CollectFormattedDiagnostics // Show prefix only for real files. Otherwise, we just want a truncated error like: // parse error FS0031: blah blah if - not (equals m range0) && not (equals m rangeStartup) + not (equals m range0) + && not (equals m rangeStartup) && not (equals m rangeCmdArgs) then let file = file.Replace("/", "\\") diff --git a/src/Compiler/Driver/CompilerImports.fs b/src/Compiler/Driver/CompilerImports.fs index 422581ec470..e6e8ddfdbb2 100644 --- a/src/Compiler/Driver/CompilerImports.fs +++ b/src/Compiler/Driver/CompilerImports.fs @@ -402,7 +402,8 @@ type TcConfig with seq { yield! tcConfig.GetSearchPathsForLibraryFiles() - if isHashRReference m then Path.GetDirectoryName(m.FileName) + if isHashRReference m then + Path.GetDirectoryName(m.FileName) } let resolved = TryResolveFileUsingPaths(searchPaths, m, nm) @@ -592,8 +593,10 @@ type TcConfig with // O(N^2) here over a small set of referenced assemblies. let IsResolved (originalName: string) = - if resultingResolutions - |> List.exists (fun resolution -> resolution.originalReference.Text = originalName) then + if + resultingResolutions + |> List.exists (fun resolution -> resolution.originalReference.Text = originalName) + then true else // MSBuild resolution may have unified the result of two duplicate references. Try to re-resolve now. @@ -615,8 +618,10 @@ type TcConfig with // If mode=Speculative, then we haven't reported any errors. // We report the error condition by returning an empty list of resolutions - if mode = ResolveAssemblyReferenceMode.Speculative - && unresolvedReferences.Length > 0 then + if + mode = ResolveAssemblyReferenceMode.Speculative + && unresolvedReferences.Length > 0 + then [], unresolved else resultingResolutions, unresolved @@ -736,7 +741,8 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, resolutions.Length = 1 - if found then asm + if found then + asm if tcConfig.implicitlyReferenceDotNetAssemblies then let references, _useDotNetFramework = @@ -1097,7 +1103,9 @@ and [] TcImports let mutable disposed = false // this doesn't need locking, it's only for debugging let mutable tcGlobals = None // this doesn't need locking, it's set during construction of the TcImports - let CheckDisposed () = if disposed then assert false + let CheckDisposed () = + if disposed then + assert false let dispose () = CheckDisposed() @@ -1116,8 +1124,11 @@ and [] TcImports let unsuccessful = [ for ccuThunk, func in contents do - if ccuThunk.IsUnresolvedReference then func () - if ccuThunk.IsUnresolvedReference then (ccuThunk, func) + if ccuThunk.IsUnresolvedReference then + func () + + if ccuThunk.IsUnresolvedReference then + (ccuThunk, func) ] ccuThunks <- ResizeArray unsuccessful) @@ -1352,7 +1363,7 @@ and [] TcImports tcImports.RegisterDll dllinfo let ccuContents = - Construct.NewCcuContents ilScopeRef m ilShortAssemName (Construct.NewEmptyModuleOrNamespaceType Namespace) + Construct.NewCcuContents ilScopeRef m ilShortAssemName (Construct.NewEmptyModuleOrNamespaceType(Namespace true)) let ccuData: CcuData = { @@ -1597,11 +1608,11 @@ and [] TcImports ILScopeRef.Local, injectedNamespace |> List.rev - |> List.map (fun n -> (n, ModuleOrNamespaceKind.Namespace)) + |> List.map (fun n -> (n, ModuleOrNamespaceKind.Namespace true)) ) let mid = ident (next, rangeStartup) - let mty = Construct.NewEmptyModuleOrNamespaceType Namespace + let mty = Construct.NewEmptyModuleOrNamespaceType(Namespace true) let newNamespace = Construct.NewModuleOrNamespace (Some cpath) taccessPublic mid XmlDoc.Empty [] (MaybeLazy.Strict mty) diff --git a/src/Compiler/Driver/CompilerOptions.fs b/src/Compiler/Driver/CompilerOptions.fs index 4ff07d1addb..7d5d7f92922 100644 --- a/src/Compiler/Driver/CompilerOptions.fs +++ b/src/Compiler/Driver/CompilerOptions.fs @@ -288,9 +288,11 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler let getSwitchOpt (opt: string) = // if opt is a switch, strip the '+' or '-' - if opt <> "--" - && opt.Length > 1 - && (opt.EndsWithOrdinal("+") || opt.EndsWithOrdinal("-")) then + if + opt <> "--" + && opt.Length > 1 + && (opt.EndsWithOrdinal("+") || opt.EndsWithOrdinal("-")) + then opt[0 .. opt.Length - 2] else opt @@ -368,7 +370,10 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler | CompilerOption (s, _, OptionString f, d, _) as compilerOption :: _ when optToken = s -> reportDeprecatedOption d let oa = getOptionArg compilerOption argString - if oa <> "" then f (getOptionArg compilerOption oa) + + if oa <> "" then + f (getOptionArg compilerOption oa) + t | CompilerOption (s, _, OptionInt f, d, _) as compilerOption :: _ when optToken = s -> reportDeprecatedOption d @@ -1238,13 +1243,25 @@ let noFrameworkFlag isFsc tcConfigB = tagNone, OptionUnit(fun () -> tcConfigB.implicitlyReferenceDotNetAssemblies <- false - if isFsc then tcConfigB.implicitlyResolveAssemblies <- false), + + if isFsc then + tcConfigB.implicitlyResolveAssemblies <- false), None, Some(FSComp.SR.optsNoframework ()) ) let advancedFlagsFsi tcConfigB = - advancedFlagsBoth tcConfigB @ [ noFrameworkFlag false tcConfigB ] + advancedFlagsBoth tcConfigB + @ [ + CompilerOption( + "clearResultsCache", + tagNone, + OptionUnit(fun () -> tcConfigB.clearResultsCache <- true), + None, + Some(FSComp.SR.optsClearResultsCache ()) + ) + noFrameworkFlag false tcConfigB + ] let advancedFlagsFsc tcConfigB = advancedFlagsBoth tcConfigB @@ -1388,29 +1405,51 @@ let editorSpecificFlags (tcConfigB: TcConfigBuilder) = let internalFlags (tcConfigB: TcConfigBuilder) = [ - CompilerOption("stamps", tagNone, OptionUnit ignore, Some(InternalCommandLineOption("--stamps", rangeCmdArgs)), None) + CompilerOption( + "typedtree", + tagNone, + OptionUnit(fun () -> tcConfigB.showTerms <- true), + Some(InternalCommandLineOption("--typedtree", rangeCmdArgs)), + None + ) CompilerOption( - "ranges", + "typedtreefile", tagNone, - OptionSet DebugPrint.layoutRanges, - Some(InternalCommandLineOption("--ranges", rangeCmdArgs)), + OptionUnit(fun () -> tcConfigB.writeTermsToFiles <- true), + Some(InternalCommandLineOption("--typedtreefile", rangeCmdArgs)), None ) CompilerOption( - "terms", + "typedtreestamps", tagNone, - OptionUnit(fun () -> tcConfigB.showTerms <- true), - Some(InternalCommandLineOption("--terms", rangeCmdArgs)), + OptionUnit(fun () -> DebugPrint.layoutStamps <- true), + Some(InternalCommandLineOption("--typedtreestamps", rangeCmdArgs)), None ) CompilerOption( - "termsfile", + "typedtreeranges", tagNone, - OptionUnit(fun () -> tcConfigB.writeTermsToFiles <- true), - Some(InternalCommandLineOption("--termsfile", rangeCmdArgs)), + OptionUnit(fun () -> DebugPrint.layoutRanges <- true), + Some(InternalCommandLineOption("--typedtreeranges", rangeCmdArgs)), + None + ) + + CompilerOption( + "typedtreetypes", + tagNone, + OptionUnit(fun () -> DebugPrint.layoutTypes <- true), + Some(InternalCommandLineOption("--typedtreetypes", rangeCmdArgs)), + None + ) + + CompilerOption( + "typedtreevalreprinfo", + tagNone, + OptionUnit(fun () -> DebugPrint.layoutValReprInfo <- true), + Some(InternalCommandLineOption("--typedtreevalreprinfo", rangeCmdArgs)), None ) @@ -2206,7 +2245,7 @@ let ApplyCommandLineArgs (tcConfigB: TcConfigBuilder, sourceFiles: string list, let mutable showTermFileCount = 0 -let PrintWholeAssemblyImplementation g (tcConfig: TcConfig) outfile header expr = +let PrintWholeAssemblyImplementation (tcConfig: TcConfig) outfile header expr = if tcConfig.showTerms then if tcConfig.writeTermsToFiles then let fileName = outfile + ".terms" @@ -2217,10 +2256,10 @@ let PrintWholeAssemblyImplementation g (tcConfig: TcConfig) outfile header expr .GetWriter() showTermFileCount <- showTermFileCount + 1 - LayoutRender.outL f (Display.squashTo 192 (DebugPrint.implFilesL g expr)) + LayoutRender.outL f (Display.squashTo 192 (DebugPrint.implFilesL expr)) else dprintf "\n------------------\nshowTerm: %s:\n" header - LayoutRender.outL stderr (Display.squashTo 192 (DebugPrint.implFilesL g expr)) + LayoutRender.outL stderr (Display.squashTo 192 (DebugPrint.implFilesL expr)) dprintf "\n------------------\n" //---------------------------------------------------------------------------- diff --git a/src/Compiler/Driver/CreateILModule.fs b/src/Compiler/Driver/CreateILModule.fs index 9039453478c..55ec3ad40a1 100644 --- a/src/Compiler/Driver/CreateILModule.fs +++ b/src/Compiler/Driver/CreateILModule.fs @@ -195,9 +195,10 @@ module MainModuleBuilder = "System.Runtime.Numerics" let numericsAssemblyRef = - match tcImports.GetImportedAssemblies() - |> List.tryFind (fun a -> a.FSharpViewOfMetadata.AssemblyName = refNumericsDllName) - with + match + tcImports.GetImportedAssemblies() + |> List.tryFind (fun a -> a.FSharpViewOfMetadata.AssemblyName = refNumericsDllName) + with | Some asm -> match asm.ILScopeRef with | ILScopeRef.Assembly aref -> Some aref @@ -581,10 +582,12 @@ module MainModuleBuilder = tcConfig.win32manifest // don't embed a manifest if target is not an exe, if manifest is specifically excluded, if another native resource is being included, or if running on mono - elif not (tcConfig.target.IsExe) - || not (tcConfig.includewin32manifest) - || not (tcConfig.win32res = "") - || runningOnMono then + elif + not (tcConfig.target.IsExe) + || not (tcConfig.includewin32manifest) + || not (tcConfig.win32res = "") + || runningOnMono + then "" // otherwise, include the default manifest else @@ -617,9 +620,11 @@ module MainModuleBuilder = tcConfig.target = CompilerTarget.Dll )) |] - if tcConfig.win32res = "" - && tcConfig.win32icon <> "" - && tcConfig.target <> CompilerTarget.Dll then + if + tcConfig.win32res = "" + && tcConfig.win32icon <> "" + && tcConfig.target <> CompilerTarget.Dll + then use ms = new MemoryStream() use iconStream = FileSystem.OpenFileForReadShim(tcConfig.win32icon) Win32ResourceConversions.AppendIconToResourceStream(ms, iconStream) diff --git a/src/Compiler/Driver/FxResolver.fs b/src/Compiler/Driver/FxResolver.fs index 2d1eb4ce7ae..d769b36678e 100644 --- a/src/Compiler/Driver/FxResolver.fs +++ b/src/Compiler/Driver/FxResolver.fs @@ -492,13 +492,14 @@ type internal FxResolver defaultMscorlibVersion // Get the ProductVersion of this framework compare with table compatible monikers - match desktopProductVersionMonikers - |> Array.tryFind (fun (major, minor, build, revision, _) -> - (majorPart >= major) - && (minorPart >= minor) - && (buildPart >= build) - && (privatePart >= revision)) - with + match + desktopProductVersionMonikers + |> Array.tryFind (fun (major, minor, build, revision, _) -> + (majorPart >= major) + && (minorPart >= minor) + && (buildPart >= build) + && (privatePart >= revision)) + with | Some (_, _, _, _, moniker) -> moniker | None -> // no TFM could be found, assume latest stable? @@ -653,7 +654,8 @@ type internal FxResolver "System.Configuration" getFSharpCoreLibraryName - if useFsiAuxLib then fsiLibraryName + if useFsiAuxLib then + fsiLibraryName // always include a default reference to System.ValueTuple.dll in scripts and out-of-project sources match getSystemValueTupleImplementationReference () with @@ -687,7 +689,8 @@ type internal FxResolver [ yield! Directory.GetFiles(implDir, "*.dll") getFSharpCoreImplementationReference () - if useFsiAuxLib then getFsiLibraryImplementationReference () + if useFsiAuxLib then + getFsiLibraryImplementationReference () ] (getDependenciesOf roots).Values |> Seq.toList @@ -979,7 +982,8 @@ type internal FxResolver [ yield! Directory.GetFiles(path, "*.dll") getFSharpCoreImplementationReference () - if useFsiAuxLib then getFsiLibraryImplementationReference () + if useFsiAuxLib then + getFsiLibraryImplementationReference () ] |> List.filter (fun f -> systemAssemblies.Contains(Path.GetFileNameWithoutExtension(f))) diff --git a/src/Compiler/Driver/OptimizeInputs.fs b/src/Compiler/Driver/OptimizeInputs.fs index 13bf68ef799..4818ae1756d 100644 --- a/src/Compiler/Driver/OptimizeInputs.fs +++ b/src/Compiler/Driver/OptimizeInputs.fs @@ -20,7 +20,7 @@ open FSharp.Compiler.TypedTreeOps let mutable showTermFileCount = 0 -let PrintWholeAssemblyImplementation g (tcConfig: TcConfig) outfile header expr = +let PrintWholeAssemblyImplementation (tcConfig: TcConfig) outfile header expr = if tcConfig.showTerms then if tcConfig.writeTermsToFiles then let fileName = outfile + ".terms" @@ -31,10 +31,10 @@ let PrintWholeAssemblyImplementation g (tcConfig: TcConfig) outfile header expr .GetWriter() showTermFileCount <- showTermFileCount + 1 - LayoutRender.outL f (Display.squashTo 192 (DebugPrint.implFilesL g expr)) + LayoutRender.outL f (Display.squashTo 192 (DebugPrint.implFilesL expr)) else dprintf "\n------------------\nshowTerm: %s:\n" header - LayoutRender.outL stderr (Display.squashTo 192 (DebugPrint.implFilesL g expr)) + LayoutRender.outL stderr (Display.squashTo 192 (DebugPrint.implFilesL expr)) dprintf "\n------------------\n" let AddExternalCcuToOptimizationEnv tcGlobals optEnv (ccuinfo: ImportedAssembly) = @@ -65,15 +65,13 @@ let ApplyAllOptimizations // Always optimize once - the results of this step give the x-module optimization // info. Subsequent optimization steps choose representations etc. which we don't // want to save in the x-module info (i.e. x-module info is currently "high level"). - PrintWholeAssemblyImplementation tcGlobals tcConfig outfile "pass-start" implFiles + PrintWholeAssemblyImplementation tcConfig outfile "pass-start" implFiles #if DEBUG if tcConfig.showOptimizationData then - dprintf - "Expression prior to optimization:\n%s\n" - (LayoutRender.showL (Display.squashTo 192 (DebugPrint.implFilesL tcGlobals implFiles))) + dprintf "Expression prior to optimization:\n%s\n" (LayoutRender.showL (Display.squashTo 192 (DebugPrint.implFilesL implFiles))) if tcConfig.showOptimizationData then - dprintf "CCU prior to optimization:\n%s\n" (LayoutRender.showL (Display.squashTo 192 (DebugPrint.entityL tcGlobals ccu.Contents))) + dprintf "CCU prior to optimization:\n%s\n" (LayoutRender.showL (Display.squashTo 192 (DebugPrint.entityL ccu.Contents))) #endif let optEnv0 = optEnv @@ -205,7 +203,7 @@ let ApplyAllOptimizations let implFiles, implFileOptDatas = List.unzip results let assemblyOptData = Optimizer.UnionOptimizationInfos implFileOptDatas let tassembly = CheckedAssemblyAfterOptimization implFiles - PrintWholeAssemblyImplementation tcGlobals tcConfig outfile "pass-end" (implFiles |> List.map (fun implFile -> implFile.ImplFile)) + PrintWholeAssemblyImplementation tcConfig outfile "pass-end" (implFiles |> List.map (fun implFile -> implFile.ImplFile)) ReportTime tcConfig "Ending Optimizations" tassembly, assemblyOptData, optEnvFirstLoop @@ -234,8 +232,10 @@ let GenerateIlxCode ) = let mainMethodInfo = - if (tcConfig.target = CompilerTarget.Dll) - || (tcConfig.target = CompilerTarget.Module) then + if + (tcConfig.target = CompilerTarget.Dll) + || (tcConfig.target = CompilerTarget.Module) + then None else Some topAttrs.mainMethodAttrs @@ -245,7 +245,7 @@ let GenerateIlxCode generateFilterBlocks = tcConfig.generateFilterBlocks emitConstantArraysUsingStaticDataBlobs = not isInteractiveOnMono workAroundReflectionEmitBugs = tcConfig.isInteractive - generateDebugSymbols = tcConfig.debuginfo + generateDebugSymbols = tcConfig.debuginfo // REVIEW: is this still required? fragName = fragName localOptimizationsEnabled = tcConfig.optSettings.LocalOptimizationsEnabled testFlagEmitFeeFeeAs100001 = tcConfig.testFlagEmitFeeFeeAs100001 diff --git a/src/Compiler/Driver/ParseAndCheckInputs.fs b/src/Compiler/Driver/ParseAndCheckInputs.fs index 889abccff5f..6d764f264dd 100644 --- a/src/Compiler/Driver/ParseAndCheckInputs.fs +++ b/src/Compiler/Driver/ParseAndCheckInputs.fs @@ -617,7 +617,8 @@ let ParseOneInputLexbuf (tcConfig: TcConfig, lexResourceManager, lexbuf, fileNam ) // Report the statistics for testing purposes - if tcConfig.reportNumDecls then ReportParsingStatistics res + if tcConfig.reportNumDecls then + ReportParsingStatistics res res) @@ -1067,7 +1068,7 @@ let GetInitialTcState (m, ccuName, tcConfig: TcConfig, tcGlobals, tcImports: TcI // Create a ccu to hold all the results of compilation let ccuContents = - Construct.NewCcuContents ILScopeRef.Local m ccuName (Construct.NewEmptyModuleOrNamespaceType Namespace) + Construct.NewCcuContents ILScopeRef.Local m ccuName (Construct.NewEmptyModuleOrNamespaceType(Namespace true)) let ccuData: CcuData = { @@ -1105,7 +1106,7 @@ let GetInitialTcState (m, ccuName, tcConfig: TcConfig, tcGlobals, tcImports: TcI tcsCreatesGeneratedProvidedTypes = false tcsRootSigs = Zmap.empty qnameOrder tcsRootImpls = Zset.empty qnameOrder - tcsCcuSig = Construct.NewEmptyModuleOrNamespaceType Namespace + tcsCcuSig = Construct.NewEmptyModuleOrNamespaceType(Namespace true) tcsImplicitOpenDeclarations = openDecls0 } @@ -1211,7 +1212,7 @@ let CheckOneInput let typeCheckOne = if skipImplIfSigExists && hadSig then (EmptyTopAttrs, CreateEmptyDummyImplFile qualNameOfFile rootSigOpt.Value, Unchecked.defaultof<_>, tcImplEnv, false) - |> Cancellable.ret + |> cancellable.Return else CheckOneImplFile( tcGlobals, diff --git a/src/Compiler/Driver/ScriptClosure.fs b/src/Compiler/Driver/ScriptClosure.fs index 67adfb1e8de..868a9f80cae 100644 --- a/src/Compiler/Driver/ScriptClosure.fs +++ b/src/Compiler/Driver/ScriptClosure.fs @@ -98,7 +98,8 @@ module ScriptPreprocessClosure = let seen = Dictionary<_, bool>() member _.SetSeen check = - if not (seen.ContainsKey check) then seen.Add(check, true) + if not (seen.ContainsKey check) then + seen.Add(check, true) member _.HaveSeen check = seen.ContainsKey check diff --git a/src/Compiler/Driver/StaticLinking.fs b/src/Compiler/Driver/StaticLinking.fs index 6c23eb9b024..5ad9ff15f40 100644 --- a/src/Compiler/Driver/StaticLinking.fs +++ b/src/Compiler/Driver/StaticLinking.fs @@ -304,8 +304,10 @@ let FindDependentILModulesForStaticLinking (ctok, tcConfig: TcConfig, tcImports: let ilAssemRef = List.head remaining remaining <- List.tail remaining - if assumedIndependentSet.Contains ilAssemRef.Name - || (ilAssemRef.PublicKey = Some ecmaPublicKey) then + if + assumedIndependentSet.Contains ilAssemRef.Name + || (ilAssemRef.PublicKey = Some ecmaPublicKey) + then depModuleTable[ilAssemRef.Name] <- dummyEntry ilAssemRef.Name else if not (depModuleTable.ContainsKey ilAssemRef.Name) then match tcImports.TryFindDllInfo(ctok, rangeStartup, ilAssemRef.Name, lookupOnly = false) with @@ -502,10 +504,11 @@ let StaticLink (ctok, tcConfig: TcConfig, tcImports: TcImports, ilGlobals: ILGlo | Some provAssemStaticLinkInfo -> (importedBinary, provAssemStaticLinkInfo) ] #endif - if not tcConfig.standalone - && tcConfig.extraStaticLinkRoots.IsEmpty + if + not tcConfig.standalone + && tcConfig.extraStaticLinkRoots.IsEmpty #if !NO_TYPEPROVIDERS - && providerGeneratedAssemblies.IsEmpty + && providerGeneratedAssemblies.IsEmpty #endif then id diff --git a/src/Compiler/Driver/XmlDocFileWriter.fs b/src/Compiler/Driver/XmlDocFileWriter.fs index 97125744ace..fe6ac2a3fac 100644 --- a/src/Compiler/Driver/XmlDocFileWriter.fs +++ b/src/Compiler/Driver/XmlDocFileWriter.fs @@ -63,7 +63,8 @@ module XmlDocWriter = let ptext = defaultArg path "" - if mspec.IsModule then doModuleMemberSig ptext mspec + if mspec.IsModule then + doModuleMemberSig ptext mspec let vals = mtype.AllValsAndMembers @@ -116,7 +117,9 @@ module XmlDocWriter = let rec doModule (mspec: ModuleOrNamespace) = let mtype = mspec.ModuleOrNamespaceType - if mspec.IsModule then modulMember mspec + + if mspec.IsModule then + modulMember mspec let vals = mtype.AllValsAndMembers diff --git a/src/Compiler/Driver/fsc.fs b/src/Compiler/Driver/fsc.fs index c6ae4d83b67..84fd4742d6d 100644 --- a/src/Compiler/Driver/fsc.fs +++ b/src/Compiler/Driver/fsc.fs @@ -149,7 +149,8 @@ type ConsoleLoggerProvider() = /// Notify the exiter if any error has occurred let AbortOnError (diagnosticsLogger: DiagnosticsLogger, exiter: Exiter) = - if diagnosticsLogger.ErrorCount > 0 then exiter.Exit 1 + if diagnosticsLogger.ErrorCount > 0 then + exiter.Exit 1 let TypeCheck ( @@ -382,7 +383,8 @@ module InterfaceFileWriter = for impl in declaredImpls do writeToFile os impl - if tcConfig.printSignatureFile <> "" then os.Dispose() + if tcConfig.printSignatureFile <> "" then + os.Dispose() let extensionForFile (filePath: string) = if (List.exists (FileSystemUtils.checkSuffix filePath) FSharpMLCompatFileSuffixes) then @@ -489,11 +491,13 @@ let main1 // See Bug 735819 let lcidFromCodePage = - if (Console.OutputEncoding.CodePage <> 65001) - && (Console.OutputEncoding.CodePage - <> Thread.CurrentThread.CurrentUICulture.TextInfo.OEMCodePage) - && (Console.OutputEncoding.CodePage - <> Thread.CurrentThread.CurrentUICulture.TextInfo.ANSICodePage) then + if + (Console.OutputEncoding.CodePage <> 65001) + && (Console.OutputEncoding.CodePage + <> Thread.CurrentThread.CurrentUICulture.TextInfo.OEMCodePage) + && (Console.OutputEncoding.CodePage + <> Thread.CurrentThread.CurrentUICulture.TextInfo.ANSICodePage) + then Thread.CurrentThread.CurrentUICulture <- CultureInfo("en-US") Some 1033 else @@ -553,7 +557,8 @@ let main1 tcConfigB.conditionalDefines <- "COMPILED" :: tcConfigB.conditionalDefines // Display the banner text, if necessary - if not bannerAlreadyPrinted then DisplayBannerText tcConfigB + if not bannerAlreadyPrinted then + DisplayBannerText tcConfigB // Create tcGlobals and frameworkTcImports let outfile, pdbfile, assemblyName = @@ -618,15 +623,7 @@ let main1 (fun exiter -> diagnosticsLoggerProvider.CreateDelayAndForwardLogger(exiter) :> CapturingDiagnosticsLogger) let inputs = - ParseInputFiles( - tcConfig, - lexResourceManager, - sourceFiles, - diagnosticsLogger, - exiter, - createDiagnosticsLogger (*retryLocked*) , - false - ) + ParseInputFiles(tcConfig, lexResourceManager, sourceFiles, diagnosticsLogger, exiter, createDiagnosticsLogger, false) let inputs, _ = (Map.empty, inputs) @@ -641,7 +638,8 @@ let main1 printfn "%+A" input printf "\n" - if tcConfig.parseOnly then exiter.Exit 0 + if tcConfig.parseOnly then + exiter.Exit 0 if not tcConfig.continueAfterParseFailure then AbortOnError(diagnosticsLogger, exiter) @@ -667,7 +665,8 @@ let main1 if not tcConfig.continueAfterParseFailure then AbortOnError(diagnosticsLogger, exiter) - if tcConfig.importAllReferencesOnly then exiter.Exit 0 + if tcConfig.importAllReferencesOnly then + exiter.Exit 0 // Build the initial type checking environment ReportTime tcConfig "Typecheck" @@ -920,7 +919,8 @@ let main2 ilSourceDocs)) = - if tcConfig.typeCheckOnly then exiter.Exit 0 + if tcConfig.typeCheckOnly then + exiter.Exit 0 generatedCcu.Contents.SetAttribs(generatedCcu.Contents.Attribs @ topAttrs.assemblyAttrs) @@ -953,7 +953,7 @@ let main2 "AssemblyVersionAttribute" topAttrs.assemblyAttrs tcConfig.deterministic - with + with | Some v -> match tcConfig.version with | VersionNone -> Some v @@ -1359,9 +1359,11 @@ let main6 AbortOnError(diagnosticsLogger, exiter) // Don't copy referenced FSharp.core.dll if we are building FSharp.Core.dll - if (tcConfig.copyFSharpCore = CopyFSharpCoreFlag.Yes) - && not tcConfig.compilingFSharpCore - && not tcConfig.standalone then + if + (tcConfig.copyFSharpCore = CopyFSharpCoreFlag.Yes) + && not tcConfig.compilingFSharpCore + && not tcConfig.standalone + then CopyFSharpCore(outfile, tcConfig.referencedDLLs) ReportTime tcConfig "Exiting" diff --git a/src/Compiler/FSComp.txt b/src/Compiler/FSComp.txt index cbd9071612c..e058c9694c4 100644 --- a/src/Compiler/FSComp.txt +++ b/src/Compiler/FSComp.txt @@ -271,7 +271,6 @@ chkUnionCaseDefaultAugmentation,"default augmentation of the union case" 435,chkGetterSetterDoNotMatchAbstract,"The property '%s' of type '%s' has a getter and a setter that do not match. If one is abstract then the other must be as well." 436,chkPropertySameNameIndexer,"The property '%s' has the same name as another property in type '%s', but one takes indexer arguments and the other does not. You may be missing an indexer argument to one of your properties." 437,chkCantStoreByrefValue,"A type would store a byref typed value. This is not permitted by Common IL." -#See related 1205 chkDuplicateInherittedVirtualMethod 438,chkDuplicateMethod,"Duplicate method. The method '%s' has the same name and signature as another method in type '%s'." 438,chkDuplicateMethodWithSuffix,"Duplicate method. The method '%s' has the same name and signature as another method in type '%s' once tuples, functions, units of measure and/or provided types are erased." 439,chkDuplicateMethodCurried,"The method '%s' has curried arguments but has the same name as another method in type '%s'. Methods with curried arguments cannot be overloaded. Consider using a method taking tupled arguments." @@ -475,7 +474,6 @@ parsSyntaxModuleStructEndDeprecated,"The syntax 'module ... = struct .. end' is parsSyntaxModuleSigEndDeprecated,"The syntax 'module ... : sig .. end' is not used in F# code. Consider using 'module ... = begin .. end'" 627,tcStaticFieldUsedWhenInstanceFieldExpected,"A static field was used where an instance field is expected" 629,tcMethodNotAccessible,"Method '%s' is not accessible from this code location" -#630,tcTypeFunctionFieldsCannotBeMutated,"Fields which are type functions cannot be mutated" 632,tcImplicitMeasureFollowingSlash,"Implicit product of measures following /" 633,tcUnexpectedMeasureAnon,"Unexpected SynMeasure.Anon" 634,tcNonZeroConstantCannotHaveGenericUnit,"Non-zero constants cannot have generic units. For generic zero, write 0.0<_>." @@ -648,8 +646,6 @@ tcExpressionWithIfRequiresParenthesis,"This list or array expression includes an 799,tcInvalidAssignment,"Invalid assignment" 800,tcInvalidUseOfTypeName,"Invalid use of a type name" 801,tcTypeHasNoAccessibleConstructor,"This type has no accessible object constructors" -#802,tcInvalidUseOfTypeNameOrConstructor,"Invalid use of a type name and/or object constructor. If necessary use 'new' and apply the constructor to its arguments, e.g. 'new Type(args)'." -#803,tcInvalidUseOfTypeNameOrConstructorWithOverloads,"Invalid use of a type name and/or object constructor. If necessary use 'new' and apply the constructor to its arguments, e.g. 'new Type(args)'. The required signature is:\n\t%s." 804,tcInvalidUseOfInterfaceType,"Invalid use of an interface type" 805,tcInvalidUseOfDelegate,"Invalid use of a delegate constructor. Use the syntax 'new Type(args)' or just 'Type(args)'." 806,tcPropertyIsNotStatic,"Property '%s' is not static" @@ -766,7 +762,6 @@ tcTypeOrModule,"type or module" 919,tcExceptionAbbreviationsMustReferToValidExceptions,"Exception abbreviations must refer to existing exceptions or F# types deriving from System.Exception" 920,tcAbbreviationsFordotNetExceptionsMustHaveMatchingObjectConstructor,"Abbreviations for Common IL exception types must have a matching object constructor" 921,tcNotAnException,"Not an exception" -#922,tcUnexpectedConstraintsOrParametersOnModule,"Unexpected constraints or parameters on module specification" 924,tcInvalidModuleName,"Invalid module name" 925,tcInvalidTypeExtension,"Invalid type extension" 926,tcAttributesOfTypeSpecifyMultipleKindsForType,"The attributes of this type specify multiple kinds for the type" @@ -799,7 +794,6 @@ tcTypeAbbreviationHasTypeParametersMissingOnType,"This type abbreviation has one 949,tcInvalidDelegateSpecification,"Delegate specifications must be of the form 'typ -> typ'" 950,tcDelegatesCannotBeCurried,"Delegate specifications must not be curried types. Use 'typ * ... * typ -> typ' for multi-argument delegates, and 'typ -> (typ -> typ)' for delegates returning function values." 951,tcInvalidTypeForLiteralEnumeration,"Literal enumerations must have type int, uint, int16, uint16, int64, uint64, byte, sbyte or char" -#952,tcTypeAbbreviationMustBePublic,"Type abbreviations must be public. If you want to use a private type abbreviation you must use an explicit signature." 953,tcTypeDefinitionIsCyclic,"This type definition involves an immediate cyclic reference through an abbreviation" 954,tcTypeDefinitionIsCyclicThroughInheritance,"This type definition involves an immediate cyclic reference through a struct field or inheritance relation" tcReservedSyntaxForAugmentation,"The syntax 'type X with ...' is reserved for augmentations. Types whose representations are hidden but which have members are now declared in signatures using 'type X = ...'. You may also need to add the '[] attribute to the type definition in the signature" @@ -814,8 +808,6 @@ tcReservedSyntaxForAugmentation,"The syntax 'type X with ...' is reserved for au 965,tcModuleAbbreviationForNamespace,"The path '%s' is a namespace. A module abbreviation may not abbreviate a namespace." 966,tcTypeUsedInInvalidWay,"The type '%s' is used in an invalid way. A value prior to '%s' has an inferred type involving '%s', which is an invalid forward reference." 967,tcMemberUsedInInvalidWay,"The member '%s' is used in an invalid way. A use of '%s' has been inferred prior to the definition of '%s', which is an invalid forward reference." -#968,tcExplicitSignaturesInImplementationFileCannotBeUsed,"Explicit signatures within implementation files are not permitted" -#969,tcModulesCannotUseNamedModuleSignatures,"Modules cannot use named module signature definitions" 970,tcAttributeAutoOpenWasIgnored,"The attribute 'AutoOpen(\"%s\")' in the assembly '%s' did not refer to a valid module or namespace in that assembly and has been ignored" 971,ilUndefinedValue,"Undefined value '%s'" 972,ilLabelNotFound,"Label %s not found" @@ -893,6 +885,7 @@ optsHelp,"Display this usage message (Short form: -?)" optsVersion,"Display compiler version banner and exit" optsResponseFile,"Read response file for more options" optsCodepage,"Specify the codepage used to read source files" +optsClearResultsCache,"Clear the package manager results cache" optsUtf8output,"Output messages in UTF-8 encoding" optsFullpaths,"Output messages with fully qualified paths" optsLib,"Specify a directory for the include path which is used to resolve source files and assemblies (Short form: -I)" @@ -1030,7 +1023,7 @@ lexUnexpectedChar,"Unexpected character '%s'" 1153,lexInvalidFloat,"Invalid floating point number" 1154,lexOusideDecimal,"This number is outside the allowable range for decimal literals" 1155,lexOusideThirtyTwoBitFloat,"This number is outside the allowable range for 32-bit floats" -1156,lexInvalidNumericLiteral,"This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger)." +1156,lexInvalidNumericLiteral,"This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint)." 1157,lexInvalidByteLiteral,"This is not a valid byte literal" 1158,lexInvalidCharLiteral,"This is not a valid character literal" 1159,lexThisUnicodeOnlyInStringLiterals,"This Unicode encoding is only valid in string literals" @@ -1070,8 +1063,6 @@ lexHashBangMustBeFirstInFile,"#! may only appear as the first line at the start 1189,parsNonAdjacentTypars,"Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name." 1190,parsNonAdjacentTyargs,"Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name." parsNonAtomicType,"The use of the type syntax 'int C' and 'C ' is not permitted here. Consider adjusting this type to be written in the form 'C'" -# 1191,tastUndefinedTyconItemField,"The type %s did not contain the field '%s'" -# 1192,tastUndefinedTyconItemUnionCase,"The type %s did not contain the union case '%s'" 1193,tastUndefinedItemRefModuleNamespace,"The module/namespace '%s' from compilation unit '%s' did not contain the module/namespace '%s'" 1194,tastUndefinedItemRefVal,"The module/namespace '%s' from compilation unit '%s' did not contain the val '%s'" 1195,tastUndefinedItemRefModuleNamespaceType,"The module/namespace '%s' from compilation unit '%s' did not contain the namespace, module or type '%s'" @@ -1091,7 +1082,6 @@ mlCompatSigColonNoLongerSupported,"The use of 'module M: sig ... end ' was depre mlCompatSigEndNoLongerSupported,"The use of 'module M = sig ... end ' was deprecated in F# 2.0 and is no longer supported. Remove the 'sig' and 'end' and use indentation instead" mlCompatMultiPrefixTyparsNoLongerSupported,"The use of multiple parenthesized type parameters before a generic type name such as '(int, int) Map' was deprecated in F# 2.0 and is no longer supported" mlCompatStructEndNoLongerSupported,"The use of 'module M = struct ... end ' was deprecated in F# 2.0 and is no longer supported. Remove the 'struct' and 'end' and use indentation instead" -#1205,chkDuplicateInherittedVirtualMethod,"Duplicate virtual methods. There are multiple virtual methods named '%s' with the same signature in the parent (inherited) type. This may be a result of instantiating the parent type." 1206,ilFieldDoesNotHaveValidOffsetForStructureLayout,"The type '%s' has been marked as having an Explicit layout, but the field '%s' has not been marked with the 'FieldOffset' attribute" 1207,tcInterfacesShouldUseInheritNotInterface,"Interfaces inherited by other interfaces should be declared using 'inherit ...' instead of 'interface ...'" 1208,parsInvalidPrefixOperator,"Invalid prefix operator" @@ -1104,7 +1094,6 @@ lexIfOCaml,"IF-FSHARP/IF-CAML regions are no longer supported" 1211,ilFieldHasOffsetForSequentialLayout,"The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)" 1212,tcOptionalArgsMustComeAfterNonOptionalArgs,"Optional arguments must come at the end of the argument list, after any non-optional arguments" 1213,tcConditionalAttributeUsage,"Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes" -#1214,monoRegistryBugWorkaround,"Could not determine highest installed .NET framework version from Registry keys, using version 2.0" 1215,tcMemberOperatorDefinitionInExtrinsic,"Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead." 1216,ilwriteMDBFileNameCannotBeChangedWarning,"The name of the MDB file must be .mdb. The --pdb option will be ignored." 1217,ilwriteMDBMemberMissing,"MDB generation failed. Could not find compatible member %s" @@ -1216,7 +1205,6 @@ fscTooManyErrors,"Exiting - too many errors" 3049,etProviderHasDesignerAssemblyException,"The type provider designer assembly '%s' could not be loaded from folder '%s'. The exception reported was: %s - %s" invalidNamespaceForProvidedType,"invalid namespace for provided type" invalidFullNameForProvidedType,"invalid full name for provided type" -#3050,etGenerateAttributeRequiresInternal,"The 'Generate' attribute must be used with a type definition with 'internal' visibility" 3051,etProviderReturnedNull,"The type provider returned 'null', which is not a valid return value from '%s'" 3053,etTypeProviderConstructorException,"The type provider constructor has thrown an exception: %s" 3056,etNullProvidedExpression,"Type provider '%s' returned null from GetInvokerExpression." @@ -1557,6 +1545,7 @@ featureStructActivePattern,"struct representation for active patterns" featureRelaxWhitespace2,"whitespace relaxation v2" featureReallyLongList,"list literals of any size" featureErrorOnDeprecatedRequireQualifiedAccess,"give error on deprecated access of construct with RequireQualifiedAccess attribute" +featureLowercaseDUWhenRequireQualifiedAccess,"Allow lowercase DU when RequireQualifiedAccess attribute" 3353,fsiInvalidDirective,"Invalid directive '#%s %s'" 3354,tcNotAFunctionButIndexerNamedIndexingNotYetEnabled,"This value supports indexing, e.g. '%s.[index]'. The syntax '%s[index]' requires /langversion:preview. See https://aka.ms/fsharp-index-notation." 3354,tcNotAFunctionButIndexerIndexingNotYetEnabled,"This expression supports indexing, e.g. 'expr.[index]'. The syntax 'expr[index]' requires /langversion:preview. See https://aka.ms/fsharp-index-notation." @@ -1605,7 +1594,6 @@ forFormatInvalidForInterpolated4,"Interpolated strings used as type IFormattable 3388,tcSubsumptionImplicitConversionUsed,"This expression implicitly converts type '%s' to type '%s'. See https://aka.ms/fsharp-implicit-convs." 3389,tcBuiltInImplicitConversionUsed,"This expression uses a built-in implicit conversion to convert type '%s' to type '%s'. See https://aka.ms/fsharp-implicit-convs." 3391,tcImplicitConversionUsedForNonMethodArg,"This expression uses the implicit conversion '%s' to convert type '%s' to type '%s'. See https://aka.ms/fsharp-implicit-convs. This warning may be disabled using '#nowarn \"3391\"." -#3501 "This construct is not supported by your version of the F# compiler" CompilerMessage(ExperimentalAttributeMessages.NotSupportedYet, 3501, IsError=true) 3390,xmlDocBadlyFormed,"This XML comment is invalid: '%s'" 3390,xmlDocMissingParameterName,"This XML comment is invalid: missing 'name' attribute for parameter or parameter reference" 3390,xmlDocMissingCrossReference,"This XML comment is invalid: missing 'cref' attribute for cross-reference" @@ -1645,4 +1633,5 @@ reprStateMachineInvalidForm,"The state machine has an unexpected form" 3520,invalidXmlDocPosition,"XML comment is not placed on a valid language element." 3521,tcInvalidMemberDeclNameMissingOrHasParen,"Invalid member declaration. The name of the member is missing or has parentheses." 3522,tcAnonRecdDuplicateFieldId,"The field '%s' appears multiple times in this record expression." -3523,tcAnonRecdTypeDuplicateFieldId,"The field '%s' appears multiple times in this anonymous record type." \ No newline at end of file +3523,tcAnonRecdTypeDuplicateFieldId,"The field '%s' appears multiple times in this anonymous record type." +3524,parsExpectingExpressionInTuple,"Expecting expression" diff --git a/src/Compiler/FSStrings.resx b/src/Compiler/FSStrings.resx index bf1c66b0f29..51f172fbbea 100644 --- a/src/Compiler/FSStrings.resx +++ b/src/Compiler/FSStrings.resx @@ -1107,4 +1107,7 @@ internal error: {0} + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + \ No newline at end of file diff --git a/src/Compiler/FSharp.Compiler.Service.fsproj b/src/Compiler/FSharp.Compiler.Service.fsproj index 4e80e0956dc..5ee3256d378 100644 --- a/src/Compiler/FSharp.Compiler.Service.fsproj +++ b/src/Compiler/FSharp.Compiler.Service.fsproj @@ -77,8 +77,10 @@ + + @@ -334,6 +336,8 @@ + + @@ -461,9 +465,9 @@ + - @@ -481,7 +485,6 @@ - diff --git a/src/Compiler/Facilities/BuildGraph.fs b/src/Compiler/Facilities/BuildGraph.fs index 9facb562bcc..8227b96043f 100644 --- a/src/Compiler/Facilities/BuildGraph.fs +++ b/src/Compiler/Facilities/BuildGraph.fs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. module FSharp.Compiler.BuildGraph @@ -10,70 +10,95 @@ open System.Globalization open FSharp.Compiler.DiagnosticsLogger open Internal.Utilities.Library -[] +[] type NodeCode<'T> = Node of Async<'T> let wrapThreadStaticInfo computation = async { let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger let phase = DiagnosticsThreadStatics.BuildPhase + try - return! computation + return! computation finally DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger - DiagnosticsThreadStatics.BuildPhase <- phase + DiagnosticsThreadStatics.BuildPhase <- phase } type Async<'T> with static member AwaitNodeCode(node: NodeCode<'T>) = match node with - | Node(computation) -> wrapThreadStaticInfo computation + | Node (computation) -> wrapThreadStaticInfo computation [] type NodeCodeBuilder() = static let zero = Node(async.Zero()) - [] - member _.Zero () : NodeCode = zero + [] + member _.Zero() : NodeCode = zero - [] - member _.Delay (f: unit -> NodeCode<'T>) = - Node(async.Delay(fun () -> match f() with Node(p) -> p)) + [] + member _.Delay(f: unit -> NodeCode<'T>) = + Node( + async.Delay(fun () -> + match f () with + | Node (p) -> p) + ) - [] + [] member _.Return value = Node(async.Return(value)) - [] - member _.ReturnFrom (computation: NodeCode<_>) = computation + [] + member _.ReturnFrom(computation: NodeCode<_>) = computation - [] - member _.Bind (Node(p): NodeCode<'a>, binder: 'a -> NodeCode<'b>) : NodeCode<'b> = - Node(async.Bind(p, fun x -> match binder x with Node p -> p)) + [] + member _.Bind(Node (p): NodeCode<'a>, binder: 'a -> NodeCode<'b>) : NodeCode<'b> = + Node( + async.Bind( + p, + fun x -> + match binder x with + | Node p -> p + ) + ) - [] - member _.TryWith(Node(p): NodeCode<'T>, binder: exn -> NodeCode<'T>) : NodeCode<'T> = - Node(async.TryWith(p, fun ex -> match binder ex with Node p -> p)) + [] + member _.TryWith(Node (p): NodeCode<'T>, binder: exn -> NodeCode<'T>) : NodeCode<'T> = + Node( + async.TryWith( + p, + fun ex -> + match binder ex with + | Node p -> p + ) + ) - [] - member _.TryFinally(Node(p): NodeCode<'T>, binder: unit -> unit) : NodeCode<'T> = - Node(async.TryFinally(p, binder)) + [] + member _.TryFinally(Node (p): NodeCode<'T>, binder: unit -> unit) : NodeCode<'T> = Node(async.TryFinally(p, binder)) - [] + [] member _.For(xs: 'T seq, binder: 'T -> NodeCode) : NodeCode = - Node(async.For(xs, fun x -> match binder x with Node p -> p)) + Node( + async.For( + xs, + fun x -> + match binder x with + | Node p -> p + ) + ) - [] - member _.Combine(Node(p1): NodeCode, Node(p2): NodeCode<'T>) : NodeCode<'T> = - Node(async.Combine(p1, p2)) + [] + member _.Combine(Node (p1): NodeCode, Node (p2): NodeCode<'T>) : NodeCode<'T> = Node(async.Combine(p1, p2)) - [] + [] member _.Using(value: CompilationGlobalsScope, binder: CompilationGlobalsScope -> NodeCode<'U>) = Node( async { DiagnosticsThreadStatics.DiagnosticsLogger <- value.DiagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- value.BuildPhase + try return! binder value |> Async.AwaitNodeCode finally @@ -83,15 +108,15 @@ type NodeCodeBuilder() = let node = NodeCodeBuilder() -[] +[] type NodeCode private () = - static let cancellationToken = - Node(wrapThreadStaticInfo Async.CancellationToken) + static let cancellationToken = Node(wrapThreadStaticInfo Async.CancellationToken) - static member RunImmediate (computation: NodeCode<'T>, ct: CancellationToken) = + static member RunImmediate(computation: NodeCode<'T>, ct: CancellationToken) = let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger let phase = DiagnosticsThreadStatics.BuildPhase + try try let work = @@ -100,20 +125,21 @@ type NodeCode private () = DiagnosticsThreadStatics.BuildPhase <- phase return! computation |> Async.AwaitNodeCode } - Async.StartImmediateAsTask(work, cancellationToken=ct).Result + + Async.StartImmediateAsTask(work, cancellationToken = ct).Result finally DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- phase - with - | :? AggregateException as ex when ex.InnerExceptions.Count = 1 -> - raise(ex.InnerExceptions[0]) + with :? AggregateException as ex when ex.InnerExceptions.Count = 1 -> + raise (ex.InnerExceptions[0]) - static member RunImmediateWithoutCancellation (computation: NodeCode<'T>) = + static member RunImmediateWithoutCancellation(computation: NodeCode<'T>) = NodeCode.RunImmediate(computation, CancellationToken.None) - static member StartAsTask_ForTesting (computation: NodeCode<'T>, ?ct: CancellationToken) = + static member StartAsTask_ForTesting(computation: NodeCode<'T>, ?ct: CancellationToken) = let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger let phase = DiagnosticsThreadStatics.BuildPhase + try let work = async { @@ -121,24 +147,24 @@ type NodeCode private () = DiagnosticsThreadStatics.BuildPhase <- phase return! computation |> Async.AwaitNodeCode } - Async.StartAsTask(work, cancellationToken=defaultArg ct CancellationToken.None) + + Async.StartAsTask(work, cancellationToken = defaultArg ct CancellationToken.None) finally DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- phase static member CancellationToken = cancellationToken - static member FromCancellable(computation: Cancellable<'T>) = + static member FromCancellable(computation: Cancellable<'T>) = Node(wrapThreadStaticInfo (Cancellable.toAsync computation)) - static member AwaitAsync(computation: Async<'T>) = - Node(wrapThreadStaticInfo computation) + static member AwaitAsync(computation: Async<'T>) = Node(wrapThreadStaticInfo computation) static member AwaitTask(task: Task<'T>) = - Node(wrapThreadStaticInfo(Async.AwaitTask task)) + Node(wrapThreadStaticInfo (Async.AwaitTask task)) static member AwaitTask(task: Task) = - Node(wrapThreadStaticInfo(Async.AwaitTask task)) + Node(wrapThreadStaticInfo (Async.AwaitTask task)) static member AwaitWaitHandle_ForTesting(waitHandle: WaitHandle) = Node(wrapThreadStaticInfo (Async.AwaitWaitHandle(waitHandle))) @@ -149,14 +175,15 @@ type NodeCode private () = static member Sequential(computations: NodeCode<'T> seq) = node { let results = ResizeArray() + for computation in computations do let! res = computation results.Add(res) + return results.ToArray() } -type private AgentMessage<'T> = - | GetValue of AsyncReplyChannel> * callerCancellationToken: CancellationToken +type private AgentMessage<'T> = GetValue of AsyncReplyChannel> * callerCancellationToken: CancellationToken type private Agent<'T> = MailboxProcessor> * CancellationTokenSource @@ -169,13 +196,13 @@ type private GraphNodeAction<'T> = [] module GraphNode = - // We need to store the culture for the VS thread that is executing now, + // We need to store the culture for the VS thread that is executing now, // so that when the agent in the async lazy object picks up thread from the thread pool we can set the culture let mutable culture = CultureInfo(CultureInfo.CurrentUICulture.Name) - let SetPreferredUILang (preferredUiLang: string option) = + let SetPreferredUILang (preferredUiLang: string option) = match preferredUiLang with - | Some s -> + | Some s -> culture <- CultureInfo s #if FX_RESHAPED_GLOBALIZATION CultureInfo.CurrentUICulture <- culture @@ -185,7 +212,7 @@ module GraphNode = | None -> () [] -type GraphNode<'T> (retryCompute: bool, computation: NodeCode<'T>) = +type GraphNode<'T>(retryCompute: bool, computation: NodeCode<'T>) = let gate = obj () let mutable computation = computation @@ -194,44 +221,45 @@ type GraphNode<'T> (retryCompute: bool, computation: NodeCode<'T>) = let mutable cachedResult: Task<'T> = Unchecked.defaultof<_> let mutable cachedResultNode: NodeCode<'T> = Unchecked.defaultof<_> - let isCachedResultNodeNotNull() = + let isCachedResultNodeNotNull () = not (obj.ReferenceEquals(cachedResultNode, null)) - let isCachedResultNotNull() = + let isCachedResultNotNull () = not (obj.ReferenceEquals(cachedResult, null)) // retryCompute indicates that we abandon computations when the originator is - // cancelled. + // cancelled. // - // If retryCompute is 'true', the computation is run directly in the originating requestor's + // If retryCompute is 'true', the computation is run directly in the originating requestor's // thread. If cancelled, other awaiting computations must restart the computation from scratch. // // If retryCompute is 'false', a MailboxProcessor is used to allow the cancelled originator // to detach from the computation, while other awaiting computations continue to wait on the result. // - // Currently, 'retryCompute' = true for all graph nodes. However, the code for we include the + // Currently, 'retryCompute' = true for all graph nodes. However, the code for we include the // code to allow 'retryCompute' = false in case it's needed in the future, and ensure it is under independent // unit test. let loop (agent: MailboxProcessor>) = async { assert (not retryCompute) + try while true do match! agent.Receive() with | GetValue (replyChannel, callerCancellationToken) -> Thread.CurrentThread.CurrentUICulture <- GraphNode.culture + try - use _reg = + use _reg = // When a cancellation has occured, notify the reply channel to let the requester stop waiting for a response. - callerCancellationToken.Register (fun () -> + callerCancellationToken.Register(fun () -> let ex = OperationCanceledException() :> exn - replyChannel.Reply (Result.Error ex) - ) + replyChannel.Reply(Result.Error ex)) - callerCancellationToken.ThrowIfCancellationRequested () + callerCancellationToken.ThrowIfCancellationRequested() - if isCachedResultNotNull() then + if isCachedResultNotNull () then replyChannel.Reply(Ok cachedResult.Result) else // This computation can only be canceled if the requestCount reaches zero. @@ -239,20 +267,19 @@ type GraphNode<'T> (retryCompute: bool, computation: NodeCode<'T>) = cachedResult <- Task.FromResult(result) cachedResultNode <- node.Return result computation <- Unchecked.defaultof<_> + if not callerCancellationToken.IsCancellationRequested then replyChannel.Reply(Ok result) - with - | ex -> + with ex -> if not callerCancellationToken.IsCancellationRequested then replyChannel.Reply(Result.Error ex) - with - | _ -> + with _ -> () } let mutable agent: Agent<'T> = Unchecked.defaultof<_> - let semaphore: SemaphoreSlim = + let semaphore: SemaphoreSlim = if retryCompute then new SemaphoreSlim(1, 1) else @@ -260,20 +287,22 @@ type GraphNode<'T> (retryCompute: bool, computation: NodeCode<'T>) = member _.GetOrComputeValue() = // fast path - if isCachedResultNodeNotNull() then + if isCachedResultNodeNotNull () then cachedResultNode else node { - if isCachedResultNodeNotNull() then + if isCachedResultNodeNotNull () then return! cachedResult |> NodeCode.AwaitTask else let action = - lock gate <| fun () -> + lock gate + <| fun () -> // We try to get the cached result after the lock so we don't spin up a new mailbox processor. - if isCachedResultNodeNotNull() then + if isCachedResultNodeNotNull () then GraphNodeAction<'T>.CachedValue cachedResult.Result else requestCount <- requestCount + 1 + if retryCompute then GraphNodeAction<'T>.GetValue else @@ -290,35 +319,39 @@ type GraphNode<'T> (retryCompute: bool, computation: NodeCode<'T>) = agent <- Unchecked.defaultof<_> PreserveStackTrace exn raise exn - | _ -> - GraphNodeAction<'T>.GetValueByAgent + | _ -> GraphNodeAction<'T>.GetValueByAgent match action with | GraphNodeAction.CachedValue result -> return result | GraphNodeAction.GetValue -> try let! ct = NodeCode.CancellationToken - + // We must set 'taken' before any implicit cancellation checks // occur, making sure we are under the protection of the 'try'. // For example, NodeCode's 'try/finally' (TryFinally) uses async.TryFinally which does // implicit cancellation checks even before the try is entered, as do the // de-sugaring of 'do!' and other CodeCode constructs. let mutable taken = false + try - do! - semaphore.WaitAsync(ct) - .ContinueWith( - (fun _ -> taken <- true), - (TaskContinuationOptions.NotOnCanceled ||| TaskContinuationOptions.NotOnFaulted ||| TaskContinuationOptions.ExecuteSynchronously) - ) - |> NodeCode.AwaitTask - - if isCachedResultNotNull() then + do! + semaphore + .WaitAsync(ct) + .ContinueWith( + (fun _ -> taken <- true), + (TaskContinuationOptions.NotOnCanceled + ||| TaskContinuationOptions.NotOnFaulted + ||| TaskContinuationOptions.ExecuteSynchronously) + ) + |> NodeCode.AwaitTask + + if isCachedResultNotNull () then return cachedResult.Result else let tcs = TaskCompletionSource<'T>() - let (Node(p)) = computation + let (Node (p)) = computation + Async.StartWithContinuations( async { Thread.CurrentThread.CurrentUICulture <- GraphNode.culture @@ -328,51 +361,56 @@ type GraphNode<'T> (retryCompute: bool, computation: NodeCode<'T>) = cachedResult <- Task.FromResult(res) cachedResultNode <- node.Return res computation <- Unchecked.defaultof<_> - tcs.SetResult(res) - ), - (fun ex -> - tcs.SetException(ex) - ), - (fun _ -> - tcs.SetCanceled() - ), + tcs.SetResult(res)), + (fun ex -> tcs.SetException(ex)), + (fun _ -> tcs.SetCanceled()), ct ) + return! tcs.Task |> NodeCode.AwaitTask finally - if taken then - semaphore.Release() |> ignore + if taken then semaphore.Release() |> ignore finally - lock gate <| fun () -> - requestCount <- requestCount - 1 + lock gate <| fun () -> requestCount <- requestCount - 1 - | GraphNodeAction.GetValueByAgent -> + | GraphNodeAction.GetValueByAgent -> assert (not retryCompute) let mbp, cts = agent + try let! ct = NodeCode.CancellationToken - let! res = mbp.PostAndAsyncReply(fun replyChannel -> GetValue(replyChannel, ct)) |> NodeCode.AwaitAsync + + let! res = + mbp.PostAndAsyncReply(fun replyChannel -> GetValue(replyChannel, ct)) + |> NodeCode.AwaitAsync + match res with | Ok result -> return result | Result.Error ex -> return raise ex finally - lock gate <| fun () -> + lock gate + <| fun () -> requestCount <- requestCount - 1 + if requestCount = 0 then - cts.Cancel() // cancel computation when all requests are cancelled - try (mbp :> IDisposable).Dispose () with | _ -> () - cts.Dispose() - agent <- Unchecked.defaultof<_> + cts.Cancel() // cancel computation when all requests are cancelled + + try + (mbp :> IDisposable).Dispose() + with _ -> + () + + cts.Dispose() + agent <- Unchecked.defaultof<_> } - member _.TryPeekValue() = - match box cachedResult with - | null -> ValueNone - | _ -> ValueSome cachedResult.Result + member _.TryPeekValue() = + match box cachedResult with + | null -> ValueNone + | _ -> ValueSome cachedResult.Result - member _.HasValue = isCachedResultNotNull() + member _.HasValue = isCachedResultNotNull () - member _.IsComputing = requestCount > 0 + member _.IsComputing = requestCount > 0 - new(computation) = - GraphNode(retryCompute=true, computation=computation) \ No newline at end of file + new(computation) = GraphNode(retryCompute = true, computation = computation) diff --git a/src/Compiler/Facilities/BuildGraph.fsi b/src/Compiler/Facilities/BuildGraph.fsi index ef0319fabec..798653f5f4b 100644 --- a/src/Compiler/Facilities/BuildGraph.fsi +++ b/src/Compiler/Facilities/BuildGraph.fsi @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. module internal FSharp.Compiler.BuildGraph diff --git a/src/Compiler/Facilities/CompilerLocation.fs b/src/Compiler/Facilities/CompilerLocation.fs index 3e22c1aab0a..993443e57d5 100644 --- a/src/Compiler/Facilities/CompilerLocation.fs +++ b/src/Compiler/Facilities/CompilerLocation.fs @@ -17,22 +17,26 @@ open Microsoft.Win32 module internal FSharpEnvironment = - type private TypeInThisAssembly = class end + type private TypeInThisAssembly = + class + end /// The F# version reported in the banner - let FSharpBannerVersion = UtilsStrings.SR.fSharpBannerVersion(FSharp.BuildProperties.fsProductVersion, FSharp.BuildProperties.fsLanguageVersion) + let FSharpBannerVersion = + UtilsStrings.SR.fSharpBannerVersion (FSharp.BuildProperties.fsProductVersion, FSharp.BuildProperties.fsLanguageVersion) - let FSharpProductName = UtilsStrings.SR.buildProductName(FSharpBannerVersion) + let FSharpProductName = UtilsStrings.SR.buildProductName (FSharpBannerVersion) - let versionOf<'t> = - typeof<'t>.Assembly.GetName().Version.ToString() + let versionOf<'t> = typeof<'t>.Assembly.GetName().Version.ToString() let FSharpCoreLibRunningVersion = - try match versionOf with + try + match versionOf with | null -> None | "" -> None - | s -> Some(s) - with _ -> None + | s -> Some(s) + with _ -> + None // The F# binary format revision number. The first three digits of this form the significant part of the // format revision number for F# binary signature and optimization metadata. The last digit is not significant. @@ -40,15 +44,15 @@ module internal FSharpEnvironment = // WARNING: Do not change this revision number unless you absolutely know what you're doing. let FSharpBinaryMetadataFormatRevision = "2.0.0.0" - let isRunningOnCoreClr = typeof.Assembly.FullName.StartsWith("System.Private.CoreLib", StringComparison.InvariantCultureIgnoreCase) - + let isRunningOnCoreClr = + typeof.Assembly.FullName.StartsWith ("System.Private.CoreLib", StringComparison.InvariantCultureIgnoreCase) #if !FX_NO_WIN_REGISTRY [] - extern uint32 RegOpenKeyExW(UIntPtr _hKey, string _lpSubKey, uint32 _ulOptions, int _samDesired, UIntPtr & _phkResult); + extern uint32 RegOpenKeyExW(UIntPtr _hKey, string _lpSubKey, uint32 _ulOptions, int _samDesired, UIntPtr& _phkResult) [] - extern uint32 RegQueryValueExW(UIntPtr _hKey, string _lpValueName, uint32 _lpReserved, uint32 & _lpType, IntPtr _lpData, int & _lpchData); + extern uint32 RegQueryValueExW(UIntPtr _hKey, string _lpValueName, uint32 _lpReserved, uint32& _lpType, IntPtr _lpData, int& _lpchData) [] extern uint32 RegCloseKey(UIntPtr _hKey) @@ -56,12 +60,11 @@ module internal FSharpEnvironment = module Option = /// Convert string into Option string where null and String.Empty result in None let ofString s = - if String.IsNullOrEmpty(s) then None - else Some(s) + if String.IsNullOrEmpty(s) then None else Some(s) // MaxPath accounts for the null-terminating character, for example, the maximum path on the D drive is "D:\<256 chars>\0". // See: ndp\clr\src\BCL\System\IO\Path.cs - let maxPath = 260; + let maxPath = 260 let maxDataLength = (System.Text.UTF32Encoding()).GetMaxByteCount(maxPath) #if !FX_NO_WIN_REGISTRY @@ -71,71 +74,80 @@ module internal FSharpEnvironment = let KEY_QUERY_VALUE = 0x1 let REG_SZ = 1u - let GetDefaultRegistryStringValueViaDotNet(subKey: string) = - Option.ofString - (try - downcast Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\"+subKey,null,null) - with e-> + let GetDefaultRegistryStringValueViaDotNet (subKey: string) = + Option.ofString ( + try + downcast Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\" + subKey, null, null) + with e -> #if DEBUG Debug.Assert(false, sprintf "Failed in GetDefaultRegistryStringValueViaDotNet: %s" (e.ToString())) #endif - null) + null + ) - let Get32BitRegistryStringValueViaPInvoke(subKey:string) = - Option.ofString - (try + let Get32BitRegistryStringValueViaPInvoke (subKey: string) = + Option.ofString ( + try // 64 bit flag is not available <= Win2k let options = let hasWow6432Node = use x = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node") x <> null + try match hasWow6432Node with - | true -> KEY_WOW64_32KEY + | true -> KEY_WOW64_32KEY | false -> KEY_WOW64_DEFAULT - with - | _ -> KEY_WOW64_DEFAULT + with _ -> + KEY_WOW64_DEFAULT - let mutable hkey = UIntPtr.Zero; - let pathResult = Marshal.AllocCoTaskMem(maxDataLength); + let mutable hkey = UIntPtr.Zero + let pathResult = Marshal.AllocCoTaskMem(maxDataLength) try - let res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,subKey, 0u, KEY_QUERY_VALUE ||| options, & hkey) + let res = + RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey, 0u, KEY_QUERY_VALUE ||| options, &hkey) + if res = 0u then - let mutable uType = REG_SZ; - let mutable cbData = maxDataLength; + let mutable uType = REG_SZ + let mutable cbData = maxDataLength - let res = RegQueryValueExW(hkey, null, 0u, &uType, pathResult, &cbData); + let res = RegQueryValueExW(hkey, null, 0u, &uType, pathResult, &cbData) if (res = 0u && cbData > 0 && cbData <= maxDataLength) then - Marshal.PtrToStringUni(pathResult, (cbData - 2)/2); + Marshal.PtrToStringUni(pathResult, (cbData - 2) / 2) else null else null finally - if hkey <> UIntPtr.Zero then - RegCloseKey(hkey) |> ignore + if hkey <> UIntPtr.Zero then RegCloseKey(hkey) |> ignore if pathResult <> IntPtr.Zero then Marshal.FreeCoTaskMem(pathResult) - with e-> + with e -> #if DEBUG Debug.Assert(false, sprintf "Failed in Get32BitRegistryStringValueViaPInvoke: %s" (e.ToString())) #endif - null) + null + ) let is32Bit = IntPtr.Size = 4 - let runningOnMono = try System.Type.GetType("Mono.Runtime") <> null with e-> false + let runningOnMono = + try + System.Type.GetType("Mono.Runtime") <> null + with e -> + false - let tryRegKey(subKey:string) = + let tryRegKey (subKey: string) = //if we are running on mono simply return None // GetDefaultRegistryStringValueViaDotNet will result in an access denied by default, // and Get32BitRegistryStringValueViaPInvoke will fail due to Advapi32.dll not existing - if runningOnMono then None else - if is32Bit then + if runningOnMono then + None + else if is32Bit then let s = GetDefaultRegistryStringValueViaDotNet(subKey) // If we got here AND we're on a 32-bit OS then we can validate that Get32BitRegistryStringValueViaPInvoke(...) works // by comparing against the result from GetDefaultRegistryStringValueViaDotNet(...) @@ -148,27 +160,31 @@ module internal FSharpEnvironment = Get32BitRegistryStringValueViaPInvoke(subKey) #endif - let internal tryCurrentDomain() = - let pathFromCurrentDomain = - AppDomain.CurrentDomain.BaseDirectory - if not(String.IsNullOrEmpty(pathFromCurrentDomain)) then + let internal tryCurrentDomain () = + let pathFromCurrentDomain = AppDomain.CurrentDomain.BaseDirectory + + if not (String.IsNullOrEmpty(pathFromCurrentDomain)) then Some pathFromCurrentDomain else None #if FX_NO_SYSTEM_CONFIGURATION - let internal tryAppConfig (_appConfigKey:string) = None + let internal tryAppConfig (_appConfigKey: string) = None #else - let internal tryAppConfig (_appConfigKey:string) = - let locationFromAppConfig = System.Configuration.ConfigurationSettings.AppSettings.[_appConfigKey] + let internal tryAppConfig (_appConfigKey: string) = + let locationFromAppConfig = + System.Configuration.ConfigurationSettings.AppSettings.[_appConfigKey] #if DEBUG Debug.Print(sprintf "Considering _appConfigKey %s which has value '%s'" _appConfigKey locationFromAppConfig) #endif if String.IsNullOrEmpty(locationFromAppConfig) then None else - let exeAssemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) - let locationFromAppConfig = locationFromAppConfig.Replace("{exepath}", exeAssemblyFolder) + let exeAssemblyFolder = + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + + let locationFromAppConfig = + locationFromAppConfig.Replace("{exepath}", exeAssemblyFolder) #if DEBUG Debug.Print(sprintf "Using path %s" locationFromAppConfig) #endif @@ -182,40 +198,49 @@ module internal FSharpEnvironment = // - default F# binaries directory in service.fs (REVIEW: check this) // - default location of fsi.exe in FSharp.VS.FSI.dll (REVIEW: check this) // - default F# binaries directory in (project system) Project.fs - let BinFolderOfDefaultFSharpCompiler(probePoint:string option) = + let BinFolderOfDefaultFSharpCompiler (probePoint: string option) = // Check for an app.config setting to redirect the default compiler location // Like fsharp-compiler-location try // We let you set FSHARP_COMPILER_BIN. I've rarely seen this used and its not documented in the install instructions. match Environment.GetEnvironmentVariable("FSHARP_COMPILER_BIN") with | result when not (String.IsNullOrWhiteSpace result) -> Some result - |_-> - // FSharp.Compiler support setting an appKey for compiler location. I've never seen this used. - let result = tryAppConfig "fsharp-compiler-location" - match result with - | Some _ -> result - | None -> - - let safeExists f = (try File.Exists(f) with _ -> false) - - // Look in the probePoint if given, e.g. look for a compiler alongside of FSharp.Build.dll - match probePoint with - | Some p when safeExists (Path.Combine(p,"FSharp.Core.dll")) -> Some p | _ -> - let fallback() = - let d = Assembly.GetExecutingAssembly() - Some (Path.GetDirectoryName d.Location) - match tryCurrentDomain() with - | None -> fallback() - | Some path -> Some path - with e -> None + // FSharp.Compiler support setting an appKey for compiler location. I've never seen this used. + let result = tryAppConfig "fsharp-compiler-location" + + match result with + | Some _ -> result + | None -> + + let safeExists f = + (try + File.Exists(f) + with _ -> + false) + + // Look in the probePoint if given, e.g. look for a compiler alongside of FSharp.Build.dll + match probePoint with + | Some p when safeExists (Path.Combine(p, "FSharp.Core.dll")) -> Some p + | _ -> + let fallback () = + let d = Assembly.GetExecutingAssembly() + Some(Path.GetDirectoryName d.Location) + + match tryCurrentDomain () with + | None -> fallback () + | Some path -> Some path + with e -> + None #if !FX_NO_WIN_REGISTRY // Apply the given function to the registry entry corresponding to the subKey. // The reg key is disposed at the end of the scope. let useKey subKey f = let key = Registry.LocalMachine.OpenSubKey subKey - try f key + + try + f key finally match key with | null -> () @@ -223,25 +248,26 @@ module internal FSharpEnvironment = // Check if the framework version 4.5 or above is installed at the given key entry let IsNetFx45OrAboveInstalledAt subKey = - try - useKey subKey (fun regKey -> - match regKey with - | null -> false - | _ -> regKey.GetValue("Release", 0) :?> int |> (fun s -> s >= 0x50000)) // 0x50000 implies 4.5.0 - with _ -> false + try + useKey subKey (fun regKey -> + match regKey with + | null -> false + | _ -> regKey.GetValue("Release", 0) :?> int |> (fun s -> s >= 0x50000)) // 0x50000 implies 4.5.0 + with _ -> + false // Check if the framework version 4.5 or above is installed let IsNetFx45OrAboveInstalled = - IsNetFx45OrAboveInstalledAt @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client" || - IsNetFx45OrAboveInstalledAt @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" || - runningOnMono + IsNetFx45OrAboveInstalledAt @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client" + || IsNetFx45OrAboveInstalledAt @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" + || runningOnMono // Check if the running framework version is 4.5 or above. // Use the presence of v4.5.x in the registry to distinguish between 4.0 and 4.5 let IsRunningOnNetFx45OrAbove = - let version = new Version(versionOf) - let major = version.Major - major > 4 || (major = 4 && IsNetFx45OrAboveInstalled) + let version = new Version(versionOf) + let major = version.Major + major > 4 || (major = 4 && IsNetFx45OrAboveInstalled) #endif @@ -252,33 +278,55 @@ module internal FSharpEnvironment = // Represents the F#-compiler <-> type provider protocol. // When the API or protocol updates, add a new version moniker to the front of the list here. - let toolingCompatibleTypeProviderProtocolMonikers() = - [ "fsharp41" ] + let toolingCompatibleTypeProviderProtocolMonikers () = [ "fsharp41" ] // Detect the host tooling context let toolingCompatibleVersions = if typeof.Assembly.GetName().Name = "mscorlib" then - [| "net48"; "net472"; "net471";"net47";"net462";"net461"; "net452"; "net451"; "net45"; "netstandard2.0" |] + [| + "net48" + "net472" + "net471" + "net47" + "net462" + "net461" + "net452" + "net451" + "net45" + "netstandard2.0" + |] elif typeof.Assembly.GetName().Name = "System.Private.CoreLib" then - [| "net6.0"; "net5.0"; "netcoreapp3.1"; "netcoreapp3.0"; "netstandard2.1"; "netcoreapp2.2"; "netcoreapp2.1"; "netcoreapp2.0"; "netstandard2.0" |] + [| + "net6.0" + "net5.0" + "netcoreapp3.1" + "netcoreapp3.0" + "netstandard2.1" + "netcoreapp2.2" + "netcoreapp2.1" + "netcoreapp2.0" + "netstandard2.0" + |] else Debug.Assert(false, "Couldn't determine runtime tooling context, assuming it supports at least .NET Standard 2.0") [| "netstandard2.0" |] let toolPaths = [| "tools"; "typeproviders" |] - let toolingCompatiblePaths() = [ - for toolPath in toolPaths do - for protocol in toolingCompatibleTypeProviderProtocolMonikers() do - for netRuntime in toolingCompatibleVersions do - yield Path.Combine(toolPath, protocol, netRuntime) + let toolingCompatiblePaths () = + [ + for toolPath in toolPaths do + for protocol in toolingCompatibleTypeProviderProtocolMonikers () do + for netRuntime in toolingCompatibleVersions do + yield Path.Combine(toolPath, protocol, netRuntime) ] let searchToolPath compilerToolPath = seq { yield compilerToolPath - for toolPath in toolingCompatiblePaths() do - yield Path.Combine (compilerToolPath, toolPath) + + for toolPath in toolingCompatiblePaths () do + yield Path.Combine(compilerToolPath, toolPath) } let rec searchToolPaths path compilerToolPaths = @@ -291,12 +339,18 @@ module internal FSharpEnvironment = | Some path -> yield! searchToolPath path } - let getTypeProviderAssembly (runTimeAssemblyFileName: string, designTimeAssemblyName: string, compilerToolPaths: string list, raiseError) = + let getTypeProviderAssembly + ( + 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 = try - Some (Assembly.UnsafeLoadFrom designTimeAssemblyPath) + Some(Assembly.UnsafeLoadFrom designTimeAssemblyPath) with e -> raiseError (Some designTimeAssemblyPath) e @@ -304,27 +358,28 @@ module internal FSharpEnvironment = seq { match path with | None -> () - | Some (p:string) -> + | Some (p: string) -> match Path.GetDirectoryName(p) with | s when s = "" || s = null || Path.GetFileName(p) = "packages" || s = p -> () | parentDir -> yield! searchParentDirChain (Some parentDir) assemblyName for p in searchToolPaths path compilerToolPaths do - let fileName = Path.Combine (p, assemblyName) + let fileName = Path.Combine(p, assemblyName) if File.Exists fileName then yield fileName } let loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeAssemblyName = let runTimeAssemblyPath = Path.GetDirectoryName runTimeAssemblyFileName let paths = searchParentDirChain (Some runTimeAssemblyPath) designTimeAssemblyName + paths |> Seq.tryHead |> function - | Some res -> loadFromLocation res - | None -> + | Some res -> loadFromLocation res + | None -> // The search failed, just load from the first location and report an error let runTimeAssemblyPath = Path.GetDirectoryName runTimeAssemblyFileName - loadFromLocation (Path.Combine (runTimeAssemblyPath, designTimeAssemblyName)) + loadFromLocation (Path.Combine(runTimeAssemblyPath, designTimeAssemblyName)) if designTimeAssemblyName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) then loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeAssemblyName @@ -334,7 +389,8 @@ 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.Name.Equals(name.FullName, StringComparison.OrdinalIgnoreCase) then let designTimeFileName = designTimeAssemblyName + ".dll" loadFromParentDirRelativeToRuntimeAssemblyLocation designTimeFileName @@ -343,12 +399,11 @@ module internal FSharpEnvironment = // never in the GAC these days and "x.DesignTIme, Version= ..." specifications are never used. try let name = AssemblyName designTimeAssemblyName - Some (Assembly.Load name) + Some(Assembly.Load name) with e -> raiseError None e - let getCompilerToolsDesignTimeAssemblyPaths compilerToolPaths = - searchToolPaths None compilerToolPaths + let getCompilerToolsDesignTimeAssemblyPaths compilerToolPaths = searchToolPaths None compilerToolPaths let getFSharpCoreLibraryName = "FSharp.Core" let fsiLibraryName = "FSharp.Compiler.Interactive.Settings" @@ -356,29 +411,36 @@ module internal FSharpEnvironment = let getFSharpCompilerLocationWithDefaultFromType (defaultLocation: Type) = let location = try - Some (Path.GetDirectoryName(defaultLocation.Assembly.Location)) - with | _ -> + Some(Path.GetDirectoryName(defaultLocation.Assembly.Location)) + with _ -> None - match BinFolderOfDefaultFSharpCompiler (location) with + + match BinFolderOfDefaultFSharpCompiler(location) with | Some path -> path | None -> let path = location |> Option.defaultValue "" - #if DEBUG - Debug.Print(sprintf """FSharpEnvironment.BinFolderOfDefaultFSharpCompiler (Some '%s') returned None Location +#if DEBUG + Debug.Print( + sprintf + """FSharpEnvironment.BinFolderOfDefaultFSharpCompiler (Some '%s') returned None Location customized incorrectly: algorithm here: https://github.com/dotnet/fsharp/blob/03f3f1c35f82af26593d025dabca57a6ef3ea9a1/src/utils/CompilerLocationUtils.fs#L171""" - path) - #endif + path + ) +#endif // Use the location of this dll path // Fallback to ambient FSharp.CompilerService.dll - let getFSharpCompilerLocation() = Path.Combine(getFSharpCompilerLocationWithDefaultFromType(typeof)); + let getFSharpCompilerLocation () = + Path.Combine(getFSharpCompilerLocationWithDefaultFromType (typeof)) // Fallback to ambient FSharp.Core.dll - let getDefaultFSharpCoreLocation() = Path.Combine(getFSharpCompilerLocationWithDefaultFromType(typeof), getFSharpCoreLibraryName + ".dll") + let getDefaultFSharpCoreLocation () = + Path.Combine(getFSharpCompilerLocationWithDefaultFromType (typeof), getFSharpCoreLibraryName + ".dll") // Must be alongside the location of FSharp.CompilerService.dll - let getDefaultFsiLibraryLocation() = Path.Combine(Path.GetDirectoryName(getFSharpCompilerLocation()), fsiLibraryName + ".dll") + let getDefaultFsiLibraryLocation () = + Path.Combine(Path.GetDirectoryName(getFSharpCompilerLocation ()), fsiLibraryName + ".dll") let isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) @@ -387,20 +449,28 @@ module internal FSharpEnvironment = let fileExists pathToFile = try File.Exists(pathToFile) - with | _ -> false + with _ -> + false // Look for global install of dotnet sdk - let getDotnetGlobalHostPath() = + let getDotnetGlobalHostPath () = let pf = Environment.GetEnvironmentVariable("ProgramW6432") - let pf = if String.IsNullOrEmpty(pf) then Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) else pf + + let pf = + if String.IsNullOrEmpty(pf) then + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + else + pf + let candidate = Path.Combine(pf, "dotnet", dotnet) + if fileExists candidate then Some candidate else // Can't find it --- give up None - let getDotnetHostPath() = + let getDotnetHostPath () = // How to find dotnet.exe --- woe is me; probing rules make me sad. // Algorithm: // 1. Look for DOTNET_HOST_PATH environment variable @@ -412,11 +482,11 @@ module internal FSharpEnvironment = // See if the host is dotnet.exe ... from net5.0 on this is fairly unlikely // 4. If it's none of the above we are going to have to rely on the path containing the way to find dotnet.exe // Use the path to search for dotnet.exe - let probePathForDotnetHost() = + let probePathForDotnetHost () = let paths = let p = Environment.GetEnvironmentVariable("PATH") - if not(isNull p) then p.Split(Path.PathSeparator) - else [||] + if not (isNull p) then p.Split(Path.PathSeparator) else [||] + paths |> Array.tryFind (fun f -> fileExists (Path.Combine(f, dotnet))) match (Environment.GetEnvironmentVariable("DOTNET_HOST_PATH")) with @@ -425,37 +495,44 @@ module internal FSharpEnvironment = | _ -> // Probe for netsdk install, dotnet. and dotnet.exe is a constant offset from the location of System.Int32 let candidate = - let assemblyLocation = Path.GetDirectoryName(typeof.GetTypeInfo().Assembly.Location) + let assemblyLocation = + Path.GetDirectoryName(typeof.GetTypeInfo().Assembly.Location) + Path.GetFullPath(Path.Combine(assemblyLocation, "..", "..", "..", dotnet)) + if fileExists candidate then Some candidate else match probePathForDotnetHost () with - | Some f -> Some (Path.Combine(f, dotnet)) - | None -> getDotnetGlobalHostPath() + | Some f -> Some(Path.Combine(f, dotnet)) + | None -> getDotnetGlobalHostPath () + + let getDotnetHostDirectories () = + let isDotnetMultilevelLookup = + (Int32.TryParse(Environment.GetEnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP")) + |> snd) + <> 0 - let getDotnetHostDirectories() = - let isDotnetMultilevelLookup = (Int32.TryParse(Environment.GetEnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP")) |> snd) <> 0 [| - match getDotnetHostPath(), getDotnetGlobalHostPath() with + match getDotnetHostPath (), getDotnetGlobalHostPath () with | Some hostPath, Some globalHostPath -> 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) - | None, None -> - () + | Some hostPath, None -> yield Path.GetDirectoryName(hostPath) + | None, Some globalHostPath -> yield Path.GetDirectoryName(globalHostPath) + | None, None -> () |] - let getDotnetHostDirectory() = getDotnetHostDirectories() |> Array.tryHead + let getDotnetHostDirectory () = + getDotnetHostDirectories () |> Array.tryHead - let getDotnetHostSubDirectories(path: string) = + let getDotnetHostSubDirectories (path: string) = [| - for directory in getDotnetHostDirectories() do + for directory in getDotnetHostDirectories () do let subdirectory = Path.Combine(directory, path) + if Directory.Exists(subdirectory) then yield! DirectoryInfo(subdirectory).GetDirectories() |] diff --git a/src/Compiler/Facilities/DiagnosticOptions.fs b/src/Compiler/Facilities/DiagnosticOptions.fs index 350703012ed..18854baa400 100644 --- a/src/Compiler/Facilities/DiagnosticOptions.fs +++ b/src/Compiler/Facilities/DiagnosticOptions.fs @@ -6,28 +6,28 @@ namespace FSharp.Compiler.Diagnostics [] -type FSharpDiagnosticSeverity = +type FSharpDiagnosticSeverity = | Hidden | Info - | Warning + | Warning | Error type FSharpDiagnosticOptions = { - WarnLevel: int - GlobalWarnAsError: bool - WarnOff: int list - WarnOn: int list - WarnAsError: int list - WarnAsWarn: int list + WarnLevel: int + GlobalWarnAsError: bool + WarnOff: int list + WarnOn: int list + WarnAsError: int list + WarnAsWarn: int list } + static member Default = { - WarnLevel = 3 - GlobalWarnAsError = false - WarnOff = [] - WarnOn = [] - WarnAsError = [] - WarnAsWarn = [] + WarnLevel = 3 + GlobalWarnAsError = false + WarnOff = [] + WarnOn = [] + WarnAsError = [] + WarnAsWarn = [] } - diff --git a/src/Compiler/Facilities/DiagnosticResolutionHints.fs b/src/Compiler/Facilities/DiagnosticResolutionHints.fs index c9c35c04cd7..27ff2059914 100644 --- a/src/Compiler/Facilities/DiagnosticResolutionHints.fs +++ b/src/Compiler/Facilities/DiagnosticResolutionHints.fs @@ -20,58 +20,65 @@ let minStringLengthForSuggestion = 3 /// The threshold is set to about a quarter of the number of characters. let IsInEditDistanceProximity idText suggestion = let editDistance = EditDistance.CalculateEditDistance(idText, suggestion) + let threshold = match idText.Length with | x when x < 5 -> 1 | x when x < 7 -> 2 | x -> x / 4 + 1 - + editDistance <= threshold /// Demangles a suggestion let DemangleOperator (nm: string) = if nm.StartsWithOrdinal("( ") && nm.EndsWithOrdinal(" )") then - nm[2..nm.Length - 3] - else + nm[2 .. nm.Length - 3] + else nm -type SuggestionBufferEnumerator(tail: int, data: KeyValuePair []) = +type SuggestionBufferEnumerator(tail: int, data: KeyValuePair[]) = let mutable current = data.Length + interface IEnumerator with - member _.Current - with get () = - let kvpr = &data[current] - kvpr.Value + member _.Current = + let kvpr = &data[current] + kvpr.Value + interface IEnumerator with - member _.Current with get () = box data[current].Value + member _.Current = box data[current].Value + member _.MoveNext() = current <- current - 1 current > tail || (current = tail && data[current] <> Unchecked.defaultof<_>) - member _.Reset () = current <- data.Length + + member _.Reset() = current <- data.Length + interface System.IDisposable with - member _.Dispose () = () + member _.Dispose() = () -type SuggestionBuffer(idText: string) = - let data = Array.zeroCreate>(maxSuggestions) +type SuggestionBuffer(idText: string) = + let data = Array.zeroCreate> (maxSuggestions) let mutable tail = maxSuggestions - 1 let uppercaseText = idText.ToUpperInvariant() let dotIdText = "." + idText let mutable disableSuggestions = idText.Length < minStringLengthForSuggestion - let insert (k,v) = + let insert (k, v) = let mutable pos = tail + while pos < maxSuggestions && (let kv = &data[pos] in kv.Key < k) do pos <- pos + 1 if pos > 0 then if pos >= maxSuggestions || (let kv = &data[pos] in k <> kv.Key || v <> kv.Value) then if tail < pos - 1 then - for i = tail to pos - 2 do + for i = tail to pos - 2 do data[i] <- data[i + 1] - data[pos - 1] <- KeyValuePair(k,v) + + data[pos - 1] <- KeyValuePair(k, v) if tail > 0 then tail <- tail - 1 - member _.Add (suggestion: string) = + member _.Add(suggestion: string) = if not disableSuggestions then if suggestion = idText then // some other parse error happened disableSuggestions <- true @@ -80,29 +87,33 @@ type SuggestionBuffer(idText: string) = // value as well as to formally squelch the associated compiler // error/warning (FS1182), we remove such names from the suggestions, // both to prevent accidental usages as well as to encourage good taste - if suggestion.Length >= minStringLengthForSuggestion && not (suggestion.StartsWithOrdinal "_") then - let suggestion:string = DemangleOperator suggestion + if + suggestion.Length >= minStringLengthForSuggestion + && not (suggestion.StartsWithOrdinal "_") + then + let suggestion: string = DemangleOperator suggestion let suggestedText = suggestion.ToUpperInvariant() let similarity = EditDistance.JaroWinklerDistance uppercaseText suggestedText - if similarity >= highConfidenceThreshold || - suggestion.EndsWithOrdinal dotIdText || - (similarity >= minThresholdForSuggestions && IsInEditDistanceProximity uppercaseText suggestedText) - then - insert(similarity, suggestion) - - member _.Disabled with get () = disableSuggestions - member _.IsEmpty with get () = disableSuggestions || (tail = maxSuggestions - 1) + if similarity >= highConfidenceThreshold + || suggestion.EndsWithOrdinal dotIdText + || (similarity >= minThresholdForSuggestions + && IsInEditDistanceProximity uppercaseText suggestedText) then + insert (similarity, suggestion) + + member _.Disabled = disableSuggestions + + member _.IsEmpty = disableSuggestions || (tail = maxSuggestions - 1) interface IEnumerable with - member this.GetEnumerator () = + member this.GetEnumerator() = if this.IsEmpty then Seq.empty.GetEnumerator() else new SuggestionBufferEnumerator(tail, data) :> IEnumerator interface IEnumerable with - member this.GetEnumerator () = + member this.GetEnumerator() = if this.IsEmpty then Seq.empty.GetEnumerator() :> IEnumerator else diff --git a/src/Compiler/Facilities/DiagnosticsLogger.fs b/src/Compiler/Facilities/DiagnosticsLogger.fs index a786fa314f0..2e9a9c47d6b 100644 --- a/src/Compiler/Facilities/DiagnosticsLogger.fs +++ b/src/Compiler/Facilities/DiagnosticsLogger.fs @@ -8,16 +8,17 @@ open FSharp.Compiler.Text.Range open FSharp.Compiler.Text open System open System.Diagnostics +open System.Reflection open System.Threading open Internal.Utilities.Library open Internal.Utilities.Library.Extras /// Represents the style being used to format errors [] -type DiagnosticStyle = - | Default - | Emacs - | Test +type DiagnosticStyle = + | Default + | Emacs + | Test | VisualStudio | Gcc @@ -36,33 +37,38 @@ exception WrappedError of exn * range with /// situations (LazyWithContext) we may need to re-report the original error /// when a lazy thunk is re-evaluated. exception ReportedError of exn option with - override this.Message = - let msg = "The exception has been reported. This internal exception should now be caught at an error recovery point on the stack." + override this.Message = + let msg = + "The exception has been reported. This internal exception should now be caught at an error recovery point on the stack." + match this :> exn with | ReportedError (Some exn) -> msg + " Original message: " + exn.Message + ")" | _ -> msg -let rec findOriginalException err = - match err with +let rec findOriginalException err = + match err with | ReportedError (Some err) -> err - | WrappedError(err, _) -> findOriginalException err + | WrappedError (err, _) -> findOriginalException err | _ -> err type Suggestions = (string -> unit) -> unit -let NoSuggestions : Suggestions = ignore +let NoSuggestions: Suggestions = ignore /// Thrown when we stop processing the F# Interactive entry or #load. exception StopProcessingExn of exn option with - override _.Message = "Processing of a script fragment has stopped because an exception has been raised" + override _.Message = + "Processing of a script fragment has stopped because an exception has been raised" - override this.ToString() = - match this :> exn with - | StopProcessingExn(Some exn) -> "StopProcessingExn, originally (" + exn.ToString() + ")" + override this.ToString() = + match this :> exn with + | StopProcessingExn (Some exn) -> "StopProcessingExn, originally (" + exn.ToString() + ")" | _ -> "StopProcessingExn" - -let (|StopProcessing|_|) exn = match exn with StopProcessingExn _ -> Some () | _ -> None +let (|StopProcessing|_|) exn = + match exn with + | StopProcessingExn _ -> Some() + | _ -> None let StopProcessing<'T> = StopProcessingExn None @@ -70,13 +76,13 @@ let StopProcessing<'T> = StopProcessingExn None exception DiagnosticWithText of number: int * message: string * range: range with override this.Message = match this :> exn with - | DiagnosticWithText(_, msg, _) -> msg + | DiagnosticWithText (_, msg, _) -> msg | _ -> "impossible" -exception InternalError of message: string * range: range with - override this.Message = - match this :> exn with - | InternalError(msg, m) -> msg + m.ToString() +exception InternalError of message: string * range: range with + override this.Message = + match this :> exn with + | InternalError (msg, m) -> msg + m.ToString() | _ -> "impossible" exception UserCompilerMessage of message: string * number: int * range: range @@ -89,142 +95,148 @@ exception Experimental of message: string * range: range exception PossibleUnverifiableCode of range: range -exception UnresolvedReferenceNoRange of assemblyName: string +exception UnresolvedReferenceNoRange of assemblyName: string exception UnresolvedReferenceError of assemblyName: string * range: range exception UnresolvedPathReferenceNoRange of assemblyName: string * path: string with override this.Message = match this :> exn with - | UnresolvedPathReferenceNoRange(assemblyName, path) -> sprintf "Assembly: %s, full path: %s" assemblyName path + | UnresolvedPathReferenceNoRange (assemblyName, path) -> sprintf "Assembly: %s, full path: %s" assemblyName path | _ -> "impossible" exception UnresolvedPathReference of assemblyName: string * path: string * range: range -exception DiagnosticWithSuggestions of number: int * message: string * range: range * identifier: string * suggestions: Suggestions with // int is e.g. 191 in FS0191 +exception DiagnosticWithSuggestions of number: int * message: string * range: range * identifier: string * suggestions: Suggestions with // int is e.g. 191 in FS0191 override this.Message = match this :> exn with - | DiagnosticWithSuggestions(_, msg, _, _, _) -> msg + | DiagnosticWithSuggestions (_, msg, _, _, _) -> msg | _ -> "impossible" /// The F# compiler code currently uses 'Error(...)' in many places to create /// an DiagnosticWithText as an exception even if it's a warning. /// /// We will eventually rename this to remove this use of "Error" -let Error ((n, text), m) = - DiagnosticWithText (n, text, m) +let Error ((n, text), m) = DiagnosticWithText(n, text, m) /// The F# compiler code currently uses 'ErrorWithSuggestions(...)' in many places to create /// an DiagnosticWithText as an exception even if it's a warning. /// /// We will eventually rename this to remove this use of "Error" let ErrorWithSuggestions ((n, message), m, id, suggestions) = - DiagnosticWithSuggestions (n, message, m, id, suggestions) + DiagnosticWithSuggestions(n, message, m, id, suggestions) -let inline protectAssemblyExploration dflt f = - try - f() +let inline protectAssemblyExploration dflt f = + try + f () with | UnresolvedPathReferenceNoRange _ -> dflt - | _ -> reraise() + | _ -> reraise () -let inline protectAssemblyExplorationF dflt f = - try - f() +let inline protectAssemblyExplorationF dflt f = + try + f () with - | UnresolvedPathReferenceNoRange (asmName, path) -> dflt(asmName, path) - | _ -> reraise() + | UnresolvedPathReferenceNoRange (asmName, path) -> dflt (asmName, path) + | _ -> reraise () -let inline protectAssemblyExplorationNoReraise dflt1 dflt2 f = - try - f() +let inline protectAssemblyExplorationNoReraise dflt1 dflt2 f = + try + f () with | UnresolvedPathReferenceNoRange _ -> dflt1 | _ -> dflt2 // Attach a range if this is a range dual exception. -let rec AttachRange m (exn:exn) = - if equals m range0 then exn - else +let rec AttachRange m (exn: exn) = + if equals m range0 then + exn + else match exn with // Strip TargetInvocationException wrappers | :? System.Reflection.TargetInvocationException -> AttachRange m exn.InnerException | UnresolvedReferenceNoRange a -> UnresolvedReferenceError(a, m) - | UnresolvedPathReferenceNoRange(a, p) -> UnresolvedPathReference(a, p, m) + | UnresolvedPathReferenceNoRange (a, p) -> UnresolvedPathReference(a, p, m) | Failure msg -> InternalError(msg + " (Failure)", m) | :? ArgumentException as exn -> InternalError(exn.Message + " (ArgumentException)", m) | notARangeDual -> notARangeDual -type Exiter = - abstract Exit : int -> 'T +type Exiter = + abstract Exit: int -> 'T -let QuitProcessExiter = - { new Exiter with - member _.Exit n = - try - Environment.Exit n - with _ -> - () - FSComp.SR.elSysEnvExitDidntExit() - |> failwith } +let QuitProcessExiter = + { new Exiter with + member _.Exit n = + try + Environment.Exit n + with _ -> + () + + FSComp.SR.elSysEnvExitDidntExit () |> failwith + } /// Closed enumeration of build phases. [] type BuildPhase = - | DefaultPhase - | Compile - | Parameter | Parse | TypeCheck - | CodeGen - | Optimize | IlxGen | IlGen | Output + | DefaultPhase + | Compile + | Parameter + | Parse + | TypeCheck + | CodeGen + | Optimize + | IlxGen + | IlGen + | Output | Interactive // An error seen during interactive execution - + /// Literal build phase subcategory strings. module BuildPhaseSubcategory = - [] + [] let DefaultPhase = "" - [] + [] let Compile = "compile" - [] + [] let Parameter = "parameter" - [] + [] let Parse = "parse" - [] + [] let TypeCheck = "typecheck" - [] + [] let CodeGen = "codegen" - [] + [] let Optimize = "optimize" - [] + [] let IlxGen = "ilxgen" - [] - let IlGen = "ilgen" + [] + let IlGen = "ilgen" - [] - let Output = "output" + [] + let Output = "output" - [] - let Interactive = "interactive" + [] + let Interactive = "interactive" - [] - let Internal = "internal" // Compiler ICE + [] + let Internal = "internal" // Compiler ICE [] -type PhasedDiagnostic = - { Exception:exn - Phase:BuildPhase } +type PhasedDiagnostic = + { + Exception: exn + Phase: BuildPhase + } /// Construct a phased error - static member Create(exn:exn, phase:BuildPhase) : PhasedDiagnostic = - { Exception = exn - Phase=phase} + static member Create(exn: exn, phase: BuildPhase) : PhasedDiagnostic = { Exception = exn; Phase = phase } member this.DebugDisplay() = sprintf "%s: %s" (this.Subcategory()) this.Exception.Message @@ -248,113 +260,118 @@ type PhasedDiagnostic = | BuildPhase.Interactive -> BuildPhaseSubcategory.Interactive /// Return true if the textual phase given is from the compile part of the build process. - /// This set needs to be equal to the set of subcategories that the language service can produce. - static member IsSubcategoryOfCompile(subcategory:string) = + /// This set needs to be equal to the set of subcategories that the language service can produce. + static member IsSubcategoryOfCompile(subcategory: string) = // This code logic is duplicated in DocumentTask.cs in the language service. - match subcategory with - | BuildPhaseSubcategory.Compile - | BuildPhaseSubcategory.Parameter - | BuildPhaseSubcategory.Parse + match subcategory with + | BuildPhaseSubcategory.Compile + | BuildPhaseSubcategory.Parameter + | BuildPhaseSubcategory.Parse | BuildPhaseSubcategory.TypeCheck -> true - | BuildPhaseSubcategory.DefaultPhase - | BuildPhaseSubcategory.CodeGen - | BuildPhaseSubcategory.Optimize - | BuildPhaseSubcategory.IlxGen - | BuildPhaseSubcategory.IlGen - | BuildPhaseSubcategory.Output + | BuildPhaseSubcategory.DefaultPhase + | BuildPhaseSubcategory.CodeGen + | BuildPhaseSubcategory.Optimize + | BuildPhaseSubcategory.IlxGen + | BuildPhaseSubcategory.IlGen + | BuildPhaseSubcategory.Output | BuildPhaseSubcategory.Interactive -> false - | BuildPhaseSubcategory.Internal - // Getting here means the compiler has ICE-d. Let's not pile on by showing the unknownSubcategory assert below. - // Just treat as an unknown-to-LanguageService error. - -> false - | unknownSubcategory -> + | BuildPhaseSubcategory.Internal + // Getting here means the compiler has ICE-d. Let's not pile on by showing the unknownSubcategory assert below. + // Just treat as an unknown-to-LanguageService error. + -> false + | unknownSubcategory -> Debug.Assert(false, sprintf "Subcategory '%s' could not be correlated with a build phase." unknownSubcategory) // Recovery is to treat this as a 'build' error. Downstream, the project system and language service will treat this as // if it came from the build and not the language service. false /// Return true if this phase is one that's known to be part of the 'compile'. This is the initial phase of the entire compilation that - /// the language service knows about. - member pe.IsPhaseInCompile() = + /// the language service knows about. + member pe.IsPhaseInCompile() = match pe.Phase with - | BuildPhase.Compile | BuildPhase.Parameter | BuildPhase.Parse | BuildPhase.TypeCheck -> true + | BuildPhase.Compile + | BuildPhase.Parameter + | BuildPhase.Parse + | BuildPhase.TypeCheck -> true | _ -> false [] [] -type DiagnosticsLogger(nameForDebugging:string) = +type DiagnosticsLogger(nameForDebugging: string) = abstract ErrorCount: int - // The 'Impl' factoring enables a developer to place a breakpoint at the non-Impl + // The 'Impl' factoring enables a developer to place a breakpoint at the non-Impl // code just below and get a breakpoint for all error logger implementations. abstract DiagnosticSink: diagnostic: PhasedDiagnostic * severity: FSharpDiagnosticSeverity -> unit - member _.DebugDisplay() = sprintf "DiagnosticsLogger(%s)" nameForDebugging + member _.DebugDisplay() = + sprintf "DiagnosticsLogger(%s)" nameForDebugging let DiscardErrorsLogger = - { new DiagnosticsLogger("DiscardErrorsLogger") with + { new DiagnosticsLogger("DiscardErrorsLogger") with member _.DiagnosticSink(diagnostic, severity) = () member _.ErrorCount = 0 } let AssertFalseDiagnosticsLogger = - { new DiagnosticsLogger("AssertFalseDiagnosticsLogger") with + { new DiagnosticsLogger("AssertFalseDiagnosticsLogger") with // TODO: reenable these asserts in the compiler service member _.DiagnosticSink(diagnostic, severity) = (* assert false; *) () - member _.ErrorCount = (* assert false; *) 0 + member _.ErrorCount = (* assert false; *) 0 } -type CapturingDiagnosticsLogger(nm) = - inherit DiagnosticsLogger(nm) - let mutable errorCount = 0 +type CapturingDiagnosticsLogger(nm) = + inherit DiagnosticsLogger(nm) + let mutable errorCount = 0 let diagnostics = ResizeArray() - override _.DiagnosticSink(diagnostic, severity) = - if severity = FSharpDiagnosticSeverity.Error then errorCount <- errorCount + 1 - diagnostics.Add (diagnostic, severity) + override _.DiagnosticSink(diagnostic, severity) = + if severity = FSharpDiagnosticSeverity.Error then + errorCount <- errorCount + 1 + + diagnostics.Add(diagnostic, severity) override _.ErrorCount = errorCount member _.Diagnostics = diagnostics |> Seq.toList - member _.CommitDelayedDiagnostics(diagnosticsLogger:DiagnosticsLogger) = + member _.CommitDelayedDiagnostics(diagnosticsLogger: DiagnosticsLogger) = // Eagerly grab all the errors and warnings from the mutable collection let errors = diagnostics.ToArray() errors |> Array.iter diagnosticsLogger.DiagnosticSink /// Type holds thread-static globals for use by the compile. type internal DiagnosticsThreadStatics = - [] + [] static val mutable private buildPhase: BuildPhase - - [] + + [] static val mutable private diagnosticsLogger: DiagnosticsLogger static member BuildPhaseUnchecked = DiagnosticsThreadStatics.buildPhase static member BuildPhase - with get() = + with get () = match box DiagnosticsThreadStatics.buildPhase with | Null -> BuildPhase.DefaultPhase | _ -> DiagnosticsThreadStatics.buildPhase and set v = DiagnosticsThreadStatics.buildPhase <- v - + static member DiagnosticsLogger - with get() = + with get () = match box DiagnosticsThreadStatics.diagnosticsLogger with | Null -> AssertFalseDiagnosticsLogger | _ -> DiagnosticsThreadStatics.diagnosticsLogger and set v = DiagnosticsThreadStatics.diagnosticsLogger <- v - [] -module DiagnosticsLoggerExtensions = - open System.Reflection +module DiagnosticsLoggerExtensions = // Dev15.0 shipped with a bug in diasymreader in the portable pdb symbol reader which causes an AV // This uses a simple heuristic to detect it (the vsversion is < 16.0) let tryAndDetectDev15 = let vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") + match Double.TryParse vsVersion with | true, v -> v < 16.0 | _ -> false @@ -363,19 +380,21 @@ module DiagnosticsLoggerExtensions = let PreserveStackTrace exn = try if not tryAndDetectDev15 then - let preserveStackTrace = typeof.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) + let preserveStackTrace = + typeof.GetMethod ("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) + preserveStackTrace.Invoke(exn, null) |> ignore with _ -> - // This is probably only the mono case. - Debug.Assert(false, "Could not preserve stack trace for watson exception.") - () + // This is probably only the mono case. + Debug.Assert(false, "Could not preserve stack trace for watson exception.") + () /// Reraise an exception if it is one we want to report to Watson. - let ReraiseIfWatsonable(exn:exn) = - match exn with + let ReraiseIfWatsonable (exn: exn) = + match exn with // These few SystemExceptions which we don't report to Watson are because we handle these in some way in Build.fs | :? TargetInvocationException -> () - | :? NotSupportedException -> () + | :? NotSupportedException -> () | :? System.IO.IOException -> () // This covers FileNotFoundException and DirectoryNotFoundException | :? UnauthorizedAccessException -> () | Failure _ // This gives reports for compiler INTERNAL ERRORs @@ -384,95 +403,108 @@ module DiagnosticsLoggerExtensions = raise exn | _ -> () - type DiagnosticsLogger with + type DiagnosticsLogger with - member x.EmitDiagnostic (exn, severity) = - match exn with - | InternalError (s, _) - | Failure s as exn -> Debug.Assert(false, sprintf "Unexpected exception raised in compiler: %s\n%s" s (exn.ToString())) + member x.EmitDiagnostic(exn, severity) = + match exn with + | InternalError (s, _) + | Failure s as exn -> Debug.Assert(false, sprintf "Unexpected exception raised in compiler: %s\n%s" s (exn.ToString())) | _ -> () - match exn with - | StopProcessing - | ReportedError _ -> + match exn with + | StopProcessing + | ReportedError _ -> PreserveStackTrace exn - raise exn + raise exn | _ -> x.DiagnosticSink(PhasedDiagnostic.Create(exn, DiagnosticsThreadStatics.BuildPhase), severity) - member x.ErrorR exn = - x.EmitDiagnostic (exn, FSharpDiagnosticSeverity.Error) + member x.ErrorR exn = + x.EmitDiagnostic(exn, FSharpDiagnosticSeverity.Error) - member x.Warning exn = - x.EmitDiagnostic (exn, FSharpDiagnosticSeverity.Warning) + member x.Warning exn = + x.EmitDiagnostic(exn, FSharpDiagnosticSeverity.Warning) - member x.InformationalWarning exn = - x.EmitDiagnostic (exn, FSharpDiagnosticSeverity.Info) + member x.InformationalWarning exn = + x.EmitDiagnostic(exn, FSharpDiagnosticSeverity.Info) - member x.Error exn = + member x.Error exn = x.ErrorR exn - raise (ReportedError (Some exn)) + raise (ReportedError(Some exn)) member x.SimulateError diagnostic = - x.DiagnosticSink (diagnostic, FSharpDiagnosticSeverity.Error) - raise (ReportedError (Some diagnostic.Exception)) + x.DiagnosticSink(diagnostic, FSharpDiagnosticSeverity.Error) + raise (ReportedError(Some diagnostic.Exception)) member x.ErrorRecovery (exn: exn) (m: range) = // Never throws ReportedError. // Throws StopProcessing and exceptions raised by the DiagnosticSink(exn) handler. match exn with // Don't send ThreadAbortException down the error channel - | :? System.Threading.ThreadAbortException | WrappedError(:? System.Threading.ThreadAbortException, _) -> () - | ReportedError _ | WrappedError(ReportedError _, _) -> () - | StopProcessing | WrappedError(StopProcessing, _) -> + | :? System.Threading.ThreadAbortException + | WrappedError (:? System.Threading.ThreadAbortException, _) -> () + | ReportedError _ + | WrappedError (ReportedError _, _) -> () + | StopProcessing + | WrappedError (StopProcessing, _) -> PreserveStackTrace exn raise exn | _ -> - try - x.ErrorR (AttachRange m exn) // may raise exceptions, e.g. an fsi error sink raises StopProcessing. + try + x.ErrorR(AttachRange m exn) // may raise exceptions, e.g. an fsi error sink raises StopProcessing. ReraiseIfWatsonable exn with - | ReportedError _ | WrappedError(ReportedError _, _) -> () + | ReportedError _ + | WrappedError (ReportedError _, _) -> () - member x.StopProcessingRecovery (exn:exn) (m:range) = + member x.StopProcessingRecovery (exn: exn) (m: range) = // Do standard error recovery. // Additionally ignore/catch StopProcessing. [This is the only catch handler for StopProcessing]. // Additionally ignore/catch ReportedError. - // Can throw other exceptions raised by the DiagnosticSink(exn) handler. + // Can throw other exceptions raised by the DiagnosticSink(exn) handler. match exn with - | StopProcessing | WrappedError(StopProcessing, _) -> () // suppress, so skip error recovery. + | StopProcessing + | WrappedError (StopProcessing, _) -> () // suppress, so skip error recovery. | _ -> try x.ErrorRecovery exn m with - | StopProcessing | WrappedError(StopProcessing, _) -> () // catch, e.g. raised by DiagnosticSink. - | ReportedError _ | WrappedError(ReportedError _, _) -> () // catch, but not expected unless ErrorRecovery is changed. + | StopProcessing + | WrappedError (StopProcessing, _) -> () // catch, e.g. raised by DiagnosticSink. + | ReportedError _ + | WrappedError (ReportedError _, _) -> () // catch, but not expected unless ErrorRecovery is changed. - member x.ErrorRecoveryNoRange (exn:exn) = - x.ErrorRecovery exn range0 + member x.ErrorRecoveryNoRange(exn: exn) = x.ErrorRecovery exn range0 /// NOTE: The change will be undone when the returned "unwind" object disposes -let PushThreadBuildPhaseUntilUnwind (phase:BuildPhase) = +let PushThreadBuildPhaseUntilUnwind (phase: BuildPhase) = let oldBuildPhase = DiagnosticsThreadStatics.BuildPhaseUnchecked DiagnosticsThreadStatics.BuildPhase <- phase - { new IDisposable with - member x.Dispose() = DiagnosticsThreadStatics.BuildPhase <- oldBuildPhase } + + { new IDisposable with + member x.Dispose() = + DiagnosticsThreadStatics.BuildPhase <- oldBuildPhase + } /// NOTE: The change will be undone when the returned "unwind" object disposes -let PushDiagnosticsLoggerPhaseUntilUnwind(diagnosticsLoggerTransformer: DiagnosticsLogger -> #DiagnosticsLogger) = +let PushDiagnosticsLoggerPhaseUntilUnwind (diagnosticsLoggerTransformer: DiagnosticsLogger -> #DiagnosticsLogger) = let oldDiagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLoggerTransformer oldDiagnosticsLogger - { new IDisposable with - member _.Dispose() = - DiagnosticsThreadStatics.DiagnosticsLogger <- oldDiagnosticsLogger } -let SetThreadBuildPhaseNoUnwind(phase:BuildPhase) = DiagnosticsThreadStatics.BuildPhase <- phase + { new IDisposable with + member _.Dispose() = + DiagnosticsThreadStatics.DiagnosticsLogger <- oldDiagnosticsLogger + } + +let SetThreadBuildPhaseNoUnwind (phase: BuildPhase) = + DiagnosticsThreadStatics.BuildPhase <- phase -let SetThreadDiagnosticsLoggerNoUnwind diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger +let SetThreadDiagnosticsLoggerNoUnwind diagnosticsLogger = + DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger /// This represents the thread-local state established as each task function runs as part of the build. /// /// Use to reset error and warning handlers. -type CompilationGlobalsScope(diagnosticsLogger: DiagnosticsLogger, buildPhase: BuildPhase) = +type CompilationGlobalsScope(diagnosticsLogger: DiagnosticsLogger, buildPhase: BuildPhase) = let unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind(fun _ -> diagnosticsLogger) let unwindBP = PushThreadBuildPhaseUntilUnwind buildPhase @@ -482,130 +514,157 @@ type CompilationGlobalsScope(diagnosticsLogger: DiagnosticsLogger, buildPhase: B // Return the disposable object that cleans up interface IDisposable with member _.Dispose() = - unwindBP.Dispose() + unwindBP.Dispose() unwindEL.Dispose() // Global functions are still used by parser and TAST ops. /// Raises an exception with error recovery and returns unit. -let errorR exn = DiagnosticsThreadStatics.DiagnosticsLogger.ErrorR exn +let errorR exn = + DiagnosticsThreadStatics.DiagnosticsLogger.ErrorR exn /// Raises a warning with error recovery and returns unit. -let warning exn = DiagnosticsThreadStatics.DiagnosticsLogger.Warning exn +let warning exn = + DiagnosticsThreadStatics.DiagnosticsLogger.Warning exn /// Raises a warning with error recovery and returns unit. -let informationalWarning exn = DiagnosticsThreadStatics.DiagnosticsLogger.InformationalWarning exn +let informationalWarning exn = + DiagnosticsThreadStatics.DiagnosticsLogger.InformationalWarning exn /// Raises a special exception and returns 'T - can be caught later at an errorRecovery point. -let error exn = DiagnosticsThreadStatics.DiagnosticsLogger.Error exn +let error exn = + DiagnosticsThreadStatics.DiagnosticsLogger.Error exn /// Simulates an error. For test purposes only. -let simulateError (diagnostic : PhasedDiagnostic) = +let simulateError (diagnostic: PhasedDiagnostic) = DiagnosticsThreadStatics.DiagnosticsLogger.SimulateError diagnostic -let diagnosticSink (diagnostic, severity) = DiagnosticsThreadStatics.DiagnosticsLogger.DiagnosticSink (diagnostic, severity) +let diagnosticSink (diagnostic, severity) = + DiagnosticsThreadStatics.DiagnosticsLogger.DiagnosticSink(diagnostic, severity) -let errorSink diagnostic = diagnosticSink (diagnostic, FSharpDiagnosticSeverity.Error) +let errorSink diagnostic = + diagnosticSink (diagnostic, FSharpDiagnosticSeverity.Error) -let warnSink diagnostic = diagnosticSink (diagnostic, FSharpDiagnosticSeverity.Warning) +let warnSink diagnostic = + diagnosticSink (diagnostic, FSharpDiagnosticSeverity.Warning) -let errorRecovery exn m = DiagnosticsThreadStatics.DiagnosticsLogger.ErrorRecovery exn m +let errorRecovery exn m = + DiagnosticsThreadStatics.DiagnosticsLogger.ErrorRecovery exn m -let stopProcessingRecovery exn m = DiagnosticsThreadStatics.DiagnosticsLogger.StopProcessingRecovery exn m +let stopProcessingRecovery exn m = + DiagnosticsThreadStatics.DiagnosticsLogger.StopProcessingRecovery exn m -let errorRecoveryNoRange exn = DiagnosticsThreadStatics.DiagnosticsLogger.ErrorRecoveryNoRange exn +let errorRecoveryNoRange exn = + DiagnosticsThreadStatics.DiagnosticsLogger.ErrorRecoveryNoRange exn -let report f = - f() +let deprecatedWithError s m = errorR (Deprecated(s, m)) -let deprecatedWithError s m = errorR(Deprecated(s, m)) +let libraryOnlyError m = errorR (LibraryUseOnly m) -let libraryOnlyError m = errorR(LibraryUseOnly m) +let libraryOnlyWarning m = warning (LibraryUseOnly m) -let libraryOnlyWarning m = warning(LibraryUseOnly m) +let deprecatedOperator m = + deprecatedWithError (FSComp.SR.elDeprecatedOperator ()) m -let deprecatedOperator m = deprecatedWithError (FSComp.SR.elDeprecatedOperator()) m +let mlCompatWarning s m = + warning (UserCompilerMessage(FSComp.SR.mlCompatMessage s, 62, m)) -let mlCompatWarning s m = warning(UserCompilerMessage(FSComp.SR.mlCompatMessage s, 62, m)) - -let mlCompatError s m = errorR(UserCompilerMessage(FSComp.SR.mlCompatError s, 62, m)) +let mlCompatError s m = + errorR (UserCompilerMessage(FSComp.SR.mlCompatError s, 62, m)) +[] let suppressErrorReporting f = let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger + try - let diagnosticsLogger = - { new DiagnosticsLogger("suppressErrorReporting") with + let diagnosticsLogger = + { new DiagnosticsLogger("suppressErrorReporting") with member _.DiagnosticSink(_phasedError, _isError) = () - member _.ErrorCount = 0 } + member _.ErrorCount = 0 + } + SetThreadDiagnosticsLoggerNoUnwind diagnosticsLogger - f() + f () finally SetThreadDiagnosticsLoggerNoUnwind diagnosticsLogger -let conditionallySuppressErrorReporting cond f = if cond then suppressErrorReporting f else f() +[] +let conditionallySuppressErrorReporting cond f = + if cond then suppressErrorReporting f else f () //------------------------------------------------------------------------ -// Errors as data: Sometimes we have to reify errors as data, e.g. if backtracking +// Errors as data: Sometimes we have to reify errors as data, e.g. if backtracking /// The result type of a computational modality to colelct warnings and possibly fail [] -type OperationResult<'T> = +type OperationResult<'T> = | OkResult of warnings: exn list * result: 'T | ErrorResult of warnings: exn list * error: exn - + type ImperativeOperationResult = OperationResult -let ReportWarnings warns = - match warns with +let ReportWarnings warns = + match warns with | [] -> () // shortcut in common case | _ -> List.iter warning warns -let CommitOperationResult res = - match res with - | OkResult (warns, res) -> ReportWarnings warns; res - | ErrorResult (warns, err) -> ReportWarnings warns; error err +let CommitOperationResult res = + match res with + | OkResult (warns, res) -> + ReportWarnings warns + res + | ErrorResult (warns, err) -> + ReportWarnings warns + error err let RaiseOperationResult res : unit = CommitOperationResult res let ErrorD err = ErrorResult([], err) -let WarnD err = OkResult([err], ()) +let WarnD err = OkResult([ err ], ()) let CompleteD = OkResult([], ()) let ResultD x = OkResult([], x) -let CheckNoErrorsAndGetWarnings res = - match res with - | OkResult (warns, res2) -> Some (warns, res2) - | ErrorResult _ -> None - -/// The bind in the monad. Stop on first error. Accumulate warnings and continue. -let (++) res f = - match res with - | OkResult([], res) -> (* tailcall *) f res - | OkResult(warns, res) -> - match f res with - | OkResult(warns2, res2) -> OkResult(warns@warns2, res2) - | ErrorResult(warns2, err) -> ErrorResult(warns@warns2, err) - | ErrorResult(warns, err) -> - ErrorResult(warns, err) - -/// Stop on first error. Accumulate warnings and continue. -let rec IterateD f xs = +let CheckNoErrorsAndGetWarnings res = + match res with + | OkResult (warns, res2) -> Some(warns, res2) + | ErrorResult _ -> None + +/// The bind in the monad. Stop on first error. Accumulate warnings and continue. +[] +let (++) res f = + match res with + | OkResult ([], res) -> (* tailcall *) f res + | OkResult (warns, res) -> + match f res with + | OkResult (warns2, res2) -> OkResult(warns @ warns2, res2) + | ErrorResult (warns2, err) -> ErrorResult(warns @ warns2, err) + | ErrorResult (warns, err) -> ErrorResult(warns, err) + +/// Stop on first error. Accumulate warnings and continue. +[] +let rec IterateD f xs = match xs with - | [] -> CompleteD + | [] -> CompleteD | h :: t -> f h ++ (fun () -> IterateD f t) -let rec WhileD gd body = if gd() then body() ++ (fun () -> WhileD gd body) else CompleteD +[] +let rec WhileD gd body = + if gd () then + body () ++ (fun () -> WhileD gd body) + else + CompleteD -let MapD f xs = - let rec loop acc xs = - match xs with - | [] -> ResultD (List.rev acc) - | h :: t -> f h ++ (fun x -> loop (x :: acc) t) +[] +let rec MapD_loop f acc xs = + match xs with + | [] -> ResultD(List.rev acc) + | h :: t -> f h ++ (fun x -> MapD_loop f (x :: acc) t) - loop [] xs +[] +let MapD f xs = MapD_loop f [] xs type TrackErrorsBuilder() = member x.Bind(res, k) = res ++ k @@ -614,79 +673,106 @@ type TrackErrorsBuilder() = member x.For(seq, k) = IterateD k seq member x.Combine(expr1, expr2) = expr1 ++ expr2 member x.While(gd, k) = WhileD gd k - member x.Zero() = CompleteD + member x.Zero() = CompleteD member x.Delay fn = fun () -> fn () member x.Run fn = fn () let trackErrors = TrackErrorsBuilder() - -/// Stop on first error. Accumulate warnings and continue. -let OptionD f xs = - match xs with - | None -> CompleteD - | Some h -> f h - -/// Stop on first error. Report index -let IterateIdxD f xs = - let rec loop xs i = match xs with [] -> CompleteD | h :: t -> f i h ++ (fun () -> loop t (i+1)) + +/// Stop on first error. Accumulate warnings and continue. +[] +let OptionD f xs = + match xs with + | None -> CompleteD + | Some h -> f h + +/// Stop on first error. Report index +[] +let IterateIdxD f xs = + let rec loop xs i = + match xs with + | [] -> CompleteD + | h :: t -> f i h ++ (fun () -> loop t (i + 1)) + loop xs 0 -/// Stop on first error. Accumulate warnings and continue. -let rec Iterate2D f xs ys = - match xs, ys with - | [], [] -> CompleteD - | h1 :: t1, h2 :: t2 -> f h1 h2 ++ (fun () -> Iterate2D f t1 t2) +/// Stop on first error. Accumulate warnings and continue. +[] +let rec Iterate2D f xs ys = + match xs, ys with + | [], [] -> CompleteD + | h1 :: t1, h2 :: t2 -> f h1 h2 ++ (fun () -> Iterate2D f t1 t2) | _ -> failwith "Iterate2D" /// Keep the warnings, propagate the error to the exception continuation. -let TryD f g = - match f() with - | ErrorResult(warns, err) -> +[] +let TryD f g = + match f () with + | ErrorResult (warns, err) -> trackErrors { do! OkResult(warns, ()) return! g err } | res -> res -let rec RepeatWhileD nDeep body = body nDeep ++ (fun x -> if x then RepeatWhileD (nDeep+1) body else CompleteD) +[] +let rec RepeatWhileD nDeep body = + body nDeep ++ (fun x -> if x then RepeatWhileD (nDeep + 1) body else CompleteD) -let inline AtLeastOneD f l = MapD f l ++ (fun res -> ResultD (List.exists id res)) +[] +let inline AtLeastOneD f l = + MapD f l ++ (fun res -> ResultD(List.exists id res)) -let inline AtLeastOne2D f xs ys = List.zip xs ys |> AtLeastOneD (fun (x,y) -> f x y) +[] +let inline AtLeastOne2D f xs ys = + List.zip xs ys |> AtLeastOneD(fun (x, y) -> f x y) -let inline MapReduceD mapper zero reducer l = MapD mapper l ++ (fun res -> ResultD (match res with [] -> zero | _ -> List.reduce reducer res)) +[] +let inline MapReduceD mapper zero reducer l = + MapD mapper l + ++ (fun res -> + ResultD( + match res with + | [] -> zero + | _ -> List.reduce reducer res + )) -let inline MapReduce2D mapper zero reducer xs ys = List.zip xs ys |> MapReduceD (fun (x,y) -> mapper x y) zero reducer +[] +let inline MapReduce2D mapper zero reducer xs ys = + List.zip xs ys |> MapReduceD (fun (x, y) -> mapper x y) zero reducer [] module OperationResult = let inline ignore (res: OperationResult<'a>) = match res with - | OkResult(warnings, _) -> OkResult(warnings, ()) - | ErrorResult(warnings, err) -> ErrorResult(warnings, err) + | OkResult (warnings, _) -> OkResult(warnings, ()) + | ErrorResult (warnings, err) -> ErrorResult(warnings, err) // Code below is for --flaterrors flag that is only used by the IDE -let stringThatIsAProxyForANewlineInFlatErrors = String [|char 29 |] +let stringThatIsAProxyForANewlineInFlatErrors = String [| char 29 |] -let NewlineifyErrorString (message:string) = message.Replace(stringThatIsAProxyForANewlineInFlatErrors, Environment.NewLine) +let NewlineifyErrorString (message: string) = + message.Replace(stringThatIsAProxyForANewlineInFlatErrors, Environment.NewLine) /// fixes given string by replacing all control chars with spaces. -/// NOTE: newlines are recognized and replaced with stringThatIsAProxyForANewlineInFlatErrors (ASCII 29, the 'group separator'), +/// NOTE: newlines are recognized and replaced with stringThatIsAProxyForANewlineInFlatErrors (ASCII 29, the 'group separator'), /// which is decoded by the IDE with 'NewlineifyErrorString' back into newlines, so that multi-line errors can be displayed in QuickInfo -let NormalizeErrorString (text : string MaybeNull) = +let NormalizeErrorString (text: string MaybeNull) = let text = nullArgCheck "text" text let text = text.Trim() let buf = System.Text.StringBuilder() let mutable i = 0 + while i < text.Length do - let delta = + let delta = match text[i] with | '\r' when i + 1 < text.Length && text[i + 1] = '\n' -> // handle \r\n sequence - replace it with one single space buf.Append stringThatIsAProxyForANewlineInFlatErrors |> ignore 2 - | '\n' | '\r' -> + | '\n' + | '\r' -> buf.Append stringThatIsAProxyForANewlineInFlatErrors |> ignore 1 | c -> @@ -694,7 +780,9 @@ let NormalizeErrorString (text : string MaybeNull) = let c = if Char.IsControl c then ' ' else c buf.Append c |> ignore 1 + i <- i + delta + buf.ToString() let private tryLanguageFeatureErrorAux (langVersion: LanguageVersion) (langFeature: LanguageFeature) (m: range) = @@ -702,7 +790,7 @@ let private tryLanguageFeatureErrorAux (langVersion: LanguageVersion) (langFeatu let featureStr = langVersion.GetFeatureString langFeature let currentVersionStr = langVersion.SpecifiedVersionString let suggestedVersionStr = langVersion.GetFeatureVersionString langFeature - Some (Error(FSComp.SR.chkFeatureNotLanguageSupported(featureStr, currentVersionStr, suggestedVersionStr), m)) + Some(Error(FSComp.SR.chkFeatureNotLanguageSupported (featureStr, currentVersionStr, suggestedVersionStr), m)) else None @@ -722,27 +810,31 @@ let internal tryLanguageFeatureErrorOption langVersion langFeature m = let internal languageFeatureNotSupportedInLibraryError (langVersion: LanguageVersion) (langFeature: LanguageFeature) (m: range) = let featureStr = langVersion.GetFeatureString langFeature let suggestedVersionStr = langVersion.GetFeatureVersionString langFeature - error (Error(FSComp.SR.chkFeatureNotSupportedInLibrary(featureStr, suggestedVersionStr), m)) + error (Error(FSComp.SR.chkFeatureNotSupportedInLibrary (featureStr, suggestedVersionStr), m)) /// Guard against depth of expression nesting, by moving to new stack when a maximum depth is reached type StackGuard(maxDepth: int) = let mutable depth = 1 + [] member _.Guard(f) = depth <- depth + 1 + try - if depth % maxDepth = 0 then + if depth % maxDepth = 0 then let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger let buildPhase = DiagnosticsThreadStatics.BuildPhase - async { + + async { do! Async.SwitchToNewThread() Thread.CurrentThread.Name <- "F# Extra Compilation Thread" use _scope = new CompilationGlobalsScope(diagnosticsLogger, buildPhase) - return f() - } |> Async.RunImmediate + return f () + } + |> Async.RunImmediate else - f() + f () finally depth <- depth - 1 @@ -753,6 +845,5 @@ type StackGuard(maxDepth: int) = GetEnvInteger "FSHARP_DefaultStackGuardDepth" 100 #endif - static member GetDepthOption (name: string) = + static member GetDepthOption(name: string) = GetEnvInteger ("FSHARP_" + name + "StackGuardDepth") StackGuard.DefaultDepth - diff --git a/src/Compiler/Facilities/DiagnosticsLogger.fsi b/src/Compiler/Facilities/DiagnosticsLogger.fsi index 170c04baa06..a818ae893c9 100644 --- a/src/Compiler/Facilities/DiagnosticsLogger.fsi +++ b/src/Compiler/Facilities/DiagnosticsLogger.fsi @@ -267,8 +267,6 @@ val stopProcessingRecovery: exn: exn -> m: range -> unit val errorRecoveryNoRange: exn: exn -> unit -val report: f: (unit -> 'T) -> 'T - val deprecatedWithError: s: string -> m: range -> unit val libraryOnlyError: m: range -> unit diff --git a/src/Compiler/Facilities/LanguageFeatures.fs b/src/Compiler/Facilities/LanguageFeatures.fs index 6a6e57ee896..77b93032baa 100644 --- a/src/Compiler/Facilities/LanguageFeatures.fs +++ b/src/Compiler/Facilities/LanguageFeatures.fs @@ -6,7 +6,7 @@ module internal FSharp.Compiler.Features //------------------------------------------------------------------------------------------------------------------ // Language version command line switch //------------------------------------------------------------------------------------------------------------------ -// Add your features to this List - in code use languageVersion.SupportsFeature(LanguageFeatures.yourFeature) +// Add your features to this List - in code use languageVersion.SupportsFeature(LanguageFeatures.yourFeature) // a return value of false means your feature is not supported by the user's language selection // All new language features added from now on must be protected by this. // Note: @@ -49,70 +49,75 @@ type LanguageFeature = | DelegateTypeNameResolutionFix | ReallyLongLists | ErrorOnDeprecatedRequireQualifiedAccess + | LowercaseDUWhenRequireQualifiedAccess /// LanguageVersion management -type LanguageVersion (versionText) = +type LanguageVersion(versionText) = // When we increment language versions here preview is higher than current RTM version static let languageVersion46 = 4.6m static let languageVersion47 = 4.7m static let languageVersion50 = 5.0m static let languageVersion60 = 6.0m - static let previewVersion = 9999m // Language version when preview specified - static let defaultVersion = languageVersion60 // Language version when default specified - static let latestVersion = defaultVersion // Language version when latest specified - static let latestMajorVersion = languageVersion60 // Language version when latestmajor specified + static let previewVersion = 9999m // Language version when preview specified + static let defaultVersion = languageVersion60 // Language version when default specified + static let latestVersion = defaultVersion // Language version when latest specified + static let latestMajorVersion = languageVersion60 // Language version when latestmajor specified static let validOptions = [| "preview"; "default"; "latest"; "latestmajor" |] - static let languageVersions = set [| languageVersion46; languageVersion47; languageVersion50; languageVersion60 |] + + static let languageVersions = + set [| languageVersion46; languageVersion47; languageVersion50; languageVersion60 |] static let features = - dict [ - // F# 4.7 - LanguageFeature.SingleUnderscorePattern, languageVersion47 - LanguageFeature.WildCardInForLoop, languageVersion47 - LanguageFeature.RelaxWhitespace, languageVersion47 - LanguageFeature.ImplicitYield, languageVersion47 - - // F# 5.0 - LanguageFeature.FixedIndexSlice3d4d, languageVersion50 - LanguageFeature.DotlessFloat32Literal, languageVersion50 - LanguageFeature.AndBang, languageVersion50 - LanguageFeature.NullableOptionalInterop, languageVersion50 - LanguageFeature.DefaultInterfaceMemberConsumption, languageVersion50 - LanguageFeature.OpenTypeDeclaration, languageVersion50 - LanguageFeature.PackageManagement, languageVersion50 - LanguageFeature.WitnessPassing, languageVersion50 - LanguageFeature.InterfacesWithMultipleGenericInstantiation, languageVersion50 - LanguageFeature.NameOf, languageVersion50 - LanguageFeature.StringInterpolation, languageVersion50 - - // F# 6.0 - LanguageFeature.AdditionalTypeDirectedConversions, languageVersion60 - LanguageFeature.RelaxWhitespace2, languageVersion60 - LanguageFeature.OverloadsForCustomOperations, languageVersion60 - LanguageFeature.ExpandedMeasurables, languageVersion60 - LanguageFeature.ResumableStateMachines, languageVersion60 - LanguageFeature.StructActivePattern, languageVersion60 - LanguageFeature.PrintfBinaryFormat, languageVersion60 - LanguageFeature.IndexerNotationWithoutDot, languageVersion60 - LanguageFeature.RefCellNotationInformationals, languageVersion60 - LanguageFeature.UseBindingValueDiscard, languageVersion60 - LanguageFeature.NonVariablePatternsToRightOfAsPatterns, languageVersion60 - LanguageFeature.AttributesToRightOfModuleKeyword, languageVersion60 - LanguageFeature.DelegateTypeNameResolutionFix,languageVersion60 - - // F# preview - LanguageFeature.FromEndSlicing, previewVersion - LanguageFeature.MLCompatRevisions,previewVersion - LanguageFeature.BetterExceptionPrinting,previewVersion - LanguageFeature.ReallyLongLists, previewVersion - LanguageFeature.ErrorOnDeprecatedRequireQualifiedAccess,previewVersion - ] + dict + [ + // F# 4.7 + LanguageFeature.SingleUnderscorePattern, languageVersion47 + LanguageFeature.WildCardInForLoop, languageVersion47 + LanguageFeature.RelaxWhitespace, languageVersion47 + LanguageFeature.ImplicitYield, languageVersion47 + + // F# 5.0 + LanguageFeature.FixedIndexSlice3d4d, languageVersion50 + LanguageFeature.DotlessFloat32Literal, languageVersion50 + LanguageFeature.AndBang, languageVersion50 + LanguageFeature.NullableOptionalInterop, languageVersion50 + LanguageFeature.DefaultInterfaceMemberConsumption, languageVersion50 + LanguageFeature.OpenTypeDeclaration, languageVersion50 + LanguageFeature.PackageManagement, languageVersion50 + LanguageFeature.WitnessPassing, languageVersion50 + LanguageFeature.InterfacesWithMultipleGenericInstantiation, languageVersion50 + LanguageFeature.NameOf, languageVersion50 + LanguageFeature.StringInterpolation, languageVersion50 + + // F# 6.0 + LanguageFeature.AdditionalTypeDirectedConversions, languageVersion60 + LanguageFeature.RelaxWhitespace2, languageVersion60 + LanguageFeature.OverloadsForCustomOperations, languageVersion60 + LanguageFeature.ExpandedMeasurables, languageVersion60 + LanguageFeature.ResumableStateMachines, languageVersion60 + LanguageFeature.StructActivePattern, languageVersion60 + LanguageFeature.PrintfBinaryFormat, languageVersion60 + LanguageFeature.IndexerNotationWithoutDot, languageVersion60 + LanguageFeature.RefCellNotationInformationals, languageVersion60 + LanguageFeature.UseBindingValueDiscard, languageVersion60 + LanguageFeature.NonVariablePatternsToRightOfAsPatterns, languageVersion60 + LanguageFeature.AttributesToRightOfModuleKeyword, languageVersion60 + LanguageFeature.DelegateTypeNameResolutionFix, languageVersion60 + + // F# preview + LanguageFeature.FromEndSlicing, previewVersion + LanguageFeature.MLCompatRevisions, previewVersion + LanguageFeature.BetterExceptionPrinting, previewVersion + LanguageFeature.ReallyLongLists, previewVersion + LanguageFeature.ErrorOnDeprecatedRequireQualifiedAccess, previewVersion + LanguageFeature.LowercaseDUWhenRequireQualifiedAccess, previewVersion + ] static let defaultLanguageVersion = LanguageVersion("default") - static let getVersionFromString (version:string) = + static let getVersionFromString (version: string) = match version.ToUpperInvariant() with | "?" -> 0m | "PREVIEW" -> previewVersion @@ -121,15 +126,16 @@ type LanguageVersion (versionText) = | "LATESTMAJOR" -> latestMajorVersion | "4.6" -> languageVersion46 | "4.7" -> languageVersion47 - | "5.0" | "5" -> languageVersion50 - | "6.0" | "6" -> languageVersion60 + | "5.0" + | "5" -> languageVersion50 + | "6.0" + | "6" -> languageVersion60 | _ -> 0m let specified = getVersionFromString versionText let versionToString v = - if v = previewVersion then "'PREVIEW'" - else string v + if v = previewVersion then "'PREVIEW'" else string v let specifiedString = versionToString specified @@ -145,8 +151,7 @@ type LanguageVersion (versionText) = v <> 0.0m && v <= 5.0m /// Has preview been explicitly specified - member _.IsPreviewEnabled = - specified = previewVersion + member _.IsPreviewEnabled = specified = previewVersion /// Does the languageVersion support this version string member _.ContainsVersion version = @@ -159,8 +164,7 @@ type LanguageVersion (versionText) = /// Get a list of valid versions for help text member _.ValidVersions = [| - for v in languageVersions |> Seq.sort -> - sprintf "%M%s" v (if v = defaultVersion then " (Default)" else "") + for v in languageVersions |> Seq.sort -> sprintf "%M%s" v (if v = defaultVersion then " (Default)" else "") |] /// Get the text used to specify the version @@ -175,39 +179,40 @@ type LanguageVersion (versionText) = /// Get a string name for the given feature. member _.GetFeatureString feature = match feature with - | LanguageFeature.SingleUnderscorePattern -> FSComp.SR.featureSingleUnderscorePattern() - | LanguageFeature.WildCardInForLoop -> FSComp.SR.featureWildCardInForLoop() - | LanguageFeature.RelaxWhitespace -> FSComp.SR.featureRelaxWhitespace() - | LanguageFeature.RelaxWhitespace2 -> FSComp.SR.featureRelaxWhitespace2() - | LanguageFeature.NameOf -> FSComp.SR.featureNameOf() - | LanguageFeature.ImplicitYield -> FSComp.SR.featureImplicitYield() - | LanguageFeature.OpenTypeDeclaration -> FSComp.SR.featureOpenTypeDeclaration() - | LanguageFeature.DotlessFloat32Literal -> FSComp.SR.featureDotlessFloat32Literal() - | LanguageFeature.PackageManagement -> FSComp.SR.featurePackageManagement() - | LanguageFeature.FromEndSlicing -> FSComp.SR.featureFromEndSlicing() - | LanguageFeature.FixedIndexSlice3d4d -> FSComp.SR.featureFixedIndexSlice3d4d() - | LanguageFeature.AndBang -> FSComp.SR.featureAndBang() - | LanguageFeature.ResumableStateMachines -> FSComp.SR.featureResumableStateMachines() - | LanguageFeature.NullableOptionalInterop -> FSComp.SR.featureNullableOptionalInterop() - | LanguageFeature.DefaultInterfaceMemberConsumption -> FSComp.SR.featureDefaultInterfaceMemberConsumption() - | LanguageFeature.WitnessPassing -> FSComp.SR.featureWitnessPassing() - | LanguageFeature.AdditionalTypeDirectedConversions -> FSComp.SR.featureAdditionalImplicitConversions() - | LanguageFeature.InterfacesWithMultipleGenericInstantiation -> FSComp.SR.featureInterfacesWithMultipleGenericInstantiation() - | LanguageFeature.StringInterpolation -> FSComp.SR.featureStringInterpolation() - | LanguageFeature.OverloadsForCustomOperations -> FSComp.SR.featureOverloadsForCustomOperations() - | LanguageFeature.ExpandedMeasurables -> FSComp.SR.featureExpandedMeasurables() - | LanguageFeature.StructActivePattern -> FSComp.SR.featureStructActivePattern() - | LanguageFeature.PrintfBinaryFormat -> FSComp.SR.featurePrintfBinaryFormat() - | LanguageFeature.IndexerNotationWithoutDot -> FSComp.SR.featureIndexerNotationWithoutDot() - | LanguageFeature.RefCellNotationInformationals -> FSComp.SR.featureRefCellNotationInformationals() - | LanguageFeature.UseBindingValueDiscard -> FSComp.SR.featureDiscardUseValue() - | LanguageFeature.NonVariablePatternsToRightOfAsPatterns -> FSComp.SR.featureNonVariablePatternsToRightOfAsPatterns() - | LanguageFeature.AttributesToRightOfModuleKeyword -> FSComp.SR.featureAttributesToRightOfModuleKeyword() - | LanguageFeature.MLCompatRevisions -> FSComp.SR.featureMLCompatRevisions() - | LanguageFeature.BetterExceptionPrinting -> FSComp.SR.featureBetterExceptionPrinting() - | LanguageFeature.DelegateTypeNameResolutionFix -> FSComp.SR.featureDelegateTypeNameResolutionFix() - | LanguageFeature.ReallyLongLists -> FSComp.SR.featureReallyLongList() - | LanguageFeature.ErrorOnDeprecatedRequireQualifiedAccess -> FSComp.SR.featureErrorOnDeprecatedRequireQualifiedAccess() + | LanguageFeature.SingleUnderscorePattern -> FSComp.SR.featureSingleUnderscorePattern () + | LanguageFeature.WildCardInForLoop -> FSComp.SR.featureWildCardInForLoop () + | LanguageFeature.RelaxWhitespace -> FSComp.SR.featureRelaxWhitespace () + | LanguageFeature.RelaxWhitespace2 -> FSComp.SR.featureRelaxWhitespace2 () + | LanguageFeature.NameOf -> FSComp.SR.featureNameOf () + | LanguageFeature.ImplicitYield -> FSComp.SR.featureImplicitYield () + | LanguageFeature.OpenTypeDeclaration -> FSComp.SR.featureOpenTypeDeclaration () + | LanguageFeature.DotlessFloat32Literal -> FSComp.SR.featureDotlessFloat32Literal () + | LanguageFeature.PackageManagement -> FSComp.SR.featurePackageManagement () + | LanguageFeature.FromEndSlicing -> FSComp.SR.featureFromEndSlicing () + | LanguageFeature.FixedIndexSlice3d4d -> FSComp.SR.featureFixedIndexSlice3d4d () + | LanguageFeature.AndBang -> FSComp.SR.featureAndBang () + | LanguageFeature.ResumableStateMachines -> FSComp.SR.featureResumableStateMachines () + | LanguageFeature.NullableOptionalInterop -> FSComp.SR.featureNullableOptionalInterop () + | LanguageFeature.DefaultInterfaceMemberConsumption -> FSComp.SR.featureDefaultInterfaceMemberConsumption () + | LanguageFeature.WitnessPassing -> FSComp.SR.featureWitnessPassing () + | LanguageFeature.AdditionalTypeDirectedConversions -> FSComp.SR.featureAdditionalImplicitConversions () + | LanguageFeature.InterfacesWithMultipleGenericInstantiation -> FSComp.SR.featureInterfacesWithMultipleGenericInstantiation () + | LanguageFeature.StringInterpolation -> FSComp.SR.featureStringInterpolation () + | LanguageFeature.OverloadsForCustomOperations -> FSComp.SR.featureOverloadsForCustomOperations () + | LanguageFeature.ExpandedMeasurables -> FSComp.SR.featureExpandedMeasurables () + | LanguageFeature.StructActivePattern -> FSComp.SR.featureStructActivePattern () + | LanguageFeature.PrintfBinaryFormat -> FSComp.SR.featurePrintfBinaryFormat () + | LanguageFeature.IndexerNotationWithoutDot -> FSComp.SR.featureIndexerNotationWithoutDot () + | LanguageFeature.RefCellNotationInformationals -> FSComp.SR.featureRefCellNotationInformationals () + | LanguageFeature.UseBindingValueDiscard -> FSComp.SR.featureDiscardUseValue () + | LanguageFeature.NonVariablePatternsToRightOfAsPatterns -> FSComp.SR.featureNonVariablePatternsToRightOfAsPatterns () + | LanguageFeature.AttributesToRightOfModuleKeyword -> FSComp.SR.featureAttributesToRightOfModuleKeyword () + | LanguageFeature.MLCompatRevisions -> FSComp.SR.featureMLCompatRevisions () + | LanguageFeature.BetterExceptionPrinting -> FSComp.SR.featureBetterExceptionPrinting () + | LanguageFeature.DelegateTypeNameResolutionFix -> FSComp.SR.featureDelegateTypeNameResolutionFix () + | LanguageFeature.ReallyLongLists -> FSComp.SR.featureReallyLongList () + | LanguageFeature.ErrorOnDeprecatedRequireQualifiedAccess -> FSComp.SR.featureErrorOnDeprecatedRequireQualifiedAccess () + | LanguageFeature.LowercaseDUWhenRequireQualifiedAccess -> FSComp.SR.featureLowercaseDUWhenRequireQualifiedAccess () /// Get a version string associated with the given feature. member _.GetFeatureVersionString feature = @@ -216,7 +221,7 @@ type LanguageVersion (versionText) = | _ -> invalidArg "feature" "Internal error: Unable to find feature." override x.Equals(yobj: obj) = - match yobj with + match yobj with | :? LanguageVersion as y -> x.SpecifiedVersion = y.SpecifiedVersion | _ -> false diff --git a/src/Compiler/Facilities/LanguageFeatures.fsi b/src/Compiler/Facilities/LanguageFeatures.fsi index ec884903b49..8227c947c77 100644 --- a/src/Compiler/Facilities/LanguageFeatures.fsi +++ b/src/Compiler/Facilities/LanguageFeatures.fsi @@ -39,6 +39,7 @@ type LanguageFeature = | DelegateTypeNameResolutionFix | ReallyLongLists | ErrorOnDeprecatedRequireQualifiedAccess + | LowercaseDUWhenRequireQualifiedAccess /// LanguageVersion management type LanguageVersion = diff --git a/src/Compiler/Facilities/Logger.fs b/src/Compiler/Facilities/Logger.fs index a7356377b79..dc425c506fe 100644 --- a/src/Compiler/Facilities/Logger.fs +++ b/src/Compiler/Facilities/Logger.fs @@ -13,9 +13,9 @@ type LogCompilerFunctionId = | CompileOps_TypeCheckOneInputAndFinishEventually = 5 | IncrementalBuild_CreateItemKeyStoreAndSemanticClassification = 6 | IncrementalBuild_TypeCheck = 7 - + /// This is for ETW tracing across FSharp.Compiler. -[] +[] type FSharpCompilerEventSource() = inherit EventSource() @@ -24,9 +24,7 @@ type FSharpCompilerEventSource() = [] member this.Log(functionId: LogCompilerFunctionId) = - if this.IsEnabled() then - this.WriteEvent(1, int functionId) - + if this.IsEnabled() then this.WriteEvent(1, int functionId) [] member this.LogMessage(message: string, functionId: LogCompilerFunctionId) = @@ -35,13 +33,11 @@ type FSharpCompilerEventSource() = [] member this.BlockStart(functionId: LogCompilerFunctionId) = - if this.IsEnabled() then - this.WriteEvent(3, int functionId) + if this.IsEnabled() then this.WriteEvent(3, int functionId) [] member this.BlockStop(functionId: LogCompilerFunctionId) = - if this.IsEnabled() then - this.WriteEvent(4, int functionId) + if this.IsEnabled() then this.WriteEvent(4, int functionId) [] member this.BlockMessageStart(message: string, functionId: LogCompilerFunctionId) = @@ -56,16 +52,16 @@ type FSharpCompilerEventSource() = [] module Logger = - let Log functionId = + let Log functionId = FSharpCompilerEventSource.Instance.Log(functionId) - let LogMessage message functionId = + let LogMessage message functionId = FSharpCompilerEventSource.Instance.LogMessage(message, functionId) - let LogBlockStart functionId = + let LogBlockStart functionId = FSharpCompilerEventSource.Instance.BlockStart(functionId) - let LogBlockStop functionId = + let LogBlockStop functionId = FSharpCompilerEventSource.Instance.BlockStop(functionId) let LogBlockMessageStart message functionId = @@ -76,12 +72,16 @@ module Logger = let LogBlock functionId = FSharpCompilerEventSource.Instance.BlockStart(functionId) + { new IDisposable with member _.Dispose() = - FSharpCompilerEventSource.Instance.BlockStop(functionId) } + FSharpCompilerEventSource.Instance.BlockStop(functionId) + } let LogBlockMessage message functionId = FSharpCompilerEventSource.Instance.BlockMessageStart(message, functionId) + { new IDisposable with member _.Dispose() = - FSharpCompilerEventSource.Instance.BlockMessageStop(message, functionId) } + FSharpCompilerEventSource.Instance.BlockMessageStop(message, functionId) + } diff --git a/src/Compiler/Facilities/ReferenceResolver.fs b/src/Compiler/Facilities/ReferenceResolver.fs index 67105cc6784..d4eeb29871d 100644 --- a/src/Compiler/Facilities/ReferenceResolver.fs +++ b/src/Compiler/Facilities/ReferenceResolver.fs @@ -5,26 +5,27 @@ namespace FSharp.Compiler.CodeAnalysis exception internal LegacyResolutionFailure [] -type LegacyResolutionEnvironment = +type LegacyResolutionEnvironment = /// Indicates a script or source being edited or compiled. Uses reference assemblies (not implementation assemblies). | EditingOrCompilation of isEditing: bool /// Indicates a script or source being dynamically compiled and executed. Uses implementation assemblies. - | CompilationAndEvaluation + | CompilationAndEvaluation -type LegacyResolvedFile = - { +type LegacyResolvedFile = + { /// Item specification. - itemSpec:string + itemSpec: string /// Prepare textual information about where the assembly was resolved from, used for tooltip output prepareToolTip: string * string -> string - /// Round-tripped baggage - baggage:string + /// Round-tripped baggage + baggage: string } - override this.ToString() = sprintf "LegacyResolvedFile(%s)" this.itemSpec + override this.ToString() = + sprintf "LegacyResolvedFile(%s)" this.itemSpec [] type internal ILegacyReferenceResolver = @@ -34,30 +35,27 @@ type internal ILegacyReferenceResolver = /// Note: If an explicit "mscorlib" is given, then --noframework is being used, and the whole ReferenceResolver logic is essentially /// unused. However in the future an option may be added to allow an explicit specification of /// a .NET Framework version to use for scripts. - abstract HighestInstalledNetFrameworkVersion : unit -> string - + abstract HighestInstalledNetFrameworkVersion: unit -> string + /// Get the Reference Assemblies directory for the .NET Framework (on Windows) - /// This is added to the default resolution path for + /// This is added to the default resolution path for /// design-time compilations. - abstract DotNetFrameworkReferenceAssembliesRootDirectory : string + abstract DotNetFrameworkReferenceAssembliesRootDirectory: string /// Perform assembly resolution on the given references under the given conditions - abstract Resolve : + abstract Resolve: resolutionEnvironment: LegacyResolutionEnvironment * - // The actual reference paths or assembly name text, plus baggage - references:(string (* baggage *) * string)[] * - // e.g. v4.5.1 - targetFrameworkVersion:string * - targetFrameworkDirectories:string list * - targetProcessorArchitecture:string * - fsharpCoreDir:string * - explicitIncludeDirs:string list * - implicitIncludeDir:string * - logMessage:(string->unit) * - logDiagnostic:(bool -> string -> string -> unit) - -> LegacyResolvedFile[] + references: (string * string)[] * + targetFrameworkVersion: string * + targetFrameworkDirectories: string list * + targetProcessorArchitecture: string * + fsharpCoreDir: string * + explicitIncludeDirs: string list * + implicitIncludeDir: string * + logMessage: (string -> unit) * + logDiagnostic: (bool -> string -> string -> unit) -> + LegacyResolvedFile[] [] -type LegacyReferenceResolver(impl:ILegacyReferenceResolver) = +type LegacyReferenceResolver(impl: ILegacyReferenceResolver) = member internal _.Impl = impl - diff --git a/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs b/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs index f98e18288ca..2dfeb45460d 100644 --- a/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs +++ b/src/Compiler/Facilities/SimulatedMSBuildReferenceResolver.fs @@ -48,7 +48,8 @@ let private Net472 = "v4.7.2" [] let private Net48 = "v4.8" -let SupportedDesktopFrameworkVersions = [ Net48; Net472; Net471; Net47; Net462; Net461; Net46; Net452; Net451; Net45 ] +let SupportedDesktopFrameworkVersions = + [ Net48; Net472; Net471; Net47; Net462; Net461; Net46; Net452; Net451; Net45 ] let private SimulatedMSBuildResolver = @@ -57,7 +58,7 @@ let private SimulatedMSBuildResolver = let GetPathToDotNetFrameworkImlpementationAssemblies v = let v = match v with - | Net45 -> Some TargetDotNetFrameworkVersion.Version45 + | Net45 -> Some TargetDotNetFrameworkVersion.Version45 | Net451 -> Some TargetDotNetFrameworkVersion.Version451 | Net452 -> Some TargetDotNetFrameworkVersion.Version452 | Net46 -> Some TargetDotNetFrameworkVersion.Version46 @@ -67,30 +68,38 @@ let private SimulatedMSBuildResolver = | Net471 -> Some TargetDotNetFrameworkVersion.Version471 | Net472 -> Some TargetDotNetFrameworkVersion.Version472 | Net48 -> Some TargetDotNetFrameworkVersion.Version48 - | _ -> assert false; None + | _ -> + assert false + None + match v with | Some v -> match ToolLocationHelper.GetPathToDotNetFramework v with | null -> [] - | x -> [x] + | x -> [ x ] | _ -> [] let GetPathToDotNetFrameworkReferenceAssemblies version = #if NETSTANDARD ignore version - let r : string list = [] + let r: string list = [] r #else - match Microsoft.Build.Utilities.ToolLocationHelper.GetPathToStandardLibraries(".NETFramework",version,"") with - | null | "" -> [] - | x -> [x] + match Microsoft.Build.Utilities.ToolLocationHelper.GetPathToStandardLibraries(".NETFramework", version, "") with + | null + | "" -> [] + | x -> [ x ] #endif { new ILegacyReferenceResolver with member x.HighestInstalledNetFrameworkVersion() = let root = x.DotNetFrameworkReferenceAssembliesRootDirectory - let fwOpt = SupportedDesktopFrameworkVersions |> Seq.tryFind(fun fw -> FileSystem.DirectoryExistsShim(Path.Combine(root, fw) )) + + let fwOpt = + SupportedDesktopFrameworkVersions + |> Seq.tryFind (fun fw -> FileSystem.DirectoryExistsShim(Path.Combine(root, fw))) + match fwOpt with | Some fw -> fw | None -> "v4.5" @@ -99,135 +108,193 @@ 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" else "" - member _.Resolve(resolutionEnvironment, references, targetFrameworkVersion, targetFrameworkDirectories, targetProcessorArchitecture, - fsharpCoreDir, explicitIncludeDirs, implicitIncludeDir, logMessage, logWarningOrError) = + member _.Resolve + ( + resolutionEnvironment, + references, + targetFrameworkVersion, + targetFrameworkDirectories, + targetProcessorArchitecture, + fsharpCoreDir, + explicitIncludeDirs, + implicitIncludeDir, + logMessage, + logWarningOrError + ) = #if !FX_NO_WIN_REGISTRY - let registrySearchPaths() = - [ let registryKey = @"Software\Microsoft\.NetFramework" - use key = Registry.LocalMachine.OpenSubKey registryKey - match key with - | null -> () - | _ -> - for subKeyName in key.GetSubKeyNames() do - use subKey = key.OpenSubKey subKeyName - use subSubKey = subKey.OpenSubKey("AssemblyFoldersEx") - match subSubKey with + let registrySearchPaths () = + [ + let registryKey = @"Software\Microsoft\.NetFramework" + use key = Registry.LocalMachine.OpenSubKey registryKey + + match key with | null -> () | _ -> - for subSubSubKeyName in subSubKey.GetSubKeyNames() do - use subSubSubKey = subSubKey.OpenSubKey subSubSubKeyName - match subSubSubKey.GetValue null with - | :? string as s -> yield s - | _ -> () - use subSubKey = key.OpenSubKey("AssemblyFolders") - match subSubKey with - | null -> () - | _ -> - for subSubSubKeyName in subSubKey.GetSubKeyNames() do - let subSubSubKey = subSubKey.OpenSubKey subSubSubKeyName - match subSubSubKey.GetValue null with - | :? string as s -> yield s - | _ -> () ] + for subKeyName in key.GetSubKeyNames() do + use subKey = key.OpenSubKey subKeyName + use subSubKey = subKey.OpenSubKey("AssemblyFoldersEx") + + match subSubKey with + | null -> () + | _ -> + for subSubSubKeyName in subSubKey.GetSubKeyNames() do + use subSubSubKey = subSubKey.OpenSubKey subSubSubKeyName + + match subSubSubKey.GetValue null with + | :? string as s -> yield s + | _ -> () + + use subSubKey = key.OpenSubKey("AssemblyFolders") + + match subSubKey with + | null -> () + | _ -> + for subSubSubKeyName in subSubKey.GetSubKeyNames() do + let subSubSubKey = subSubKey.OpenSubKey subSubSubKeyName + + match subSubSubKey.GetValue null with + | :? string as s -> yield s + | _ -> () + ] #endif let results = ResizeArray() + let searchPaths = - [ yield! targetFrameworkDirectories - yield! explicitIncludeDirs - yield fsharpCoreDir - yield implicitIncludeDir + [ + yield! targetFrameworkDirectories + yield! explicitIncludeDirs + yield fsharpCoreDir + yield implicitIncludeDir #if !FX_NO_WIN_REGISTRY - if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then - yield! registrySearchPaths() + if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then + yield! registrySearchPaths () #endif - yield! GetPathToDotNetFrameworkReferenceAssemblies targetFrameworkVersion - yield! GetPathToDotNetFrameworkImlpementationAssemblies targetFrameworkVersion - ] + yield! GetPathToDotNetFrameworkReferenceAssemblies targetFrameworkVersion + yield! GetPathToDotNetFrameworkImlpementationAssemblies targetFrameworkVersion + ] for r, baggage in references do //printfn "resolving %s" r let mutable found = false + let success path = if not found then //printfn "resolved %s --> %s" r path found <- true - results.Add { itemSpec = path; prepareToolTip = snd; baggage=baggage } + + results.Add + { + itemSpec = path + prepareToolTip = snd + baggage = baggage + } try if not found && FileSystem.IsPathRootedShim r then - if FileSystem.FileExistsShim r then - success r - with e -> logWarningOrError false "SR001" (e.ToString()) + if FileSystem.FileExistsShim r then success r + with e -> + logWarningOrError false "SR001" (e.ToString()) // For this one we need to get the version search exactly right, without doing a load try - if not found && r.StartsWithOrdinal("FSharp.Core, Version=") && Environment.OSVersion.Platform = PlatformID.Win32NT then + if not found + && r.StartsWithOrdinal("FSharp.Core, Version=") + && Environment.OSVersion.Platform = PlatformID.Win32NT then let n = AssemblyName r + let fscoreDir0 = let PF = match Environment.GetEnvironmentVariable("ProgramFiles(x86)") with | null -> Environment.GetEnvironmentVariable("ProgramFiles") | s -> s - PF + @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\" + n.Version.ToString() + + PF + + @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\" + + n.Version.ToString() + let trialPath = Path.Combine(fscoreDir0, n.Name + ".dll") + if FileSystem.FileExistsShim trialPath then success trialPath - with e -> logWarningOrError false "SR001" (e.ToString()) + with e -> + logWarningOrError false "SR001" (e.ToString()) let isFileName = - r.EndsWith("dll", StringComparison.OrdinalIgnoreCase) || - r.EndsWith("exe", StringComparison.OrdinalIgnoreCase) - - let qual = if isFileName then r else try AssemblyName(r).Name + ".dll" with _ -> r + ".dll" + r.EndsWith("dll", StringComparison.OrdinalIgnoreCase) + || r.EndsWith("exe", StringComparison.OrdinalIgnoreCase) + + let qual = + if isFileName then + r + else + try + AssemblyName(r).Name + ".dll" + with _ -> + r + ".dll" for searchPath in searchPaths do - try - if not found then - let trialPath = Path.Combine(searchPath, qual) - if FileSystem.FileExistsShim trialPath then - success trialPath - with e -> logWarningOrError false "SR001" (e.ToString()) + try + if not found then + let trialPath = Path.Combine(searchPath, qual) + + if FileSystem.FileExistsShim trialPath then + success trialPath + with e -> + logWarningOrError false "SR001" (e.ToString()) try // Search the GAC on Windows - if not found && not isFileName && Environment.OSVersion.Platform = PlatformID.Win32NT then + if not found + && not isFileName + && Environment.OSVersion.Platform = PlatformID.Win32NT then let n = AssemblyName r let netFx = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() - let gac = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(netFx.TrimEnd('\\'))), "assembly") - match n.Version, n.GetPublicKeyToken() with - | null, _ | _, null -> + + let gac = + Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(netFx.TrimEnd('\\'))), "assembly") + + match n.Version, n.GetPublicKeyToken() with + | null, _ + | _, null -> let options = - [ if FileSystem.DirectoryExistsShim gac then - for gacDir in FileSystem.EnumerateDirectoriesShim gac do - let assemblyDir = Path.Combine(gacDir, n.Name) - if FileSystem.DirectoryExistsShim assemblyDir then - for tdir in FileSystem.EnumerateDirectoriesShim assemblyDir do - let trialPath = Path.Combine(tdir, qual) - if FileSystem.FileExistsShim trialPath then - yield trialPath ] + [ + if FileSystem.DirectoryExistsShim gac then + for gacDir in FileSystem.EnumerateDirectoriesShim gac do + let assemblyDir = Path.Combine(gacDir, n.Name) + + if FileSystem.DirectoryExistsShim assemblyDir then + for tdir in FileSystem.EnumerateDirectoriesShim assemblyDir do + let trialPath = Path.Combine(tdir, qual) + if FileSystem.FileExistsShim trialPath then yield trialPath + ] //printfn "sorting GAC paths: %A" options options |> List.sort // puts latest version last |> List.tryLast - |> function None -> () | Some p -> success p + |> function + | None -> () + | Some p -> success p | v, tok -> if FileSystem.DirectoryExistsShim gac then for gacDir in Directory.EnumerateDirectories gac do //printfn "searching GAC directory: %s" gacDir let assemblyDir = Path.Combine(gacDir, n.Name) + if FileSystem.DirectoryExistsShim assemblyDir then //printfn "searching GAC directory: %s" assemblyDir let tokText = String.concat "" [| for b in tok -> sprintf "%02x" b |] - let verDir = Path.Combine(assemblyDir, "v4.0_"+v.ToString()+"__"+tokText) + let verDir = Path.Combine(assemblyDir, "v4.0_" + v.ToString() + "__" + tokText) //printfn "searching GAC directory: %s" verDir if FileSystem.DirectoryExistsShim verDir then @@ -235,14 +302,15 @@ let private SimulatedMSBuildResolver = //printfn "searching GAC: %s" trialPath if FileSystem.FileExistsShim trialPath then success trialPath - with e -> logWarningOrError false "SR001" (e.ToString()) + with e -> + logWarningOrError false "SR001" (e.ToString()) - results.ToArray() } + results.ToArray() + } |> LegacyReferenceResolver let internal getResolver () = SimulatedMSBuildResolver - #if INTERACTIVE // Some manual testing SimulatedMSBuildResolver.DotNetFrameworkReferenceAssembliesRootDirectory @@ -252,40 +320,66 @@ let fscoreDir = if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows 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\FSharp\.NETFramework\v4.0\4.4.0.0" else System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() let resolve s = - SimulatedMSBuildResolver.Resolve - (ResolutionEnvironment.EditingOrCompilation, [| for a in s -> (a, "") |], "v4.5.1", - [SimulatedMSBuildResolver.DotNetFrameworkReferenceAssembliesRootDirectory + @"\v4.5.1" ], "", "", - fscoreDir, [], __SOURCE_DIRECTORY__, ignore, (fun _ _ -> ()), (fun _ _-> ())) + SimulatedMSBuildResolver.Resolve( + ResolutionEnvironment.EditingOrCompilation, + [| for a in s -> (a, "") |], + "v4.5.1", + [ + SimulatedMSBuildResolver.DotNetFrameworkReferenceAssembliesRootDirectory + + @"\v4.5.1" + ], + "", + "", + fscoreDir, + [], + __SOURCE_DIRECTORY__, + ignore, + (fun _ _ -> ()), + (fun _ _ -> ()) + ) // Resolve partial name to something on search path -resolve ["FSharp.Core" ] +resolve [ "FSharp.Core" ] // Resolve DLL name to something on search path -resolve ["FSharp.Core.dll" ] +resolve [ "FSharp.Core.dll" ] // Resolve from reference assemblies -resolve ["System"; "mscorlib"; "mscorlib.dll" ] +resolve [ "System"; "mscorlib"; "mscorlib.dll" ] // Resolve from Registry AssemblyFolders -resolve ["Microsoft.SqlServer.Dmf.dll"; "Microsoft.SqlServer.Dmf" ] +resolve [ "Microsoft.SqlServer.Dmf.dll"; "Microsoft.SqlServer.Dmf" ] // Resolve exact version of FSharp.Core -resolve [ "FSharp.Core, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" ] +resolve + [ + "FSharp.Core, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" + ] // Resolve from GAC: -resolve [ "EventViewer, Version=6.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ] +resolve + [ + "EventViewer, Version=6.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" + ] // Resolve from GAC: -resolve [ "EventViewer" ] +resolve [ "EventViewer" ] -resolve [ "Microsoft.SharePoint.Client, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" ] -resolve [ "Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" ] -#endif +resolve + [ + "Microsoft.SharePoint.Client, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" + ] +resolve + [ + "Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" + ] +#endif diff --git a/src/Compiler/Facilities/TextLayoutRender.fs b/src/Compiler/Facilities/TextLayoutRender.fs index f042b1fdc64..e9b7cd8637a 100644 --- a/src/Compiler/Facilities/TextLayoutRender.fs +++ b/src/Compiler/Facilities/TextLayoutRender.fs @@ -45,6 +45,8 @@ module WordL = let keywordFalse = wordL TaggedText.keywordFalse let bar = wordL TaggedText.bar let keywordStruct = wordL TaggedText.keywordStruct + let keywordClass = wordL TaggedText.keywordClass + let keywordInterface = wordL TaggedText.keywordInterface let keywordInherit = wordL TaggedText.keywordInherit let keywordBegin = wordL TaggedText.keywordBegin let keywordEnd = wordL TaggedText.keywordEnd @@ -77,12 +79,12 @@ module RightL = let rightBracketBar = rightL TaggedText.rightBracketBar type LayoutRenderer<'a, 'b> = - abstract Start : unit -> 'b - abstract AddText : 'b -> TaggedText -> 'b - abstract AddBreak : 'b -> int -> 'b - abstract AddTag : 'b -> string * (string * string) list * bool -> 'b - abstract Finish : 'b -> 'a - + abstract Start: unit -> 'b + abstract AddText: 'b -> TaggedText -> 'b + abstract AddBreak: 'b -> int -> 'b + abstract AddTag: 'b -> string * (string * string) list * bool -> 'b + abstract Finish: 'b -> 'a + type NoState = NoState type NoResult = NoResult @@ -91,82 +93,116 @@ module LayoutRender = let mkNav r t = NavigableTaggedText(t, r) :> TaggedText let spaces n = String(' ', n) - + let renderL (rr: LayoutRenderer<_, _>) layout = - let rec addL z pos i layout k = - match layout with - | ObjLeaf _ -> failwith "ObjLeaf should never appear here" + let rec addL z pos i layout k = + match layout with + | ObjLeaf _ -> failwith "ObjLeaf should never appear here" (* pos is tab level *) - | Leaf (_, text, _) -> - k(rr.AddText z text, i + text.Text.Length) - | Node (l, r, Broken indent) -> - addL z pos i l <| - fun (z, _i) -> - let z, i = rr.AddBreak z (pos+indent), (pos+indent) - addL z (pos+indent) i r k - | Node (l, r, _) -> - let jm = Layout.JuxtapositionMiddle (l, r) - addL z pos i l <| - fun (z, i) -> - let z, i = if jm then z, i else rr.AddText z TaggedText.space, i+1 - let pos = i - addL z pos i r k - | Attr (tag, attrs, l) -> - let z = rr.AddTag z (tag, attrs, true) - addL z pos i l <| - fun (z, i) -> - let z = rr.AddTag z (tag, attrs, false) - k(z, i) - let pos = 0 - let z, i = rr.Start(), 0 + | Leaf (_, text, _) -> k (rr.AddText z text, i + text.Text.Length) + | Node (l, r, Broken indent) -> + addL z pos i l + <| fun (z, _i) -> + let z, i = rr.AddBreak z (pos + indent), (pos + indent) + addL z (pos + indent) i r k + | Node (l, r, _) -> + let jm = Layout.JuxtapositionMiddle(l, r) + + addL z pos i l + <| fun (z, i) -> + let z, i = if jm then z, i else rr.AddText z TaggedText.space, i + 1 + let pos = i + addL z pos i r k + | Attr (tag, attrs, l) -> + let z = rr.AddTag z (tag, attrs, true) + + addL z pos i l + <| fun (z, i) -> + let z = rr.AddTag z (tag, attrs, false) + k (z, i) + + let pos = 0 + let z, i = rr.Start(), 0 let z, _i = addL z pos i layout id rr.Finish z - /// string render + /// string render let stringR = - { new LayoutRenderer with - member _.Start () = [] - member _.AddText rstrs taggedText = taggedText.Text :: rstrs - member _.AddBreak rstrs n = (spaces n) :: "\n" :: rstrs - member _.AddTag z (_, _, _) = z - member _.Finish rstrs = String.Join("", Array.ofList (List.rev rstrs)) } - - /// string render + { new LayoutRenderer with + member _.Start() = [] + member _.AddText rstrs taggedText = taggedText.Text :: rstrs + member _.AddBreak rstrs n = (spaces n) :: "\n" :: rstrs + member _.AddTag z (_, _, _) = z + + member _.Finish rstrs = + String.Join("", Array.ofList (List.rev rstrs)) + } + + /// string render let taggedTextListR collector = - { new LayoutRenderer with - member _.Start () = NoState - member _.AddText z text = collector text; z - member _.AddBreak rstrs n = collector TaggedText.lineBreak; collector (TaggedText.tagSpace(spaces n)); rstrs - member _.AddTag z (_, _, _) = z - member _.Finish rstrs = NoResult } + { new LayoutRenderer with + member _.Start() = NoState + + member _.AddText z text = + collector text + z + + member _.AddBreak rstrs n = + collector TaggedText.lineBreak + collector (TaggedText.tagSpace (spaces n)) + rstrs + + member _.AddTag z (_, _, _) = z + member _.Finish rstrs = NoResult + } /// channel LayoutRenderer - let channelR (chan:TextWriter) = - { new LayoutRenderer with - member r.Start () = NoState - member r.AddText z s = chan.Write s.Text; z - member r.AddBreak z n = chan.WriteLine(); chan.Write (spaces n); z - member r.AddTag z (tag, attrs, start) = z - member r.Finish z = NoResult } + let channelR (chan: TextWriter) = + { new LayoutRenderer with + member r.Start() = NoState + + member r.AddText z s = + chan.Write s.Text + z + + member r.AddBreak z n = + chan.WriteLine() + chan.Write(spaces n) + z + + member r.AddTag z (tag, attrs, start) = z + member r.Finish z = NoResult + } /// buffer render let bufferR os = - { new LayoutRenderer with - member r.Start () = NoState - member r.AddText z s = bprintf os "%s" s.Text; z - member r.AddBreak z n = bprintf os "\n"; bprintf os "%s" (spaces n); z - member r.AddTag z (tag, attrs, start) = z - member r.Finish z = NoResult } + { new LayoutRenderer with + member r.Start() = NoState + + member r.AddText z s = + bprintf os "%s" s.Text + z + + member r.AddBreak z n = + bprintf os "\n" + bprintf os "%s" (spaces n) + z + + member r.AddTag z (tag, attrs, start) = z + member r.Finish z = NoResult + } let showL layout = renderL stringR layout - let outL (chan:TextWriter) layout = renderL (channelR chan) layout |> ignore + let outL (chan: TextWriter) layout = + renderL (channelR chan) layout |> ignore let bufferL os layout = renderL (bufferR os) layout |> ignore - let emitL f layout = renderL (taggedTextListR f) layout |> ignore + let emitL f layout = + renderL (taggedTextListR f) layout |> ignore - let toArray layout = + let toArray layout = let output = ResizeArray() - renderL (taggedTextListR (fun tt -> output.Add(tt))) layout |> ignore + renderL (taggedTextListR output.Add) layout |> ignore output.ToArray() diff --git a/src/Compiler/Facilities/TextLayoutRender.fsi b/src/Compiler/Facilities/TextLayoutRender.fsi index 1af7571cf75..88dc9921e72 100644 --- a/src/Compiler/Facilities/TextLayoutRender.fsi +++ b/src/Compiler/Facilities/TextLayoutRender.fsi @@ -84,6 +84,8 @@ module internal WordL = val keywordFalse: Layout val bar: Layout val keywordStruct: Layout + val keywordClass: Layout + val keywordInterface: Layout val keywordInherit: Layout val keywordBegin: Layout val keywordEnd: Layout diff --git a/src/Compiler/Facilities/prim-lexing.fs b/src/Compiler/Facilities/prim-lexing.fs index b78054ddc92..58b57ddace0 100644 --- a/src/Compiler/Facilities/prim-lexing.fs +++ b/src/Compiler/Facilities/prim-lexing.fs @@ -26,22 +26,25 @@ type ISourceText = abstract ContentEquals: sourceText: ISourceText -> bool - abstract CopyTo: sourceIndex: int * destination: char [] * destinationIndex: int * count: int -> unit + abstract CopyTo: sourceIndex: int * destination: char[] * destinationIndex: int * count: int -> unit [] type StringText(str: string) = let getLines (str: string) = use reader = new StringReader(str) + [| - let mutable line = reader.ReadLine() - while not (isNull line) do - yield line - line <- reader.ReadLine() - if str.EndsWith("\n", StringComparison.Ordinal) then - // last trailing space not returned - // http://stackoverflow.com/questions/19365404/stringreader-omits-trailing-linebreak - yield String.Empty + let mutable line = reader.ReadLine() + + while not (isNull line) do + yield line + line <- reader.ReadLine() + + if str.EndsWith("\n", StringComparison.Ordinal) then + // last trailing space not returned + // http://stackoverflow.com/questions/19365404/stringreader-omits-trailing-linebreak + yield String.Empty |] let getLines = @@ -53,31 +56,33 @@ type StringText(str: string) = member _.String = str override _.GetHashCode() = str.GetHashCode() - override _.Equals(obj: obj) = + + override _.Equals(obj: obj) = match obj with | :? StringText as other -> other.String.Equals(str) | :? string as other -> other.Equals(str) - | _ -> false + | _ -> false + override _.ToString() = str interface ISourceText with - member _.Item with get index = str[index] + member _.Item + with get index = str[index] member _.GetLastCharacterPosition() = let lines = getLines.Value + if lines.Length > 0 then (lines.Length, lines[lines.Length - 1].Length) else (0, 0) - member _.GetLineString(lineIndex) = - getLines.Value[lineIndex] + member _.GetLineString(lineIndex) = getLines.Value[lineIndex] member _.GetLineCount() = getLines.Value.Length - member _.GetSubTextString(start, length) = - str.Substring(start, length) + member _.GetSubTextString(start, length) = str.Substring(start, length) member _.SubTextEquals(target, startIndex) = if startIndex < 0 || startIndex >= str.Length then @@ -87,10 +92,11 @@ type StringText(str: string) = invalidArg "target" "Is null or empty." let lastIndex = startIndex + target.Length + if lastIndex <= startIndex || lastIndex >= str.Length then invalidArg "target" "Too big." - str.IndexOf(target, startIndex, target.Length) <> -1 + str.IndexOf(target, startIndex, target.Length) <> -1 member _.Length = str.Length @@ -109,291 +115,307 @@ module SourceText = namespace Internal.Utilities.Text.Lexing - open FSharp.Compiler.Text - open Microsoft.FSharp.Core - open Microsoft.FSharp.Collections - open FSharp.Compiler.Features - open System.Collections.Generic - - [] - type internal Position = - val FileIndex: int - val Line: int - val OriginalLine: int - val AbsoluteOffset: int - val StartOfLineAbsoluteOffset: int - member x.Column = x.AbsoluteOffset - x.StartOfLineAbsoluteOffset - - new (fileIndex: int, line: int, originalLine: int, startOfLineAbsoluteOffset: int, absoluteOffset: int) = - { FileIndex = fileIndex - Line = line - OriginalLine = originalLine - AbsoluteOffset = absoluteOffset - StartOfLineAbsoluteOffset = startOfLineAbsoluteOffset } - - member x.NextLine = - Position (x.FileIndex, - x.Line + 1, - x.OriginalLine + 1, - x.AbsoluteOffset, - x.AbsoluteOffset) - - member x.EndOfToken n = - Position (x.FileIndex, - x.Line, - x.OriginalLine, - x.StartOfLineAbsoluteOffset, - x.AbsoluteOffset + n) - - member x.ShiftColumnBy by = - Position (x.FileIndex, - x.Line, - x.OriginalLine, - x.StartOfLineAbsoluteOffset, - x.AbsoluteOffset + by) - - member x.ColumnMinusOne = - Position (x.FileIndex, - x.Line, - x.OriginalLine, - x.StartOfLineAbsoluteOffset, - x.StartOfLineAbsoluteOffset - 1) - - member x.ApplyLineDirective (fileIdx, line) = - Position (fileIdx, - line, - x.OriginalLine, - x.AbsoluteOffset, - x.AbsoluteOffset) - - static member Empty = Position () - - static member FirstLine fileIdx = - Position (fileIdx, - 1, - 0, - 0, - 0) - - type internal LexBufferFiller<'Char> = LexBuffer<'Char> -> unit - - and [] - internal LexBuffer<'Char>(filler: LexBufferFiller<'Char>, reportLibraryOnlyFeatures: bool, langVersion:LanguageVersion) = - let context = Dictionary(1) - let mutable buffer = [||] - /// number of valid characters beyond bufferScanStart. - let mutable bufferMaxScanLength = 0 - /// count into the buffer when scanning. - let mutable bufferScanStart = 0 - /// number of characters scanned so far. - let mutable bufferScanLength = 0 - /// length of the scan at the last accepting state. - let mutable lexemeLength = 0 - /// action related to the last accepting state. - let mutable bufferAcceptAction = 0 - let mutable eof = false - let mutable startPos = Position.Empty - let mutable endPos = Position.Empty - - // Throw away all the input besides the lexeme, which is placed at start of buffer - let discardInput () = - Array.blit buffer bufferScanStart buffer 0 bufferScanLength - bufferScanStart <- 0 - bufferMaxScanLength <- bufferScanLength - - member lexbuf.EndOfScan () : int = - //Printf.eprintf "endOfScan, lexBuffer.lexemeLength = %d\n" lexBuffer.lexemeLength; - if bufferAcceptAction < 0 then - failwith "unrecognized input" - - //printf "endOfScan %d state %d on unconsumed input '%c' (%d)\n" a s (Char.chr inp) inp; - //Printf.eprintf "accept, lexeme = %s\n" (lexeme lexBuffer); - lexbuf.StartPos <- endPos; - lexbuf.EndPos <- endPos.EndOfToken(lexbuf.LexemeLength); - bufferAcceptAction - - member lexbuf.StartPos - with get() = startPos - and set b = startPos <- b - - member lexbuf.EndPos - with get() = endPos - and set b = endPos <- b - - member lexbuf.LexemeView = System.ReadOnlySpan<'Char>(buffer, bufferScanStart, lexemeLength) - member lexbuf.LexemeChar n = buffer[n+bufferScanStart] - member lexbuf.LexemeContains (c:'Char) = array.IndexOf(buffer, c, bufferScanStart, lexemeLength) >= 0 - member lexbuf.BufferLocalStore = (context :> IDictionary<_,_>) - member lexbuf.LexemeLength with get() : int = lexemeLength and set v = lexemeLength <- v - member lexbuf.Buffer with get() : 'Char[] = buffer and set v = buffer <- v - member lexbuf.BufferMaxScanLength with get() = bufferMaxScanLength and set v = bufferMaxScanLength <- v - member lexbuf.BufferScanLength with get() = bufferScanLength and set v = bufferScanLength <- v - member lexbuf.BufferScanStart with get() : int = bufferScanStart and set v = bufferScanStart <- v - member lexbuf.BufferAcceptAction with get() = bufferAcceptAction and set v = bufferAcceptAction <- v - member lexbuf.RefillBuffer () = filler lexbuf - static member LexemeString(lexbuf:LexBuffer) = - System.String(lexbuf.Buffer,lexbuf.BufferScanStart,lexbuf.LexemeLength) - - member lexbuf.IsPastEndOfStream - with get() = eof - and set b = eof <- b - - member lexbuf.DiscardInput () = discardInput () - - member x.BufferScanPos = bufferScanStart + bufferScanLength - - member lexbuf.EnsureBufferSize n = - if lexbuf.BufferScanPos + n >= buffer.Length then - let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) - Array.blit buffer bufferScanStart repl bufferScanStart bufferScanLength - buffer <- repl - - member _.ReportLibraryOnlyFeatures = reportLibraryOnlyFeatures - - member _.LanguageVersion = langVersion - - member _.SupportsFeature featureId = langVersion.SupportsFeature featureId - - member _.CheckLanguageFeatureErrorRecover featureId range = - FSharp.Compiler.DiagnosticsLogger.checkLanguageFeatureAndRecover langVersion featureId range - - static member FromFunction (reportLibraryOnlyFeatures, langVersion, f : 'Char[] * int * int -> int) : LexBuffer<'Char> = - let extension= Array.zeroCreate 4096 - let filler (lexBuffer: LexBuffer<'Char>) = - let n = f (extension,0,extension.Length) - lexBuffer.EnsureBufferSize n - Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n - new LexBuffer<'Char>(filler, reportLibraryOnlyFeatures, langVersion) - - // Important: This method takes ownership of the array - static member FromArrayNoCopy (reportLibraryOnlyFeatures, langVersion, buffer: 'Char[]) : LexBuffer<'Char> = - let lexBuffer = new LexBuffer<'Char>((fun _ -> ()), reportLibraryOnlyFeatures, langVersion) - lexBuffer.Buffer <- buffer - lexBuffer.BufferMaxScanLength <- buffer.Length - lexBuffer - - // Important: this method does copy the array - static member FromArray (reportLibraryOnlyFeatures, langVersion, s: 'Char[]) : LexBuffer<'Char> = - let buffer = Array.copy s - LexBuffer<'Char>.FromArrayNoCopy(reportLibraryOnlyFeatures, langVersion, buffer) - - // Important: This method takes ownership of the array - static member FromChars (reportLibraryOnlyFeatures, langVersion, arr:char[]) = - LexBuffer.FromArrayNoCopy (reportLibraryOnlyFeatures, langVersion, arr) - - static member FromSourceText (reportLibraryOnlyFeatures, langVersion, sourceText: ISourceText) = - let mutable currentSourceIndex = 0 - LexBuffer.FromFunction(reportLibraryOnlyFeatures, langVersion, fun (chars, start, length) -> - let lengthToCopy = - if currentSourceIndex + length <= sourceText.Length then - length - else - sourceText.Length - currentSourceIndex +open FSharp.Compiler.Text +open Microsoft.FSharp.Core +open Microsoft.FSharp.Collections +open FSharp.Compiler.Features +open System.Collections.Generic + +[] +type internal Position = + val FileIndex: int + val Line: int + val OriginalLine: int + val AbsoluteOffset: int + val StartOfLineAbsoluteOffset: int + member x.Column = x.AbsoluteOffset - x.StartOfLineAbsoluteOffset + + new(fileIndex: int, line: int, originalLine: int, startOfLineAbsoluteOffset: int, absoluteOffset: int) = + { + FileIndex = fileIndex + Line = line + OriginalLine = originalLine + AbsoluteOffset = absoluteOffset + StartOfLineAbsoluteOffset = startOfLineAbsoluteOffset + } + + member x.NextLine = + Position(x.FileIndex, x.Line + 1, x.OriginalLine + 1, x.AbsoluteOffset, x.AbsoluteOffset) + + member x.EndOfToken n = + Position(x.FileIndex, x.Line, x.OriginalLine, x.StartOfLineAbsoluteOffset, x.AbsoluteOffset + n) + + member x.ShiftColumnBy by = + Position(x.FileIndex, x.Line, x.OriginalLine, x.StartOfLineAbsoluteOffset, x.AbsoluteOffset + by) + + member x.ColumnMinusOne = + Position(x.FileIndex, x.Line, x.OriginalLine, x.StartOfLineAbsoluteOffset, x.StartOfLineAbsoluteOffset - 1) + + member x.ApplyLineDirective(fileIdx, line) = + Position(fileIdx, line, x.OriginalLine, x.AbsoluteOffset, x.AbsoluteOffset) + + static member Empty = Position() + + static member FirstLine fileIdx = Position(fileIdx, 1, 0, 0, 0) + +type internal LexBufferFiller<'Char> = LexBuffer<'Char> -> unit + +and [] internal LexBuffer<'Char>(filler: LexBufferFiller<'Char>, reportLibraryOnlyFeatures: bool, langVersion: LanguageVersion) = + let context = Dictionary(1) + let mutable buffer = [||] + /// number of valid characters beyond bufferScanStart. + let mutable bufferMaxScanLength = 0 + /// count into the buffer when scanning. + let mutable bufferScanStart = 0 + /// number of characters scanned so far. + let mutable bufferScanLength = 0 + /// length of the scan at the last accepting state. + let mutable lexemeLength = 0 + /// action related to the last accepting state. + let mutable bufferAcceptAction = 0 + let mutable eof = false + let mutable startPos = Position.Empty + let mutable endPos = Position.Empty + + // Throw away all the input besides the lexeme, which is placed at start of buffer + let discardInput () = + Array.blit buffer bufferScanStart buffer 0 bufferScanLength + bufferScanStart <- 0 + bufferMaxScanLength <- bufferScanLength + + member lexbuf.EndOfScan() : int = + //Printf.eprintf "endOfScan, lexBuffer.lexemeLength = %d\n" lexBuffer.lexemeLength; + if bufferAcceptAction < 0 then failwith "unrecognized input" + + //printf "endOfScan %d state %d on unconsumed input '%c' (%d)\n" a s (Char.chr inp) inp; + //Printf.eprintf "accept, lexeme = %s\n" (lexeme lexBuffer); + lexbuf.StartPos <- endPos + lexbuf.EndPos <- endPos.EndOfToken(lexbuf.LexemeLength) + bufferAcceptAction + + member lexbuf.StartPos + with get () = startPos + and set b = startPos <- b + + member lexbuf.EndPos + with get () = endPos + and set b = endPos <- b + + member lexbuf.LexemeView = + System.ReadOnlySpan<'Char>(buffer, bufferScanStart, lexemeLength) + + member lexbuf.LexemeChar n = buffer[n + bufferScanStart] + + member lexbuf.LexemeContains(c: 'Char) = + array.IndexOf(buffer, c, bufferScanStart, lexemeLength) >= 0 + + member lexbuf.BufferLocalStore = (context :> IDictionary<_, _>) + + member lexbuf.LexemeLength + with get (): int = lexemeLength + and set v = lexemeLength <- v + + member lexbuf.Buffer + with get (): 'Char[] = buffer + and set v = buffer <- v + + member lexbuf.BufferMaxScanLength + with get () = bufferMaxScanLength + and set v = bufferMaxScanLength <- v + + member lexbuf.BufferScanLength + with get () = bufferScanLength + and set v = bufferScanLength <- v + + member lexbuf.BufferScanStart + with get (): int = bufferScanStart + and set v = bufferScanStart <- v + + member lexbuf.BufferAcceptAction + with get () = bufferAcceptAction + and set v = bufferAcceptAction <- v + + member lexbuf.RefillBuffer() = filler lexbuf + + static member LexemeString(lexbuf: LexBuffer) = + System.String(lexbuf.Buffer, lexbuf.BufferScanStart, lexbuf.LexemeLength) + + member lexbuf.IsPastEndOfStream + with get () = eof + and set b = eof <- b + + member lexbuf.DiscardInput() = discardInput () + + member x.BufferScanPos = bufferScanStart + bufferScanLength + + member lexbuf.EnsureBufferSize n = + if lexbuf.BufferScanPos + n >= buffer.Length then + let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) + Array.blit buffer bufferScanStart repl bufferScanStart bufferScanLength + buffer <- repl + + member _.ReportLibraryOnlyFeatures = reportLibraryOnlyFeatures + + member _.LanguageVersion = langVersion + + member _.SupportsFeature featureId = langVersion.SupportsFeature featureId + + member _.CheckLanguageFeatureErrorRecover featureId range = + FSharp.Compiler.DiagnosticsLogger.checkLanguageFeatureAndRecover langVersion featureId range + + static member FromFunction(reportLibraryOnlyFeatures, langVersion, f: 'Char[] * int * int -> int) : LexBuffer<'Char> = + let extension = Array.zeroCreate 4096 + + let filler (lexBuffer: LexBuffer<'Char>) = + let n = f (extension, 0, extension.Length) + lexBuffer.EnsureBufferSize n + Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n + lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n + + new LexBuffer<'Char>(filler, reportLibraryOnlyFeatures, langVersion) + + // Important: This method takes ownership of the array + static member FromArrayNoCopy(reportLibraryOnlyFeatures, langVersion, buffer: 'Char[]) : LexBuffer<'Char> = + let lexBuffer = + new LexBuffer<'Char>((fun _ -> ()), reportLibraryOnlyFeatures, langVersion) + + lexBuffer.Buffer <- buffer + lexBuffer.BufferMaxScanLength <- buffer.Length + lexBuffer - if lengthToCopy <= 0 then 0 + // Important: this method does copy the array + static member FromArray(reportLibraryOnlyFeatures, langVersion, s: 'Char[]) : LexBuffer<'Char> = + let buffer = Array.copy s + LexBuffer<'Char>.FromArrayNoCopy (reportLibraryOnlyFeatures, langVersion, buffer) + + // Important: This method takes ownership of the array + static member FromChars(reportLibraryOnlyFeatures, langVersion, arr: char[]) = + LexBuffer.FromArrayNoCopy(reportLibraryOnlyFeatures, langVersion, arr) + + static member FromSourceText(reportLibraryOnlyFeatures, langVersion, sourceText: ISourceText) = + let mutable currentSourceIndex = 0 + + LexBuffer.FromFunction + (reportLibraryOnlyFeatures, + langVersion, + fun (chars, start, length) -> + let lengthToCopy = + if currentSourceIndex + length <= sourceText.Length then + length + else + sourceText.Length - currentSourceIndex + + if lengthToCopy <= 0 then + 0 + else + sourceText.CopyTo(currentSourceIndex, chars, start, lengthToCopy) + currentSourceIndex <- currentSourceIndex + lengthToCopy + lengthToCopy) + +module GenericImplFragments = + let startInterpret (lexBuffer: LexBuffer) = + lexBuffer.BufferScanStart <- lexBuffer.BufferScanStart + lexBuffer.LexemeLength + lexBuffer.BufferMaxScanLength <- lexBuffer.BufferMaxScanLength - lexBuffer.LexemeLength + lexBuffer.BufferScanLength <- 0 + lexBuffer.LexemeLength <- 0 + lexBuffer.BufferAcceptAction <- -1 + + let afterRefill (trans: uint16[][], sentinel, lexBuffer: LexBuffer, scanUntilSentinel, endOfScan, state, eofPos) = + // end of file occurs if we couldn't extend the buffer + if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then + let snew = int trans[state].[eofPos] // == EOF + + if snew = sentinel then + endOfScan () + else + if lexBuffer.IsPastEndOfStream then + failwith "End of file on lexing stream" + + lexBuffer.IsPastEndOfStream <- true + //printf "state %d --> %d on eof\n" state snew; + scanUntilSentinel lexBuffer snew + else + scanUntilSentinel lexBuffer state + + let onAccept (lexBuffer: LexBuffer, a) = + lexBuffer.LexemeLength <- lexBuffer.BufferScanLength + lexBuffer.BufferAcceptAction <- a + +open GenericImplFragments + +[] +type internal UnicodeTables(trans: uint16[] array, accept: uint16[]) = + let sentinel = 255 * 256 + 255 + let numUnicodeCategories = 30 + let numLowUnicodeChars = 128 + + let numSpecificUnicodeChars = + (trans[0].Length - 1 - numLowUnicodeChars - numUnicodeCategories) / 2 + + let lookupUnicodeCharacters state inp = + let inpAsInt = int inp + // Is it a fast ASCII character? + if inpAsInt < numLowUnicodeChars then + int trans[state].[inpAsInt] + else + // Search for a specific unicode character + let baseForSpecificUnicodeChars = numLowUnicodeChars + + let rec loop i = + if i >= numSpecificUnicodeChars then + // OK, if we failed then read the 'others' entry in the alphabet, + // which covers all Unicode characters not covered in other + // ways + let baseForUnicodeCategories = numLowUnicodeChars + numSpecificUnicodeChars * 2 + let unicodeCategory = System.Char.GetUnicodeCategory(inp) + //System.Console.WriteLine("inp = {0}, unicodeCategory = {1}", [| box inp; box unicodeCategory |]); + int trans[state].[baseForUnicodeCategories + int32 unicodeCategory] else - sourceText.CopyTo(currentSourceIndex, chars, start, lengthToCopy) - currentSourceIndex <- currentSourceIndex + lengthToCopy - lengthToCopy - ) - - module GenericImplFragments = - let startInterpret(lexBuffer:LexBuffer) = - lexBuffer.BufferScanStart <- lexBuffer.BufferScanStart + lexBuffer.LexemeLength; - lexBuffer.BufferMaxScanLength <- lexBuffer.BufferMaxScanLength - lexBuffer.LexemeLength; - lexBuffer.BufferScanLength <- 0; - lexBuffer.LexemeLength <- 0; - lexBuffer.BufferAcceptAction <- -1; - - let afterRefill (trans: uint16[][],sentinel,lexBuffer:LexBuffer,scanUntilSentinel,endOfScan,state,eofPos) = - // end of file occurs if we couldn't extend the buffer - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - let snew = int trans[state].[eofPos] // == EOF - if snew = sentinel then - endOfScan() - else - if lexBuffer.IsPastEndOfStream then failwith "End of file on lexing stream"; - lexBuffer.IsPastEndOfStream <- true; - //printf "state %d --> %d on eof\n" state snew; - scanUntilSentinel lexBuffer snew - else - scanUntilSentinel lexBuffer state - - let onAccept (lexBuffer:LexBuffer,a) = - lexBuffer.LexemeLength <- lexBuffer.BufferScanLength; - lexBuffer.BufferAcceptAction <- a; - - open GenericImplFragments - - [] - type internal UnicodeTables(trans: uint16[] array, accept: uint16[]) = - let sentinel = 255 * 256 + 255 - let numUnicodeCategories = 30 - let numLowUnicodeChars = 128 - let numSpecificUnicodeChars = (trans[0].Length - 1 - numLowUnicodeChars - numUnicodeCategories)/2 - let lookupUnicodeCharacters state inp = - let inpAsInt = int inp - // Is it a fast ASCII character? - if inpAsInt < numLowUnicodeChars then - int trans[state].[inpAsInt] - else - // Search for a specific unicode character - let baseForSpecificUnicodeChars = numLowUnicodeChars - let rec loop i = - if i >= numSpecificUnicodeChars then - // OK, if we failed then read the 'others' entry in the alphabet, - // which covers all Unicode characters not covered in other - // ways - let baseForUnicodeCategories = numLowUnicodeChars+numSpecificUnicodeChars*2 - let unicodeCategory = - System.Char.GetUnicodeCategory(inp) - //System.Console.WriteLine("inp = {0}, unicodeCategory = {1}", [| box inp; box unicodeCategory |]); - int trans[state].[baseForUnicodeCategories + int32 unicodeCategory] - else - // This is the specific unicode character - let c = char (int trans[state].[baseForSpecificUnicodeChars+i*2]) - //System.Console.WriteLine("c = {0}, inp = {1}, i = {2}", [| box c; box inp; box i |]); - // OK, have we found the entry for a specific unicode character? - if c = inp - then int trans[state].[baseForSpecificUnicodeChars+i*2+1] - else loop(i+1) - loop 0 - let eofPos = numLowUnicodeChars + 2*numSpecificUnicodeChars + numUnicodeCategories - - let rec scanUntilSentinel lexBuffer state = - // Return an endOfScan after consuming the input - let a = int accept[state] - if a <> sentinel then - onAccept(lexBuffer,a) - - if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then - lexBuffer.DiscardInput(); - lexBuffer.RefillBuffer (); - // end of file occurs if we couldn't extend the buffer - afterRefill (trans,sentinel,lexBuffer,scanUntilSentinel,lexBuffer.EndOfScan,state,eofPos) + // This is the specific unicode character + let c = char (int trans[state].[baseForSpecificUnicodeChars + i * 2]) + //System.Console.WriteLine("c = {0}, inp = {1}, i = {2}", [| box c; box inp; box i |]); + // OK, have we found the entry for a specific unicode character? + if c = inp then + int trans[state].[baseForSpecificUnicodeChars + i * 2 + 1] + else + loop (i + 1) + + loop 0 + + let eofPos = numLowUnicodeChars + 2 * numSpecificUnicodeChars + numUnicodeCategories + + let rec scanUntilSentinel lexBuffer state = + // Return an endOfScan after consuming the input + let a = int accept[state] + if a <> sentinel then onAccept (lexBuffer, a) + + if lexBuffer.BufferScanLength = lexBuffer.BufferMaxScanLength then + lexBuffer.DiscardInput() + lexBuffer.RefillBuffer() + // end of file occurs if we couldn't extend the buffer + afterRefill (trans, sentinel, lexBuffer, scanUntilSentinel, lexBuffer.EndOfScan, state, eofPos) + else + // read a character - end the scan if there are no further transitions + let inp = lexBuffer.Buffer[lexBuffer.BufferScanPos] + + // Find the new state + let snew = lookupUnicodeCharacters state inp + + if snew = sentinel then + lexBuffer.EndOfScan() else - // read a character - end the scan if there are no further transitions - let inp = lexBuffer.Buffer[lexBuffer.BufferScanPos] - - // Find the new state - let snew = lookupUnicodeCharacters state inp - - if snew = sentinel then - lexBuffer.EndOfScan() - else - lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1; - //printf "state %d --> %d on '%c' (%d)\n" s snew (char inp) inp; - scanUntilSentinel lexBuffer snew - - // Each row for the Unicode table has format - // 128 entries for ASCII characters - // A variable number of 2*UInt16 entries for SpecificUnicodeChars - // 30 entries, one for each UnicodeCategory - // 1 entry for EOF - - member tables.Interpret(initialState,lexBuffer : LexBuffer) = - startInterpret(lexBuffer) - scanUntilSentinel lexBuffer initialState - - static member Create(trans,accept) = UnicodeTables(trans,accept) + lexBuffer.BufferScanLength <- lexBuffer.BufferScanLength + 1 + //printf "state %d --> %d on '%c' (%d)\n" s snew (char inp) inp; + scanUntilSentinel lexBuffer snew + + // Each row for the Unicode table has format + // 128 entries for ASCII characters + // A variable number of 2*UInt16 entries for SpecificUnicodeChars + // 30 entries, one for each UnicodeCategory + // 1 entry for EOF + + member tables.Interpret(initialState, lexBuffer: LexBuffer) = + startInterpret (lexBuffer) + scanUntilSentinel lexBuffer initialState + + static member Create(trans, accept) = UnicodeTables(trans, accept) diff --git a/src/Compiler/Facilities/prim-parsing.fs b/src/Compiler/Facilities/prim-parsing.fs index 59243a98a3f..91b00ba592f 100644 --- a/src/Compiler/Facilities/prim-parsing.fs +++ b/src/Compiler/Facilities/prim-parsing.fs @@ -2,7 +2,7 @@ // NOTE: the code in this file is a drop-in replacement runtime for Parsing.fs from the FsLexYacc repository -namespace Internal.Utilities.Text.Parsing +namespace Internal.Utilities.Text.Parsing open Internal.Utilities.Text.Lexing @@ -13,78 +13,89 @@ exception RecoverableParseError exception Accept of obj [] -type internal IParseState(ruleStartPoss:Position[], ruleEndPoss:Position[], lhsPos:Position[], ruleValues:obj[], lexbuf:LexBuffer) = +type internal IParseState + ( + ruleStartPoss: Position[], + ruleEndPoss: Position[], + lhsPos: Position[], + ruleValues: obj[], + lexbuf: LexBuffer + ) = member _.LexBuffer = lexbuf - member _.InputRange index = ruleStartPoss[index-1], ruleEndPoss[index-1] + member _.InputRange index = + ruleStartPoss[index - 1], ruleEndPoss[index - 1] - member _.InputStartPosition index = ruleStartPoss[index-1] + member _.InputStartPosition index = ruleStartPoss[index - 1] - member _.InputEndPosition index = ruleEndPoss[index-1] + member _.InputEndPosition index = ruleEndPoss[index - 1] member _.ResultStartPosition = lhsPos[0] member _.ResultEndPosition = lhsPos[1] - member _.GetInput index = ruleValues[index-1] + member _.GetInput index = ruleValues[index - 1] - member _.ResultRange = (lhsPos[0], lhsPos[1]) + member _.ResultRange = (lhsPos[0], lhsPos[1]) // Side note: this definition coincidentally tests the fairly complex logic associated with an object expression implementing a generic abstract method. - member _.RaiseError() = raise RecoverableParseError + member _.RaiseError() = raise RecoverableParseError /// This context is passed to the error reporter when a syntax error occurs [] type internal ParseErrorContext<'Token> - (//lexbuf: LexBuffer<_>, - stateStack:int list, - parseState: IParseState, - reduceTokens: int list, - currentToken: 'Token option, - reducibleProductions: int list list, - shiftableTokens: int list, - message : string) = + ( + stateStack: int list, + parseState: IParseState, + reduceTokens: int list, + currentToken: 'Token option, + reducibleProductions: int list list, + shiftableTokens: int list, + message: string + ) = - //member _.LexBuffer = lexbuf + //member _.LexBuffer = lexbuf - member _.StateStack = stateStack + member _.StateStack = stateStack - member _.ReduceTokens = reduceTokens + member _.ReduceTokens = reduceTokens - member _.CurrentToken = currentToken + member _.CurrentToken = currentToken - member _.ParseState = parseState + member _.ParseState = parseState - member _.ReducibleProductions = reducibleProductions + member _.ReducibleProductions = reducibleProductions - member _.ShiftTokens = shiftableTokens + member _.ShiftTokens = shiftableTokens - member _.Message = message + member _.Message = message //------------------------------------------------------------------------- -// This is the data structure emitted as code by FSYACC. - -type internal Tables<'Token> = - { reductions: (IParseState -> obj)[] - endOfInputTag: int - tagOfToken: 'Token -> int - dataOfToken: 'Token -> obj - actionTableElements: uint16[] - actionTableRowOffsets: uint16[] - reductionSymbolCounts: uint16[] - immediateActions: uint16[] - gotos: uint16[] - sparseGotoTableRowOffsets: uint16[] - stateToProdIdxsTableElements: uint16[] - stateToProdIdxsTableRowOffsets: uint16[] - productionToNonTerminalTable: uint16[] - - /// For fsyacc.exe, this entry is filled in by context from the generated parser file. If no 'parse_error' function - /// is defined by the user then ParseHelpers.parse_error is used by default (ParseHelpers is opened - /// at the top of the generated parser file) - parseError: ParseErrorContext<'Token> -> unit - numTerminals: int - tagOfErrorTerminal: int } +// This is the data structure emitted as code by FSYACC. + +type internal Tables<'Token> = + { + reductions: (IParseState -> obj)[] + endOfInputTag: int + tagOfToken: 'Token -> int + dataOfToken: 'Token -> obj + actionTableElements: uint16[] + actionTableRowOffsets: uint16[] + reductionSymbolCounts: uint16[] + immediateActions: uint16[] + gotos: uint16[] + sparseGotoTableRowOffsets: uint16[] + stateToProdIdxsTableElements: uint16[] + stateToProdIdxsTableRowOffsets: uint16[] + productionToNonTerminalTable: uint16[] + + /// For fsyacc.exe, this entry is filled in by context from the generated parser file. If no 'parse_error' function + /// is defined by the user then ParseHelpers.parse_error is used by default (ParseHelpers is opened + /// at the top of the generated parser file) + parseError: ParseErrorContext<'Token> -> unit + numTerminals: int + tagOfErrorTerminal: int + } //------------------------------------------------------------------------- // An implementation of stacks. @@ -92,40 +103,47 @@ type internal Tables<'Token> = // This type is in System.dll so for the moment we can't use it in FSharp.Core.dll // type Stack<'a> = System.Collections.Generic.Stack<'a> -type Stack<'a>(n) = - let mutable contents = Array.zeroCreate<'a>(n) +type Stack<'a>(n) = + let mutable contents = Array.zeroCreate<'a> (n) let mutable count = 0 - member buf.Ensure newSize = + member buf.Ensure newSize = let oldSize = contents.Length - if newSize > oldSize then + + if newSize > oldSize then let old = contents contents <- Array.zeroCreate (max newSize (oldSize * 2)) Array.blit old 0 contents 0 count - + member buf.Count = count member buf.Pop() = count <- count - 1 member buf.Peep() = contents[count - 1] - member buf.Top(n) = [ for x in contents[max 0 (count-n)..count - 1] -> x ] |> List.rev + + member buf.Top(n) = + [ for x in contents[max 0 (count - n) .. count - 1] -> x ] |> List.rev + member buf.Push(x) = - buf.Ensure(count + 1) - contents[count] <- x + buf.Ensure(count + 1) + contents[count] <- x count <- count + 1 - + member buf.IsEmpty = (count = 0) - member buf.PrintStack() = - for i = 0 to (count - 1) do - Console.Write("{0}{1}",contents[i],if i=count-1 then ":" else "-") - + member buf.PrintStack() = + for i = 0 to (count - 1) do + Console.Write("{0}{1}", contents[i], (if i = count - 1 then ":" else "-")) + +module Flags = #if DEBUG -module Flags = let mutable debug = false +#else + // Debugging tracing for parsing always off for release code + let debug = false #endif -module internal Implementation = - - // Definitions shared with fsyacc +module internal Implementation = + + // Definitions shared with fsyacc let anyMarker = 0xffff let shiftFlag = 0x0000 let reduceFlag = 0x4000 @@ -133,30 +151,35 @@ module internal Implementation = let acceptFlag = 0xc000 let actionMask = 0xc000 - let actionValue action = action &&& (~~~ actionMask) + let actionValue action = action &&& (~~~actionMask) let actionKind action = action &&& actionMask - + //------------------------------------------------------------------------- - // Read the tables written by FSYACC. + // Read the tables written by FSYACC. type AssocTable(elemTab: uint16[], offsetTab: uint16[], cache: int[], cacheSize: int) = - member t.ReadAssoc (minElemNum,maxElemNum,defaultValueOfAssoc,keyToFind) = - // do a binary chop on the table - let elemNumber : int = (minElemNum+maxElemNum)/2 - if elemNumber = maxElemNum - then defaultValueOfAssoc - else - let x = int elemTab[elemNumber*2] - if keyToFind = x then int elemTab[elemNumber*2+1] - elif keyToFind < x then t.ReadAssoc (minElemNum ,elemNumber,defaultValueOfAssoc,keyToFind) - else t.ReadAssoc (elemNumber+1,maxElemNum,defaultValueOfAssoc,keyToFind) + member t.ReadAssoc(minElemNum, maxElemNum, defaultValueOfAssoc, keyToFind) = + // do a binary chop on the table + let elemNumber: int = (minElemNum + maxElemNum) / 2 + + if elemNumber = maxElemNum then + defaultValueOfAssoc + else + let x = int elemTab[elemNumber * 2] + + if keyToFind = x then + int elemTab[elemNumber * 2 + 1] + elif keyToFind < x then + t.ReadAssoc(minElemNum, elemNumber, defaultValueOfAssoc, keyToFind) + else + t.ReadAssoc(elemNumber + 1, maxElemNum, defaultValueOfAssoc, keyToFind) - member t.Read(rowNumber,keyToFind) = + member t.Read(rowNumber, keyToFind) = // First check the sparse lookaside table // Performance note: without this lookaside table the binary chop in ReadAssoc - // takes up around 10% of of parsing time + // takes up around 10% of of parsing time // for parsing intensive samples such as the bootstrapped F# compiler. // // NOTE: using a .NET Dictionary for this int -> int table looks like it could be sub-optimal. @@ -166,224 +189,253 @@ module internal Implementation = let cacheKey = (rowNumber <<< 16) ||| keyToFind let cacheIdx = (int32 (uint32 cacheKey % uint32 cacheSize)) * 2 let cacheKey2 = cache[cacheIdx] - let v = cache[cacheIdx+1] - if cacheKey = cacheKey2 then v + let v = cache[cacheIdx + 1] + + if cacheKey = cacheKey2 then + v else let headOfTable = int offsetTab[rowNumber] - let firstElemNumber = headOfTable + 1 - let numberOfElementsInAssoc = int elemTab[headOfTable*2] - let defaultValueOfAssoc = int elemTab[headOfTable*2+1] - let res = t.ReadAssoc (firstElemNumber,firstElemNumber+numberOfElementsInAssoc,defaultValueOfAssoc,keyToFind) + let firstElemNumber = headOfTable + 1 + let numberOfElementsInAssoc = int elemTab[headOfTable * 2] + let defaultValueOfAssoc = int elemTab[headOfTable * 2 + 1] + + let res = + t.ReadAssoc(firstElemNumber, firstElemNumber + numberOfElementsInAssoc, defaultValueOfAssoc, keyToFind) + cache[cacheIdx] <- cacheKey - cache[cacheIdx+1] <- res + cache[cacheIdx + 1] <- res res // Read all entries in the association table // Used during error recovery to find all valid entries in the table - member _.ReadAll(n) = + member _.ReadAll(n) = let headOfTable = int offsetTab[n] - let firstElemNumber = headOfTable + 1 - let numberOfElementsInAssoc = int32 elemTab[headOfTable*2] - let defaultValueOfAssoc = int elemTab[headOfTable*2+1] - [ for i in firstElemNumber .. (firstElemNumber+numberOfElementsInAssoc-1) -> - (int elemTab[i*2], int elemTab[i*2+1]) ], defaultValueOfAssoc + let firstElemNumber = headOfTable + 1 + let numberOfElementsInAssoc = int32 elemTab[headOfTable * 2] + let defaultValueOfAssoc = int elemTab[headOfTable * 2 + 1] - type IdxToIdxListTable(elemTab:uint16[], offsetTab:uint16[]) = + [ + for i in firstElemNumber .. (firstElemNumber + numberOfElementsInAssoc - 1) -> (int elemTab[i * 2], int elemTab[i * 2 + 1]) + ], + defaultValueOfAssoc + + type IdxToIdxListTable(elemTab: uint16[], offsetTab: uint16[]) = // Read all entries in a row of the table - member _.ReadAll(n) = + member _.ReadAll(n) = let headOfTable = int offsetTab[n] - let firstElemNumber = headOfTable + 1 - let numberOfElements = int32 elemTab[headOfTable] - [ for i in firstElemNumber .. (firstElemNumber+numberOfElements-1) -> int elemTab[i] ] + let firstElemNumber = headOfTable + 1 + let numberOfElements = int32 elemTab[headOfTable] + + [ + for i in firstElemNumber .. (firstElemNumber + numberOfElements - 1) -> int elemTab[i] + ] //------------------------------------------------------------------------- - // interpret the tables emitted by FSYACC. + // interpret the tables emitted by FSYACC. [] [] - type ValueInfo = + type ValueInfo = val value: obj val startPos: Position val endPos: Position - new(value,startPos,endPos) = { value=value; startPos=startPos;endPos=endPos } - let interpret (tables: Tables<'Token>) lexer (lexbuf : LexBuffer<_>) initialState = -#if DEBUG - if Flags.debug then Console.WriteLine("\nParser: interpret tables") -#endif - let stateStack : Stack = Stack<_>(100) + new(value, startPos, endPos) = + { + value = value + startPos = startPos + endPos = endPos + } + + let interpret (tables: Tables<'Token>) lexer (lexbuf: LexBuffer<_>) initialState = + if Flags.debug then + Console.WriteLine("\nParser: interpret tables") + + let stateStack: Stack = Stack<_>(100) stateStack.Push(initialState) let valueStack = Stack(100) - let mutable haveLookahead = false + let mutable haveLookahead = false let mutable lookaheadToken = Unchecked.defaultof<'Token> let mutable lookaheadEndPos = Unchecked.defaultof let mutable lookaheadStartPos = Unchecked.defaultof let mutable finished = false // After an error occurs, we suppress errors until we've shifted three tokens in a row. let mutable errorSuppressionCountDown = 0 - + // When we hit the end-of-file we don't fail straight away but rather keep permitting shift // and reduce against the last token in the token stream 20 times or until we've accepted // or exhausted the stack. This allows error recovery rules of the form // input : realInput EOF | realInput error EOF | error EOF - // where consuming one EOF to trigger an error doesn't result in overall parse failure + // where consuming one EOF to trigger an error doesn't result in overall parse failure // catastrophe and the loss of intermediate results. // let mutable inEofCountDown = false let mutable eofCountDown = 20 // Number of EOFs to supply at the end for error recovery // The 100 here means a maximum of 100 elements for each rule - let ruleStartPoss = (Array.zeroCreate 100 : Position[]) - let ruleEndPoss = (Array.zeroCreate 100 : Position[]) - let ruleValues = (Array.zeroCreate 100 : obj[]) - let lhsPos = (Array.zeroCreate 2 : Position[]) + let ruleStartPoss = (Array.zeroCreate 100: Position[]) + let ruleEndPoss = (Array.zeroCreate 100: Position[]) + let ruleValues = (Array.zeroCreate 100: obj[]) + let lhsPos = (Array.zeroCreate 2: Position[]) let reductions = tables.reductions let cacheSize = 7919 // the 1000'th prime // Use a simpler hash table with faster lookup, but only one // hash bucket per key. - let actionTableCache = ArrayPool.Shared.Rent(cacheSize * 2) - let gotoTableCache = ArrayPool.Shared.Rent(cacheSize * 2) + let actionTableCache = ArrayPool.Shared.Rent (cacheSize * 2) + let gotoTableCache = ArrayPool.Shared.Rent (cacheSize * 2) // Clear the arrays since ArrayPool does not Array.Clear(actionTableCache, 0, actionTableCache.Length) Array.Clear(gotoTableCache, 0, gotoTableCache.Length) - use _cacheDisposal = - { new IDisposable with - member _.Dispose() = + + use _cacheDisposal = + { new IDisposable with + member _.Dispose() = ArrayPool.Shared.Return actionTableCache - ArrayPool.Shared.Return gotoTableCache } - let actionTable = AssocTable(tables.actionTableElements, tables.actionTableRowOffsets, actionTableCache, cacheSize) - let gotoTable = AssocTable(tables.gotos, tables.sparseGotoTableRowOffsets, gotoTableCache, cacheSize) - let stateToProdIdxsTable = IdxToIdxListTable(tables.stateToProdIdxsTableElements, tables.stateToProdIdxsTableRowOffsets) + ArrayPool.Shared.Return gotoTableCache + } - let parseState = - IParseState(ruleStartPoss,ruleEndPoss,lhsPos,ruleValues,lexbuf) + let actionTable = + AssocTable(tables.actionTableElements, tables.actionTableRowOffsets, actionTableCache, cacheSize) -#if DEBUG - let report haveLookahead lookaheadToken = - if haveLookahead then sprintf "%+A" lookaheadToken - else "[TBC]" -#endif + let gotoTable = + AssocTable(tables.gotos, tables.sparseGotoTableRowOffsets, gotoTableCache, cacheSize) + + let stateToProdIdxsTable = + IdxToIdxListTable(tables.stateToProdIdxsTableElements, tables.stateToProdIdxsTableRowOffsets) + + let parseState = IParseState(ruleStartPoss, ruleEndPoss, lhsPos, ruleValues, lexbuf) + + let report haveLookahead lookaheadToken = + if haveLookahead then + sprintf "%+A" lookaheadToken + else + "[TBC]" // Pop the stack until we can shift the 'error' token. If 'tokenOpt' is given // then keep popping until we can shift both the 'error' token and the token in 'tokenOpt'. // This is used at end-of-file to make sure we can shift both the 'error' token and the 'EOF' token. let rec popStackUntilErrorShifted tokenOpt = // Keep popping the stack until the "error" terminal is shifted -#if DEBUG - if Flags.debug then Console.WriteLine("popStackUntilErrorShifted") -#endif - if stateStack.IsEmpty then -#if DEBUG - if Flags.debug then + if Flags.debug then + Console.WriteLine("popStackUntilErrorShifted") + + if stateStack.IsEmpty then + if Flags.debug then Console.WriteLine("state stack empty during error recovery - generating parse error") -#endif + failwith "parse error" - + let currState = stateStack.Peep() -#if DEBUG - if Flags.debug then + + if Flags.debug then Console.WriteLine("In state {0} during error recovery", currState) -#endif - + let action = actionTable.Read(currState, tables.tagOfErrorTerminal) - - if actionKind action = shiftFlag && - (match tokenOpt with - | None -> true - | Some(token) -> - let nextState = actionValue action - actionKind (actionTable.Read(nextState, tables.tagOfToken(token))) = shiftFlag) then -#if DEBUG - if Flags.debug then Console.WriteLine("shifting error, continuing with error recovery") -#endif - let nextState = actionValue action + if actionKind action = shiftFlag + && (match tokenOpt with + | None -> true + | Some (token) -> + let nextState = actionValue action + actionKind (actionTable.Read(nextState, tables.tagOfToken (token))) = shiftFlag) then + + if Flags.debug then + Console.WriteLine("shifting error, continuing with error recovery") + + let nextState = actionValue action // The "error" non terminal needs position information, though it tends to be unreliable. // Use the StartPos/EndPos from the lex buffer. valueStack.Push(ValueInfo(box (), lexbuf.StartPos, lexbuf.EndPos)) stateStack.Push(nextState) else - if valueStack.IsEmpty then - failwith "parse error" -#if DEBUG - if Flags.debug then + if valueStack.IsEmpty then failwith "parse error" + + if Flags.debug then Console.WriteLine("popping stack during error recovery") -#endif + valueStack.Pop() stateStack.Pop() - popStackUntilErrorShifted(tokenOpt) + popStackUntilErrorShifted (tokenOpt) - while not finished do - if stateStack.IsEmpty then + while not finished do + if stateStack.IsEmpty then finished <- true else let state = stateStack.Peep() -#if DEBUG - if Flags.debug then (Console.Write("{0} value(state), state ",valueStack.Count); stateStack.PrintStack()) -#endif - let action = + + if Flags.debug then + (Console.Write("{0} value(state), state ", valueStack.Count) + stateStack.PrintStack()) + + let action = let immediateAction = int tables.immediateActions[state] + if not (immediateAction = anyMarker) then - // Action has been pre-determined, no need to lookahead - // Expecting it to be a Reduce action on a non-fakeStartNonTerminal ? + // Action has been pre-determined, no need to lookahead + // Expecting it to be a Reduce action on a non-fakeStartNonTerminal ? immediateAction else - // Lookahead required to determine action - if not haveLookahead then - if lexbuf.IsPastEndOfStream then + // Lookahead required to determine action + if not haveLookahead then + if lexbuf.IsPastEndOfStream then // When the input runs out, keep supplying the last token for eofCountDown times - if eofCountDown>0 then + if eofCountDown > 0 then haveLookahead <- true eofCountDown <- eofCountDown - 1 inEofCountDown <- true - else + else haveLookahead <- false - else + else lookaheadToken <- lexer lexbuf lookaheadStartPos <- lexbuf.StartPos lookaheadEndPos <- lexbuf.EndPos haveLookahead <- true - let tag = - if haveLookahead then tables.tagOfToken lookaheadToken - else tables.endOfInputTag - - // printf "state %d\n" state - actionTable.Read(state,tag) - - let kind = actionKind action - if kind = shiftFlag then ( - if errorSuppressionCountDown > 0 then - errorSuppressionCountDown <- errorSuppressionCountDown - 1 -#if DEBUG - if Flags.debug then Console.WriteLine("shifting, reduced errorRecoveryLevel to {0}\n", errorSuppressionCountDown) -#endif - let nextState = actionValue action - if not haveLookahead then failwith "shift on end of input!" - let data = tables.dataOfToken lookaheadToken - valueStack.Push(ValueInfo(data, lookaheadStartPos, lookaheadEndPos)) - stateStack.Push(nextState) -#if DEBUG - if Flags.debug then Console.WriteLine("shift/consume input {0}, shift to state {1}", report haveLookahead lookaheadToken, nextState) -#endif - haveLookahead <- false + let tag = + if haveLookahead then + tables.tagOfToken lookaheadToken + else + tables.endOfInputTag + + // printf "state %d\n" state + actionTable.Read(state, tag) + + let kind = actionKind action - ) elif kind = reduceFlag then - let prod = actionValue action - let reduction = reductions[prod] + if kind = shiftFlag then + (if errorSuppressionCountDown > 0 then + errorSuppressionCountDown <- errorSuppressionCountDown - 1 + + if Flags.debug then + Console.WriteLine("shifting, reduced errorRecoveryLevel to {0}\n", errorSuppressionCountDown) + + let nextState = actionValue action + if not haveLookahead then failwith "shift on end of input!" + let data = tables.dataOfToken lookaheadToken + valueStack.Push(ValueInfo(data, lookaheadStartPos, lookaheadEndPos)) + stateStack.Push(nextState) + + if Flags.debug then + Console.WriteLine("shift/consume input {0}, shift to state {1}", report haveLookahead lookaheadToken, nextState) + + haveLookahead <- false + + ) + elif kind = reduceFlag then + let prod = actionValue action + let reduction = reductions[prod] let n = int tables.reductionSymbolCounts[prod] - // pop the symbols, populate the values and populate the locations -#if DEBUG - if Flags.debug then Console.Write("reduce popping {0} values/states, lookahead {1}", n, report haveLookahead lookaheadToken) -#endif + // pop the symbols, populate the values and populate the locations + if Flags.debug then + Console.Write("reduce popping {0} values/states, lookahead {1}", n, report haveLookahead lookaheadToken) // For every range to reduce merge it for i = 0 to n - 1 do if valueStack.IsEmpty then failwith "empty symbol stack" - let topVal = valueStack.Peep() // Grab topVal + let topVal = valueStack.Peep() // Grab topVal valueStack.Pop() stateStack.Pop() - let ruleIndex = (n-i)-1 + let ruleIndex = (n - i) - 1 ruleValues[ruleIndex] <- topVal.value ruleStartPoss[ruleIndex] <- topVal.startPos ruleEndPoss[ruleIndex] <- topVal.endPos @@ -392,124 +444,136 @@ module internal Implementation = // Initial range lhsPos[0] <- topVal.startPos lhsPos[1] <- topVal.endPos - elif topVal.startPos.FileIndex = lhsPos[1].FileIndex && topVal.startPos.Line <= lhsPos[1].Line then + elif topVal.startPos.FileIndex = lhsPos[1].FileIndex + && topVal.startPos.Line <= lhsPos[1].Line then // Reduce range if same file as the initial end point lhsPos[0] <- topVal.startPos // Use the lookahead token to populate the locations if the rhs is empty if n = 0 then - if haveLookahead then - lhsPos[0] <- lookaheadStartPos - lhsPos[1] <- lookaheadEndPos - else - lhsPos[0] <- lexbuf.StartPos - lhsPos[1] <- lexbuf.EndPos + if haveLookahead then + lhsPos[0] <- lookaheadStartPos + lhsPos[1] <- lookaheadEndPos + else + lhsPos[0] <- lexbuf.StartPos + lhsPos[1] <- lexbuf.EndPos + try - // printf "reduce %d\n" prod + // printf "reduce %d\n" prod let redResult = reduction parseState let valueInfo = ValueInfo(redResult, lhsPos[0], lhsPos[1]) valueStack.Push(valueInfo) let currState = stateStack.Peep() - let newGotoState = gotoTable.Read(int tables.productionToNonTerminalTable[prod], currState) + + let newGotoState = + gotoTable.Read(int tables.productionToNonTerminalTable[prod], currState) + stateStack.Push(newGotoState) -#if DEBUG - if Flags.debug then Console.WriteLine(" goto state {0}", newGotoState) -#endif + if Flags.debug then + Console.WriteLine(" goto state {0}", newGotoState) with | Accept res -> - finished <- true - valueStack.Push(ValueInfo(res, lhsPos[0], lhsPos[1])) + finished <- true + valueStack.Push(ValueInfo(res, lhsPos[0], lhsPos[1])) | RecoverableParseError -> -#if DEBUG - if Flags.debug then Console.WriteLine("RecoverableParseErrorException...\n") -#endif - popStackUntilErrorShifted(None) - // User code raised a Parse_error. Don't report errors again until three tokens have been shifted - errorSuppressionCountDown <- 3 - elif kind = errorFlag then ( -#if DEBUG - if Flags.debug then Console.Write("ErrorFlag... ") -#endif - // Silently discard inputs and don't report errors - // until three tokens in a row have been shifted -#if DEBUG - if Flags.debug then printfn "error on token '%s' " (report haveLookahead lookaheadToken) -#endif - if errorSuppressionCountDown > 0 then - // If we're in the end-of-file count down then we're very keen to 'Accept'. - // We can only do this by repeatedly popping the stack until we can shift both an 'error' token - // and an EOF token. - if inEofCountDown && eofCountDown < 10 then -#if DEBUG - if Flags.debug then printfn "popping stack, looking to shift both 'error' and that token, during end-of-file error recovery" -#endif - popStackUntilErrorShifted(if haveLookahead then Some(lookaheadToken) else None) + if Flags.debug then + Console.WriteLine("RecoverableParseErrorException...\n") - // If we don't haveLookahead then the end-of-file count down is over and we have no further options. - if not haveLookahead then - failwith "parse error: unexpected end of file" - -#if DEBUG - if Flags.debug then printfn "discarding token '%s' during error suppression" (report haveLookahead lookaheadToken) -#endif - // Discard the token - haveLookahead <- false - // Try again to shift three tokens + popStackUntilErrorShifted (None) + // User code raised a Parse_error. Don't report errors again until three tokens have been shifted errorSuppressionCountDown <- 3 - else ( - - let currentToken = if haveLookahead then Some(lookaheadToken) else None - let actions,defaultAction = actionTable.ReadAll(state) - let explicit = Set.ofList [ for tag,_action in actions -> tag ] - - let shiftableTokens = - [ for tag,action in actions do - if (actionKind action) = shiftFlag then - yield tag - if actionKind defaultAction = shiftFlag then - for tag in 0 .. tables.numTerminals-1 do - if not (explicit.Contains(tag)) then - yield tag ] in - - let stateStack = stateStack.Top(12) in - let reducibleProductions = - [ for state in stateStack do - yield stateToProdIdxsTable.ReadAll(state) ] - - let reduceTokens = - [ for tag,action in actions do - if actionKind(action) = reduceFlag then - yield tag - if actionKind(defaultAction) = reduceFlag then - for tag in 0 .. tables.numTerminals-1 do - if not (explicit.Contains(tag)) then - yield tag ] in - //let activeRules = stateStack |> List.iter (fun state -> - let errorContext = new ParseErrorContext<'Token>(stateStack, parseState, reduceTokens, currentToken, reducibleProductions, shiftableTokens, "syntax error") - tables.parseError(errorContext) - popStackUntilErrorShifted(None) - errorSuppressionCountDown <- 3 -#if DEBUG - if Flags.debug then Console.WriteLine("generated syntax error and shifted error token, haveLookahead = {0}\n", haveLookahead) -#endif - ) - ) elif kind = acceptFlag then + elif kind = errorFlag then + (if Flags.debug then Console.Write("ErrorFlag... ") + // Silently discard inputs and don't report errors + // until three tokens in a row have been shifted + if Flags.debug then + printfn "error on token '%s' " (report haveLookahead lookaheadToken) + + if errorSuppressionCountDown > 0 then + // If we're in the end-of-file count down then we're very keen to 'Accept'. + // We can only do this by repeatedly popping the stack until we can shift both an 'error' token + // and an EOF token. + if inEofCountDown && eofCountDown < 10 then + if Flags.debug then + printfn "popping stack, looking to shift both 'error' and that token, during end-of-file error recovery" + + popStackUntilErrorShifted (if haveLookahead then Some(lookaheadToken) else None) + + // If we don't haveLookahead then the end-of-file count down is over and we have no further options. + if not haveLookahead then + failwith "parse error: unexpected end of file" + + if Flags.debug then + printfn "discarding token '%s' during error suppression" (report haveLookahead lookaheadToken) + // Discard the token + haveLookahead <- false + // Try again to shift three tokens + errorSuppressionCountDown <- 3 + else + ( + + let currentToken = if haveLookahead then Some(lookaheadToken) else None + let actions, defaultAction = actionTable.ReadAll(state) + let explicit = Set.ofList [ for tag, _action in actions -> tag ] + + let shiftableTokens = + [ + for tag, action in actions do + if (actionKind action) = shiftFlag then yield tag + if actionKind defaultAction = shiftFlag then + for tag in 0 .. tables.numTerminals - 1 do + if not (explicit.Contains(tag)) then yield tag + ] + + let stateStack = stateStack.Top(12) + + let reducibleProductions = + [ + for state in stateStack do + yield stateToProdIdxsTable.ReadAll(state) + ] + + let reduceTokens = + [ + for tag, action in actions do + if actionKind (action) = reduceFlag then yield tag + if actionKind (defaultAction) = reduceFlag then + for tag in 0 .. tables.numTerminals - 1 do + if not (explicit.Contains(tag)) then yield tag + ] + //let activeRules = stateStack |> List.iter (fun state -> + let errorContext = + new ParseErrorContext<'Token>( + stateStack, + parseState, + reduceTokens, + currentToken, + reducibleProductions, + shiftableTokens, + "syntax error" + ) + + tables.parseError (errorContext) + popStackUntilErrorShifted (None) + errorSuppressionCountDown <- 3 + + if Flags.debug then + Console.WriteLine("generated syntax error and shifted error token, haveLookahead = {0}\n", haveLookahead))) + elif kind = acceptFlag then finished <- true -#if DEBUG - else - if Flags.debug then Console.WriteLine("ALARM!!! drop through case in parser") -#endif - done + else if Flags.debug then + Console.WriteLine("ALARM!!! drop through case in parser") // OK, we're done - read off the overall generated value valueStack.Peep().value type internal Tables<'Token> with - member tables.Interpret (lexer, lexbuf, initialState) = + + member tables.Interpret(lexer, lexbuf, initialState) = Implementation.interpret tables lexer lexbuf initialState - -module internal ParseHelpers = - let parse_error (_s:string) = () +module internal ParseHelpers = + + let parse_error (_s: string) = () - let parse_error_rich = (None : (ParseErrorContext<_> -> unit) option) + let parse_error_rich = (None: (ParseErrorContext<_> -> unit) option) diff --git a/src/Compiler/Facilities/prim-parsing.fsi b/src/Compiler/Facilities/prim-parsing.fsi index 50ebcc95029..4177d66e9a9 100644 --- a/src/Compiler/Facilities/prim-parsing.fsi +++ b/src/Compiler/Facilities/prim-parsing.fsi @@ -123,9 +123,11 @@ exception internal Accept of obj /// Indicates a parse error has occurred and parse recovery is in progress. exception internal RecoverableParseError -#if DEBUG module internal Flags = +#if DEBUG val mutable debug : bool +#else + val debug : bool #endif /// Helpers used by generated parsers. diff --git a/src/Compiler/Interactive/ControlledExecution.fs b/src/Compiler/Interactive/ControlledExecution.fs new file mode 100644 index 00000000000..5ec0e929c0c --- /dev/null +++ b/src/Compiler/Interactive/ControlledExecution.fs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +// This wraps System.Runtime.CompilerServices.ControlledExecution +// This class enables scripting engines such as Fsi to abort threads safely in the coreclr +// This functionality will be introduced in .net 7.0. +// because we continue to dupport older coreclrs and the windows desktop framework through netstandard2.0 +// we access the features using reflection + +namespace FSharp.Compiler.Interactive + +open System +open System.Reflection +open System.Threading + +open Internal.Utilities.FSharpEnvironment + +type internal ControlledExecution (thread:Thread) = + + static let ceType: Type option = + Option.ofObj (Type.GetType("System.Runtime.CompilerServices.ControlledExecution, System.Private.CoreLib", false)) + + static let threadType: Type option = + Option.ofObj (typeof) + + static let ceConstructor: ConstructorInfo option = + match ceType with + | None -> None + | Some t -> Option.ofObj (t.GetConstructor([|typeof|])) + + static let ceRun: MethodInfo option = + match ceType with + | None -> None + | Some t -> Option.ofObj (t.GetMethod("Run", [||]) ) + + static let ceTryAbort: MethodInfo option = + match ceType with + | None -> None + | Some t -> Option.ofObj (t.GetMethod("TryAbort", [|typeof|])) + + static let threadResetAbort: MethodInfo option = + match isRunningOnCoreClr, threadType with + | false, Some t -> Option.ofObj (t.GetMethod("ResetAbort", [||])) + | _ -> None + + let newInstance (action: Action) = + match ceConstructor with + | None -> None + | Some c -> Option.ofObj (c.Invoke([|action|])) + + let mutable instance = Unchecked.defaultof + + member this.Run(action: Action) = + let newinstance = newInstance(action) + match newinstance, ceRun with + | Some inst, Some ceRun -> + instance <- newinstance + ceRun.Invoke(inst, [||]) |> ignore + | _ -> action.Invoke() + + member _.TryAbort(timeout: TimeSpan): bool = + match isRunningOnCoreClr, instance, ceTryAbort with + | _, Some instance, Some tryAbort -> tryAbort.Invoke(instance, [|timeout|]) :?> bool + | false, _, _ -> thread.Abort(); true + | true, _, _ -> true + + member _.ResetAbort() = + match thread, threadResetAbort with + | thread, Some threadResetAbort -> threadResetAbort.Invoke(thread, [||]) |> ignore + | _ -> () + + static member StripTargetInvocationException(exn: Exception) = + match exn with + | :? TargetInvocationException as e when not(isNull e.InnerException) -> + ControlledExecution.StripTargetInvocationException(e.InnerException) + | _ -> exn diff --git a/src/Compiler/Interactive/FSIstrings.txt b/src/Compiler/Interactive/FSIstrings.txt index 74f278cd303..2d41ffcc406 100644 --- a/src/Compiler/Interactive/FSIstrings.txt +++ b/src/Compiler/Interactive/FSIstrings.txt @@ -57,4 +57,5 @@ fsiOperationCouldNotBeCompleted,"Operation could not be completed due to earlier fsiOperationFailed,"Operation failed. The error text has been printed in the error stream. To return the corresponding FSharpDiagnostic use the EvalInteractionNonThrowing, EvalScriptNonThrowing or EvalExpressionNonThrowing" fsiMultiAssemblyEmitOption,"Emit multiple assemblies (on by default)" fsiMultiAssemblyEmitOptionOffByDefault,"Emit multiple assemblies (off by default for .NET Framework)" -2303,fsiInternalAccess,"Accessing the internal type, method or field '%s' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option." \ No newline at end of file +2303,fsiInternalAccess,"Accessing the internal type, method or field '%s' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option." +2304,fsiEntryPointWontBeInvoked,"Functions with [] are not invoked in FSI. '%s' was not invoked. Execute '%s ' in order to invoke '%s' with the appropriate string array of command line arguments." diff --git a/src/Compiler/Interactive/fsi.fs b/src/Compiler/Interactive/fsi.fs index 0cbade7c234..5d8966fd9a1 100644 --- a/src/Compiler/Interactive/fsi.fs +++ b/src/Compiler/Interactive/fsi.fs @@ -47,6 +47,7 @@ open FSharp.Compiler.EditorServices open FSharp.Compiler.DiagnosticsLogger open FSharp.Compiler.Features open FSharp.Compiler.IlxGen +open FSharp.Compiler.Interactive open FSharp.Compiler.InfoReader open FSharp.Compiler.IO open FSharp.Compiler.Lexhelp @@ -989,6 +990,8 @@ type internal FsiCommandLineOptions(fsi: FsiEvaluationSessionHostConfig, let dependencyProvider = new DependencyProvider(NativeResolutionProbe(tcConfigB.GetNativeProbingRoots)) do + if tcConfigB.clearResultsCache then + dependencyProvider.ClearResultsCache(tcConfigB.compilerToolPaths, getOutputDir tcConfigB, reportError rangeCmdArgs) if tcConfigB.utf8output then let prev = Console.OutputEncoding Console.OutputEncoding <- Encoding.UTF8 @@ -1646,6 +1649,30 @@ type internal FsiDynamicCompiler( diagnosticsLogger.AbortOnError(fsiConsoleOutput) codegenResults, optEnv, fragName + /// Check FSI entries for the presence of EntryPointAttribute and issue a warning if it's found + let CheckEntryPoint (tcGlobals: TcGlobals) (declaredImpls: CheckedImplFile list) = + let tryGetEntryPoint (TBind (var = value)) = + TryFindFSharpAttribute tcGlobals tcGlobals.attrib_EntryPointAttribute value.Attribs + |> Option.map (fun attrib -> value.DisplayName, attrib) + + let rec findEntryPointInContents = function + | TMDefLet (binding = binding) -> tryGetEntryPoint binding + | TMDefs defs -> defs |> List.tryPick findEntryPointInContents + | TMDefRec (bindings = bindings) -> bindings |> List.tryPick findEntryPointInBinding + | _ -> None + + and findEntryPointInBinding = function + | ModuleOrNamespaceBinding.Binding binding -> tryGetEntryPoint binding + | ModuleOrNamespaceBinding.Module (moduleOrNamespaceContents = contents) -> findEntryPointInContents contents + + let entryPointBindings = + declaredImpls + |> Seq.where (fun implFile -> implFile.HasExplicitEntryPoint) + |> Seq.choose (fun implFile -> implFile.Contents |> findEntryPointInContents) + + for name, attrib in entryPointBindings do + warning(Error(FSIstrings.SR.fsiEntryPointWontBeInvoked(name, name, name), attrib.Range)) + let ProcessInputs (ctok, diagnosticsLogger: DiagnosticsLogger, istate: FsiDynamicCompilerState, inputs: ParsedInput list, showTypes: bool, isIncrementalFragment: bool, isInteractiveItExpr: bool, prefixPath: LongIdent, m) = let optEnv = istate.optEnv let tcState = istate.tcState @@ -1660,6 +1687,8 @@ type internal FsiDynamicCompiler( let codegenResults, optEnv, fragName = ProcessTypedImpl(diagnosticsLogger, optEnv, tcState, tcConfig, isInteractiveItExpr, topCustomAttrs, prefixPath, isIncrementalFragment, declaredImpls, ilxGenerator) let newState, declaredImpls = ProcessCodegenResults(ctok, diagnosticsLogger, istate, optEnv, tcState, tcConfig, prefixPath, showTypes, isIncrementalFragment, fragName, declaredImpls, ilxGenerator, codegenResults, m) + + CheckEntryPoint istate.tcGlobals declaredImpls (newState, tcEnvAtEndOfLastInput, declaredImpls) @@ -1785,9 +1814,9 @@ type internal FsiDynamicCompiler( ilTy |> Morphs.morphILTypeRefsInILType emEnv.ReverseMapTypeRef | _ -> ilTy) - ((istate, []), ilTys) ||> List.fold (fun (state, addedTypes) ilTy -> - let nextState, addedType = addTypeToEnvironment state ilTy - nextState, addedTypes @ [addedType]) + ((istate, []), ilTys) ||> List.fold (fun (state, addedTys) ilTy -> + let nextState, addedTy = addTypeToEnvironment state ilTy + nextState, addedTys @ [addedTy]) member _.DynamicAssemblies = dynamicAssemblies.ToArray() @@ -1810,7 +1839,7 @@ type internal FsiDynamicCompiler( let m = match defs with [] -> rangeStdin0 | _ -> List.reduce unionRanges [for d in defs -> d.Range] let prefix = mkFragmentPath m i let prefixPath = pathOfLid prefix - let impl = SynModuleOrNamespace(prefix,(*isRec*)false, SynModuleOrNamespaceKind.NamedModule,defs,PreXmlDoc.Empty,[],None,m, { ModuleKeyword = None; NamespaceKeyword = None }) + let impl = SynModuleOrNamespace(prefix,false, SynModuleOrNamespaceKind.NamedModule,defs,PreXmlDoc.Empty,[],None,m, { ModuleKeyword = None; NamespaceKeyword = None }) let isLastCompiland = true let isExe = false let input = ParsedInput.ImplFile (ParsedImplFileInput (fileName,true, ComputeQualifiedNameOfFileFromUniquePath (m,prefixPath),[],[],[impl],(isLastCompiland, isExe), { ConditionalDirectives = []; CodeComments = [] })) @@ -2030,7 +2059,7 @@ type internal FsiDynamicCompiler( input.MetaCommandDiagnostics |> List.iter diagnosticSink let parsedInput = match input.SyntaxTree with - | None -> ParseOneInputFile(tcConfig, lexResourceManager, input.FileName, (true, false), diagnosticsLogger, (*retryLocked*)false) + | None -> ParseOneInputFile(tcConfig, lexResourceManager, input.FileName, (true, false), diagnosticsLogger, false) | Some parseTree -> parseTree input.FileName, parsedInput) |> List.unzip @@ -2180,7 +2209,10 @@ type internal FsiInterruptControllerKillerThreadRequest = | ExitRequest | PrintInterruptRequest -type internal FsiInterruptController(fsiOptions: FsiCommandLineOptions, fsiConsoleOutput: FsiConsoleOutput) = +type internal FsiInterruptController( + fsiOptions: FsiCommandLineOptions, + controlledExecution: ControlledExecution, + fsiConsoleOutput: FsiConsoleOutput) = let mutable stdinInterruptState = StdinNormal let CTRL_C = 0 @@ -2212,7 +2244,12 @@ type internal FsiInterruptController(fsiOptions: FsiCommandLineOptions, fsiConso member _.EventHandlers = ctrlEventHandlers - member controller.InstallKillThread(threadToKill:Thread, pauseMilliseconds:int) = + member _.ControlledExecution() = controlledExecution + + member controller.InstallKillThread() = + // Compute how long to pause before a ThreadAbort is actually executed. + // A somewhat arbitrary choice. + let pauseMilliseconds = (if fsiOptions.Gui then 400 else 100) // Fsi Interrupt handler let raiseCtrlC() = @@ -2231,8 +2268,11 @@ type internal FsiInterruptController(fsiOptions: FsiCommandLineOptions, fsiConso if killThreadRequest = ThreadAbortRequest then if progress then fsiConsoleOutput.uprintnfn "%s" (FSIstrings.SR.fsiAbortingMainThread()) killThreadRequest <- NoRequest - threadToKill.Abort() - ()),Name="ControlCAbortThread") + let rec abortLoop n = + if n > 0 then + if not (controlledExecution.TryAbort(TimeSpan.FromSeconds(30))) then abortLoop (n-1) + abortLoop 3 + ()), Name="ControlCAbortThread") killerThread.IsBackground <- true killerThread.Start() @@ -2825,24 +2865,35 @@ type FsiInteractionProcessor /// Execute a single parsed interaction on the parser/execute thread. let mainThreadProcessAction ctok action istate = try - let tcConfig = TcConfig.Create(tcConfigB,validate=false) - if progress then fprintfn fsiConsoleOutput.Out "In mainThreadProcessAction..."; - fsiInterruptController.InterruptAllowed <- InterruptCanRaiseException; - let res = action ctok tcConfig istate - fsiInterruptController.ClearInterruptRequest() - fsiInterruptController.InterruptAllowed <- InterruptIgnored; - res + let mutable result = Unchecked.defaultof<'a * FsiInteractionStepStatus> + fsiInterruptController.ControlledExecution().Run( + fun () -> + let tcConfig = TcConfig.Create(tcConfigB,validate=false) + if progress then fprintfn fsiConsoleOutput.Out "In mainThreadProcessAction..." + fsiInterruptController.InterruptAllowed <- InterruptCanRaiseException; + let res = action ctok tcConfig istate + fsiInterruptController.ClearInterruptRequest() + fsiInterruptController.InterruptAllowed <- InterruptIgnored + result <- res) + result with | :? ThreadAbortException -> - fsiInterruptController.ClearInterruptRequest() - fsiInterruptController.InterruptAllowed <- InterruptIgnored; - (try Thread.ResetAbort() with _ -> ()); - (istate,CtrlC) + fsiInterruptController.ClearInterruptRequest() + fsiInterruptController.InterruptAllowed <- InterruptIgnored + fsiInterruptController.ControlledExecution().ResetAbort() + (istate,CtrlC) + + | :? TargetInvocationException as e when (ControlledExecution.StripTargetInvocationException(e)).GetType().Name = "ThreadAbortException" -> + fsiInterruptController.ClearInterruptRequest() + fsiInterruptController.InterruptAllowed <- InterruptIgnored + fsiInterruptController.ControlledExecution().ResetAbort() + (istate,CtrlC) + | e -> - fsiInterruptController.ClearInterruptRequest() - fsiInterruptController.InterruptAllowed <- InterruptIgnored; - stopProcessingRecovery e range0; - istate, CompletedWithReportedError e + fsiInterruptController.ClearInterruptRequest() + fsiInterruptController.InterruptAllowed <- InterruptIgnored; + stopProcessingRecovery e range0; + istate, CompletedWithReportedError e let mainThreadProcessParsedInteractions ctok diagnosticsLogger (action, istate) cancellationToken = istate |> mainThreadProcessAction ctok (fun ctok tcConfig istate -> @@ -3152,27 +3203,32 @@ let internal SpawnInteractiveServer /// Repeatedly drive the event loop (e.g. Application.Run()) but catching ThreadAbortException and re-running. /// /// This gives us a last chance to catch an abort on the main execution thread. -let internal DriveFsiEventLoop (fsi: FsiEvaluationSessionHostConfig, fsiConsoleOutput: FsiConsoleOutput) = +let internal DriveFsiEventLoop (fsi: FsiEvaluationSessionHostConfig, fsiInterruptController: FsiInterruptController, fsiConsoleOutput: FsiConsoleOutput) = + + if progress then fprintfn fsiConsoleOutput.Out "GUI thread runLoop" + fsiInterruptController.InstallKillThread() + let rec runLoop() = - if progress then fprintfn fsiConsoleOutput.Out "GUI thread runLoop"; + let restart = try - // BLOCKING POINT: The GUI Thread spends most (all) of its time this event loop - if progress then fprintfn fsiConsoleOutput.Out "MAIN: entering event loop..."; - fsi.EventLoopRun() + fsi.EventLoopRun() with - | :? ThreadAbortException -> + | :? TargetInvocationException as e when (ControlledExecution.StripTargetInvocationException(e)).GetType().Name = "ThreadAbortException" -> // If this TAE handler kicks it's almost certainly too late to save the // state of the process - the state of the message loop may have been corrupted - fsiConsoleOutput.uprintnfn "%s" (FSIstrings.SR.fsiUnexpectedThreadAbortException()); - (try Thread.ResetAbort() with _ -> ()); + fsiInterruptController.ControlledExecution().ResetAbort() true - // Try again, just case we can restart - | e -> - stopProcessingRecovery e range0; + | :? ThreadAbortException -> + // If this TAE handler kicks it's almost certainly too late to save the + // state of the process - the state of the message loop may have been corrupted + fsiInterruptController.ControlledExecution().ResetAbort() true - // Try again, just case we can restart - if progress then fprintfn fsiConsoleOutput.Out "MAIN: exited event loop..."; + | e -> + stopProcessingRecovery e range0 + true + // Try again, just case we can restart + if progress then fprintfn fsiConsoleOutput.Out "MAIN: exited event loop..." if restart then runLoop() runLoop(); @@ -3352,7 +3408,9 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i let fsiDynamicCompiler = FsiDynamicCompiler(fsi, timeReporter, tcConfigB, tcLockObject, outWriter, tcImports, tcGlobals, fsiOptions, fsiConsoleOutput, fsiCollectible, niceNameGen, resolveAssemblyRef) - let fsiInterruptController = FsiInterruptController(fsiOptions, fsiConsoleOutput) + let controlledExecution = ControlledExecution(Thread.CurrentThread) + + let fsiInterruptController = FsiInterruptController(fsiOptions, controlledExecution, fsiConsoleOutput) let uninstallMagicAssemblyResolution = MagicAssemblyResolution.Install(tcConfigB, tcImports, fsiDynamicCompiler, fsiConsoleOutput) @@ -3612,14 +3670,6 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i if fsiOptions.Interact then // page in the type check env fsiInteractionProcessor.LoadDummyInteraction(ctokStartup, diagnosticsLogger) - if progress then fprintfn fsiConsoleOutput.Out "MAIN: InstallKillThread!"; - - // Compute how long to pause before a ThreadAbort is actually executed. - // A somewhat arbitrary choice. - let pauseMilliseconds = (if fsiOptions.Gui then 400 else 100) - - // Request that ThreadAbort interrupts be performed on this (current) thread - fsiInterruptController.InstallKillThread(Thread.CurrentThread, pauseMilliseconds) if progress then fprintfn fsiConsoleOutput.Out "MAIN: got initial state, creating form"; #if !FX_NO_APP_DOMAINS @@ -3629,12 +3679,10 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i | :? System.Exception as err -> x.ReportUnhandledExceptionSafe false err | _ -> ()) #endif - fsiInteractionProcessor.LoadInitialFiles(ctokRun, diagnosticsLogger) - fsiInteractionProcessor.StartStdinReadAndProcessThread(diagnosticsLogger) - DriveFsiEventLoop (fsi, fsiConsoleOutput ) + DriveFsiEventLoop (fsi, fsiInterruptController, fsiConsoleOutput) else // not interact if progress then fprintfn fsiConsoleOutput.Out "Run: not interact, loading initial files..." diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.cs.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.cs.xlf index 3d2a756ba80..33da7169c95 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.cs.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.cs.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. Přístup k internímu typu, metodě nebo poli {0} z předchozího vyhodnocení ve F# Interactive je zastaralý a může způsobit následné chyby přístupu. Pokud chcete povolit starší generaci jednoho dynamického sestavení, které má přístup k interním sestavením, použijte možnost --multiemit-. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.de.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.de.xlf index b5cf0ffba1d..26d2e829a97 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.de.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.de.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. Der Zugriff auf den internen Typ, die Methode oder das Feld “{0}” aus einer vorherigen Auswertung in F# Interactive ist veraltet und kann zu nachfolgenden Zugriffsfehlern führen. Verwenden Sie die Option “--multiemit-”, um die Legacygenerierung einer einzelnen dynamischen Assembly zu aktivieren, die auf Interne zugreifen kann. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.es.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.es.xlf index 7ec9ae7cc6a..6a2d481c45e 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.es.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.es.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. El acceso al tipo, método o campo interno “{0}” de una evaluación anterior en F# interactivo está en desuso y puede provocar errores de acceso posteriores. Para habilitar la generación heredada de un único ensamblado dinámico que pueda acceder a elementos internos, use la opción “--multiemit-”. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.fr.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.fr.xlf index 1b3f74b6c59..ef696d1b4d9 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.fr.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.fr.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. L’accès au type interne, à la méthode ou au champ «{0}» d’une évaluation précédente dans F# Interactive est déconseillé et peut entraîner des erreurs d’accès ultérieures. Pour activer la génération héritée d’un assemblée dynamique unique qui peut accéder aux éléments internes, utilisez l’option « --multiemit- ». diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.it.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.it.xlf index 77b204ed756..3faf69e0d7b 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.it.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.it.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. L'accesso al tipo, al metodo o al campo interno '{0}' da una valutazione precedente in F# Interactive è deprecato e potrebbe causare errori di accesso successivi. Per abilitare la generazione legacy di un singolo assembly dinamico che può accedere agli elementi interni, usare l'opzione '--multiemit-'. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.ja.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.ja.xlf index b6634357a3a..dfe34bf22d2 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.ja.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.ja.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. F# インタラクティブの以前の評価から内部型、メソッド、またはフィールド `{0}` にアクセスすることは非推奨であり、その後のアクセス エラーが発生する可能性があります。内部にアクセスできる単一の動的アセンブリのレガシ生成を有効にするには、`--multiemit-` オプションを使用します。 diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.ko.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.ko.xlf index f53eaece75e..90d31334a02 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.ko.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.ko.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. F# 대화형의 이전 평가에서 내부 형식, 메서드 또는 필드 '{0}'에 액세스하는 것은 더 이상 사용되지 않으며 후속 액세스 오류가 발생할 수 있습니다. 내부에 액세스할 수 있는 단일 동적 어셈블리의 레거시 생성을 사용하도록 설정하려면 '--multiemit-' 옵션을 사용합니다. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.pl.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.pl.xlf index 56343d35f14..cfaba706da9 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.pl.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.pl.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. Uzyskiwanie dostępu do typu wewnętrznego, metody lub pola „{0}“ z poprzedniej oceny w programie F# Interactive jest przestarzałe i może powodować kolejne błędy dostępu. Aby włączyć starszą generację pojedynczego zestawu dynamicznego, który może uzyskiwać dostęp wewnętrzny, użyj opcji „--multiemit-“. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.pt-BR.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.pt-BR.xlf index 70f2b502e0f..abb545d1307 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.pt-BR.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.pt-BR.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. O acesso ao tipo, método ou campo interno '{0}' de uma avaliação anterior em F# Interativo é preterido e pode causar erros de acesso subsequentes. Para habilitar a geração herdada de uma única assembly dinâmica que possa acessar os elementos internos, use a opção '--multiemit-'. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.ru.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.ru.xlf index 79326da8477..e3a78e2b9d0 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.ru.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.ru.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. Доступ ко внутреннему типу, методу или полю \"{0}\" из предыдущей оценки в F# Interactive является нерекомендуемым и может привести к последующим ошибкам доступа. Чтобы включить устаревшее создание одной динамической сборки, которая может получать доступ ко внутренним данным, используйте параметр \"--multiemit-\". diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.tr.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.tr.xlf index 1d265249fa9..06a7b0ee488 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.tr.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.tr.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. F# Etkileşimli’de önceki bir değerlendirmeden '{0}' iç türüne, yöntemine veya alanına erişim kullanım dışıdır ve sonraki erişim hatalarına neden olabilir. İç öğelere erişen tek bir dinamik bütünleştirilmiş kodun eski neslini etkinleştirmek için '--multiemit-' seçeneğini kullanın. diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hans.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hans.xlf index 56c3b71a953..8bcd80b8e77 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hans.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hans.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. 已弃用从 F# 交互窗口的上一个评估中访问内部类型、方法或字段“{0}”,并可能导致后续访问错误。如果要启用可以访问内部的单个动态程序集的旧的生成,请使用 “--multiemit-” 选项。 diff --git a/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hant.xlf b/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hant.xlf index 7ca07f0da9c..0ca4235ff1a 100644 --- a/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hant.xlf +++ b/src/Compiler/Interactive/xlf/FSIstrings.txt.zh-Hant.xlf @@ -2,6 +2,11 @@ + + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + Functions with [<EntryPoint>] are not invoked in FSI. '{0}' was not invoked. Execute '{1} <args>' in order to invoke '{2}' with the appropriate string array of command line arguments. + + Accessing the internal type, method or field '{0}' from a previous evaluation in F# Interactive is deprecated and may cause subsequent access errors. To enable the legacy generation of a single dynamic assembly that can access internals, use the '--multiemit-' option. 從之前 F# 互動中的評估存取內部類型、方法或欄位 '{0}' 已過時,可能造成後續存取錯誤。若要啟用可存取內部之單一動態組件的舊版世代,請使用 '--multiemit-' 選項。 diff --git a/src/Compiler/Legacy/LegacyMSBuildReferenceResolver.fs b/src/Compiler/Legacy/LegacyMSBuildReferenceResolver.fs index 7dd37ef50e1..b78e3334f52 100644 --- a/src/Compiler/Legacy/LegacyMSBuildReferenceResolver.fs +++ b/src/Compiler/Legacy/LegacyMSBuildReferenceResolver.fs @@ -225,7 +225,7 @@ module FSharp.Compiler.CodeAnalysis.LegacyMSBuildReferenceResolver /// Perform assembly resolution by instantiating the ResolveAssembly task directly from the MSBuild SDK. let ResolveCore(resolutionEnvironment: LegacyResolutionEnvironment, - references:(string*(*baggage*)string)[], + references:(string*string)[], targetFrameworkVersion: string, targetFrameworkDirectories: string list, targetProcessorArchitecture: string, diff --git a/src/Compiler/Optimize/DetupleArgs.fs b/src/Compiler/Optimize/DetupleArgs.fs index 718cc21e87a..4bdb5262a0f 100644 --- a/src/Compiler/Optimize/DetupleArgs.fs +++ b/src/Compiler/Optimize/DetupleArgs.fs @@ -321,9 +321,9 @@ module GlobalUsageAnalysis = let internalError str = raise(Failure(str)) -let mkLocalVal m name ty topValInfo = +let mkLocalVal m name ty valReprInfo = let compgen = false - Construct.NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) + Construct.NewVal(name, m, None, ty, Immutable, compgen, valReprInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) /// Represents inferred information about a tuple value type TupleStructure = @@ -467,7 +467,7 @@ let mkTransform g (f: Val) m tps x1Ntys retTy (callPattern, tyfringes: (TType li // Create transformedVal replacement for f // Mark the arity of the value - let topValInfo = + let valReprInfo = match f.ValReprInfo with | None -> None | _ -> Some(ValReprInfo (ValReprInfo.InferTyparInfo tps, List.collect ValReprInfoForTS callPattern, ValReprInfo.unnamedRetVal)) @@ -479,7 +479,7 @@ let mkTransform g (f: Val) m tps x1Ntys retTy (callPattern, tyfringes: (TType li let transformedVal = // Ensure that we have an g.CompilerGlobalState assert(g.CompilerGlobalState |> Option.isSome) - mkLocalVal f.Range (g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName (f.LogicalName, f.Range)) fCty topValInfo + mkLocalVal f.Range (g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName (f.LogicalName, f.Range)) fCty valReprInfo { transformCallPattern = callPattern transformedFormals = transformedFormals transformedVal = transformedVal } diff --git a/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs b/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs index 6739dcc3d83..a8e15eac7b1 100644 --- a/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs +++ b/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs @@ -86,8 +86,8 @@ let isDelayedRepr (f: Val) e = // REVIEW: these should just be replaced by direct calls to mkLocal, mkCompGenLocal etc. // REVIEW: However these set an arity whereas the others don't -let mkLocalNameTypeArity compgen m name ty topValInfo = - Construct.NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) +let mkLocalNameTypeArity compgen m name ty valReprInfo = + Construct.NewVal(name, m, None, ty, Immutable, compgen, valReprInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) //------------------------------------------------------------------------- // definitions: TLR, arity, arity-met, arity-short @@ -771,8 +771,6 @@ let FlatEnvPacks g fclassM topValS declist (reqdItemsMap: Zmap // Only transform if necessary, i.e. there are not enough arguments match vref.ValReprInfo with - | Some(topValInfo) -> + | Some(valReprInfo) -> let argsl = List.map cont argsl let f0 = - if topValInfo.AritiesOfArgs.Length > argsl.Length - then fst(AdjustValForExpectedArity g m vref flags topValInfo) + if valReprInfo.AritiesOfArgs.Length > argsl.Length + then fst(AdjustValForExpectedArity g m vref flags valReprInfo) else f0 Some (MakeApplicationAndBetaReduce g (f0, f0ty, [tyargsl], argsl, m)) diff --git a/src/Compiler/Optimize/LowerLocalMutables.fs b/src/Compiler/Optimize/LowerLocalMutables.fs index 08b46d70727..a4ff9ba8f08 100644 --- a/src/Compiler/Optimize/LowerLocalMutables.fs +++ b/src/Compiler/Optimize/LowerLocalMutables.fs @@ -36,11 +36,11 @@ let DecideEscapes syntacticArgs body = frees.FreeLocals |> Zset.filter isMutableEscape /// Find all the mutable locals that escape a lambda expression, ignoring the arguments to the lambda -let DecideLambda exprF cenv topValInfo expr exprTy z = +let DecideLambda exprF cenv valReprInfo expr exprTy z = match stripDebugPoints expr with | Expr.Lambda _ | Expr.TyLambda _ -> - let _tps, ctorThisValOpt, baseValOpt, vsl, body, _bodyty = destTopLambda cenv.g cenv.amap topValInfo (expr, exprTy) + let _tps, ctorThisValOpt, baseValOpt, vsl, body, _bodyty = destTopLambda cenv.g cenv.amap valReprInfo (expr, exprTy) let snoc = fun x y -> y :: x let args = List.concat vsl let args = Option.fold snoc args baseValOpt @@ -78,14 +78,14 @@ let DecideExpr cenv exprF noInterceptF z expr = let g = cenv.g match stripDebugPoints expr with | Expr.Lambda (_, _ctorThisValOpt, _baseValOpt, argvs, _, m, bodyTy) -> - let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy g m argvs bodyTy - DecideLambda (Some exprF) cenv topValInfo expr ty z + DecideLambda (Some exprF) cenv valReprInfo expr ty z | Expr.TyLambda (_, tps, _, _m, bodyTy) -> - let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) let ty = mkForallTyIfNeeded tps bodyTy - DecideLambda (Some exprF) cenv topValInfo expr ty z + DecideLambda (Some exprF) cenv valReprInfo expr ty z | Expr.Obj (_, _, baseValOpt, superInitCall, overrides, iimpls, _m) -> let CheckMethod z (TObjExprMethod(_, _attribs, _tps, vs, body, _m)) = @@ -111,8 +111,8 @@ let DecideExpr cenv exprF noInterceptF z expr = /// Find all the mutable locals that escape a binding let DecideBinding cenv z (TBind(v, expr, _m) as bind) = - let topValInfo = match bind.Var.ValReprInfo with Some info -> info | _ -> ValReprInfo.emptyValData - DecideLambda None cenv topValInfo expr v.Type z + let valReprInfo = match bind.Var.ValReprInfo with Some info -> info | _ -> ValReprInfo.emptyValData + DecideLambda None cenv valReprInfo expr v.Type z /// Find all the mutable locals that escape a set of bindings let DecideBindings cenv z binds = (z, binds) ||> List.fold (DecideBinding cenv) diff --git a/src/Compiler/Optimize/LowerStateMachines.fs b/src/Compiler/Optimize/LowerStateMachines.fs index abb8210b2af..31972252340 100644 --- a/src/Compiler/Optimize/LowerStateMachines.fs +++ b/src/Compiler/Optimize/LowerStateMachines.fs @@ -395,11 +395,11 @@ type LowerStateMachine(g: TcGlobals) = let remake2 (moveNextExprR, stateVars, thisVars) = if sm_verbose then printfn "----------- AFTER REWRITE moveNextExprWithJumpTable ----------------------" - printfn "%s" (DebugPrint.showExpr g moveNextExprR) + printfn "%s" (DebugPrint.showExpr moveNextExprR) printfn "----------- AFTER REWRITE setStateMachineBodyR ----------------------" - printfn "%s" (DebugPrint.showExpr g setStateMachineBodyR) + printfn "%s" (DebugPrint.showExpr setStateMachineBodyR) printfn "----------- AFTER REWRITE afterCodeBodyR ----------------------" - printfn "%s" (DebugPrint.showExpr g afterCodeBodyR) + printfn "%s" (DebugPrint.showExpr afterCodeBodyR) LoweredStateMachine (templateStructTy, dataTy, stateVars, thisVars, (moveNextThisVar, moveNextExprR), @@ -434,13 +434,13 @@ type LowerStateMachine(g: TcGlobals) = let rec ConvertResumableCode env (pcValInfo: ((Val * Expr) * Expr) option) expr : Result = if sm_verbose then printfn "---------ConvertResumableCode-------------------" - printfn "%s" (DebugPrint.showExpr g expr) + printfn "%s" (DebugPrint.showExpr expr) printfn "---------" let env, expr = RepeatBindAndApplyOuterDefinitions env expr if sm_verbose then - printfn "After RepeatBindAndApplyOuterDefinitions:\n%s" (DebugPrint.showExpr g expr) + printfn "After RepeatBindAndApplyOuterDefinitions:\n%s" (DebugPrint.showExpr expr) printfn "---------" // Detect the different permitted constructs in the expanded state machine @@ -520,14 +520,14 @@ type LowerStateMachine(g: TcGlobals) = match res with | Result.Ok res -> printfn "-------------------" - printfn "Phase 1 Done for %s" (DebugPrint.showExpr g res.phase1) + printfn "Phase 1 Done for %s" (DebugPrint.showExpr res.phase1) printfn "Phase 1 Done, resumableVars = %A" (res.resumableVars.FreeLocals |> Zset.elements |> List.map (fun v -> v.CompiledName(g.CompilerGlobalState)) |> String.concat ",") printfn "Phase 1 Done, stateVars = %A" (res.stateVars |> List.map (fun v -> v.CompiledName(g.CompilerGlobalState)) |> String.concat ",") printfn "Phase 1 Done, thisVars = %A" (res.thisVars |> List.map (fun v -> v.CompiledName(g.CompilerGlobalState)) |> String.concat ",") printfn "-------------------" | Result.Error msg-> printfn "Phase 1 failed: %s" msg - printfn "Phase 1 failed for %s" (DebugPrint.showExpr g expr) + printfn "Phase 1 failed for %s" (DebugPrint.showExpr expr) res and ConvertResumableEntry env pcValInfo (noneBranchExpr, someVar, someBranchExpr, _rebuild) = @@ -872,9 +872,9 @@ type LowerStateMachine(g: TcGlobals) = if sm_verbose then printfn "Found state machine override method and code expression..." printfn "----------- OVERALL EXPRESSION FOR STATE MACHINE CONVERSION ----------------------" - printfn "%s" (DebugPrint.showExpr g overallExpr) + printfn "%s" (DebugPrint.showExpr overallExpr) printfn "----------- INPUT TO STATE MACHINE CONVERSION ----------------------" - printfn "%s" (DebugPrint.showExpr g codeExpr) + printfn "%s" (DebugPrint.showExpr codeExpr) printfn "----------- START STATE MACHINE CONVERSION ----------------------" // Perform phase1 of the conversion diff --git a/src/Compiler/Optimize/Optimizer.fs b/src/Compiler/Optimize/Optimizer.fs index 788d82dfe8e..f4462122337 100644 --- a/src/Compiler/Optimize/Optimizer.fs +++ b/src/Compiler/Optimize/Optimizer.fs @@ -194,7 +194,6 @@ let seqL xL xs = Seq.fold (fun z x -> z @@ xL x) emptyL xs let namemapL xL xmap = NameMap.foldBack (fun nm x z -> xL nm x @@ z) xmap emptyL let rec exprValueInfoL g exprVal = - let exprL expr = exprL g expr match exprVal with | ConstValue (x, ty) -> NicePrint.layoutConst g ty x | UnknownValue -> wordL (tagText "?") @@ -607,9 +606,9 @@ let inline BindInternalValsToUnknown cenv vs env = ignore vs env -let BindTypeVar tyv typeinfo env = { env with typarInfos= (tyv, typeinfo) :: env.typarInfos } +let BindTypar tyv typeinfo env = { env with typarInfos= (tyv, typeinfo) :: env.typarInfos } -let BindTypeVarsToUnknown (tps: Typar list) env = +let BindTyparsToUnknown (tps: Typar list) env = if isNil tps then env else // The optimizer doesn't use the type values it could track. // However here we mutate to provide better names for generalized type parameters @@ -618,7 +617,7 @@ let BindTypeVarsToUnknown (tps: Typar list) env = (tps, nms) ||> List.iter2 (fun tp nm -> if PrettyTypes.NeedsPrettyTyparName tp then tp.typar_id <- ident (nm, tp.Range)) - List.fold (fun sofar arg -> BindTypeVar arg UnknownTypeValue sofar) env tps + List.fold (fun sofar arg -> BindTypar arg UnknownTypeValue sofar) env tps let BindCcu (ccu: CcuThunk) mval env (_g: TcGlobals) = { env with globalModuleInfos=env.globalModuleInfos.Add(ccu.AssemblyName, mval) } @@ -882,7 +881,7 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 = a2) | _ -> UnknownValue - | [ AI_clt ], [a;b], _ -> + | [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> match stripValue a, stripValue b with | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 < a2) @@ -890,6 +889,54 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkBoolVal g (a1 < a2) | _ -> UnknownValue + | [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.int32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | _ -> UnknownValue + | [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.uint32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | _ -> UnknownValue + | [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.int16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | _ -> UnknownValue + | [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.uint16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | _ -> UnknownValue + | [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.sbyte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | _ -> UnknownValue + | [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.byte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | _ -> UnknownValue | [ AI_conv DT_U1 ], [a], [ty] when typeEquiv g ty g.byte_ty -> match stripValue a with @@ -995,6 +1042,55 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 < a2) | _ -> UnknownValue + | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.int32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0) + | _ -> UnknownValue + | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.uint32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u) + | _ -> UnknownValue + | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.int16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s) + | _ -> UnknownValue + | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.uint16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us) + | _ -> UnknownValue + | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.sbyte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y) + | _ -> UnknownValue + | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.byte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy) + | _ -> UnknownValue + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> match stripValue a, stripValue b with @@ -1003,6 +1099,48 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 > a2) | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 > a2) | _ -> UnknownValue + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.int32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | _ -> UnknownValue + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.uint32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | _ -> UnknownValue + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.int16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | _ -> UnknownValue + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.uint16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | _ -> UnknownValue + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.sbyte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | _ -> UnknownValue + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.byte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | _ -> UnknownValue | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> match stripValue a, stripValue b with @@ -1012,6 +1150,55 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkBoolVal g (a1 > a2) | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 > a2) | _ -> UnknownValue + | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.int32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkInt32Val g (if a1 > a2 then 1 else 0) + | _ -> UnknownValue + | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.uint32_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkUInt32Val g (if a1 > a2 then 1u else 0u) + | _ -> UnknownValue + | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.int16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkInt16Val g (if a1 > a2 then 1s else 0s) + | _ -> UnknownValue + | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.uint16_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkUInt16Val g (if a1 > a2 then 1us else 0us) + | _ -> UnknownValue + | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.sbyte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkInt8Val g (if a1 > a2 then 1y else 0y) + | _ -> UnknownValue + | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.byte_ty -> + match stripValue a, stripValue b with + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkUInt8Val g (if a1 > a2 then 1uy else 0uy) + | _ -> UnknownValue + | [ AI_shl ], [a;n], _ -> match stripValue a, stripValue n with @@ -2058,8 +2245,8 @@ let TryDetectQueryQuoteAndRun cenv (expr: Expr) = match reqdResultInfo, exprIsEnumerableInfo with | Some _, Some _ | None, None -> resultExpr // the expression is a QuerySource, the result is a QuerySource, nothing to do | Some resultElemTy, None -> - let iety = TType_app(g.tcref_System_Collections_IEnumerable, [], g.knownWithoutNull) - mkCallGetQuerySourceAsEnumerable g expr.Range resultElemTy iety resultExpr + let enumerableTy = TType_app(g.tcref_System_Collections_IEnumerable, [], g.knownWithoutNull) + mkCallGetQuerySourceAsEnumerable g expr.Range resultElemTy enumerableTy resultExpr | None, Some (resultElemTy, qTy) -> mkCallNewQuerySource g expr.Range resultElemTy qTy resultExpr Some resultExprAfterConvertToResultTy @@ -2180,14 +2367,14 @@ let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = | None -> OptimizeApplication cenv env (f, fty, tyargs, argsl, m) | Expr.Lambda (_lambdaId, _, _, argvs, _body, m, bodyTy) -> - let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy g m argvs bodyTy - OptimizeLambdas None cenv env topValInfo expr ty + OptimizeLambdas None cenv env valReprInfo expr ty | Expr.TyLambda (_lambdaId, tps, _body, _m, bodyTy) -> - let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) + let valReprInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) let ty = mkForallTyIfNeeded tps bodyTy - OptimizeLambdas None cenv env topValInfo expr ty + OptimizeLambdas None cenv env valReprInfo expr ty | Expr.TyChoose _ -> OptimizeExpr cenv env (ChooseTyparSolutionsForFreeChoiceTypars g cenv.amap expr) @@ -2238,7 +2425,7 @@ and OptimizeMethods cenv env baseValOpt methods = and OptimizeMethod cenv env baseValOpt (TObjExprMethod(slotsig, attribs, tps, vs, e, m) as tmethod) = let env = {env with latestBoundId=Some tmethod.Id; functionVal = None} - let env = BindTypeVarsToUnknown tps env + let env = BindTyparsToUnknown tps env let env = BindInternalValsToUnknown cenv vs env let env = Option.foldBack (BindInternalValToUnknown cenv) baseValOpt env let eR, einfo = OptimizeExpr cenv env e @@ -2321,11 +2508,11 @@ and OptimizeExprOp cenv env (op, tyargs, args, m) = // Special cases match op, tyargs, args with - | TOp.Coerce, [toty;fromty], [arg] -> + | TOp.Coerce, [tgtTy; srcTy], [arg] -> let argR, einfo = OptimizeExpr cenv env arg - if typeEquiv g toty fromty then argR, einfo + if typeEquiv g tgtTy srcTy then argR, einfo else - mkCoerceExpr(argR, toty, m, fromty), + mkCoerceExpr(argR, tgtTy, m, srcTy), { TotalSize=einfo.TotalSize + 1 FunctionSize=einfo.FunctionSize + 1 HasEffect = true @@ -3544,18 +3731,18 @@ and OptimizeFSharpDelegateInvoke cenv env (delInvokeRef, delExpr, delInvokeTy, d Info=ValueOfExpr newExpr } /// Optimize/analyze a lambda expression -and OptimizeLambdas (vspec: Val option) cenv env topValInfo expr exprTy = +and OptimizeLambdas (vspec: Val option) cenv env valReprInfo expr exprTy = let g = cenv.g match expr with | Expr.Lambda (lambdaId, _, _, _, _, m, _) | Expr.TyLambda (lambdaId, _, _, m, _) -> let env = { env with methEnv = { pipelineCount = 0 }} - let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = IteratedAdjustArityOfLambda g cenv.amap topValInfo expr - let env = { env with functionVal = (match vspec with None -> None | Some v -> Some (v, topValInfo)) } + let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyTy = IteratedAdjustArityOfLambda g cenv.amap valReprInfo expr + let env = { env with functionVal = (match vspec with None -> None | Some v -> Some (v, valReprInfo)) } let env = Option.foldBack (BindInternalValToUnknown cenv) ctorThisValOpt env let env = Option.foldBack (BindInternalValToUnknown cenv) baseValOpt env - let env = BindTypeVarsToUnknown tps env + let env = BindTyparsToUnknown tps env let env = List.foldBack (BindInternalValsToUnknown cenv) vsl env let bodyR, bodyinfo = OptimizeExpr cenv env body let exprR = mkMemberLambdas g m tps ctorThisValOpt baseValOpt vsl (bodyR, bodyTy) @@ -3790,7 +3977,7 @@ and TryOptimizeDecisionTreeTest cenv test vinfo = | DecisionTreeTest.ArrayLength _, _ -> None | DecisionTreeTest.Const c1, StripConstValue c2 -> if c1 = Const.Zero || c2 = Const.Zero then None else Some(c1=c2) | DecisionTreeTest.IsNull, StripConstValue c2 -> Some(c2=Const.Zero) - | DecisionTreeTest.IsInst (_srcty1, _tgty1), _ -> None + | DecisionTreeTest.IsInst (_srcTy1, _tgtTy1), _ -> None // These should not occur in optimization | DecisionTreeTest.ActivePatternCase _, _ -> None | _ -> None @@ -3802,8 +3989,8 @@ and OptimizeSwitch cenv env (e, cases, dflt, m) = // Replace IsInst tests by calls to the helper for type tests, which may then get optimized let e, cases = match cases with - | [ TCase(DecisionTreeTest.IsInst (_srcTy, tgTy), success)] -> - let testExpr = mkCallTypeTest g m tgTy e + | [ TCase(DecisionTreeTest.IsInst (_srcTy, tgtTy), success)] -> + let testExpr = mkCallTypeTest g m tgtTy e let testCases = [TCase(DecisionTreeTest.Const(Const.Bool true), success)] testExpr, testCases | _ -> e, cases diff --git a/src/Compiler/Service/ExternalSymbol.fs b/src/Compiler/Service/ExternalSymbol.fs index f91a586cd48..0111eb5731a 100644 --- a/src/Compiler/Service/ExternalSymbol.fs +++ b/src/Compiler/Service/ExternalSymbol.fs @@ -9,13 +9,13 @@ open System.Diagnostics module Option = - let ofOptionList (xs : 'a option list) : 'a list option = + let ofOptionList (xs: 'a option list) : 'a list option = if xs |> List.forall Option.isSome then xs |> List.map Option.get |> Some else None - + /// Represents a type in an external (non F#) assembly. [] type FindDeclExternalType = @@ -36,36 +36,29 @@ type FindDeclExternalType = | Type (name, genericArgs) -> match genericArgs with | [] -> "" - | args -> - args - |> List.map (sprintf "%O") - |> String.concat ", " - |> sprintf "<%s>" + | args -> args |> List.map (sprintf "%O") |> String.concat ", " |> sprintf "<%s>" |> sprintf "%s%s" name | Array inner -> sprintf "%O[]" inner | Pointer inner -> sprintf "&%O" inner | TypeVar name -> sprintf "'%s" name - + module FindDeclExternalType = let rec tryOfILType (typeVarNames: string array) (ilType: ILType) = - + match ilType with - | ILType.Array (_, inner) -> - tryOfILType typeVarNames inner |> Option.map FindDeclExternalType.Array + | ILType.Array (_, inner) -> tryOfILType typeVarNames inner |> Option.map FindDeclExternalType.Array | ILType.Boxed tyspec | ILType.Value tyspec -> tyspec.GenericArgs |> List.map (tryOfILType typeVarNames) |> Option.ofOptionList - |> Option.map (fun genericArgs -> FindDeclExternalType.Type (tyspec.FullName, genericArgs)) - | ILType.Ptr inner -> - tryOfILType typeVarNames inner |> Option.map FindDeclExternalType.Pointer + |> Option.map (fun genericArgs -> FindDeclExternalType.Type(tyspec.FullName, genericArgs)) + | ILType.Ptr inner -> tryOfILType typeVarNames inner |> Option.map FindDeclExternalType.Pointer | ILType.TypeVar ordinal -> typeVarNames |> Array.tryItem (int ordinal) |> Option.map (fun typeVarName -> FindDeclExternalType.TypeVar typeVarName) - | _ -> - None + | _ -> None [] type FindDeclExternalParam = @@ -74,27 +67,37 @@ type FindDeclExternalParam = | Byref of parameterType: FindDeclExternalType - member c.IsByRef = match c with Byref _ -> true | _ -> false + member c.IsByRef = + match c with + | Byref _ -> true + | _ -> false - member c.ParameterType = match c with Byref ty -> ty | Param ty -> ty + member c.ParameterType = + match c with + | Byref ty -> ty + | Param ty -> ty - static member Create(parameterType, isByRef) = + static member Create(parameterType, isByRef) = if isByRef then Byref parameterType else Param parameterType - override this.ToString () = + override this.ToString() = match this with | Param t -> t.ToString() | Byref t -> sprintf "ref %O" t module FindDeclExternalParam = - let tryOfILType (typeVarNames : string array) = + let tryOfILType (typeVarNames: string array) = function - | ILType.Byref inner -> FindDeclExternalType.tryOfILType typeVarNames inner |> Option.map FindDeclExternalParam.Byref - | ilType -> FindDeclExternalType.tryOfILType typeVarNames ilType |> Option.map FindDeclExternalParam.Param + | ILType.Byref inner -> + FindDeclExternalType.tryOfILType typeVarNames inner + |> Option.map FindDeclExternalParam.Byref + | ilType -> + FindDeclExternalType.tryOfILType typeVarNames ilType + |> Option.map FindDeclExternalParam.Param let tryOfILTypes typeVarNames ilTypes = ilTypes |> List.map (tryOfILType typeVarNames) |> Option.ofOptionList - + [] [] type FindDeclExternalSymbol = @@ -105,7 +108,7 @@ type FindDeclExternalSymbol = | Event of typeName: string * name: string | Property of typeName: string * name: string - override this.ToString () = + override this.ToString() = match this with | Type fullName -> fullName | Constructor (typeName, args) -> @@ -114,9 +117,7 @@ type FindDeclExternalSymbol = |> String.concat ", " |> sprintf "%s..ctor(%s)" typeName | Method (typeName, name, args, genericArity) -> - let genericAritySuffix = - if genericArity > 0 then sprintf "`%d" genericArity - else "" + let genericAritySuffix = if genericArity > 0 then sprintf "`%d" genericArity else "" args |> List.map (sprintf "%O") @@ -124,15 +125,14 @@ type FindDeclExternalSymbol = |> sprintf "%s.%s%s(%s)" typeName name genericAritySuffix | Field (typeName, name) | Event (typeName, name) - | Property (typeName, name) -> - sprintf "%s.%s" typeName name + | Property (typeName, name) -> sprintf "%s.%s" typeName name - member this.ToDebuggerDisplay () = + member this.ToDebuggerDisplay() = let caseInfo, _ = FSharpValue.GetUnionFields(this, typeof) sprintf "%s %O" caseInfo.Name this [] -type FindDeclFailureReason = +type FindDeclFailureReason = // generic reason: no particular information about error | Unknown of message: string @@ -147,7 +147,7 @@ type FindDeclFailureReason = | ProvidedMember of memberName: string [] -type FindDeclResult = +type FindDeclResult = /// declaration not found + reason | DeclNotFound of FindDeclFailureReason @@ -156,5 +156,4 @@ type FindDeclResult = | DeclFound of location: range /// Indicates an external declaration was found - | ExternalDecl of assembly : string * externalSym : FindDeclExternalSymbol - + | ExternalDecl of assembly: string * externalSym: FindDeclExternalSymbol diff --git a/src/Compiler/Service/FSharpCheckerResults.fs b/src/Compiler/Service/FSharpCheckerResults.fs index 2213ebbe331..48649d1835a 100644 --- a/src/Compiler/Service/FSharpCheckerResults.fs +++ b/src/Compiler/Service/FSharpCheckerResults.fs @@ -62,19 +62,26 @@ type FSharpUnresolvedReferencesSet = FSharpUnresolvedReferencesSet of Unresolved [] type internal DelayedILModuleReader = - val private name : string - val private gate : obj - val mutable private getStream : (CancellationToken -> Stream option) - val mutable private result : ILModuleReader + val private name: string + val private gate: obj + val mutable private getStream: (CancellationToken -> Stream option) + val mutable private result: ILModuleReader - new (name, getStream) = { name = name; gate = obj(); getStream = getStream; result = Unchecked.defaultof<_> } + new(name, getStream) = + { + name = name + gate = obj () + getStream = getStream + result = Unchecked.defaultof<_> + } member this.TryGetILModuleReader() = // fast path match box this.result with | null -> cancellable { - let! ct = Cancellable.token() + let! ct = Cancellable.token () + return lock this.gate (fun () -> // see if we have a result or not after the lock so we do not evaluate the stream more than once @@ -82,6 +89,7 @@ type internal DelayedILModuleReader = | null -> try let streamOpt = this.getStream ct + match streamOpt with | Some stream -> let ilReaderOptions: ILReaderOptions = @@ -91,25 +99,20 @@ type internal DelayedILModuleReader = metadataOnly = MetadataOnlyFlag.Yes tryGetMetadataSnapshot = fun _ -> None } + let ilReader = OpenILModuleReaderFromStream this.name stream ilReaderOptions this.result <- ilReader this.getStream <- Unchecked.defaultof<_> // clear out the function so we do not hold onto anything Some ilReader - | _ -> - None - with - | ex -> + | _ -> None + with ex -> Trace.TraceInformation("FCS: Unable to get an ILModuleReader: {0}", ex) None - | _ -> - Some this.result - ) + | _ -> Some this.result) } - | _ -> - Cancellable.ret (Some this.result) - + | _ -> cancellable.Return(Some this.result) -[] +[] type FSharpReferencedProject = | FSharpReference of projectOutputFile: string * options: FSharpProjectOptions | PEReference of projectOutputFile: string * getStamp: (unit -> DateTime) * delayedReader: DelayedILModuleReader @@ -117,9 +120,9 @@ type FSharpReferencedProject = member this.OutputFile = match this with - | FSharpReference(projectOutputFile=projectOutputFile) - | PEReference(projectOutputFile=projectOutputFile) - | ILModuleReference(projectOutputFile=projectOutputFile) -> projectOutputFile + | FSharpReference (projectOutputFile = projectOutputFile) + | PEReference (projectOutputFile = projectOutputFile) + | ILModuleReference (projectOutputFile = projectOutputFile) -> projectOutputFile static member CreateFSharp(projectOutputFile, options) = FSharpReference(projectOutputFile, options) @@ -134,88 +137,97 @@ type FSharpReferencedProject = match o with | :? FSharpReferencedProject as o -> match this, o with - | FSharpReference(projectOutputFile1, options1), FSharpReference(projectOutputFile2, options2) -> + | FSharpReference (projectOutputFile1, options1), FSharpReference (projectOutputFile2, options2) -> projectOutputFile1 = projectOutputFile2 && options1 = options2 - | PEReference(projectOutputFile1, getStamp1, _), PEReference(projectOutputFile2, getStamp2, _) -> - projectOutputFile1 = projectOutputFile2 && (getStamp1()) = (getStamp2()) - | ILModuleReference(projectOutputFile1, getStamp1, _), ILModuleReference(projectOutputFile2, getStamp2, _) -> - projectOutputFile1 = projectOutputFile2 && (getStamp1()) = (getStamp2()) - | _ -> - false - | _ -> - false + | PEReference (projectOutputFile1, getStamp1, _), PEReference (projectOutputFile2, getStamp2, _) -> + projectOutputFile1 = projectOutputFile2 && (getStamp1 ()) = (getStamp2 ()) + | ILModuleReference (projectOutputFile1, getStamp1, _), ILModuleReference (projectOutputFile2, getStamp2, _) -> + projectOutputFile1 = projectOutputFile2 && (getStamp1 ()) = (getStamp2 ()) + | _ -> false + | _ -> false override this.GetHashCode() = this.OutputFile.GetHashCode() // NOTE: may be better just to move to optional arguments here and FSharpProjectOptions = { - ProjectFileName: string - ProjectId: string option - SourceFiles: string[] - OtherOptions: string[] - ReferencedProjects: FSharpReferencedProject[] - IsIncompleteTypeCheckEnvironment: bool - UseScriptResolutionRules: bool - LoadTime: DateTime - UnresolvedReferences: FSharpUnresolvedReferencesSet option - OriginalLoadReferences: (range * string * string) list - Stamp: int64 option + ProjectFileName: string + ProjectId: string option + SourceFiles: string[] + OtherOptions: string[] + ReferencedProjects: FSharpReferencedProject[] + IsIncompleteTypeCheckEnvironment: bool + UseScriptResolutionRules: bool + LoadTime: DateTime + UnresolvedReferences: FSharpUnresolvedReferencesSet option + OriginalLoadReferences: (range * string * string) list + Stamp: int64 option } - static member UseSameProject(options1,options2) = + static member UseSameProject(options1, options2) = match options1.ProjectId, options2.ProjectId with - | Some(projectId1), Some(projectId2) when not (String.IsNullOrWhiteSpace(projectId1)) && not (String.IsNullOrWhiteSpace(projectId2)) -> + | Some (projectId1), Some (projectId2) when + not (String.IsNullOrWhiteSpace(projectId1)) + && not (String.IsNullOrWhiteSpace(projectId2)) + -> projectId1 = projectId2 | Some _, Some _ | None, None -> options1.ProjectFileName = options2.ProjectFileName | _ -> false - static member AreSameForChecking(options1,options2) = + static member AreSameForChecking(options1, options2) = match options1.Stamp, options2.Stamp with | Some x, Some y -> (x = y) | _ -> - FSharpProjectOptions.UseSameProject(options1, options2) && - options1.SourceFiles = options2.SourceFiles && - options1.OtherOptions = options2.OtherOptions && - options1.UnresolvedReferences = options2.UnresolvedReferences && - options1.OriginalLoadReferences = options2.OriginalLoadReferences && - options1.ReferencedProjects.Length = options2.ReferencedProjects.Length && - (options1.ReferencedProjects, options2.ReferencedProjects) - ||> Array.forall2 (fun r1 r2 -> - match r1, r2 with - | FSharpReferencedProject.FSharpReference(n1,a), FSharpReferencedProject.FSharpReference(n2,b) -> - n1 = n2 && FSharpProjectOptions.AreSameForChecking(a,b) - | FSharpReferencedProject.PEReference(n1, getStamp1, _), FSharpReferencedProject.PEReference(n2, getStamp2, _) -> - n1 = n2 && (getStamp1()) = (getStamp2()) - | _ -> - false) && - options1.LoadTime = options2.LoadTime + FSharpProjectOptions.UseSameProject(options1, options2) + && options1.SourceFiles = options2.SourceFiles + && options1.OtherOptions = options2.OtherOptions + && options1.UnresolvedReferences = options2.UnresolvedReferences + && options1.OriginalLoadReferences = options2.OriginalLoadReferences + && options1.ReferencedProjects.Length = options2.ReferencedProjects.Length + && (options1.ReferencedProjects, options2.ReferencedProjects) + ||> Array.forall2 (fun r1 r2 -> + match r1, r2 with + | FSharpReferencedProject.FSharpReference (n1, a), FSharpReferencedProject.FSharpReference (n2, b) -> + n1 = n2 && FSharpProjectOptions.AreSameForChecking(a, b) + | FSharpReferencedProject.PEReference (n1, getStamp1, _), FSharpReferencedProject.PEReference (n2, getStamp2, _) -> + n1 = n2 && (getStamp1 ()) = (getStamp2 ()) + | _ -> false) + && options1.LoadTime = options2.LoadTime member po.ProjectDirectory = Path.GetDirectoryName(po.ProjectFileName) - override this.ToString() = "FSharpProjectOptions(" + this.ProjectFileName + ")" + override this.ToString() = + "FSharpProjectOptions(" + this.ProjectFileName + ")" [] module internal FSharpCheckerResultsSettings = let getToolTipTextSize = GetEnvInteger "FCS_GetToolTipTextCacheSize" 5 - let maxTypeCheckErrorsOutOfProjectContext = GetEnvInteger "FCS_MaxErrorsOutOfProjectContext" 3 + let maxTypeCheckErrorsOutOfProjectContext = + GetEnvInteger "FCS_MaxErrorsOutOfProjectContext" 3 // Look for DLLs in the location of the service DLL first. - let defaultFSharpBinariesDir = FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(Some(Path.GetDirectoryName(typeof.Assembly.Location))).Value + let defaultFSharpBinariesDir = + FSharpEnvironment + .BinFolderOfDefaultFSharpCompiler( + Some(Path.GetDirectoryName(typeof.Assembly.Location)) + ) + .Value [] -type FSharpSymbolUse(denv: DisplayEnv, symbol:FSharpSymbol, inst: TyparInstantiation, itemOcc, range: range) = +type FSharpSymbolUse(denv: DisplayEnv, symbol: FSharpSymbol, inst: TyparInstantiation, itemOcc, range: range) = - member _.Symbol = symbol + member _.Symbol = symbol member _.GenericArguments = let cenv = symbol.SymbolEnv - inst |> List.map (fun (v, ty) -> FSharpGenericParameter(cenv, v), FSharpType(cenv, ty)) - member _.DisplayContext = FSharpDisplayContext(fun _ -> denv) + inst + |> List.map (fun (v, ty) -> FSharpGenericParameter(cenv, v), FSharpType(cenv, ty)) + + member _.DisplayContext = FSharpDisplayContext(fun _ -> denv) member x.IsDefinition = x.IsFromDefinition @@ -232,9 +244,11 @@ type FSharpSymbolUse(denv: DisplayEnv, symbol:FSharpSymbol, inst: TyparInstantia member _.IsFromComputationExpression = match symbol.Item, itemOcc with // 'seq' in 'seq { ... }' gets colored as keywords - | Item.Value vref, ItemOccurence.Use when valRefEq denv.g denv.g.seq_vref vref -> true + | Item.Value vref, ItemOccurence.Use when valRefEq denv.g denv.g.seq_vref vref -> true // custom builders, custom operations get colored as keywords - | (Item.CustomBuilder _ | Item.CustomOperation _), ItemOccurence.Use -> true + | (Item.CustomBuilder _ + | Item.CustomOperation _), + ItemOccurence.Use -> true | _ -> false member _.IsFromOpenStatement = itemOcc = ItemOccurence.Open @@ -268,7 +282,8 @@ type FSharpSymbolUse(denv: DisplayEnv, symbol:FSharpSymbol, inst: TyparInstantia isPrivate && declaredInTheFile - override _.ToString() = sprintf "%O, %O, %O" symbol itemOcc range + override _.ToString() = + sprintf "%O, %O, %O" symbol itemOcc range /// This type is used to describe what was found during the name resolution. /// (Depending on the kind of the items, we may stop processing or continue to find better items) @@ -280,11 +295,11 @@ type NameResResult = [] type ResolveOverloads = -| Yes -| No + | Yes + | No [] -type GetPreciseCompletionListFromExprTypingsResult = +type ExprTypingsResult = | NoneBecauseTypecheckIsStaleAndTextChanged | NoneBecauseThereWereTypeErrors | None @@ -298,51 +313,51 @@ type Names = string list /// scope object on the floor and make a new one. [] type internal TypeCheckInfo - (// Information corresponding to miscellaneous command-line options (--define, etc). - _sTcConfig: TcConfig, - g: TcGlobals, - // The signature of the assembly being checked, up to and including the current file - ccuSigForFile: ModuleOrNamespaceType, - thisCcu: CcuThunk, - tcImports: TcImports, - tcAccessRights: AccessorDomain, - projectFileName: string, - mainInputFileName: string, - projectOptions: FSharpProjectOptions, - sResolutions: TcResolutions, - sSymbolUses: TcSymbolUses, - // This is a name resolution environment to use if no better match can be found. - sFallback: NameResolutionEnv, - loadClosure : LoadClosure option, - implFileOpt: CheckedImplFile option, - openDeclarations: OpenDeclaration[]) = + ( + _sTcConfig: TcConfig, + g: TcGlobals, + ccuSigForFile: ModuleOrNamespaceType, + thisCcu: CcuThunk, + tcImports: TcImports, + tcAccessRights: AccessorDomain, + projectFileName: string, + mainInputFileName: string, + projectOptions: FSharpProjectOptions, + sResolutions: TcResolutions, + sSymbolUses: TcSymbolUses, + sFallback: NameResolutionEnv, + loadClosure: LoadClosure option, + implFileOpt: CheckedImplFile option, + openDeclarations: OpenDeclaration[] + ) = // These strings are potentially large and the editor may choose to hold them for a while. // Use this cache to fold together data tip text results that are the same. // Is not keyed on 'Names' collection because this is invariant for the current position in // this unchanged file. Keyed on lineStr though to prevent a change to the currently line // being available against a stale scope. - let getToolTipTextCache = AgedLookup(getToolTipTextSize,areSimilar=(fun (x,y) -> x = y)) + let getToolTipTextCache = + AgedLookup(getToolTipTextSize, areSimilar = (fun (x, y) -> x = y)) let amap = tcImports.GetImportMap() - let infoReader = InfoReader(g,amap) - let ncenv = NameResolver(g,amap,infoReader,FakeInstantiationGenerator) + let infoReader = InfoReader(g, amap) + let ncenv = NameResolver(g, amap, infoReader, FakeInstantiationGenerator) let cenv = SymbolEnv(g, thisCcu, Some ccuSigForFile, tcImports, amap, infoReader) /// Find the most precise naming environment for the given line and column - let GetBestEnvForPos cursorPos = + let GetBestEnvForPos cursorPos = let mutable bestSoFar = None // Find the most deeply nested enclosing scope that contains given position - sResolutions.CapturedEnvs |> ResizeArray.iter (fun (possm,env,ad) -> - if rangeContainsPos possm cursorPos then + sResolutions.CapturedEnvs + |> ResizeArray.iter (fun (mPossible, env, ad) -> + if rangeContainsPos mPossible cursorPos then match bestSoFar with - | Some (bestm,_,_) -> - if rangeContainsRange bestm possm then - bestSoFar <- Some (possm,env,ad) - | None -> - bestSoFar <- Some (possm,env,ad)) + | Some (bestm, _, _) -> + if rangeContainsRange bestm mPossible then + bestSoFar <- Some(mPossible, env, ad) + | None -> bestSoFar <- Some(mPossible, env, ad)) let mostDeeplyNestedEnclosingScope = bestSoFar @@ -354,48 +369,57 @@ type internal TypeCheckInfo let mutable bestAlmostIncludedSoFar = None - sResolutions.CapturedEnvs |> ResizeArray.iter (fun (possm,env,ad) -> + sResolutions.CapturedEnvs + |> ResizeArray.iter (fun (mPossible, env, ad) -> // take only ranges that strictly do not include cursorPos (all ranges that touch cursorPos were processed during 'Strict Inclusion' part) - if rangeBeforePos possm cursorPos && not (posEq possm.End cursorPos) then + if rangeBeforePos mPossible cursorPos && not (posEq mPossible.End cursorPos) then let contained = match mostDeeplyNestedEnclosingScope with - | Some (bestm,_,_) -> rangeContainsRange bestm possm + | Some (bestm, _, _) -> rangeContainsRange bestm mPossible | None -> true if contained then match bestAlmostIncludedSoFar with - | Some (rightm:range,_,_) -> - if posGt possm.End rightm.End || - (posEq possm.End rightm.End && posGt possm.Start rightm.Start) then - bestAlmostIncludedSoFar <- Some (possm,env,ad) - | _ -> bestAlmostIncludedSoFar <- Some (possm,env,ad)) + | Some (mRight: range, _, _) -> + if + posGt mPossible.End mRight.End + || (posEq mPossible.End mRight.End && posGt mPossible.Start mRight.Start) + then + bestAlmostIncludedSoFar <- Some(mPossible, env, ad) + | _ -> bestAlmostIncludedSoFar <- Some(mPossible, env, ad)) let resEnv = match bestAlmostIncludedSoFar, mostDeeplyNestedEnclosingScope with - | Some (_,env,ad), None -> env, ad - | Some (_,almostIncludedEnv,ad), Some (_,mostDeeplyNestedEnv,_) - when almostIncludedEnv.eFieldLabels.Count >= mostDeeplyNestedEnv.eFieldLabels.Count -> - almostIncludedEnv,ad + | Some (_, env, ad), None -> env, ad + | Some (_, almostIncludedEnv, ad), Some (_, mostDeeplyNestedEnv, _) when + almostIncludedEnv.eFieldLabels.Count >= mostDeeplyNestedEnv.eFieldLabels.Count + -> + almostIncludedEnv, ad | _ -> match mostDeeplyNestedEnclosingScope with - | Some (_,env,ad) -> - env,ad - | None -> - sFallback,AccessibleFromSomeFSharpCode + | Some (_, env, ad) -> env, ad + | None -> sFallback, AccessibleFromSomeFSharpCode + let pm = mkRange mainInputFileName cursorPos cursorPos - resEnv,pm + resEnv, pm /// The items that come back from ResolveCompletionsInType are a bit /// noisy. Filter a few things out. /// /// e.g. prefer types to constructors for ToolTipText let FilterItemsForCtors filterCtors (items: ItemWithInst list) = - let items = items |> List.filter (fun item -> match item.Item with Item.CtorGroup _ when filterCtors = ResolveTypeNamesToTypeRefs -> false | _ -> true) + let items = + items + |> List.filter (fun item -> + match item.Item with + | Item.CtorGroup _ when filterCtors = ResolveTypeNamesToTypeRefs -> false + | _ -> true) + items // Filter items to show only valid & return Some if there are any - let ReturnItemsOfType (items: ItemWithInst list) g denv (m:range) filterCtors = + let ReturnItemsOfType (items: ItemWithInst list) g denv (m: range) filterCtors = let items = items |> RemoveDuplicateItems g @@ -403,22 +427,23 @@ type internal TypeCheckInfo |> FilterItemsForCtors filterCtors if not (isNil items) then - NameResResult.Members (items, denv, m) + NameResResult.Members(items, denv, m) else NameResResult.Empty let GetCapturedNameResolutions (endOfNamesPos: pos) resolveOverloads = let filter (endPos: pos) items = - items |> ResizeArray.filter (fun (cnr: CapturedNameResolution) -> + items + |> ResizeArray.filter (fun (cnr: CapturedNameResolution) -> let range = cnr.Range range.EndLine = endPos.Line && range.EndColumn = endPos.Column) match resolveOverloads with - | ResolveOverloads.Yes -> - filter endOfNamesPos sResolutions.CapturedNameResolutions + | ResolveOverloads.Yes -> filter endOfNamesPos sResolutions.CapturedNameResolutions | ResolveOverloads.No -> let items = filter endOfNamesPos sResolutions.CapturedMethodGroupResolutions + if items.Count <> 0 then items else @@ -427,18 +452,24 @@ type internal TypeCheckInfo /// Looks at the exact name resolutions that occurred during type checking /// If 'membersByResidue' is specified, we look for members of the item obtained /// from the name resolution and filter them by the specified residue (?) - let GetPreciseItemsFromNameResolution(line, colAtEndOfNames, membersByResidue, filterCtors, resolveOverloads) = + let GetPreciseItemsFromNameResolution (line, colAtEndOfNames, membersByResidue, filterCtors, resolveOverloads) = let endOfNamesPos = mkPos line colAtEndOfNames // Logic below expects the list to be in reverse order of resolution - let cnrs = GetCapturedNameResolutions endOfNamesPos resolveOverloads |> ResizeArray.toList |> List.rev + let cnrs = + GetCapturedNameResolutions endOfNamesPos resolveOverloads + |> ResizeArray.toList + |> List.rev match cnrs, membersByResidue with // If we're looking for members using a residue, we'd expect only // a single item (pick the first one) and we need the residue (which may be "") - | CNR(Item.Types(_,ty::_), _, denv, nenv, ad, m)::_, Some _ -> - let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad true ty + | CNR (Item.Types (_, ty :: _), _, denv, nenv, ad, m) :: _, Some _ -> + let targets = + ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m) + + let items = ResolveCompletionsInType ncenv nenv targets m ad true ty let items = List.map ItemWithNoInst items ReturnItemsOfType items g denv m filterCtors @@ -449,90 +480,115 @@ type internal TypeCheckInfo // let varA = if b then 0 else varA. // then the expression typings get confused (thinking 'varA:int'), so we use name resolution even for usual values. - | CNR(Item.Value(vref), occurence, denv, nenv, ad, m)::_, Some _ -> + | CNR (Item.Value (vref), occurence, denv, nenv, ad, m) :: _, Some _ -> if occurence = ItemOccurence.Binding || occurence = ItemOccurence.Pattern then - // Return empty list to stop further lookup - for value declarations - NameResResult.Cancel(denv, m) + // Return empty list to stop further lookup - for value declarations + NameResResult.Cancel(denv, m) else - // If we have any valid items for the value, then return completions for its type now. - // Adjust the type in case this is the 'this' pointer stored in a reference cell. - let ty = StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType) - // patch accessibility domain to remove protected members if accessing NormalVal - let ad = - match vref.BaseOrThisInfo, ad with - | ValBaseOrThisInfo.NormalVal, AccessibleFrom(paths, Some tcref) -> - let thisTy = generalizedTyconRef g tcref - // check that type of value is the same or subtype of tcref - // yes - allow access to protected members - // no - strip ability to access protected members - if TypeRelations.TypeFeasiblySubsumesType 0 g amap m thisTy TypeRelations.CanCoerce ty then - ad - else - AccessibleFrom(paths, None) - | _ -> ad - - let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad false ty - let items = List.map ItemWithNoInst items - ReturnItemsOfType items g denv m filterCtors + // If we have any valid items for the value, then return completions for its type now. + // Adjust the type in case this is the 'this' pointer stored in a reference cell. + let ty = StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType) + // patch accessibility domain to remove protected members if accessing NormalVal + let ad = + match vref.BaseOrThisInfo, ad with + | ValBaseOrThisInfo.NormalVal, AccessibleFrom (paths, Some tcref) -> + let thisTy = generalizedTyconRef g tcref + // check that type of value is the same or subtype of tcref + // yes - allow access to protected members + // no - strip ability to access protected members + if TypeRelations.TypeFeasiblySubsumesType 0 g amap m thisTy TypeRelations.CanCoerce ty then + ad + else + AccessibleFrom(paths, None) + | _ -> ad + + let targets = + ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m) + + let items = ResolveCompletionsInType ncenv nenv targets m ad false ty + let items = List.map ItemWithNoInst items + ReturnItemsOfType items g denv m filterCtors // No residue, so the items are the full resolution of the name - | CNR(_, _, denv, _, _, m) :: _, None -> + | CNR (_, _, denv, _, _, m) :: _, None -> let items = cnrs |> List.map (fun cnr -> cnr.ItemWithInst) // "into" is special magic syntax, not an identifier or a library call. It is part of capturedNameResolutions as an // implementation detail of syntax coloring, but we should not report name resolution results for it, to prevent spurious QuickInfo. - |> List.filter (fun item -> match item.Item with Item.CustomOperation(CustomOperations.Into,_,_) -> false | _ -> true) + |> List.filter (fun item -> + match item.Item with + | Item.CustomOperation (CustomOperations.Into, _, _) -> false + | _ -> true) + ReturnItemsOfType items g denv m filterCtors | _, _ -> NameResResult.Empty - let TryGetTypeFromNameResolution(line, colAtEndOfNames, membersByResidue, resolveOverloads) = + let TryGetTypeFromNameResolution (line, colAtEndOfNames, membersByResidue, resolveOverloads) = let endOfNamesPos = mkPos line colAtEndOfNames - let items = GetCapturedNameResolutions endOfNamesPos resolveOverloads |> ResizeArray.toList |> List.rev + + let items = + GetCapturedNameResolutions endOfNamesPos resolveOverloads + |> ResizeArray.toList + |> List.rev match items, membersByResidue with - | CNR(Item.Types(_,ty::_),_,_,_,_,_)::_, Some _ -> Some ty - | CNR(Item.Value(vref), occurence,_,_,_,_)::_, Some _ -> - if (occurence = ItemOccurence.Binding || occurence = ItemOccurence.Pattern) then None - else Some (StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType)) + | CNR (Item.Types (_, ty :: _), _, _, _, _, _) :: _, Some _ -> Some ty + | CNR (Item.Value (vref), occurence, _, _, _, _) :: _, Some _ -> + if (occurence = ItemOccurence.Binding || occurence = ItemOccurence.Pattern) then + None + else + Some(StripSelfRefCell(g, vref.BaseOrThisInfo, vref.TauType)) | _, _ -> None - let CollectParameters (methods: MethInfo list) amap m: Item list = + let CollectParameters (methods: MethInfo list) amap m : Item list = methods |> List.collect (fun meth -> match meth.GetParamDatas(amap, m, meth.FormalMethodInst) with - | x::_ -> x |> List.choose(fun (ParamData(_isParamArray, _isInArg, _isOutArg, _optArgInfo, _callerInfo, name, _, ty)) -> - match name with - | Some n -> Some (Item.ArgName(n, ty, Some (ArgumentContainer.Method meth))) - | None -> None - ) - | _ -> [] - ) + | x :: _ -> + x + |> List.choose (fun (ParamData (_isParamArray, _isInArg, _isOutArg, _optArgInfo, _callerInfo, name, _, ty)) -> + match name with + | Some n -> Some(Item.ArgName(n, ty, Some(ArgumentContainer.Method meth))) + | None -> None) + | _ -> []) let GetNamedParametersAndSettableFields endOfExprPos = - let cnrs = GetCapturedNameResolutions endOfExprPos ResolveOverloads.No |> ResizeArray.toList |> List.rev + let cnrs = + GetCapturedNameResolutions endOfExprPos ResolveOverloads.No + |> ResizeArray.toList + |> List.rev + let result = match cnrs with - | CNR(Item.CtorGroup(_, (ctor::_ as ctors)), _, denv, nenv, ad, m) ::_ -> - let props = ResolveCompletionsInType ncenv nenv ResolveCompletionTargets.SettablePropertiesAndFields m ad false ctor.ApparentEnclosingType + | CNR (Item.CtorGroup (_, (ctor :: _ as ctors)), _, denv, nenv, ad, m) :: _ -> + let props = + ResolveCompletionsInType + ncenv + nenv + ResolveCompletionTargets.SettablePropertiesAndFields + m + ad + false + ctor.ApparentEnclosingType + let parameters = CollectParameters ctors amap m let items = props @ parameters - Some (denv, m, items) - | CNR(Item.MethodGroup(_, methods, _), _, denv, nenv, ad, m) ::_ -> + Some(denv, m, items) + | CNR (Item.MethodGroup (_, methods, _), _, denv, nenv, ad, m) :: _ -> let props = methods |> List.collect (fun meth -> let retTy = meth.GetFSharpReturnType(amap, m, meth.FormalMethodInst) - ResolveCompletionsInType ncenv nenv ResolveCompletionTargets.SettablePropertiesAndFields m ad false retTy - ) + ResolveCompletionsInType ncenv nenv ResolveCompletionTargets.SettablePropertiesAndFields m ad false retTy) + let parameters = CollectParameters methods amap m let items = props @ parameters - Some (denv, m, items) - | _ -> - None + Some(denv, m, items) + | _ -> None + match result with - | None -> - NameResResult.Empty + | None -> NameResResult.Empty | Some (denv, m, items) -> let items = List.map ItemWithNoInst items ReturnItemsOfType items g denv m TypeNameResolutionFlag.ResolveTypeNamesToTypeRefs @@ -541,68 +597,76 @@ type internal TypeCheckInfo let GetExprTypingForPosition endOfExprPos = let quals = sResolutions.CapturedExpressionTypings - |> Seq.filter (fun (ty,nenv,_,m) -> - // We only want expression types that end at the particular position in the file we are looking at. - posEq m.End endOfExprPos && - - // Get rid of function types. True, given a 2-arg curried function "f x y", it is legal to do "(f x).GetType()", - // but you almost never want to do this in practice, and we choose not to offer up any intellisense for - // F# function types. - not (isFunTy nenv.DisplayEnv.g ty)) + |> Seq.filter (fun (ty, nenv, _, m) -> + // We only want expression types that end at the particular position in the file we are looking at. + posEq m.End endOfExprPos + && + + // Get rid of function types. True, given a 2-arg curried function "f x y", it is legal to do "(f x).GetType()", + // but you almost never want to do this in practice, and we choose not to offer up any intellisense for + // F# function types. + not (isFunTy nenv.DisplayEnv.g ty)) |> Seq.toArray // filter out errors - let quals = quals - |> Array.filter (fun (ty,nenv,_,_) -> - let denv = nenv.DisplayEnv - not (isTyparTy denv.g ty && (destTyparTy denv.g ty).IsFromError)) + let quals = + quals + |> Array.filter (fun (ty, nenv, _, _) -> + let denv = nenv.DisplayEnv + not (isTyparTy denv.g ty && (destTyparTy denv.g ty).IsFromError)) let thereWereSomeQuals = not (Array.isEmpty quals) thereWereSomeQuals, quals /// obtains captured typing for the given position /// if type of captured typing is record - returns list of record fields - let GetRecdFieldsForExpr(r : range) = + let GetRecdFieldsForExpr (r: range) = let _, quals = GetExprTypingForPosition(r.End) + let bestQual = match quals with | [||] -> None | quals -> - quals |> Array.tryFind (fun (_,_,_,rq) -> - ignore(r) // for breakpoint - posEq r.Start rq.Start) + quals + |> Array.tryFind (fun (_, _, _, rq) -> + ignore (r) // for breakpoint + posEq r.Start rq.Start) + match bestQual with - | Some (ty,nenv,ad,m) when isRecdTy nenv.DisplayEnv.g ty -> + | Some (ty, nenv, ad, m) when isRecdTy nenv.DisplayEnv.g ty -> let items = ResolveRecordOrClassFieldsOfType ncenv m ad ty false - Some (items, nenv.DisplayEnv, m) + Some(items, nenv.DisplayEnv, m) | _ -> None /// Looks at the exact expression types at the position to the left of the /// residue then the source when it was typechecked. - let GetPreciseCompletionListFromExprTypings(parseResults:FSharpParseFileResults, endOfExprPos, filterCtors) = + let GetPreciseCompletionListFromExprTypings (parseResults: FSharpParseFileResults, endOfExprPos, filterCtors) = let thereWereSomeQuals, quals = GetExprTypingForPosition(endOfExprPos) match quals with - | [| |] -> + | [||] -> if thereWereSomeQuals then - GetPreciseCompletionListFromExprTypingsResult.NoneBecauseThereWereTypeErrors + ExprTypingsResult.NoneBecauseThereWereTypeErrors else - GetPreciseCompletionListFromExprTypingsResult.None + ExprTypingsResult.None | _ -> let bestQual, textChanged = let input = parseResults.ParseTree - match ParsedInput.GetRangeOfExprLeftOfDot(endOfExprPos,input) with // TODO we say "colAtEndOfNames" everywhere, but that's not really a good name ("foo . $" hit Ctrl-Space at $) - | Some( exprRange) -> + + match ParsedInput.GetRangeOfExprLeftOfDot(endOfExprPos, input) with // TODO we say "colAtEndOfNames" everywhere, but that's not really a good name ("foo . $" hit Ctrl-Space at $) + | Some (exprRange) -> // We have an up-to-date sync parse, and know the exact range of the prior expression. // The quals all already have the same ending position, so find one with a matching starting position, if it exists. // If not, then the stale typecheck info does not have a capturedExpressionTyping for this exact expression, and the // user can wait for typechecking to catch up and second-chance intellisense to give the right result. let qual = - quals |> Array.tryFind (fun (_,_,_,r) -> - ignore(r) // for breakpoint - posEq exprRange.Start r.Start) + quals + |> Array.tryFind (fun (_, _, _, r) -> + ignore (r) // for breakpoint + posEq exprRange.Start r.Start) + qual, false | None -> // TODO In theory I think we should never get to this code path; it would be nice to add an assert. @@ -612,20 +676,28 @@ type internal TypeCheckInfo match bestQual with | Some bestQual -> - let ty,nenv,ad,m = bestQual - let items = ResolveCompletionsInType ncenv nenv (ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m)) m ad false ty + let ty, nenv, ad, m = bestQual + + let targets = + ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m) + + let items = ResolveCompletionsInType ncenv nenv targets m ad false ty let items = items |> List.map ItemWithNoInst let items = items |> RemoveDuplicateItems g let items = items |> RemoveExplicitlySuppressed g let items = items |> FilterItemsForCtors filterCtors - GetPreciseCompletionListFromExprTypingsResult.Some((items,nenv.DisplayEnv,m), ty) + ExprTypingsResult.Some((items, nenv.DisplayEnv, m), ty) | None -> - if textChanged then GetPreciseCompletionListFromExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged - else GetPreciseCompletionListFromExprTypingsResult.None + if textChanged then + ExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged + else + ExprTypingsResult.None /// Find items in the best naming environment. - let GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, showObsolete) = - let items = ResolvePartialLongIdent ncenv nenv (ConstraintSolver.IsApplicableMethApprox g amap m) m ad plid showObsolete + let GetEnvironmentLookupResolutions (nenv, ad, m, plid, filterCtors, showObsolete) = + let items = + ResolvePartialLongIdent ncenv nenv (ConstraintSolver.IsApplicableMethApprox g amap m) m ad plid showObsolete + let items = items |> List.map ItemWithNoInst let items = items |> RemoveDuplicateItems g let items = items |> RemoveExplicitlySuppressed g @@ -633,14 +705,17 @@ type internal TypeCheckInfo (items, nenv.DisplayEnv, m) /// Find items in the best naming environment. - let GetEnvironmentLookupResolutionsAtPosition(cursorPos, plid, filterCtors, showObsolete) = - let (nenv,ad),m = GetBestEnvForPos cursorPos + let GetEnvironmentLookupResolutionsAtPosition (cursorPos, plid, filterCtors, showObsolete) = + let (nenv, ad), m = GetBestEnvForPos cursorPos GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, showObsolete) /// Find record fields in the best naming environment. - let GetClassOrRecordFieldsEnvironmentLookupResolutions(cursorPos, plid, fieldsOnly) = - let (nenv, ad),m = GetBestEnvForPos cursorPos - let items = ResolvePartialLongIdentToClassOrRecdFields ncenv nenv m ad plid false fieldsOnly + let GetClassOrRecordFieldsEnvironmentLookupResolutions (cursorPos, plid, fieldsOnly) = + let (nenv, ad), m = GetBestEnvForPos cursorPos + + let items = + ResolvePartialLongIdentToClassOrRecdFields ncenv nenv m ad plid false fieldsOnly + let items = items |> List.map ItemWithNoInst let items = items |> RemoveDuplicateItems g let items = items |> RemoveExplicitlySuppressed g @@ -654,43 +729,54 @@ type internal TypeCheckInfo // // The overall aim is to resolve as accurately as possible based on what we know from type inference - let GetBaseClassCandidates = function + let GetBaseClassCandidates = + function | Item.ModuleOrNamespaces _ -> true - | Item.Types(_, ty::_) when (isClassTy g ty) && not (isSealedTy g ty) -> true + | Item.Types (_, ty :: _) when (isClassTy g ty) && not (isSealedTy g ty) -> true | _ -> false - let GetInterfaceCandidates = function + let GetInterfaceCandidates = + function | Item.ModuleOrNamespaces _ -> true - | Item.Types(_, ty::_) when (isInterfaceTy g ty) -> true + | Item.Types (_, ty :: _) when (isInterfaceTy g ty) -> true | _ -> false - // Return only items with the specified name let FilterDeclItemsByResidue (getItem: 'a -> Item) residue (items: 'a list) = let attributedResidue = residue + "Attribute" - let nameMatchesResidue name = (residue = name) || (attributedResidue = name) - items |> List.filter (fun x -> + let nameMatchesResidue name = + (residue = name) || (attributedResidue = name) + + items + |> List.filter (fun x -> let item = getItem x - let n1 = item.DisplayName + let n1 = item.DisplayName + match item with | Item.Types _ -> nameMatchesResidue n1 | Item.CtorGroup (_, meths) -> - nameMatchesResidue n1 || - meths |> List.exists (fun meth -> - let tcref = meth.ApparentEnclosingTyconRef + nameMatchesResidue n1 + || meths + |> List.exists (fun meth -> + let tcref = meth.ApparentEnclosingTyconRef #if !NO_TYPEPROVIDERS - tcref.IsProvided || + tcref.IsProvided + || #endif - nameMatchesResidue tcref.DisplayName) + nameMatchesResidue tcref.DisplayName) | _ -> residue = n1) /// Post-filter items to make sure they have precisely the right name /// This also checks that there are some remaining results /// exactMatchResidueOpt = Some _ -- means that we are looking for exact matches - let FilterRelevantItemsBy (getItem: 'a -> Item) (exactMatchResidueOpt : _ option) check (items: 'a list, denv, m) = + let FilterRelevantItemsBy (getItem: 'a -> Item) (exactMatchResidueOpt: _ option) check (items: 'a list, denv, m) = // can throw if type is in located in non-resolved CCU: i.e. bigint if reference to System.Numerics is absent - let inline safeCheck item = try check item with _ -> false + let inline safeCheck item = + try + check item + with _ -> + false // Are we looking for items with precisely the given name? if isNil items then @@ -704,6 +790,7 @@ type internal TypeCheckInfo items |> FilterDeclItemsByResidue getItem exactMatchResidue |> List.filter safeCheck + if not (isNil items) then Some(items, denv, m) else None | _ -> let items = items |> List.filter safeCheck @@ -716,12 +803,15 @@ type internal TypeCheckInfo /// Find the first non-whitespace position in a line prior to the given character let FindFirstNonWhitespacePosition (lineStr: string) i = - if i >= lineStr.Length then None + if i >= lineStr.Length then + None else - let mutable p = i - while p >= 0 && Char.IsWhiteSpace(lineStr[p]) do - p <- p - 1 - if p >= 0 then Some p else None + let mutable p = i + + while p >= 0 && Char.IsWhiteSpace(lineStr[p]) do + p <- p - 1 + + if p >= 0 then Some p else None let CompletionItem (ty: ValueOption) (assemblySymbol: ValueOption) (item: ItemWithInst) = let kind = @@ -735,43 +825,75 @@ type internal TypeCheckInfo | Item.CustomOperation _ -> CompletionItemKind.CustomOperation | _ -> CompletionItemKind.Other - { ItemWithInst = item - MinorPriority = 0 - Kind = kind - IsOwnMember = false - Type = match ty with ValueSome x -> Some x | _ -> None - Unresolved = match assemblySymbol with ValueSome x -> Some x.UnresolvedSymbol | _ -> None } + let isUnresolved = + match assemblySymbol with + | ValueSome x -> Some x.UnresolvedSymbol + | _ -> None + + let ty = + match ty with + | ValueSome x -> Some x + | _ -> None + + { + ItemWithInst = item + MinorPriority = 0 + Kind = kind + IsOwnMember = false + Type = ty + Unresolved = isUnresolved + } let DefaultCompletionItem item = CompletionItem ValueNone ValueNone item let getItem (x: ItemWithInst) = x.Item - let GetDeclaredItems (parseResultsOpt: FSharpParseFileResults option, lineStr: string, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, - filterCtors, resolveOverloads, isInRangeOperator, allSymbols: unit -> AssemblySymbol list) = - // Are the last two chars (except whitespaces) = ".." - let isLikeRangeOp = - match FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1) with - | Some x when x >= 1 && lineStr[x] = '.' && lineStr[x - 1] = '.' -> true - | _ -> false + let GetDeclaredItems + ( + parseResultsOpt: FSharpParseFileResults option, + lineStr: string, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + isInRangeOperator, + allSymbols: unit -> AssemblySymbol list + ) = + + // Are the last two chars (except whitespaces) = ".." + let isLikeRangeOp = + match FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1) with + | Some x when x >= 1 && lineStr[x] = '.' && lineStr[x - 1] = '.' -> true + | _ -> false - // if last two chars are .. and we are not in range operator context - no completion - if isLikeRangeOp && not isInRangeOperator then None else + // if last two chars are .. and we are not in range operator context - no completion + if isLikeRangeOp && not isInRangeOperator then + None + else // Try to use the exact results of name resolution during type checking to generate the results // This is based on position (i.e. colAtEndOfNamesAndResidue). This is not used if a residueOpt is given. let nameResItems = match residueOpt with - | None -> GetPreciseItemsFromNameResolution(line, colAtEndOfNamesAndResidue, None, filterCtors,resolveOverloads) + | None -> GetPreciseItemsFromNameResolution(line, colAtEndOfNamesAndResidue, None, filterCtors, resolveOverloads) | Some residue -> - // deals with cases when we have spaces between dot and\or identifier, like A . $ + // Deals with cases when we have spaces between dot and\or identifier, like A . $ // if this is our case - then we need to locate end position of the name skipping whitespaces // this allows us to handle cases like: let x . $ = 1 - match lastDotPos |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) with + let lastPos = + lastDotPos + |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) + + match lastPos with | Some p when lineStr[p] = '.' -> match FindFirstNonWhitespacePosition lineStr (p - 1) with | Some colAtEndOfNames -> - let colAtEndOfNames = colAtEndOfNames + 1 // convert 0-based to 1-based - GetPreciseItemsFromNameResolution(line, colAtEndOfNames, Some(residue), filterCtors,resolveOverloads) + let colAtEndOfNames = colAtEndOfNames + 1 // convert 0-based to 1-based + GetPreciseItemsFromNameResolution(line, colAtEndOfNames, Some(residue), filterCtors, resolveOverloads) | None -> NameResResult.Empty | _ -> NameResResult.Empty @@ -780,8 +902,8 @@ type internal TypeCheckInfo let plid, exactMatchResidueOpt = match origLongIdentOpt, residueOpt with | None, _ -> [], None - | Some(origLongIdent), Some _ -> origLongIdent, None - | Some(origLongIdent), None -> + | Some (origLongIdent), Some _ -> origLongIdent, None + | Some (origLongIdent), None -> Debug.Assert(not (isNil origLongIdent), "origLongIdent is empty") // note: as above, this happens when we are called for "precise" resolution - (F1 keyword, data tip etc..) let plid, residue = List.frontAndBack origLongIdent @@ -790,15 +912,19 @@ type internal TypeCheckInfo let pos = mkPos line loc let (nenv, ad), m = GetBestEnvForPos pos - let getType() = + let getType () = match TryToResolveLongIdentAsType ncenv nenv m plid with | Some x -> tryTcrefOfAppTy g x | None -> - match lastDotPos |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) with + match + lastDotPos + |> Option.orElseWith (fun _ -> FindFirstNonWhitespacePosition lineStr (colAtEndOfNamesAndResidue - 1)) + with | Some p when lineStr[p] = '.' -> match FindFirstNonWhitespacePosition lineStr (p - 1) with | Some colAtEndOfNames -> let colAtEndOfNames = colAtEndOfNames + 1 // convert 0-based to 1-based + match TryGetTypeFromNameResolution(line, colAtEndOfNames, residueOpt, resolveOverloads) with | Some x -> tryTcrefOfAppTy g x | _ -> ValueNone @@ -806,10 +932,10 @@ type internal TypeCheckInfo | _ -> ValueNone match nameResItems with - | NameResResult.Cancel(denv,m) -> Some([], denv, m) - | NameResResult.Members(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m)) -> + | NameResResult.Cancel (denv, m) -> Some([], denv, m) + | NameResResult.Members (FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m)) -> // lookup based on name resolution results successful - Some (items |> List.map (CompletionItem (getType()) ValueNone), denv, m) + Some(items |> List.map (CompletionItem (getType ()) ValueNone), denv, m) | _ -> match origLongIdentOpt with | None -> None @@ -824,32 +950,38 @@ type internal TypeCheckInfo // if you do QuickInfo hovering over A in "f(x).A()", you will only get a tip if typechecking has a name-resolution recorded // for A, not if merely we know the capturedExpressionTyping of f(x) and you very recently typed ".A()" - in that case, // you won't won't get a tip until the typechecking catches back up. - GetPreciseCompletionListFromExprTypingsResult.None, false + ExprTypingsResult.None, false | Some parseResults -> - match ParsedInput.TryFindExpressionASTLeftOfDotLeftOfCursor(mkPos line colAtEndOfNamesAndResidue,parseResults.ParseTree) with - | Some(pos,_) -> - GetPreciseCompletionListFromExprTypings(parseResults, pos, filterCtors), true - | None -> - // Can get here in a case like: if "f xxx yyy" is legal, and we do "f xxx y" - // We have no interest in expression typings, those are only useful for dot-completion. We want to fallback - // to "Use an environment lookup as the last resort" below - GetPreciseCompletionListFromExprTypingsResult.None, false - - match qualItems,thereIsADotInvolved with - | GetPreciseCompletionListFromExprTypingsResult.Some(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty), _ - // Initially we only use the expression typings when looking up, e.g. (expr).Nam or (expr).Name1.Nam - // These come through as an empty plid and residue "". Otherwise we try an environment lookup - // and then return to the qualItems. This is because the expression typings are a little inaccurate, primarily because - // it appears we're getting some typings recorded for non-atomic expressions like "f x" - when isNil plid -> + let leftOfDot = + ParsedInput.TryFindExpressionASTLeftOfDotLeftOfCursor( + mkPos line colAtEndOfNamesAndResidue, + parseResults.ParseTree + ) + + match leftOfDot with + | Some (pos, _) -> GetPreciseCompletionListFromExprTypings(parseResults, pos, filterCtors), true + | None -> + // Can get here in a case like: if "f xxx yyy" is legal, and we do "f xxx y" + // We have no interest in expression typings, those are only useful for dot-completion. We want to fallback + // to "Use an environment lookup as the last resort" below + ExprTypingsResult.None, false + + match qualItems, thereIsADotInvolved with + | ExprTypingsResult.Some (FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty), _ when + // Initially we only use the expression typings when looking up, e.g. (expr).Nam or (expr).Name1.Nam + // These come through as an empty plid and residue "". Otherwise we try an environment lookup + // and then return to the qualItems. This is because the expression typings are a little inaccurate, primarily because + // it appears we're getting some typings recorded for non-atomic expressions like "f x" + isNil plid + -> // lookup based on expression typings successful - Some (items |> List.map (CompletionItem (tryTcrefOfAppTy g ty) ValueNone), denv, m) - | GetPreciseCompletionListFromExprTypingsResult.NoneBecauseThereWereTypeErrors, _ -> + Some(items |> List.map (CompletionItem (tryTcrefOfAppTy g ty) ValueNone), denv, m) + | ExprTypingsResult.NoneBecauseThereWereTypeErrors, _ -> // There was an error, e.g. we have "." and there is an error determining the type of // In this case, we don't want any of the fallback logic, rather, we want to produce zero results. None - | GetPreciseCompletionListFromExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged, _ -> + | ExprTypingsResult.NoneBecauseTypecheckIsStaleAndTextChanged, _ -> // we want to report no result and let second-chance intellisense kick in None | _, true when isNil plid -> @@ -858,59 +990,67 @@ type internal TypeCheckInfo // Second-chance intellisense will bring up the correct list in a moment. None | _ -> - // Use an environment lookup as the last resort - let envItems, denv, m = GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, residueOpt.IsSome) + // Use an environment lookup as the last resort + let envItems, denv, m = + GetEnvironmentLookupResolutions(nenv, ad, m, plid, filterCtors, residueOpt.IsSome) - let envResult = - match nameResItems, (envItems, denv, m), qualItems with + let envResult = + match nameResItems, (envItems, denv, m), qualItems with - // First, use unfiltered name resolution items, if they're not empty - | NameResResult.Members(items, denv, m), _, _ when not (isNil items) -> - // lookup based on name resolution results successful - ValueSome(items |> List.map (CompletionItem (getType()) ValueNone), denv, m) + // First, use unfiltered name resolution items, if they're not empty + | NameResResult.Members (items, denv, m), _, _ when not (isNil items) -> + // lookup based on name resolution results successful + ValueSome(items |> List.map (CompletionItem (getType ()) ValueNone), denv, m) - // If we have nonempty items from environment that were resolved from a type, then use them... - // (that's better than the next case - here we'd return 'int' as a type) - | _, FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), _ when not (isNil items) -> - // lookup based on name and environment successful - ValueSome(items |> List.map (CompletionItem (getType()) ValueNone), denv, m) + // If we have nonempty items from environment that were resolved from a type, then use them... + // (that's better than the next case - here we'd return 'int' as a type) + | _, FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), _ when not (isNil items) -> + // lookup based on name and environment successful + ValueSome(items |> List.map (CompletionItem (getType ()) ValueNone), denv, m) - // Try again with the qualItems - | _, _, GetPreciseCompletionListFromExprTypingsResult.Some(FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty) -> - ValueSome(items |> List.map (CompletionItem (tryTcrefOfAppTy g ty) ValueNone), denv, m) + // Try again with the qualItems + | _, _, ExprTypingsResult.Some (FilterRelevantItems getItem exactMatchResidueOpt (items, denv, m), ty) -> + ValueSome(items |> List.map (CompletionItem (tryTcrefOfAppTy g ty) ValueNone), denv, m) - | _ -> ValueNone + | _ -> ValueNone - let globalResult = - match origLongIdentOpt with - | None | Some [] -> - let globalItems = - allSymbols() - |> List.filter (fun x -> - not x.Symbol.IsExplicitlySuppressed && + let globalResult = + match origLongIdentOpt with + | None + | Some [] -> + let globalItems = + allSymbols () + |> List.filter (fun x -> + not x.Symbol.IsExplicitlySuppressed + && match x.Symbol with - | :? FSharpMemberOrFunctionOrValue as m when m.IsConstructor && filterCtors = ResolveTypeNamesToTypeRefs -> false + | :? FSharpMemberOrFunctionOrValue as m when + m.IsConstructor && filterCtors = ResolveTypeNamesToTypeRefs + -> + false | _ -> true) - let getItem (x: AssemblySymbol) = x.Symbol.Item - - match globalItems, denv, m with - | FilterRelevantItems getItem exactMatchResidueOpt (globalItemsFiltered, denv, m) when not (isNil globalItemsFiltered) -> - globalItemsFiltered - |> List.map(fun globalItem -> CompletionItem (getType()) (ValueSome globalItem) (ItemWithNoInst globalItem.Symbol.Item)) - |> fun r -> ValueSome(r, denv, m) - | _ -> ValueNone - | _ -> ValueNone // do not return unresolved items after dot - - match envResult, globalResult with - | ValueSome (items, denv, m), ValueSome (gItems,_,_) -> Some (items @ gItems, denv, m) - | ValueSome x, ValueNone -> Some x - | ValueNone, ValueSome y -> Some y - | ValueNone, ValueNone -> None - - - let toCompletionItems (items: ItemWithInst list, denv: DisplayEnv, m: range ) = + let getItem (x: AssemblySymbol) = x.Symbol.Item + + match globalItems, denv, m with + | FilterRelevantItems getItem exactMatchResidueOpt (globalItemsFiltered, denv, m) when + not (isNil globalItemsFiltered) + -> + globalItemsFiltered + |> List.map (fun globalItem -> + CompletionItem (getType ()) (ValueSome globalItem) (ItemWithNoInst globalItem.Symbol.Item)) + |> fun r -> ValueSome(r, denv, m) + | _ -> ValueNone + | _ -> ValueNone // do not return unresolved items after dot + + match envResult, globalResult with + | ValueSome (items, denv, m), ValueSome (gItems, _, _) -> Some(items @ gItems, denv, m) + | ValueSome x, ValueNone -> Some x + | ValueNone, ValueSome y -> Some y + | ValueNone, ValueNone -> None + + let toCompletionItems (items: ItemWithInst list, denv: DisplayEnv, m: range) = items |> List.map DefaultCompletionItem, denv, m /// Find record fields in the best naming environment. @@ -921,18 +1061,31 @@ type internal TypeCheckInfo // Provide both expression items in scope and available record fields. let (nenv, _), m = GetBestEnvForPos cursorPos - let fieldItems, _, _ = GetClassOrRecordFieldsEnvironmentLookupResolutions(cursorPos, plid, true) - let fieldCompletionItems, _, _ as fieldsResult = (fieldItems, nenv.DisplayEnv, m) |> toCompletionItems + let fieldItems, _, _ = + GetClassOrRecordFieldsEnvironmentLookupResolutions(cursorPos, plid, true) + + let fieldCompletionItems, _, _ as fieldsResult = + (fieldItems, nenv.DisplayEnv, m) |> toCompletionItems match envItems with - | Some(items, denv, m) -> Some(fieldCompletionItems @ items, denv, m) + | Some (items, denv, m) -> Some(fieldCompletionItems @ items, denv, m) | _ -> Some(fieldsResult) /// Get the auto-complete items at a particular location. - let GetDeclItemsForNamesAtPosition(parseResultsOpt: FSharpParseFileResults option, origLongIdentOpt: string list option, - residueOpt:string option, lastDotPos: int option, line:int, lineStr:string, colAtEndOfNamesAndResidue, filterCtors, resolveOverloads, - completionContextAtPos: (pos * CompletionContext option) option, getAllSymbols: unit -> AssemblySymbol list) - : (CompletionItem list * DisplayEnv * CompletionContext option * range) option = + let GetDeclItemsForNamesAtPosition + ( + parseResultsOpt: FSharpParseFileResults option, + origLongIdentOpt: string list option, + residueOpt: string option, + lastDotPos: int option, + line: int, + lineStr: string, + colAtEndOfNamesAndResidue, + filterCtors, + resolveOverloads, + completionContextAtPos: (pos * CompletionContext option) option, + getAllSymbols: unit -> AssemblySymbol list + ) : (CompletionItem list * DisplayEnv * CompletionContext option * range) option = let loc = match colAtEndOfNamesAndResidue with @@ -960,107 +1113,198 @@ type internal TypeCheckInfo | Some CompletionContext.Invalid -> None // Completion at 'inherit C(...)" - | Some (CompletionContext.Inherit(InheritanceContext.Class, (plid, _))) -> + | Some (CompletionContext.Inherit (InheritanceContext.Class, (plid, _))) -> GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) |> FilterRelevantItemsBy getItem None (getItem >> GetBaseClassCandidates) |> Option.map toCompletionItems // Completion at 'interface ..." - | Some (CompletionContext.Inherit(InheritanceContext.Interface, (plid, _))) -> + | Some (CompletionContext.Inherit (InheritanceContext.Interface, (plid, _))) -> GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) |> FilterRelevantItemsBy getItem None (getItem >> GetInterfaceCandidates) |> Option.map toCompletionItems // Completion at 'implement ..." - | Some (CompletionContext.Inherit(InheritanceContext.Unknown, (plid, _))) -> + | Some (CompletionContext.Inherit (InheritanceContext.Unknown, (plid, _))) -> GetEnvironmentLookupResolutionsAtPosition(mkPos line loc, plid, filterCtors, false) |> FilterRelevantItemsBy getItem None (getItem >> (fun t -> GetBaseClassCandidates t || GetInterfaceCandidates t)) |> Option.map toCompletionItems // Completion at ' { XXX = ... } " - | Some(CompletionContext.RecordField(RecordContext.New((plid, _), isFirstField))) -> + | Some (CompletionContext.RecordField (RecordContext.New ((plid, _), isFirstField))) -> if isFirstField then let cursorPos = mkPos line loc - let envItems = GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors,resolveOverloads, false, fun () -> []) + + let envItems = + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + false, + fun () -> [] + ) + GetEnvironmentLookupResolutionsIncludingRecordFieldsAtPosition cursorPos plid envItems else // { x. } can be either record construction or computation expression. Try to get all visible record fields first - match GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid, false) |> toCompletionItems with - | [],_,_ -> + match + GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid, false) + |> toCompletionItems + with + | [], _, _ -> // no record fields found, return completion list as if we were outside any computation expression - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors,resolveOverloads, false, fun() -> []) + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + false, + fun () -> [] + ) | result -> Some(result) // Completion at '{ ... }' - | Some(CompletionContext.RecordField RecordContext.Empty) -> + | Some (CompletionContext.RecordField RecordContext.Empty) -> let cursorPos = mkPos line loc - let envItems = GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors,resolveOverloads, false, fun () -> []) - GetEnvironmentLookupResolutionsIncludingRecordFieldsAtPosition cursorPos [] envItems + + let envItems = + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + false, + fun () -> [] + ) + + GetEnvironmentLookupResolutionsIncludingRecordFieldsAtPosition cursorPos [] envItems // Completion at ' { XXX = ... with ... } " - | Some(CompletionContext.RecordField(RecordContext.CopyOnUpdate(r, (plid, _)))) -> + | Some (CompletionContext.RecordField (RecordContext.CopyOnUpdate (r, (plid, _)))) -> match GetRecdFieldsForExpr(r) with | None -> - Some (GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid, false)) - |> Option.map toCompletionItems - | Some (items, denv, m) -> - Some (List.map ItemWithNoInst items, denv, m) + Some(GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, plid, false)) |> Option.map toCompletionItems + | Some (items, denv, m) -> Some(List.map ItemWithNoInst items, denv, m) |> Option.map toCompletionItems // Completion at ' { XXX = ... with ... } " - | Some(CompletionContext.RecordField(RecordContext.Constructor(typeName))) -> - Some(GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, [typeName], false)) + | Some (CompletionContext.RecordField (RecordContext.Constructor (typeName))) -> + Some(GetClassOrRecordFieldsEnvironmentLookupResolutions(mkPos line loc, [ typeName ], false)) |> Option.map toCompletionItems // No completion at '...: string' - | Some(CompletionContext.RecordField(RecordContext.Declaration true)) -> None + | Some (CompletionContext.RecordField (RecordContext.Declaration true)) -> None // Completion at ' SomeMethod( ... ) ' with named arguments - | Some(CompletionContext.ParameterList (endPos, fields)) -> + | Some (CompletionContext.ParameterList (endPos, fields)) -> let results = GetNamedParametersAndSettableFields endPos let declaredItems = - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, - false, getAllSymbols) + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + false, + getAllSymbols + ) match results with - | NameResResult.Members(items, denv, m) -> + | NameResResult.Members (items, denv, m) -> let filtered = items |> RemoveDuplicateItems g |> RemoveExplicitlySuppressed g |> List.filter (fun item -> not (fields.Contains item.Item.DisplayName)) |> List.map (fun item -> - { ItemWithInst = item - Kind = CompletionItemKind.Argument - MinorPriority = 0 - IsOwnMember = false - Type = None - Unresolved = None }) + { + ItemWithInst = item + Kind = CompletionItemKind.Argument + MinorPriority = 0 + IsOwnMember = false + Type = None + Unresolved = None + }) + match declaredItems with - | None -> Some (toCompletionItems (items, denv, m)) - | Some (declItems, declaredDisplayEnv, declaredRange) -> Some (filtered @ declItems, declaredDisplayEnv, declaredRange) + | None -> Some(toCompletionItems (items, denv, m)) + | Some (declItems, declaredDisplayEnv, declaredRange) -> Some(filtered @ declItems, declaredDisplayEnv, declaredRange) | _ -> declaredItems - | Some(CompletionContext.AttributeApplication) -> - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, false, getAllSymbols) + | Some (CompletionContext.AttributeApplication) -> + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + false, + getAllSymbols + ) |> Option.map (fun (items, denv, m) -> - items - |> List.filter (fun cItem -> - match cItem.Item with - | Item.ModuleOrNamespaces _ -> true - | _ when IsAttribute infoReader cItem.Item -> true - | _ -> false), denv, m) - - | Some(CompletionContext.OpenDeclaration isOpenType) -> - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, false, getAllSymbols) + items + |> List.filter (fun cItem -> + match cItem.Item with + | Item.ModuleOrNamespaces _ -> true + | _ when IsAttribute infoReader cItem.Item -> true + | _ -> false), + denv, + m) + + | Some (CompletionContext.OpenDeclaration isOpenType) -> + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + false, + getAllSymbols + ) |> Option.map (fun (items, denv, m) -> items |> List.filter (fun x -> match x.Item with | Item.ModuleOrNamespaces _ -> true | Item.Types _ when isOpenType -> true - | _ -> false), denv, m) + | _ -> false), + denv, + m) // Completion at '(x: ...)" | Some CompletionContext.PatternType @@ -1069,8 +1313,21 @@ type internal TypeCheckInfo // Completion at 'type Long = int6...' or 'type SomeUnion = Abc...' | Some CompletionContext.TypeAbbreviationOrSingleCaseUnion // Completion at 'Field1: ...' - | Some(CompletionContext.RecordField(RecordContext.Declaration false)) -> - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, false, getAllSymbols) + | Some (CompletionContext.RecordField (RecordContext.Declaration false)) -> + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + false, + getAllSymbols + ) |> Option.map (fun (items, denv, m) -> items |> List.filter (fun cItem -> @@ -1080,7 +1337,9 @@ type internal TypeCheckInfo | Item.TypeVar _ | Item.UnqualifiedType _ | Item.ExnCase _ -> true - | _ -> false), denv, m) + | _ -> false), + denv, + m) // Other completions | cc -> @@ -1093,21 +1352,37 @@ type internal TypeCheckInfo // because providing generic parameters list is context aware, which we don't have here (yet). None | _ -> - let isInRangeOperator = (match cc with Some CompletionContext.RangeOperator -> true | _ -> false) - GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, - residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, - isInRangeOperator, getAllSymbols) + let isInRangeOperator = + (match cc with + | Some CompletionContext.RangeOperator -> true + | _ -> false) + + GetDeclaredItems( + parseResultsOpt, + lineStr, + origLongIdentOpt, + colAtEndOfNamesAndResidue, + residueOpt, + lastDotPos, + line, + loc, + filterCtors, + resolveOverloads, + isInRangeOperator, + getAllSymbols + ) res |> Option.map (fun (items, denv, m) -> items, denv, completionContext, m) /// Return 'false' if this is not a completion item valid in an interface file. let IsValidSignatureFileItem item = match item with - | Item.Types _ | Item.ModuleOrNamespaces _ -> true + | Item.Types _ + | Item.ModuleOrNamespaces _ -> true | _ -> false /// Find the most precise display context for the given line and column. - member _.GetBestDisplayEnvForPos cursorPos = GetBestEnvForPos cursorPos + member _.GetBestDisplayEnvForPos cursorPos = GetBestEnvForPos cursorPos member _.GetVisibleNamespacesAndModulesAtPosition(cursorPos: pos) : ModuleOrNamespaceRef list = let (nenv, ad), m = GetBestEnvForPos cursorPos @@ -1130,48 +1405,93 @@ type internal TypeCheckInfo scope.IsRelativeNameResolvable(cursorPos, plid, symbol.Item) /// Get the auto-complete items at a location - member _.GetDeclarations (parseResultsOpt, line, lineStr, partialName, completionContextAtPos, getAllEntities) = + member _.GetDeclarations(parseResultsOpt, line, lineStr, partialName, completionContextAtPos, getAllEntities) = let isInterfaceFile = SourceFileImpl.IsInterfaceFile mainInputFileName - DiagnosticsScope.Protect range0 + + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition(parseResultsOpt, Some partialName.QualifyingIdents, - Some partialName.PartialIdent, partialName.LastDotPos, line, - lineStr, partialName.EndColumn + 1, ResolveTypeNamesToCtors, ResolveOverloads.Yes, - completionContextAtPos, getAllEntities) + GetDeclItemsForNamesAtPosition( + parseResultsOpt, + Some partialName.QualifyingIdents, + Some partialName.PartialIdent, + partialName.LastDotPos, + line, + lineStr, + partialName.EndColumn + 1, + ResolveTypeNamesToCtors, + ResolveOverloads.Yes, + completionContextAtPos, + getAllEntities + ) match declItemsOpt with | None -> DeclarationListInfo.Empty | Some (items, denv, ctx, m) -> - let items = if isInterfaceFile then items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) else items - let getAccessibility item = FSharpSymbol.Create(cenv, item).Accessibility + let items = + if isInterfaceFile then + items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) + else + items + + let getAccessibility item = + FSharpSymbol.Create(cenv, item).Accessibility + let currentNamespaceOrModule = parseResultsOpt |> Option.map (fun x -> x.ParseTree) - |> Option.map (fun parsedInput -> ParsedInput.GetFullNameOfSmallestModuleOrNamespaceAtPoint(mkPos line 0, parsedInput)) + |> Option.map (fun parsedInput -> + ParsedInput.GetFullNameOfSmallestModuleOrNamespaceAtPoint(mkPos line 0, parsedInput)) + let isAttributeApplication = ctx = Some CompletionContext.AttributeApplication - DeclarationListInfo.Create(infoReader,tcAccessRights,m,denv,getAccessibility,items,currentNamespaceOrModule,isAttributeApplication)) + + DeclarationListInfo.Create( + infoReader, + tcAccessRights, + m, + denv, + getAccessibility, + items, + currentNamespaceOrModule, + isAttributeApplication + )) (fun msg -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarations: '%s'" msg) DeclarationListInfo.Error msg) /// Get the symbols for auto-complete items at a location - member _.GetDeclarationListSymbols (parseResultsOpt, line, lineStr, partialName, getAllEntities) = + member _.GetDeclarationListSymbols(parseResultsOpt, line, lineStr, partialName, getAllEntities) = let isInterfaceFile = SourceFileImpl.IsInterfaceFile mainInputFileName - DiagnosticsScope.Protect range0 + + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition(parseResultsOpt, Some partialName.QualifyingIdents, - Some partialName.PartialIdent, partialName.LastDotPos, line, lineStr, - partialName.EndColumn + 1, ResolveTypeNamesToCtors, ResolveOverloads.Yes, - None, getAllEntities) + GetDeclItemsForNamesAtPosition( + parseResultsOpt, + Some partialName.QualifyingIdents, + Some partialName.PartialIdent, + partialName.LastDotPos, + line, + lineStr, + partialName.EndColumn + 1, + ResolveTypeNamesToCtors, + ResolveOverloads.Yes, + None, + getAllEntities + ) match declItemsOpt with | None -> List.Empty | Some (items, denv, _, m) -> - let items = if isInterfaceFile then items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) else items + let items = + if isInterfaceFile then + items |> List.filter (fun x -> IsValidSignatureFileItem x.Item) + else + items //do filtering like Declarationset let items = items |> RemoveExplicitlySuppressedCompletionItems g @@ -1180,16 +1500,18 @@ type internal TypeCheckInfo // - show types with fewer generic parameters first // - show types before over other related items - they usually have very useful XmlDocs let items = - items |> List.sortBy (fun d -> + items + |> List.sortBy (fun d -> let n = match d.Item with - | Item.Types (_, TType_app(tcref, _, _) :: _) -> 1 + tcref.TyparsNoRange.Length + | Item.Types (_, TType_app (tcref, _, _) :: _) -> 1 + tcref.TyparsNoRange.Length // Put delegate ctors after types, sorted by #typars. RemoveDuplicateItems will remove FakeInterfaceCtor and DelegateCtor if an earlier type is also reported with this name - | Item.FakeInterfaceCtor (TType_app(tcref, _, _)) - | Item.DelegateCtor (TType_app(tcref, _, _)) -> 1000 + tcref.TyparsNoRange.Length + | Item.FakeInterfaceCtor (TType_app (tcref, _, _)) + | Item.DelegateCtor (TType_app (tcref, _, _)) -> 1000 + tcref.TyparsNoRange.Length // Put type ctors after types, sorted by #typars. RemoveDuplicateItems will remove DefaultStructCtors if a type is also reported with this name | Item.CtorGroup (_, cinfo :: _) -> 1000 + 10 * cinfo.DeclaringTyconRef.TyparsNoRange.Length | _ -> 0 + (d.Item.DisplayName, n)) // Remove all duplicates. We've put the types first, so this removes the DelegateCtor and DefaultStructCtor's. @@ -1198,40 +1520,43 @@ type internal TypeCheckInfo // Group by compiled name for types, display name for functions // (We don't want types with the same display name to be grouped as overloads) let items = - items |> List.groupBy (fun d -> + items + |> List.groupBy (fun d -> match d.Item with - | Item.Types (_,TType_app(tcref, _, _) :: _) + | Item.Types (_, TType_app (tcref, _, _) :: _) | Item.ExnCase tcref -> tcref.LogicalName - | Item.UnqualifiedType(tcref :: _) - | Item.FakeInterfaceCtor (TType_app(tcref, _, _)) - | Item.DelegateCtor (TType_app(tcref, _, _)) -> tcref.CompiledName - | Item.CtorGroup (_, cinfo :: _) -> - cinfo.ApparentEnclosingTyconRef.CompiledName + | Item.UnqualifiedType (tcref :: _) + | Item.FakeInterfaceCtor (TType_app (tcref, _, _)) + | Item.DelegateCtor (TType_app (tcref, _, _)) -> tcref.CompiledName + | Item.CtorGroup (_, cinfo :: _) -> cinfo.ApparentEnclosingTyconRef.CompiledName | _ -> d.Item.DisplayName) // Filter out operators (and list) let items = // Check whether this item looks like an operator. - let isOpItem(nm, item: CompletionItem list) = + let isOpItem (nm, item: CompletionItem list) = match item |> List.map (fun x -> x.Item) with - | [Item.Value _] - | [Item.MethodGroup(_,[_],_)] -> IsOperatorDisplayName nm - | [Item.UnionCase _] -> IsOperatorDisplayName nm + | [ Item.Value _ ] + | [ Item.MethodGroup (_, [ _ ], _) ] -> IsOperatorDisplayName nm + | [ Item.UnionCase _ ] -> IsOperatorDisplayName nm | _ -> false let isFSharpList nm = (nm = "[]") // list shows up as a Type and a UnionCase, only such entity with a symbolic name, but want to filter out of intellisense - items |> List.filter (fun (nm,items) -> not (isOpItem(nm,items)) && not(isFSharpList nm)) + items + |> List.filter (fun (nm, items) -> not (isOpItem (nm, items)) && not (isFSharpList nm)) let items = // Filter out duplicate names - items |> List.map (fun (_nm,itemsWithSameName) -> + items + |> List.map (fun (_nm, itemsWithSameName) -> match itemsWithSameName with | [] -> failwith "Unexpected empty bag" | items -> items - |> List.map (fun item -> let symbol = FSharpSymbol.Create(cenv, item.Item) - FSharpSymbolUse(denv, symbol, item.ItemWithInst.TyparInstantiation, ItemOccurence.Use, m))) + |> List.map (fun item -> + let symbol = FSharpSymbol.Create(cenv, item.Item) + FSharpSymbolUse(denv, symbol, item.ItemWithInst.TyparInstantiation, ItemOccurence.Use, m))) //end filtering items) @@ -1240,53 +1565,65 @@ type internal TypeCheckInfo []) /// Get the "reference resolution" tooltip for at a location - member _.GetReferenceResolutionStructuredToolTipText(line,col) = + member _.GetReferenceResolutionStructuredToolTipText(line, col) = let pos = mkPos line col - let isPosMatch(pos, ar:AssemblyReference) : bool = + + let isPosMatch (pos, ar: AssemblyReference) : bool = let isRangeMatch = (rangeContainsPos ar.Range pos) - let isNotSpecialRange = not (equals ar.Range rangeStartup) && not (equals ar.Range range0) && not (equals ar.Range rangeCmdArgs) + + let isNotSpecialRange = + not (equals ar.Range rangeStartup) + && not (equals ar.Range range0) + && not (equals ar.Range rangeCmdArgs) + let isMatch = isRangeMatch && isNotSpecialRange isMatch - let dataTipOfReferences() = + let dataTipOfReferences () = let matches = match loadClosure with | None -> [] - | Some(loadClosure) -> + | Some (loadClosure) -> loadClosure.References |> List.collect snd - |> List.filter(fun ar -> isPosMatch(pos, ar.originalReference)) + |> List.filter (fun ar -> isPosMatch (pos, ar.originalReference)) match matches with - | resolved::_ // Take the first seen - | [resolved] -> - let tip = wordL (TaggedText.tagStringLiteral((resolved.prepareToolTip ()).TrimEnd([|'\n'|]))) + | resolved :: _ // Take the first seen + | [ resolved ] -> + let tip = + wordL (TaggedText.tagStringLiteral ((resolved.prepareToolTip ()).TrimEnd([| '\n' |]))) + let tip = LayoutRender.toArray tip - ToolTipText.ToolTipText [ToolTipElement.Single(tip, FSharpXmlDoc.None)] + ToolTipText.ToolTipText [ ToolTipElement.Single(tip, FSharpXmlDoc.None) ] | [] -> let matches = match loadClosure with | None -> None - | Some(loadClosure) -> + | Some (loadClosure) -> loadClosure.PackageReferences |> Array.tryFind (fun (m, _) -> rangeContainsPos m pos) + match matches with | None -> emptyToolTip | Some (_, lines) -> - let lines = lines |> List.filter (fun line -> not (line.StartsWith("//")) && not (String.IsNullOrEmpty line)) + let lines = + lines + |> List.filter (fun line -> not (line.StartsWith("//")) && not (String.IsNullOrEmpty line)) + ToolTipText.ToolTipText - [ for line in lines -> - let tip = wordL (TaggedText.tagStringLiteral line) - let tip = LayoutRender.toArray tip - ToolTipElement.Single(tip, FSharpXmlDoc.None)] + [ + for line in lines -> + let tip = wordL (TaggedText.tagStringLiteral line) + let tip = LayoutRender.toArray tip + ToolTipElement.Single(tip, FSharpXmlDoc.None) + ] - DiagnosticsScope.Protect range0 - dataTipOfReferences - (fun err -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetReferenceResolutionStructuredToolTipText: '%s'" err) - ToolTipText [ToolTipElement.CompositionError err]) + DiagnosticsScope.Protect range0 dataTipOfReferences (fun err -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetReferenceResolutionStructuredToolTipText: '%s'" err) + ToolTipText [ ToolTipElement.CompositionError err ]) member _.GetDescription(symbol: FSharpSymbol, inst: (FSharpGenericParameter * FSharpType) list, displayFullName, m: range) = let (nenv, accessorDomain), _ = GetBestEnvForPos m.Start @@ -1294,244 +1631,358 @@ type internal TypeCheckInfo let item = symbol.Item let inst = inst |> List.map (fun (typar, t) -> typar.TypeParameter, t.Type) - let itemWithInst = { ItemWithInst.Item = item; ItemWithInst.TyparInstantiation = inst } - let toolTipElement = FormatStructuredDescriptionOfItem displayFullName infoReader accessorDomain m denv itemWithInst - ToolTipText [toolTipElement] + let itemWithInst = + { + ItemWithInst.Item = item + ItemWithInst.TyparInstantiation = inst + } + + let toolTipElement = + FormatStructuredDescriptionOfItem displayFullName infoReader accessorDomain m denv itemWithInst + + ToolTipText [ toolTipElement ] // GetToolTipText: return the "pop up" (or "Quick Info") text given a certain context. member _.GetStructuredToolTipText(line, lineStr, colAtEndOfNames, names) = - let Compute() = - DiagnosticsScope.Protect range0 + let Compute () = + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition(None, Some names, None, None, - line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, - ResolveOverloads.Yes, None, (fun() -> [])) + GetDeclItemsForNamesAtPosition( + None, + Some names, + None, + None, + line, + lineStr, + colAtEndOfNames, + ResolveTypeNamesToCtors, + ResolveOverloads.Yes, + None, + (fun () -> []) + ) match declItemsOpt with | None -> emptyToolTip - | Some(items, denv, _, m) -> - ToolTipText(items |> List.map (fun x -> FormatStructuredDescriptionOfItem false infoReader tcAccessRights m denv x.ItemWithInst))) + | Some (items, denv, _, m) -> + ToolTipText( + items + |> List.map (fun x -> FormatStructuredDescriptionOfItem false infoReader tcAccessRights m denv x.ItemWithInst) + )) (fun err -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetStructuredToolTipText: '%s'" err) - ToolTipText [ToolTipElement.CompositionError err]) + ToolTipText [ ToolTipElement.CompositionError err ]) // See devdiv bug 646520 for rationale behind truncating and caching these quick infos (they can be big!) - let key = line,colAtEndOfNames,lineStr - match getToolTipTextCache.TryGet (AnyCallerThread, key) with + let key = line, colAtEndOfNames, lineStr + + match getToolTipTextCache.TryGet(AnyCallerThread, key) with | Some res -> res | None -> - let res = Compute() - getToolTipTextCache.Put(AnyCallerThread, key,res) - res + let res = Compute() + getToolTipTextCache.Put(AnyCallerThread, key, res) + res - member _.GetF1Keyword (line, lineStr, colAtEndOfNames, names) : string option = - DiagnosticsScope.Protect range0 + member _.GetF1Keyword(line, lineStr, colAtEndOfNames, names) : string option = + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition(None, Some names, None, None, - line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, - ResolveOverloads.No, None, (fun() -> [])) + GetDeclItemsForNamesAtPosition( + None, + Some names, + None, + None, + line, + lineStr, + colAtEndOfNames, + ResolveTypeNamesToCtors, + ResolveOverloads.No, + None, + (fun () -> []) + ) match declItemsOpt with | None -> None - | Some (items: CompletionItem list, _,_, _) -> + | Some (items: CompletionItem list, _, _, _) -> match items with | [] -> None - | [item] -> - GetF1Keyword g item.Item + | [ item ] -> GetF1Keyword g item.Item | _ -> // handle new Type() let allTypes, constr, ty = List.fold - (fun (allTypes,constr,ty) (item: CompletionItem) -> + (fun (allTypes, constr, ty) (item: CompletionItem) -> match item.Item, constr, ty with - | Item.Types _ as t, _, None -> allTypes, constr, Some t - | Item.Types _, _, _ -> allTypes, constr, ty - | Item.CtorGroup _, None, _ -> allTypes, Some item.Item, ty - | _ -> false, None, None) - (true,None,None) items + | Item.Types _ as t, _, None -> allTypes, constr, Some t + | Item.Types _, _, _ -> allTypes, constr, ty + | Item.CtorGroup _, None, _ -> allTypes, Some item.Item, ty + | _ -> false, None, None) + (true, None, None) + items + match allTypes, constr, ty with - | true, Some (Item.CtorGroup _ as item), _ - -> GetF1Keyword g item - | true, _, Some ty - -> GetF1Keyword g ty - | _ -> None - ) + | true, Some (Item.CtorGroup _ as item), _ -> GetF1Keyword g item + | true, _, Some ty -> GetF1Keyword g ty + | _ -> None) (fun msg -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetF1Keyword: '%s'" msg) None) - member _.GetMethods (line, lineStr, colAtEndOfNames, namesOpt) = - DiagnosticsScope.Protect range0 + member _.GetMethods(line, lineStr, colAtEndOfNames, namesOpt) = + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition(None, namesOpt, None, None, - line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, - ResolveOverloads.No, None, (fun() -> [])) + GetDeclItemsForNamesAtPosition( + None, + namesOpt, + None, + None, + line, + lineStr, + colAtEndOfNames, + ResolveTypeNamesToCtors, + ResolveOverloads.No, + None, + (fun () -> []) + ) match declItemsOpt with - | None -> MethodGroup("",[| |]) + | None -> MethodGroup("", [||]) | Some (items, denv, _, m) -> // GetDeclItemsForNamesAtPosition returns Items.Types and Item.CtorGroup for `new T(|)`, // the Item.Types is not needed here as it duplicates (at best) parameterless ctor. - let ctors = items |> List.filter (fun x -> match x.Item with Item.CtorGroup _ -> true | _ -> false) + let ctors = + items + |> List.filter (fun x -> + match x.Item with + | Item.CtorGroup _ -> true + | _ -> false) + let items = match ctors with | [] -> items | ctors -> ctors + MethodGroup.Create(infoReader, tcAccessRights, m, denv, items |> List.map (fun x -> x.ItemWithInst))) (fun msg -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetMethods: '%s'" msg) - MethodGroup(msg,[| |])) + MethodGroup(msg, [||])) - member _.GetMethodsAsSymbols (line, lineStr, colAtEndOfNames, names) = - DiagnosticsScope.Protect range0 + member _.GetMethodsAsSymbols(line, lineStr, colAtEndOfNames, names) = + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition (None, Some names, None, - None, line, lineStr, colAtEndOfNames, - ResolveTypeNamesToCtors, ResolveOverloads.No, - None, (fun() -> [])) + GetDeclItemsForNamesAtPosition( + None, + Some names, + None, + None, + line, + lineStr, + colAtEndOfNames, + ResolveTypeNamesToCtors, + ResolveOverloads.No, + None, + (fun () -> []) + ) match declItemsOpt with - | None | Some ([],_,_,_) -> None + | None + | Some ([], _, _, _) -> None | Some (items, denv, _, m) -> - let allItems = items |> List.collect (fun item -> FlattenItems g m item.ItemWithInst) - let symbols = allItems |> List.map (fun item -> FSharpSymbol.Create(cenv, item.Item), item) - Some (symbols, denv, m) - ) + let allItems = + items |> List.collect (fun item -> FlattenItems g m item.ItemWithInst) + + let symbols = + allItems |> List.map (fun item -> FSharpSymbol.Create(cenv, item.Item), item) + + Some(symbols, denv, m)) (fun msg -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetMethodsAsSymbols: '%s'" msg) None) - member _.GetDeclarationLocation (line, lineStr, colAtEndOfNames, names, preferFlag) = - DiagnosticsScope.Protect range0 + member _.GetDeclarationLocation(line, lineStr, colAtEndOfNames, names, preferFlag) = + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition (None, Some names, None, None, - line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, - ResolveOverloads.Yes, None, (fun() -> [])) + GetDeclItemsForNamesAtPosition( + None, + Some names, + None, + None, + line, + lineStr, + colAtEndOfNames, + ResolveTypeNamesToCtors, + ResolveOverloads.Yes, + None, + (fun () -> []) + ) match declItemsOpt with | None - | Some ([], _, _, _) -> FindDeclResult.DeclNotFound (FindDeclFailureReason.Unknown "") + | Some ([], _, _, _) -> FindDeclResult.DeclNotFound(FindDeclFailureReason.Unknown "") | Some (item :: _, _, _, _) -> - let getTypeVarNames (ilinfo: ILMethInfo) = - let classTypeParams = ilinfo.DeclaringTyconRef.ILTyconRawMetadata.GenericParams |> List.map (fun paramDef -> paramDef.Name) - let methodTypeParams = ilinfo.FormalMethodTypars |> List.map (fun ty -> ty.Name) - classTypeParams @ methodTypeParams |> Array.ofList + let getTypeVarNames (ilinfo: ILMethInfo) = + let classTypeParams = + ilinfo.DeclaringTyconRef.ILTyconRawMetadata.GenericParams + |> List.map (fun paramDef -> paramDef.Name) + + let methodTypeParams = ilinfo.FormalMethodTypars |> List.map (fun ty -> ty.Name) + classTypeParams @ methodTypeParams |> Array.ofList + + let result = + match item.Item with + | Item.CtorGroup (_, ILMeth (_, ilinfo, _) :: _) -> + match ilinfo.MetadataScope with + | ILScopeRef.Assembly assemblyRef -> + let typeVarNames = getTypeVarNames ilinfo - let result = - match item.Item with - | Item.CtorGroup (_, ILMeth (_,ilinfo,_) :: _) -> - match ilinfo.MetadataScope with - | ILScopeRef.Assembly assemblyRef -> - let typeVarNames = getTypeVarNames ilinfo - FindDeclExternalParam.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes - |> Option.map (fun args -> - let externalSym = FindDeclExternalSymbol.Constructor (ilinfo.ILMethodRef.DeclaringTypeRef.FullName, args) - FindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None + FindDeclExternalParam.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes + |> Option.map (fun args -> + let externalSym = + FindDeclExternalSymbol.Constructor(ilinfo.ILMethodRef.DeclaringTypeRef.FullName, args) - | Item.MethodGroup (name, ILMeth (_,ilinfo,_) :: _, _) -> - match ilinfo.MetadataScope with - | ILScopeRef.Assembly assemblyRef -> - let typeVarNames = getTypeVarNames ilinfo - FindDeclExternalParam.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes - |> Option.map (fun args -> - let externalSym = FindDeclExternalSymbol.Method (ilinfo.ILMethodRef.DeclaringTypeRef.FullName, name, args, ilinfo.ILMethodRef.GenericArity) - FindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None + FindDeclResult.ExternalDecl(assemblyRef.Name, externalSym)) + | _ -> None - | Item.Property (name, ILProp propInfo :: _) -> - let methInfo = - if propInfo.HasGetter then Some propInfo.GetterMethod - elif propInfo.HasSetter then Some propInfo.SetterMethod - else None + | Item.MethodGroup (name, ILMeth (_, ilinfo, _) :: _, _) -> + match ilinfo.MetadataScope with + | ILScopeRef.Assembly assemblyRef -> + let typeVarNames = getTypeVarNames ilinfo + + FindDeclExternalParam.tryOfILTypes typeVarNames ilinfo.ILMethodRef.ArgTypes + |> Option.map (fun args -> + let externalSym = + FindDeclExternalSymbol.Method( + ilinfo.ILMethodRef.DeclaringTypeRef.FullName, + name, + args, + ilinfo.ILMethodRef.GenericArity + ) + + FindDeclResult.ExternalDecl(assemblyRef.Name, externalSym)) + | _ -> None - match methInfo with - | Some methInfo -> - match methInfo.MetadataScope with + | Item.Property (name, ILProp propInfo :: _) -> + let methInfo = + if propInfo.HasGetter then Some propInfo.GetterMethod + elif propInfo.HasSetter then Some propInfo.SetterMethod + else None + + match methInfo with + | Some methInfo -> + match methInfo.MetadataScope with + | ILScopeRef.Assembly assemblyRef -> + let externalSym = + FindDeclExternalSymbol.Property(methInfo.ILMethodRef.DeclaringTypeRef.FullName, name) + + Some(FindDeclResult.ExternalDecl(assemblyRef.Name, externalSym)) + | _ -> None + | None -> None + + | Item.ILField (ILFieldInfo (typeInfo, fieldDef)) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> + match typeInfo.ILScopeRef with | ILScopeRef.Assembly assemblyRef -> - let externalSym = FindDeclExternalSymbol.Property (methInfo.ILMethodRef.DeclaringTypeRef.FullName, name) - Some (FindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) + let externalSym = + FindDeclExternalSymbol.Field(typeInfo.ILTypeRef.FullName, fieldDef.Name) + + Some(FindDeclResult.ExternalDecl(assemblyRef.Name, externalSym)) | _ -> None - | None -> None - | Item.ILField (ILFieldInfo (typeInfo, fieldDef)) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> - match typeInfo.ILScopeRef with - | ILScopeRef.Assembly assemblyRef -> - let externalSym = FindDeclExternalSymbol.Field (typeInfo.ILTypeRef.FullName, fieldDef.Name) - Some (FindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None + | Item.Event (ILEvent (ILEventInfo (typeInfo, eventDef))) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> + match typeInfo.ILScopeRef with + | ILScopeRef.Assembly assemblyRef -> + let externalSym = + FindDeclExternalSymbol.Event(typeInfo.ILTypeRef.FullName, eventDef.Name) - | Item.Event (ILEvent (ILEventInfo (typeInfo, eventDef))) when not typeInfo.TyconRefOfRawMetadata.IsLocalRef -> - match typeInfo.ILScopeRef with - | ILScopeRef.Assembly assemblyRef -> - let externalSym = FindDeclExternalSymbol.Event (typeInfo.ILTypeRef.FullName, eventDef.Name) - Some (FindDeclResult.ExternalDecl (assemblyRef.Name, externalSym)) - | _ -> None + Some(FindDeclResult.ExternalDecl(assemblyRef.Name, externalSym)) + | _ -> None - | Item.ImplicitOp(_, {contents = Some(TraitConstraintSln.FSMethSln(_, _vref, _))}) -> - //Item.Value(vref) - None + | Item.ImplicitOp (_, + { + contents = Some (TraitConstraintSln.FSMethSln (_, _vref, _)) + }) -> + //Item.Value(vref) + None - | Item.Types (_, TType_app (tr, _, _) :: _) when tr.IsLocalRef && tr.IsTypeAbbrev -> None + | Item.Types (_, TType_app (tr, _, _) :: _) when tr.IsLocalRef && tr.IsTypeAbbrev -> None - | Item.Types (_, [ AppTy g (tr, _) ]) when not tr.IsLocalRef -> - match tr.TypeReprInfo, tr.PublicPath with - | TILObjectRepr(TILObjectReprData (ILScopeRef.Assembly assemblyRef, _, _)), Some (PubPath parts) -> - let fullName = parts |> String.concat "." - Some (FindDeclResult.ExternalDecl (assemblyRef.Name, FindDeclExternalSymbol.Type fullName)) + | Item.Types (_, [ AppTy g (tr, _) ]) when not tr.IsLocalRef -> + match tr.TypeReprInfo, tr.PublicPath with + | TILObjectRepr (TILObjectReprData (ILScopeRef.Assembly assemblyRef, _, _)), Some (PubPath parts) -> + let fullName = parts |> String.concat "." + Some(FindDeclResult.ExternalDecl(assemblyRef.Name, FindDeclExternalSymbol.Type fullName)) + | _ -> None | _ -> None - | _ -> None - match result with - | Some x -> x - | None -> - match rangeOfItem g preferFlag item.Item with - | Some itemRange -> - let projectDir = FileSystem.GetDirectoryNameShim (if projectFileName = "" then mainInputFileName else projectFileName) - let range = fileNameOfItem g (Some projectDir) itemRange item.Item - mkRange range itemRange.Start itemRange.End - |> FindDeclResult.DeclFound - | None -> - match item.Item with + + match result with + | Some x -> x + | None -> + match rangeOfItem g preferFlag item.Item with + | Some itemRange -> + let projectDir = + FileSystem.GetDirectoryNameShim( + if projectFileName = "" then + mainInputFileName + else + projectFileName + ) + + let range = fileNameOfItem g (Some projectDir) itemRange item.Item + mkRange range itemRange.Start itemRange.End |> FindDeclResult.DeclFound + | None -> + match item.Item with #if !NO_TYPEPROVIDERS -// provided items may have TypeProviderDefinitionLocationAttribute that binds them to some location - | Item.CtorGroup (name, ProvidedMeth _::_ ) - | Item.MethodGroup(name, ProvidedMeth _::_, _) - | Item.Property (name, ProvidedProp _::_ ) -> FindDeclFailureReason.ProvidedMember name - | Item.Event ( ProvidedEvent _ as e ) -> FindDeclFailureReason.ProvidedMember e.EventName - | Item.ILField ( ProvidedField _ as f ) -> FindDeclFailureReason.ProvidedMember f.FieldName - | ItemIsProvidedType g tcref -> FindDeclFailureReason.ProvidedType tcref.DisplayName + // provided items may have TypeProviderDefinitionLocationAttribute that binds them to some location + | Item.CtorGroup (name, ProvidedMeth _ :: _) + | Item.MethodGroup (name, ProvidedMeth _ :: _, _) + | Item.Property (name, ProvidedProp _ :: _) -> FindDeclFailureReason.ProvidedMember name + | Item.Event (ProvidedEvent _ as e) -> FindDeclFailureReason.ProvidedMember e.EventName + | Item.ILField (ProvidedField _ as f) -> FindDeclFailureReason.ProvidedMember f.FieldName + | ItemIsProvidedType g tcref -> FindDeclFailureReason.ProvidedType tcref.DisplayName #endif - | _ -> FindDeclFailureReason.Unknown "" - |> FindDeclResult.DeclNotFound - ) + | _ -> FindDeclFailureReason.Unknown "" + |> FindDeclResult.DeclNotFound) (fun msg -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetDeclarationLocation: '%s'" msg) - FindDeclResult.DeclNotFound (FindDeclFailureReason.Unknown msg)) + FindDeclResult.DeclNotFound(FindDeclFailureReason.Unknown msg)) - member _.GetSymbolUseAtLocation (line, lineStr, colAtEndOfNames, names) = - DiagnosticsScope.Protect range0 + member _.GetSymbolUseAtLocation(line, lineStr, colAtEndOfNames, names) = + DiagnosticsScope.Protect + range0 (fun () -> let declItemsOpt = - GetDeclItemsForNamesAtPosition (None, Some names, None, None, - line, lineStr, colAtEndOfNames, ResolveTypeNamesToCtors, - ResolveOverloads.Yes, None, (fun() -> [])) + GetDeclItemsForNamesAtPosition( + None, + Some names, + None, + None, + line, + lineStr, + colAtEndOfNames, + ResolveTypeNamesToCtors, + ResolveOverloads.Yes, + None, + (fun () -> []) + ) match declItemsOpt with - | None | Some ([], _, _, _) -> None + | None + | Some ([], _, _, _) -> None | Some (item :: _, denv, _, m) -> let symbol = FSharpSymbol.Create(cenv, item.Item) - Some (symbol, item.ItemWithInst, denv, m) - ) + Some(symbol, item.ItemWithInst, denv, m)) (fun msg -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetSymbolUseAtLocation: '%s'" msg) None) @@ -1539,18 +1990,20 @@ type internal TypeCheckInfo member _.PartialAssemblySignatureForFile = FSharpAssemblySignature(g, thisCcu, ccuSigForFile, tcImports, None, ccuSigForFile) - member _.AccessRights = tcAccessRights + member _.AccessRights = tcAccessRights - member _.ProjectOptions = projectOptions + member _.ProjectOptions = projectOptions member _.GetReferencedAssemblies() = - [ for x in tcImports.GetImportedAssemblies() do - yield FSharpAssembly(g, tcImports, x.FSharpViewOfMetadata) ] + [ + for x in tcImports.GetImportedAssemblies() do + FSharpAssembly(g, tcImports, x.FSharpViewOfMetadata) + ] member _.GetFormatSpecifierLocationsAndArity() = - sSymbolUses.GetFormatSpecifierLocationsAndArity() + sSymbolUses.GetFormatSpecifierLocationsAndArity() - member _.GetSemanticClassification(range: range option) : SemanticClassificationItem [] = + member _.GetSemanticClassification(range: range option) : SemanticClassificationItem[] = sResolutions.GetSemanticClassification(g, amap, sSymbolUses.GetFormatSpecifierLocationsAndArity(), range) /// The resolutions in the file @@ -1576,58 +2029,72 @@ type internal TypeCheckInfo member _.SymbolEnv = cenv - override _.ToString() = "TypeCheckInfo(" + mainInputFileName + ")" + override _.ToString() = + "TypeCheckInfo(" + mainInputFileName + ")" type FSharpParsingOptions = - { SourceFiles: string [] - ConditionalDefines: string list - DiagnosticOptions: FSharpDiagnosticOptions - LangVersionText: string - IsInteractive: bool - IndentationAwareSyntax: bool option - CompilingFSharpCore: bool - IsExe: bool } + { + SourceFiles: string[] + ConditionalDefines: string list + DiagnosticOptions: FSharpDiagnosticOptions + LangVersionText: string + IsInteractive: bool + IndentationAwareSyntax: bool option + CompilingFSharpCore: bool + IsExe: bool + } member x.LastFileName = Debug.Assert(not (Array.isEmpty x.SourceFiles), "Parsing options don't contain any file") Array.last x.SourceFiles static member Default = - { SourceFiles = Array.empty - ConditionalDefines = [] - DiagnosticOptions = FSharpDiagnosticOptions.Default - LangVersionText = LanguageVersion.Default.VersionText - IsInteractive = false - IndentationAwareSyntax = None - CompilingFSharpCore = false - IsExe = false } + { + SourceFiles = Array.empty + ConditionalDefines = [] + DiagnosticOptions = FSharpDiagnosticOptions.Default + LangVersionText = LanguageVersion.Default.VersionText + IsInteractive = false + IndentationAwareSyntax = None + CompilingFSharpCore = false + IsExe = false + } static member FromTcConfig(tcConfig: TcConfig, sourceFiles, isInteractive: bool) = - { SourceFiles = sourceFiles - ConditionalDefines = tcConfig.conditionalDefines - DiagnosticOptions = tcConfig.diagnosticsOptions - LangVersionText = tcConfig.langVersion.VersionText - IsInteractive = isInteractive - IndentationAwareSyntax = tcConfig.indentationAwareSyntax - CompilingFSharpCore = tcConfig.compilingFSharpCore - IsExe = tcConfig.target.IsExe } + { + SourceFiles = sourceFiles + ConditionalDefines = tcConfig.conditionalDefines + DiagnosticOptions = tcConfig.diagnosticsOptions + LangVersionText = tcConfig.langVersion.VersionText + IsInteractive = isInteractive + IndentationAwareSyntax = tcConfig.indentationAwareSyntax + CompilingFSharpCore = tcConfig.compilingFSharpCore + IsExe = tcConfig.target.IsExe + } static member FromTcConfigBuilder(tcConfigB: TcConfigBuilder, sourceFiles, isInteractive: bool) = { - SourceFiles = sourceFiles - ConditionalDefines = tcConfigB.conditionalDefines - DiagnosticOptions = tcConfigB.diagnosticsOptions - LangVersionText = tcConfigB.langVersion.VersionText - IsInteractive = isInteractive - IndentationAwareSyntax = tcConfigB.indentationAwareSyntax - CompilingFSharpCore = tcConfigB.compilingFSharpCore - IsExe = tcConfigB.target.IsExe + SourceFiles = sourceFiles + ConditionalDefines = tcConfigB.conditionalDefines + DiagnosticOptions = tcConfigB.diagnosticsOptions + LangVersionText = tcConfigB.langVersion.VersionText + IsInteractive = isInteractive + IndentationAwareSyntax = tcConfigB.indentationAwareSyntax + CompilingFSharpCore = tcConfigB.compilingFSharpCore + IsExe = tcConfigB.target.IsExe } module internal ParseAndCheckFile = /// Error handler for parsing & type checking while processing a single file - type ErrorHandler(reportErrors, mainInputFileName, diagnosticsOptions: FSharpDiagnosticOptions, sourceText: ISourceText, suggestNamesForErrors: bool) = + type ErrorHandler + ( + reportErrors, + mainInputFileName, + diagnosticsOptions: FSharpDiagnosticOptions, + sourceText: ISourceText, + suggestNamesForErrors: bool + ) = let mutable options = diagnosticsOptions let diagnosticsCollector = ResizeArray<_>() let mutable errorCount = 0 @@ -1636,8 +2103,10 @@ module internal ParseAndCheckFile = let fileInfo = sourceText.GetLastCharacterPosition() let collectOne severity diagnostic = - for diagnostic in DiagnosticHelpers.ReportDiagnostic (options, false, mainInputFileName, fileInfo, diagnostic, severity, suggestNamesForErrors) do + for diagnostic in + DiagnosticHelpers.ReportDiagnostic(options, false, mainInputFileName, fileInfo, diagnostic, severity, suggestNamesForErrors) do diagnosticsCollector.Add diagnostic + if severity = FSharpDiagnosticSeverity.Error then errorCount <- errorCount + 1 @@ -1645,25 +2114,35 @@ module internal ParseAndCheckFile = let diagnosticSink severity (diagnostic: PhasedDiagnostic) = // Sanity check here. The phase of an error should be in a phase known to the language service. let diagnostic = - if not(diagnostic.IsPhaseInCompile()) then + if not (diagnostic.IsPhaseInCompile()) then // Reaching this point means that the error would be sticky if we let it prop up to the language service. // Assert and recover by replacing phase with one known to the language service. - Trace.TraceInformation(sprintf "The subcategory '%s' seen in an error should not be seen by the language service" (diagnostic.Subcategory())) - { diagnostic with Phase = BuildPhase.TypeCheck } - else diagnostic + Trace.TraceInformation( + sprintf + "The subcategory '%s' seen in an error should not be seen by the language service" + (diagnostic.Subcategory()) + ) + + { diagnostic with + Phase = BuildPhase.TypeCheck + } + else + diagnostic if reportErrors then match diagnostic with #if !NO_TYPEPROVIDERS - | { Exception = :? TypeProviderError as tpe } -> - tpe.Iter(fun exn -> collectOne severity { diagnostic with Exception = exn }) + | { + Exception = :? TypeProviderError as tpe + } -> tpe.Iter(fun exn -> collectOne severity { diagnostic with Exception = exn }) #endif | _ -> collectOne severity diagnostic let diagnosticsLogger = { new DiagnosticsLogger("ErrorHandler") with - member _.DiagnosticSink (exn, severity) = diagnosticSink severity exn - member _.ErrorCount = errorCount } + member _.DiagnosticSink(exn, severity) = diagnosticSink severity exn + member _.ErrorCount = errorCount + } // Public members member _.DiagnosticsLogger = diagnosticsLogger @@ -1672,13 +2151,21 @@ module internal ParseAndCheckFile = member _.ErrorCount = errorCount - member _.DiagnosticOptions with set opts = options <- opts + member _.DiagnosticOptions + with set opts = options <- opts member _.AnyErrors = errorCount > 0 let getLightSyntaxStatus fileName options = - let indentationAwareSyntaxOnByDefault = List.exists (FileSystemUtils.checkSuffix fileName) FSharpIndentationAwareSyntaxFileSuffixes - let indentationSyntaxStatus = if indentationAwareSyntaxOnByDefault then (options.IndentationAwareSyntax <> Some false) else (options.IndentationAwareSyntax = Some true) + let indentationAwareSyntaxOnByDefault = + List.exists (FileSystemUtils.checkSuffix fileName) FSharpIndentationAwareSyntaxFileSuffixes + + let indentationSyntaxStatus = + if indentationAwareSyntaxOnByDefault then + (options.IndentationAwareSyntax <> Some false) + else + (options.IndentationAwareSyntax = Some true) + IndentationAwareSyntaxStatus(indentationSyntaxStatus, true) let createLexerFunction fileName options lexbuf (errHandler: ErrorHandler) = @@ -1695,31 +2182,42 @@ module internal ParseAndCheckFile = // When analyzing files using ParseOneFile, i.e. for the use of editing clients, we do not apply line directives. // TODO(pathmap): expose PathMap on the service API, and thread it through here - let lexargs = mkLexargs(conditionalDefines, indentationSyntaxStatus, lexResourceManager, [], errHandler.DiagnosticsLogger, PathMap.empty) - let lexargs = { lexargs with applyLineDirectives = false } + let lexargs = + mkLexargs (conditionalDefines, indentationSyntaxStatus, lexResourceManager, [], errHandler.DiagnosticsLogger, PathMap.empty) + + let lexargs = + { lexargs with + applyLineDirectives = false + } + + let tokenizer = + LexFilter.LexFilter(indentationSyntaxStatus, options.CompilingFSharpCore, Lexer.token lexargs true, lexbuf) - let tokenizer = LexFilter.LexFilter(indentationSyntaxStatus, options.CompilingFSharpCore, Lexer.token lexargs true, lexbuf) (fun _ -> tokenizer.GetToken()) let createLexbuf langVersion sourceText = UnicodeLexing.SourceTextAsLexbuf(true, LanguageVersion(langVersion), sourceText) - let matchBraces(sourceText: ISourceText, fileName, options: FSharpParsingOptions, userOpName: string, suggestNamesForErrors: bool) = + let matchBraces (sourceText: ISourceText, fileName, options: FSharpParsingOptions, userOpName: string, suggestNamesForErrors: bool) = let delayedLogger = CapturingDiagnosticsLogger("matchBraces") - use _unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind (fun _ -> delayedLogger) + use _unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind(fun _ -> delayedLogger) use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "matchBraces", fileName) // Make sure there is an DiagnosticsLogger installed whenever we do stuff that might record errors, even if we ultimately ignore the errors let delayedLogger = CapturingDiagnosticsLogger("matchBraces") - use _unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind (fun _ -> delayedLogger) + use _unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind(fun _ -> delayedLogger) use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse let matchingBraces = ResizeArray<_>() - usingLexbufForParsing(createLexbuf options.LangVersionText sourceText, fileName) (fun lexbuf -> - let errHandler = ErrorHandler(false, fileName, options.DiagnosticOptions, sourceText, suggestNamesForErrors) + + usingLexbufForParsing (createLexbuf options.LangVersionText sourceText, fileName) (fun lexbuf -> + let errHandler = + ErrorHandler(false, fileName, options.DiagnosticOptions, sourceText, suggestNamesForErrors) + let lexfun = createLexerFunction fileName options lexbuf errHandler + let parenTokensBalance t1 t2 = match t1, t2 with | LPAREN, RPAREN @@ -1750,8 +2248,7 @@ module internal ParseAndCheckFile = let m2Start = match tok2 with | INTERP_STRING_PART _ - | INTERP_STRING_END _ -> - mkFileIndexRange m2.FileIndex m2.Start (mkPos m2.Start.Line (m2.Start.Column+1)) + | INTERP_STRING_END _ -> mkFileIndexRange m2.FileIndex m2.Start (mkPos m2.Start.Line (m2.Start.Column + 1)) | _ -> m2 matchingBraces.Add(m1, m2Start) @@ -1761,14 +2258,22 @@ module internal ParseAndCheckFile = let stackAfterMatch = match tok2 with | INTERP_STRING_PART _ -> - let m2End = mkFileIndexRange m2.FileIndex (mkPos m2.End.Line (max (m2.End.Column-1) 0)) m2.End - (tok2, m2End) :: stackAfterMatch + let m2End = + mkFileIndexRange m2.FileIndex (mkPos m2.End.Line (max (m2.End.Column - 1) 0)) m2.End + + (tok2, m2End) :: stackAfterMatch | _ -> stackAfterMatch matchBraces stackAfterMatch - | LPAREN | LBRACE _ | LBRACK | LBRACE_BAR | LBRACK_BAR | LQUOTE _ | LBRACK_LESS as tok, _ -> - matchBraces ((tok, lexbuf.LexemeRange) :: stack) + | LPAREN + | LBRACE _ + | LBRACK + | LBRACE_BAR + | LBRACK_BAR + | LQUOTE _ + | LBRACK_LESS as tok, + _ -> matchBraces ((tok, lexbuf.LexemeRange) :: stack) // INTERP_STRING_BEGIN_PART corresponds to $"... {" at the start of an interpolated string // @@ -1777,41 +2282,72 @@ module internal ParseAndCheckFile = // interpolation expression) // // Either way we start a new potential match at the last character - | INTERP_STRING_BEGIN_PART _ | INTERP_STRING_PART _ as tok, _ -> - let m = lexbuf.LexemeRange - let m2 = mkFileIndexRange m.FileIndex (mkPos m.End.Line (max (m.End.Column-1) 0)) m.End - matchBraces ((tok, m2) :: stack) + | INTERP_STRING_BEGIN_PART _ + | INTERP_STRING_PART _ as tok, + _ -> + let m = lexbuf.LexemeRange + + let m2 = + mkFileIndexRange m.FileIndex (mkPos m.End.Line (max (m.End.Column - 1) 0)) m.End - | (EOF _ | LEX_FAILURE _), _ -> () + matchBraces ((tok, m2) :: stack) + + | (EOF _ + | LEX_FAILURE _), + _ -> () | _ -> matchBraces stack + matchBraces []) + matchingBraces.ToArray() - let parseFile(sourceText: ISourceText, fileName, options: FSharpParsingOptions, userOpName: string, suggestNamesForErrors: bool) = + let parseFile (sourceText: ISourceText, fileName, options: FSharpParsingOptions, userOpName: string, suggestNamesForErrors: bool) = Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "parseFile", fileName) - let errHandler = ErrorHandler(true, fileName, options.DiagnosticOptions, sourceText, suggestNamesForErrors) - use unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind (fun _oldLogger -> errHandler.DiagnosticsLogger) + + let errHandler = + ErrorHandler(true, fileName, options.DiagnosticOptions, sourceText, suggestNamesForErrors) + + use unwindEL = + PushDiagnosticsLoggerPhaseUntilUnwind(fun _oldLogger -> errHandler.DiagnosticsLogger) + use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse let parseResult = - usingLexbufForParsing(createLexbuf options.LangVersionText sourceText, fileName) (fun lexbuf -> + usingLexbufForParsing (createLexbuf options.LangVersionText sourceText, fileName) (fun lexbuf -> let lexfun = createLexerFunction fileName options lexbuf errHandler + let isLastCompiland = - fileName.Equals(options.LastFileName, StringComparison.CurrentCultureIgnoreCase) || - IsScript(fileName) + fileName.Equals(options.LastFileName, StringComparison.CurrentCultureIgnoreCase) + || IsScript(fileName) + let isExe = options.IsExe try - ParseInput(lexfun, options.DiagnosticOptions, errHandler.DiagnosticsLogger, lexbuf, None, fileName, (isLastCompiland, isExe)) + ParseInput( + lexfun, + options.DiagnosticOptions, + errHandler.DiagnosticsLogger, + lexbuf, + None, + fileName, + (isLastCompiland, isExe) + ) with e -> errHandler.DiagnosticsLogger.StopProcessingRecovery e range0 // don't re-raise any exceptions, we must return None. EmptyParsedInput(fileName, (isLastCompiland, isExe))) errHandler.CollectedDiagnostics, parseResult, errHandler.AnyErrors - - let ApplyLoadClosure(tcConfig, parsedMainInput, mainInputFileName, loadClosure: LoadClosure option, tcImports: TcImports, backgroundDiagnostics) = + let ApplyLoadClosure + ( + tcConfig, + parsedMainInput, + mainInputFileName, + loadClosure: LoadClosure option, + tcImports: TcImports, + backgroundDiagnostics + ) = // If additional references were brought in by the preprocessor then we need to process them match loadClosure with @@ -1823,9 +2359,9 @@ module internal ParseAndCheckFile = loadClosure.LoadClosureRootFileDiagnostics |> List.iter diagnosticSink let fileOfBackgroundError err = - match GetRangeOfDiagnostic (fst err) with - | Some m -> Some m.FileName - | None -> None + match GetRangeOfDiagnostic(fst err) with + | Some m -> Some m.FileName + | None -> None let sameFile file hashLoadInFile = match file with @@ -1834,21 +2370,20 @@ module internal ParseAndCheckFile = // walk the list of #loads and keep the ones for this file. let hashLoadsInFile = - loadClosure.SourceFiles - |> List.filter(fun (_,ms) -> ms<>[]) // #loaded file, ranges of #load + loadClosure.SourceFiles |> List.filter (fun (_, ms) -> ms <> []) // #loaded file, ranges of #load let hashLoadBackgroundDiagnostics, otherBackgroundDiagnostics = backgroundDiagnostics |> Array.partition (fun backgroundError -> hashLoadsInFile - |> List.exists (fst >> sameFile (fileOfBackgroundError backgroundError))) + |> List.exists (fst >> sameFile (fileOfBackgroundError backgroundError))) // Create single errors for the #load-ed files. // Group errors and warnings by file name. let hashLoadBackgroundDiagnosticsGroupedByFileName = hashLoadBackgroundDiagnostics - |> Array.map(fun err -> fileOfBackgroundError err,err) - |> Array.groupBy fst // fileWithErrors, error list + |> Array.map (fun err -> fileOfBackgroundError err, err) + |> Array.groupBy fst // fileWithErrors, error list // Join the sets and report errors. // It is by-design that these messages are only present in the language service. A true build would report the errors at their @@ -1857,18 +2392,35 @@ module internal ParseAndCheckFile = for file, errorGroupedByFileName in hashLoadBackgroundDiagnosticsGroupedByFileName do if sameFile file fileOfHashLoad then for rangeOfHashLoad in rangesOfHashLoad do // Handle the case of two #loads of the same file - let diagnostics = errorGroupedByFileName |> Array.map(fun (_,(pe,f)) -> pe.Exception,f) // Strip the build phase here. It will be replaced, in total, with TypeCheck - let errors = [ for err, severity in diagnostics do if severity = FSharpDiagnosticSeverity.Error then yield err ] - let warnings = [ for err, severity in diagnostics do if severity = FSharpDiagnosticSeverity.Warning then yield err ] - let infos = [ for err, severity in diagnostics do if severity = FSharpDiagnosticSeverity.Info then yield err ] + let diagnostics = + errorGroupedByFileName |> Array.map (fun (_, (pe, f)) -> pe.Exception, f) // Strip the build phase here. It will be replaced, in total, with TypeCheck + + let errors = + [ + for err, severity in diagnostics do + if severity = FSharpDiagnosticSeverity.Error then + err + ] + + let warnings = + [ + for err, severity in diagnostics do + if severity = FSharpDiagnosticSeverity.Warning then + err + ] + + let infos = + [ + for err, severity in diagnostics do + if severity = FSharpDiagnosticSeverity.Info then + err + ] let message = HashLoadedSourceHasIssues(infos, warnings, errors, rangeOfHashLoad) - if isNil errors && isNil warnings then - warning message - elif isNil errors then - warning message - else - errorR message + + if isNil errors && isNil warnings then warning message + elif isNil errors then warning message + else errorR message // Replay other background errors. for diagnostic, severity in otherBackgroundDiagnostics do @@ -1880,398 +2432,522 @@ module internal ParseAndCheckFile = | None -> // For non-scripts, check for disallow #r and #load. - ApplyMetaCommandsFromInputToTcConfig (tcConfig, parsedMainInput, Path.GetDirectoryName mainInputFileName, tcImports.DependencyProvider) |> ignore + ApplyMetaCommandsFromInputToTcConfig( + tcConfig, + parsedMainInput, + Path.GetDirectoryName mainInputFileName, + tcImports.DependencyProvider + ) + |> ignore // Type check a single file against an initial context, gleaning both errors and intellisense information. let CheckOneFile - (parseResults: FSharpParseFileResults, - sourceText: ISourceText, - mainInputFileName: string, - projectOptions: FSharpProjectOptions, - projectFileName: string, - tcConfig: TcConfig, - tcGlobals: TcGlobals, - tcImports: TcImports, - tcState: TcState, - moduleNamesDict: ModuleNamesDict, - loadClosure: LoadClosure option, - // These are the errors and warnings seen by the background compiler for the entire antecedent - backgroundDiagnostics: (PhasedDiagnostic * FSharpDiagnosticSeverity)[], - suggestNamesForErrors: bool) = - - cancellable { - use _logBlock = Logger.LogBlock LogCompilerFunctionId.Service_CheckOneFile - - let parsedMainInput = parseResults.ParseTree - - // Initialize the error handler - let errHandler = ErrorHandler(true, mainInputFileName, tcConfig.diagnosticsOptions, sourceText, suggestNamesForErrors) - - use _unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind (fun _oldLogger -> errHandler.DiagnosticsLogger) - use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.TypeCheck - - // Apply nowarns to tcConfig (may generate errors, so ensure diagnosticsLogger is installed) - let tcConfig = ApplyNoWarnsToTcConfig (tcConfig, parsedMainInput,Path.GetDirectoryName mainInputFileName) - - // update the error handler with the modified tcConfig - errHandler.DiagnosticOptions <- tcConfig.diagnosticsOptions - - // Play background errors and warnings for this file. - do for err, severity in backgroundDiagnostics do - diagnosticSink (err, severity) + ( + parseResults: FSharpParseFileResults, + sourceText: ISourceText, + mainInputFileName: string, + projectOptions: FSharpProjectOptions, + projectFileName: string, + tcConfig: TcConfig, + tcGlobals: TcGlobals, + tcImports: TcImports, + tcState: TcState, + moduleNamesDict: ModuleNamesDict, + loadClosure: LoadClosure option, + backgroundDiagnostics: (PhasedDiagnostic * FSharpDiagnosticSeverity)[], + suggestNamesForErrors: bool + ) = - // If additional references were brought in by the preprocessor then we need to process them - ApplyLoadClosure(tcConfig, parsedMainInput, mainInputFileName, loadClosure, tcImports, backgroundDiagnostics) + cancellable { + use _logBlock = Logger.LogBlock LogCompilerFunctionId.Service_CheckOneFile - // A problem arises with nice name generation, which really should only - // be done in the backend, but is also done in the typechecker for better or worse. - // If we don't do this the NNG accumulates data and we get a memory leak. - tcState.NiceNameGenerator.Reset() + let parsedMainInput = parseResults.ParseTree - // Typecheck the real input. - let sink = TcResultsSinkImpl(tcGlobals, sourceText = sourceText) + // Initialize the error handler + let errHandler = + ErrorHandler(true, mainInputFileName, tcConfig.diagnosticsOptions, sourceText, suggestNamesForErrors) - let! resOpt = - cancellable { - try - let checkForErrors() = (parseResults.ParseHadErrors || errHandler.ErrorCount > 0) + use _unwindEL = + PushDiagnosticsLoggerPhaseUntilUnwind(fun _oldLogger -> errHandler.DiagnosticsLogger) - let parsedMainInput, _moduleNamesDict = DeduplicateParsedInputModuleName moduleNamesDict parsedMainInput + use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.TypeCheck - // Typecheck is potentially a long running operation. We chop it up here with an Eventually continuation and, at each slice, give a chance - // for the client to claim the result as obsolete and have the typecheck abort. + // Apply nowarns to tcConfig (may generate errors, so ensure diagnosticsLogger is installed) + let tcConfig = + ApplyNoWarnsToTcConfig(tcConfig, parsedMainInput, Path.GetDirectoryName mainInputFileName) - use _unwind = new CompilationGlobalsScope (errHandler.DiagnosticsLogger, BuildPhase.TypeCheck) - let! result = - CheckOneInputAndFinish(checkForErrors, tcConfig, tcImports, tcGlobals, None, TcResultsSink.WithSink sink, tcState, parsedMainInput) + // update the error handler with the modified tcConfig + errHandler.DiagnosticOptions <- tcConfig.diagnosticsOptions - return result - with e -> - errorR e - let mty = Construct.NewEmptyModuleOrNamespaceType ModuleOrNamespaceKind.Namespace - return ((tcState.TcEnvFromSignatures, EmptyTopAttrs, [], [ mty ]), tcState) - } + // Play background errors and warnings for this file. + do + for err, severity in backgroundDiagnostics do + diagnosticSink (err, severity) - let errors = errHandler.CollectedDiagnostics + // If additional references were brought in by the preprocessor then we need to process them + ApplyLoadClosure(tcConfig, parsedMainInput, mainInputFileName, loadClosure, tcImports, backgroundDiagnostics) - let res = - match resOpt with - | (tcEnvAtEnd, _, implFiles, ccuSigsForFiles), tcState -> - TypeCheckInfo(tcConfig, tcGlobals, - List.head ccuSigsForFiles, - tcState.Ccu, - tcImports, - tcEnvAtEnd.AccessRights, - projectFileName, - mainInputFileName, - projectOptions, - sink.GetResolutions(), - sink.GetSymbolUses(), - tcEnvAtEnd.NameEnv, - loadClosure, - List.tryHead implFiles, - sink.GetOpenDeclarations()) - return errors, res - } + // A problem arises with nice name generation, which really should only + // be done in the backend, but is also done in the typechecker for better or worse. + // If we don't do this the NNG accumulates data and we get a memory leak. + tcState.NiceNameGenerator.Reset() + + // Typecheck the real input. + let sink = TcResultsSinkImpl(tcGlobals, sourceText = sourceText) + + let! resOpt = + cancellable { + try + let checkForErrors () = + (parseResults.ParseHadErrors || errHandler.ErrorCount > 0) + + let parsedMainInput, _moduleNamesDict = + DeduplicateParsedInputModuleName moduleNamesDict parsedMainInput + + // Typecheck is potentially a long running operation. We chop it up here with an Eventually continuation and, at each slice, give a chance + // for the client to claim the result as obsolete and have the typecheck abort. + + use _unwind = + new CompilationGlobalsScope(errHandler.DiagnosticsLogger, BuildPhase.TypeCheck) + + let! result = + CheckOneInputAndFinish( + checkForErrors, + tcConfig, + tcImports, + tcGlobals, + None, + TcResultsSink.WithSink sink, + tcState, + parsedMainInput + ) + + return result + with e -> + errorR e + + let mty = + Construct.NewEmptyModuleOrNamespaceType(ModuleOrNamespaceKind.Namespace true) + + return ((tcState.TcEnvFromSignatures, EmptyTopAttrs, [], [ mty ]), tcState) + } + + let errors = errHandler.CollectedDiagnostics + + let res = + match resOpt with + | (tcEnvAtEnd, _, implFiles, ccuSigsForFiles), tcState -> + TypeCheckInfo( + tcConfig, + tcGlobals, + List.head ccuSigsForFiles, + tcState.Ccu, + tcImports, + tcEnvAtEnd.AccessRights, + projectFileName, + mainInputFileName, + projectOptions, + sink.GetResolutions(), + sink.GetSymbolUses(), + tcEnvAtEnd.NameEnv, + loadClosure, + List.tryHead implFiles, + sink.GetOpenDeclarations() + ) + + return errors, res + } [] type FSharpProjectContext(thisCcu: CcuThunk, assemblies: FSharpAssembly list, ad: AccessorDomain, projectOptions: FSharpProjectOptions) = - member _.ProjectOptions = projectOptions + member _.ProjectOptions = projectOptions member _.GetReferencedAssemblies() = assemblies member _.AccessibilityRights = FSharpAccessibilityRights(thisCcu, ad) - /// A live object of this type keeps the background corresponding background builder (and type providers) alive (through reference-counting). // // Note: objects returned by the methods of this type do not require the corresponding background builder to be alive. [] type FSharpCheckFileResults - (fileName: string, - errors: FSharpDiagnostic[], - scopeOptX: TypeCheckInfo option, - dependencyFiles: string[], - builderX: IncrementalBuilder option, - keepAssemblyContents: bool) = + ( + fileName: string, + errors: FSharpDiagnostic[], + scopeOptX: TypeCheckInfo option, + dependencyFiles: string[], + builderX: IncrementalBuilder option, + keepAssemblyContents: bool + ) = // Here 'details' keeps 'builder' alive - let details = match scopeOptX with None -> None | Some scopeX -> Some (scopeX, builderX) - - // Run an operation that can be called from any thread - let threadSafeOp dflt f = - match details with - | None -> dflt() - | Some (scope, _builderOpt) -> f scope + let details = + match scopeOptX with + | None -> None + | Some scopeX -> Some(scopeX, builderX) - static let emptyFindDeclResult = FindDeclResult.DeclNotFound (FindDeclFailureReason.Unknown "") + static let emptyFindDeclResult = + FindDeclResult.DeclNotFound(FindDeclFailureReason.Unknown "") member _.Diagnostics = errors member _.HasFullTypeCheckInfo = details.IsSome - member _.TryGetCurrentTcImports () = + member _.TryGetCurrentTcImports() = match details with | None -> None | Some (scope, _builderOpt) -> Some scope.TcImports /// Intellisense autocompletions member _.GetDeclarationListInfo(parsedFileResults, line, lineText, partialName, ?getAllEntities, ?completionContextAtPos) = - let getAllEntities = defaultArg getAllEntities (fun() -> []) - threadSafeOp (fun () -> DeclarationListInfo.Empty) (fun scope -> - scope.GetDeclarations(parsedFileResults, line, lineText, partialName, completionContextAtPos, getAllEntities)) + let getAllEntities = defaultArg getAllEntities (fun () -> []) + + match details with + | None -> DeclarationListInfo.Empty + | Some (scope, _builderOpt) -> + scope.GetDeclarations(parsedFileResults, line, lineText, partialName, completionContextAtPos, getAllEntities) member _.GetDeclarationListSymbols(parsedFileResults, line, lineText, partialName, ?getAllEntities) = - let getAllEntities = defaultArg getAllEntities (fun() -> []) - threadSafeOp (fun () -> []) (fun scope -> - scope.GetDeclarationListSymbols(parsedFileResults, line, lineText, partialName, getAllEntities)) + let getAllEntities = defaultArg getAllEntities (fun () -> []) + + match details with + | None -> [] + | Some (scope, _builderOpt) -> scope.GetDeclarationListSymbols(parsedFileResults, line, lineText, partialName, getAllEntities) /// Resolve the names at the given location to give a data tip member _.GetToolTip(line, colAtEndOfNames, lineText, names, tokenTag) = match tokenTagToTokenId tokenTag with | TOKEN_IDENT -> - threadSafeOp (fun () -> emptyToolTip) (fun scope -> - scope.GetStructuredToolTipText(line, lineText, colAtEndOfNames, names)) - | TOKEN_STRING | TOKEN_STRING_TEXT -> - threadSafeOp (fun () -> emptyToolTip) (fun scope -> - scope.GetReferenceResolutionStructuredToolTipText(line, colAtEndOfNames) ) - | _ -> - emptyToolTip + match details with + | None -> emptyToolTip + | Some (scope, _builderOpt) -> scope.GetStructuredToolTipText(line, lineText, colAtEndOfNames, names) + | TOKEN_STRING + | TOKEN_STRING_TEXT -> + match details with + | None -> emptyToolTip + | Some (scope, _builderOpt) -> scope.GetReferenceResolutionStructuredToolTipText(line, colAtEndOfNames) + | _ -> emptyToolTip member _.GetDescription(symbol: FSharpSymbol, inst: (FSharpGenericParameter * FSharpType) list, displayFullName, range: range) = - threadSafeOp (fun () -> emptyToolTip) (fun scope -> - scope.GetDescription(symbol, inst, displayFullName, range)) + match details with + | None -> emptyToolTip + | Some (scope, _builderOpt) -> scope.GetDescription(symbol, inst, displayFullName, range) - member _.GetF1Keyword (line, colAtEndOfNames, lineText, names) = - threadSafeOp (fun () -> None) (fun scope -> - scope.GetF1Keyword (line, lineText, colAtEndOfNames, names)) + member _.GetF1Keyword(line, colAtEndOfNames, lineText, names) = + match details with + | None -> None + | Some (scope, _builderOpt) -> scope.GetF1Keyword(line, lineText, colAtEndOfNames, names) // Resolve the names at the given location to a set of methods member _.GetMethods(line, colAtEndOfNames, lineText, names) = - threadSafeOp (fun () -> MethodGroup.Empty) (fun scope -> - scope.GetMethods (line, lineText, colAtEndOfNames, names)) + match details with + | None -> MethodGroup.Empty + | Some (scope, _builderOpt) -> scope.GetMethods(line, lineText, colAtEndOfNames, names) - member _.GetDeclarationLocation (line, colAtEndOfNames, lineText, names, ?preferFlag) = - threadSafeOp (fun () -> emptyFindDeclResult) (fun scope -> - scope.GetDeclarationLocation (line, lineText, colAtEndOfNames, names, preferFlag)) + member _.GetDeclarationLocation(line, colAtEndOfNames, lineText, names, ?preferFlag) = + match details with + | None -> emptyFindDeclResult + | Some (scope, _builderOpt) -> scope.GetDeclarationLocation(line, lineText, colAtEndOfNames, names, preferFlag) - member _.GetSymbolUseAtLocation (line, colAtEndOfNames, lineText, names) = - threadSafeOp (fun () -> None) (fun scope -> - scope.GetSymbolUseAtLocation (line, lineText, colAtEndOfNames, names) - |> Option.map (fun (sym, itemWithInst, denv,m) -> FSharpSymbolUse(denv,sym,itemWithInst.TyparInstantiation,ItemOccurence.Use,m))) + member _.GetSymbolUseAtLocation(line, colAtEndOfNames, lineText, names) = + match details with + | None -> None + | Some (scope, _builderOpt) -> + scope.GetSymbolUseAtLocation(line, lineText, colAtEndOfNames, names) + |> Option.map (fun (sym, itemWithInst, denv, m) -> + FSharpSymbolUse(denv, sym, itemWithInst.TyparInstantiation, ItemOccurence.Use, m)) - member _.GetMethodsAsSymbols (line, colAtEndOfNames, lineText, names) = - threadSafeOp (fun () -> None) (fun scope -> - scope.GetMethodsAsSymbols (line, lineText, colAtEndOfNames, names) - |> Option.map (fun (symbols,denv,m) -> - symbols |> List.map (fun (sym, itemWithInst) -> FSharpSymbolUse(denv,sym,itemWithInst.TyparInstantiation,ItemOccurence.Use,m)))) + member _.GetMethodsAsSymbols(line, colAtEndOfNames, lineText, names) = + match details with + | None -> None + | Some (scope, _builderOpt) -> + scope.GetMethodsAsSymbols(line, lineText, colAtEndOfNames, names) + |> Option.map (fun (symbols, denv, m) -> + symbols + |> List.map (fun (sym, itemWithInst) -> FSharpSymbolUse(denv, sym, itemWithInst.TyparInstantiation, ItemOccurence.Use, m))) - member _.GetSymbolAtLocation (line, colAtEndOfNames, lineStr, names) = - threadSafeOp (fun () -> None) (fun scope -> - scope.GetSymbolUseAtLocation (line, lineStr, colAtEndOfNames, names) - |> Option.map (fun (sym,_,_,_) -> sym)) + member _.GetSymbolAtLocation(line, colAtEndOfNames, lineStr, names) = + match details with + | None -> None + | Some (scope, _builderOpt) -> + scope.GetSymbolUseAtLocation(line, lineStr, colAtEndOfNames, names) + |> Option.map (fun (sym, _, _, _) -> sym) member info.GetFormatSpecifierLocations() = info.GetFormatSpecifierLocationsAndArity() |> Array.map fst member _.GetFormatSpecifierLocationsAndArity() = - threadSafeOp - (fun () -> [| |]) - (fun scope -> - scope.GetFormatSpecifierLocationsAndArity()) + match details with + | None -> [||] + | Some (scope, _builderOpt) -> scope.GetFormatSpecifierLocationsAndArity() member _.GetSemanticClassification(range: range option) = - threadSafeOp - (fun () -> [| |]) - (fun scope -> - scope.GetSemanticClassification(range)) + match details with + | None -> [||] + | Some (scope, _builderOpt) -> scope.GetSemanticClassification(range) member _.PartialAssemblySignature = - threadSafeOp - (fun () -> failwith "not available") - (fun scope -> - scope.PartialAssemblySignatureForFile) + match details with + | None -> failwith "not available" + | Some (scope, _builderOpt) -> scope.PartialAssemblySignatureForFile member _.ProjectContext = - threadSafeOp - (fun () -> failwith "not available") - (fun scope -> - FSharpProjectContext(scope.ThisCcu, scope.GetReferencedAssemblies(), scope.AccessRights, scope.ProjectOptions)) + match details with + | None -> failwith "not available" + | Some (scope, _builderOpt) -> + FSharpProjectContext(scope.ThisCcu, scope.GetReferencedAssemblies(), scope.AccessRights, scope.ProjectOptions) member _.DependencyFiles = dependencyFiles - member _.GetAllUsesOfAllSymbolsInFile(?cancellationToken: CancellationToken ) = - threadSafeOp - (fun () -> Seq.empty) - (fun scope -> - let cenv = scope.SymbolEnv - seq { - for symbolUseChunk in scope.ScopeSymbolUses.AllUsesOfSymbols do - for symbolUse in symbolUseChunk do - cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) - if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then - let symbol = FSharpSymbol.Create(cenv, symbolUse.ItemWithInst.Item) - FSharpSymbolUse(symbolUse.DisplayEnv, symbol, symbolUse.ItemWithInst.TyparInstantiation, symbolUse.ItemOccurence, symbolUse.Range) - }) - - member _.GetUsesOfSymbolInFile(symbol:FSharpSymbol, ?cancellationToken: CancellationToken) = - threadSafeOp - (fun () -> [| |]) - (fun scope -> - [| for symbolUse in scope.ScopeSymbolUses.GetUsesOfSymbol(symbol.Item) |> Seq.distinctBy (fun symbolUse -> symbolUse.ItemOccurence, symbolUse.Range) do - cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) - if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then - yield FSharpSymbolUse(symbolUse.DisplayEnv, symbol, symbolUse.ItemWithInst.TyparInstantiation, symbolUse.ItemOccurence, symbolUse.Range) |]) + member _.GetAllUsesOfAllSymbolsInFile(?cancellationToken: CancellationToken) = + match details with + | None -> Seq.empty + | Some (scope, _builderOpt) -> + let cenv = scope.SymbolEnv + + seq { + for symbolUseChunk in scope.ScopeSymbolUses.AllUsesOfSymbols do + for symbolUse in symbolUseChunk do + cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) + + if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then + let symbol = FSharpSymbol.Create(cenv, symbolUse.ItemWithInst.Item) + let inst = symbolUse.ItemWithInst.TyparInstantiation + FSharpSymbolUse(symbolUse.DisplayEnv, symbol, inst, symbolUse.ItemOccurence, symbolUse.Range) + } + + member _.GetUsesOfSymbolInFile(symbol: FSharpSymbol, ?cancellationToken: CancellationToken) = + match details with + | None -> [||] + | Some (scope, _builderOpt) -> + [| + for symbolUse in + scope.ScopeSymbolUses.GetUsesOfSymbol(symbol.Item) + |> Seq.distinctBy (fun symbolUse -> symbolUse.ItemOccurence, symbolUse.Range) do + cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) + + if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then + let inst = symbolUse.ItemWithInst.TyparInstantiation + FSharpSymbolUse(symbolUse.DisplayEnv, symbol, inst, symbolUse.ItemOccurence, symbolUse.Range) + |] member _.GetVisibleNamespacesAndModulesAtPoint(pos: pos) = - threadSafeOp - (fun () -> [| |]) - (fun scope -> scope.GetVisibleNamespacesAndModulesAtPosition(pos) |> List.toArray) + match details with + | None -> [||] + | Some (scope, _builderOpt) -> scope.GetVisibleNamespacesAndModulesAtPosition(pos) |> List.toArray member _.IsRelativeNameResolvable(cursorPos: pos, plid: string list, item: Item) = - threadSafeOp (fun () -> true) (fun scope -> - scope.IsRelativeNameResolvable(cursorPos, plid, item)) + match details with + | None -> true + | Some (scope, _builderOpt) -> scope.IsRelativeNameResolvable(cursorPos, plid, item) member _.IsRelativeNameResolvableFromSymbol(cursorPos: pos, plid: string list, symbol: FSharpSymbol) = - threadSafeOp (fun () -> true) (fun scope -> - scope.IsRelativeNameResolvableFromSymbol(cursorPos, plid, symbol)) + match details with + | None -> true + | Some (scope, _builderOpt) -> scope.IsRelativeNameResolvableFromSymbol(cursorPos, plid, symbol) member _.GetDisplayContextForPos(cursorPos: pos) = - threadSafeOp (fun () -> None) (fun scope -> + match details with + | None -> None + | Some (scope, _builderOpt) -> let (nenv, _), _ = scope.GetBestDisplayEnvForPos cursorPos - Some(FSharpDisplayContext(fun _ -> nenv.DisplayEnv))) + Some(FSharpDisplayContext(fun _ -> nenv.DisplayEnv)) - member _.GenerateSignature () = - threadSafeOp (fun () -> None) (fun scope -> + member _.GenerateSignature() = + match details with + | None -> None + | Some (scope, _builderOpt) -> scope.ImplementationFile |> Option.map (fun implFile -> let denv = DisplayEnv.InitialForSigFileGeneration scope.TcGlobals let infoReader = InfoReader(scope.TcGlobals, scope.TcImports.GetImportMap()) - let (CheckedImplFile (contents=mexpr)) = implFile + let (CheckedImplFile (contents = mexpr)) = implFile + let ad = match scopeOptX with | Some scope -> scope.AccessRights | _ -> AccessibleFromSomewhere - let layout = NicePrint.layoutImpliedSignatureOfModuleOrNamespace true denv infoReader ad range0 mexpr - layout |> LayoutRender.showL |> SourceText.ofString - ) - ) + + let layout = + NicePrint.layoutImpliedSignatureOfModuleOrNamespace true denv infoReader ad range0 mexpr + + layout |> LayoutRender.showL |> SourceText.ofString) member _.ImplementationFile = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + if not keepAssemblyContents then + invalidOp + "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + scopeOptX |> Option.map (fun scope -> - let cenv = SymbolEnv(scope.TcGlobals, scope.ThisCcu, Some scope.CcuSigForFile, scope.TcImports) - scope.ImplementationFile |> Option.map (fun implFile -> FSharpImplementationFileContents(cenv, implFile))) + let cenv = + SymbolEnv(scope.TcGlobals, scope.ThisCcu, Some scope.CcuSigForFile, scope.TcImports) + + scope.ImplementationFile + |> Option.map (fun implFile -> FSharpImplementationFileContents(cenv, implFile))) |> Option.defaultValue None member _.OpenDeclarations = scopeOptX |> Option.map (fun scope -> let cenv = scope.SymbolEnv - scope.OpenDeclarations |> Array.map (fun x -> + + scope.OpenDeclarations + |> Array.map (fun x -> let modules = x.Modules |> List.map (fun x -> FSharpEntity(cenv, x)) let types = x.Types |> List.map (fun x -> FSharpType(cenv, x)) FSharpOpenDeclaration(x.Target, x.Range, modules, types, x.AppliedScope, x.IsOwnNamespace))) - |> Option.defaultValue [| |] + |> Option.defaultValue [||] - override _.ToString() = "FSharpCheckFileResults(" + fileName + ")" + override _.ToString() = + "FSharpCheckFileResults(" + fileName + ")" static member MakeEmpty(fileName: string, creationErrors: FSharpDiagnostic[], keepAssemblyContents) = - FSharpCheckFileResults (fileName, creationErrors, None, [| |], None, keepAssemblyContents) - - static member JoinErrors(isIncompleteTypeCheckEnvironment, - creationErrors: FSharpDiagnostic[], - parseErrors: FSharpDiagnostic[], - tcErrors: FSharpDiagnostic[]) = - [| yield! creationErrors - yield! parseErrors - if isIncompleteTypeCheckEnvironment then - yield! Seq.truncate maxTypeCheckErrorsOutOfProjectContext tcErrors - else - yield! tcErrors |] + FSharpCheckFileResults(fileName, creationErrors, None, [||], None, keepAssemblyContents) + + static member JoinErrors + ( + isIncompleteTypeCheckEnvironment, + creationErrors: FSharpDiagnostic[], + parseErrors: FSharpDiagnostic[], + tcErrors: FSharpDiagnostic[] + ) = + [| + yield! creationErrors + yield! parseErrors + if isIncompleteTypeCheckEnvironment then + yield! Seq.truncate maxTypeCheckErrorsOutOfProjectContext tcErrors + else + yield! tcErrors + |] static member Make - (mainInputFileName: string, - projectFileName, - tcConfig, tcGlobals, - isIncompleteTypeCheckEnvironment: bool, - builder: IncrementalBuilder, - projectOptions, - dependencyFiles, - creationErrors: FSharpDiagnostic[], - parseErrors: FSharpDiagnostic[], - tcErrors: FSharpDiagnostic[], - keepAssemblyContents, - ccuSigForFile, - thisCcu, tcImports, tcAccessRights, - sResolutions, sSymbolUses, - sFallback, loadClosure, - implFileOpt, - openDeclarations) = + ( + mainInputFileName: string, + projectFileName, + tcConfig, + tcGlobals, + isIncompleteTypeCheckEnvironment: bool, + builder: IncrementalBuilder, + projectOptions, + dependencyFiles, + creationErrors: FSharpDiagnostic[], + parseErrors: FSharpDiagnostic[], + tcErrors: FSharpDiagnostic[], + keepAssemblyContents, + ccuSigForFile, + thisCcu, + tcImports, + tcAccessRights, + sResolutions, + sSymbolUses, + sFallback, + loadClosure, + implFileOpt, + openDeclarations + ) = let tcFileInfo = - TypeCheckInfo(tcConfig, tcGlobals, ccuSigForFile, thisCcu, tcImports, tcAccessRights, - projectFileName, mainInputFileName, - projectOptions, - sResolutions, sSymbolUses, - sFallback, loadClosure, - implFileOpt, openDeclarations) + TypeCheckInfo( + tcConfig, + tcGlobals, + ccuSigForFile, + thisCcu, + tcImports, + tcAccessRights, + projectFileName, + mainInputFileName, + projectOptions, + sResolutions, + sSymbolUses, + sFallback, + loadClosure, + implFileOpt, + openDeclarations + ) + + let errors = + FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) - let errors = FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) - FSharpCheckFileResults (mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, keepAssemblyContents) + FSharpCheckFileResults(mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, keepAssemblyContents) static member CheckOneFile - (parseResults: FSharpParseFileResults, - sourceText: ISourceText, - mainInputFileName: string, - projectFileName: string, - tcConfig: TcConfig, - tcGlobals: TcGlobals, - tcImports: TcImports, - tcState: TcState, - moduleNamesDict: ModuleNamesDict, - loadClosure: LoadClosure option, - backgroundDiagnostics: (PhasedDiagnostic * FSharpDiagnosticSeverity)[], - isIncompleteTypeCheckEnvironment: bool, - projectOptions: FSharpProjectOptions, - builder: IncrementalBuilder, - dependencyFiles: string[], - creationErrors: FSharpDiagnostic[], - parseErrors: FSharpDiagnostic[], - keepAssemblyContents: bool, - suggestNamesForErrors: bool) = + ( + parseResults: FSharpParseFileResults, + sourceText: ISourceText, + mainInputFileName: string, + projectFileName: string, + tcConfig: TcConfig, + tcGlobals: TcGlobals, + tcImports: TcImports, + tcState: TcState, + moduleNamesDict: ModuleNamesDict, + loadClosure: LoadClosure option, + backgroundDiagnostics: (PhasedDiagnostic * FSharpDiagnosticSeverity)[], + isIncompleteTypeCheckEnvironment: bool, + projectOptions: FSharpProjectOptions, + builder: IncrementalBuilder, + dependencyFiles: string[], + creationErrors: FSharpDiagnostic[], + parseErrors: FSharpDiagnostic[], + keepAssemblyContents: bool, + suggestNamesForErrors: bool + ) = cancellable { let! tcErrors, tcFileInfo = - ParseAndCheckFile.CheckOneFile - (parseResults, sourceText, mainInputFileName, projectOptions, - projectFileName, tcConfig, tcGlobals, tcImports, - tcState, moduleNamesDict, loadClosure, backgroundDiagnostics, suggestNamesForErrors) - let errors = FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) - let results = FSharpCheckFileResults (mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, keepAssemblyContents) + ParseAndCheckFile.CheckOneFile( + parseResults, + sourceText, + mainInputFileName, + projectOptions, + projectFileName, + tcConfig, + tcGlobals, + tcImports, + tcState, + moduleNamesDict, + loadClosure, + backgroundDiagnostics, + suggestNamesForErrors + ) + + let errors = + FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) + + let results = + FSharpCheckFileResults(mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, keepAssemblyContents) + return results } [] // 'details' is an option because the creation of the tcGlobals etc. for the project may have failed. type FSharpCheckProjectResults - (projectFileName:string, - tcConfigOption: TcConfig option, - keepAssemblyContents: bool, - diagnostics: FSharpDiagnostic[], - details:(TcGlobals * TcImports * CcuThunk * ModuleOrNamespaceType * Choice * - TopAttribs option * (unit -> IRawFSharpAssemblyData option) * ILAssemblyRef * - AccessorDomain * CheckedImplFile list option * string[] * FSharpProjectOptions) option) = - - let getDetails() = + ( + projectFileName: string, + tcConfigOption: TcConfig option, + keepAssemblyContents: bool, + diagnostics: FSharpDiagnostic[], + details: (TcGlobals * TcImports * CcuThunk * ModuleOrNamespaceType * Choice * TopAttribs option * (unit -> IRawFSharpAssemblyData option) * ILAssemblyRef * AccessorDomain * CheckedImplFile list option * string[] * FSharpProjectOptions) option + ) = + + let getDetails () = match details with - | None -> invalidOp ("The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + String.concat "\n" [ for e in diagnostics -> e.Message ]) + | None -> + invalidOp ( + "The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + + String.concat "\n" [ for e in diagnostics -> e.Message ] + ) | Some d -> d - let getTcConfig() = + let getTcConfig () = match tcConfigOption with - | None -> invalidOp ("The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + String.concat "\n" [ for e in diagnostics -> e.Message ]) + | None -> + invalidOp ( + "The project has no results due to critical errors in the project options. Check the HasCriticalErrors before accessing the detailed results. Errors: " + + String.concat "\n" [ for e in diagnostics -> e.Message ] + ) | Some d -> d member _.Diagnostics = diagnostics @@ -2279,50 +2955,73 @@ type FSharpCheckProjectResults member _.HasCriticalErrors = details.IsNone member _.AssemblySignature = - let tcGlobals, tcImports, thisCcu, ccuSig, _builderOrSymbolUses, topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles, _projectOptions = getDetails() + let tcGlobals, tcImports, thisCcu, ccuSig, _, topAttribs, _, _, _, _, _, _ = + getDetails () + FSharpAssemblySignature(tcGlobals, thisCcu, ccuSig, tcImports, topAttribs, ccuSig) member _.TypedImplementationFiles = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" - let tcGlobals, tcImports, thisCcu, _ccuSig, _builderOrSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles, _projectOptions = getDetails() + if not keepAssemblyContents then + invalidOp + "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + + let tcGlobals, tcImports, thisCcu, _, _, _, _, _, _, tcAssemblyExpr, _, _ = + getDetails () + let mimpls = match tcAssemblyExpr with | None -> [] | Some mimpls -> mimpls + tcGlobals, thisCcu, tcImports, mimpls member info.AssemblyContents = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" - let tcGlobals, tcImports, thisCcu, ccuSig, _builderOrSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles, _projectOptions = getDetails() + if not keepAssemblyContents then + invalidOp + "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + + let tcGlobals, tcImports, thisCcu, ccuSig, _, _, _, _, _, tcAssemblyExpr, _, _ = + getDetails () + let mimpls = match tcAssemblyExpr with | None -> [] | Some mimpls -> mimpls + FSharpAssemblyContents(tcGlobals, thisCcu, Some ccuSig, tcImports, mimpls) member _.GetOptimizedAssemblyContents() = - if not keepAssemblyContents then invalidOp "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" - let tcGlobals, tcImports, thisCcu, ccuSig, _builderOrSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, tcAssemblyExpr, _dependencyFiles, _projectOptions = getDetails() + if not keepAssemblyContents then + invalidOp + "The 'keepAssemblyContents' flag must be set to true on the FSharpChecker in order to access the checked contents of assemblies" + + let tcGlobals, tcImports, thisCcu, ccuSig, _, _, _, _, _, tcAssemblyExpr, _, _ = + getDetails () + let mimpls = match tcAssemblyExpr with | None -> [] | Some mimpls -> mimpls + let outfile = "" // only used if tcConfig.writeTermsToFiles is true let importMap = tcImports.GetImportMap() - let optEnv0 = GetInitialOptimizationEnv (tcImports, tcGlobals) - let tcConfig = getTcConfig() + let optEnv0 = GetInitialOptimizationEnv(tcImports, tcGlobals) + let tcConfig = getTcConfig () let isIncrementalFragment = false - let optimizedImpls, _optimizationData, _ = ApplyAllOptimizations (tcConfig, tcGlobals, LightweightTcValForUsingInBuildMethodCall tcGlobals, outfile, importMap, isIncrementalFragment, optEnv0, thisCcu, mimpls) + let tcVal = LightweightTcValForUsingInBuildMethodCall tcGlobals + + let optimizedImpls, _optimizationData, _ = + ApplyAllOptimizations(tcConfig, tcGlobals, tcVal, outfile, importMap, isIncrementalFragment, optEnv0, thisCcu, mimpls) + let mimpls = match optimizedImpls with - | CheckedAssemblyAfterOptimization files -> - files |> List.map (fun implFile -> implFile.ImplFile) + | CheckedAssemblyAfterOptimization files -> files |> List.map (fun implFile -> implFile.ImplFile) FSharpAssemblyContents(tcGlobals, thisCcu, Some ccuSig, tcImports, mimpls) // Not, this does not have to be a SyncOp, it can be called from any thread - member _.GetUsesOfSymbol(symbol:FSharpSymbol, ?cancellationToken: CancellationToken) = - let _, _tcImports, _thisCcu, _ccuSig, builderOrSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles, _projectOptions = getDetails() + member _.GetUsesOfSymbol(symbol: FSharpSymbol, ?cancellationToken: CancellationToken) = + let _, _, _, _, builderOrSymbolUses, _, _, _, _, _, _, _ = getDetails () let results = match builderOrSymbolUses with @@ -2333,27 +3032,25 @@ type FSharpCheckProjectResults match builder.GetCheckResultsForFileInProjectEvenIfStale x with | Some partialCheckResults -> match partialCheckResults.TryPeekTcInfoWithExtras() with - | Some(_, tcInfoExtras) -> - tcInfoExtras.TcSymbolUses.GetUsesOfSymbol symbol.Item - | _ -> - [||] - | _ -> - [||] - ) - | Choice2Of2 tcSymbolUses -> - tcSymbolUses.GetUsesOfSymbol symbol.Item + | Some (_, tcInfoExtras) -> tcInfoExtras.TcSymbolUses.GetUsesOfSymbol symbol.Item + | _ -> [||] + | _ -> [||]) + | Choice2Of2 tcSymbolUses -> tcSymbolUses.GetUsesOfSymbol symbol.Item results |> Seq.filter (fun symbolUse -> symbolUse.ItemOccurence <> ItemOccurence.RelatedText) |> Seq.distinctBy (fun symbolUse -> symbolUse.ItemOccurence, symbolUse.Range) |> Seq.map (fun symbolUse -> - cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) - FSharpSymbolUse(symbolUse.DisplayEnv, symbol, symbolUse.ItemWithInst.TyparInstantiation, symbolUse.ItemOccurence, symbolUse.Range)) + cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) + let inst = symbolUse.ItemWithInst.TyparInstantiation + FSharpSymbolUse(symbolUse.DisplayEnv, symbol, inst, symbolUse.ItemOccurence, symbolUse.Range)) |> Seq.toArray // Not, this does not have to be a SyncOp, it can be called from any thread member _.GetAllUsesOfAllSymbols(?cancellationToken: CancellationToken) = - let tcGlobals, tcImports, thisCcu, ccuSig, builderOrSymbolUses, _topAttribs, _ilAssemRef, _tcAssemblyData, _ad, _tcAssemblyExpr, _dependencyFiles, _projectOptions = getDetails() + let tcGlobals, tcImports, thisCcu, ccuSig, builderOrSymbolUses, _, _, _, _, _, _, _ = + getDetails () + let cenv = SymbolEnv(tcGlobals, thisCcu, Some ccuSig, tcImports) let tcSymbolUses = @@ -2365,115 +3062,152 @@ type FSharpCheckProjectResults match builder.GetCheckResultsForFileInProjectEvenIfStale x with | Some partialCheckResults -> match partialCheckResults.TryPeekTcInfoWithExtras() with - | Some(_, tcInfoExtras) -> - tcInfoExtras.TcSymbolUses - | _ -> - TcSymbolUses.Empty - | _ -> - TcSymbolUses.Empty - ) - | Choice2Of2 tcSymbolUses -> - [|tcSymbolUses|] - - [| for r in tcSymbolUses do - for symbolUseChunk in r.AllUsesOfSymbols do - for symbolUse in symbolUseChunk do - cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) - if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then - let symbol = FSharpSymbol.Create(cenv, symbolUse.ItemWithInst.Item) - yield FSharpSymbolUse(symbolUse.DisplayEnv, symbol, symbolUse.ItemWithInst.TyparInstantiation, symbolUse.ItemOccurence, symbolUse.Range) |] + | Some (_, tcInfoExtras) -> tcInfoExtras.TcSymbolUses + | _ -> TcSymbolUses.Empty + | _ -> TcSymbolUses.Empty) + | Choice2Of2 tcSymbolUses -> [| tcSymbolUses |] + + [| + for r in tcSymbolUses do + for symbolUseChunk in r.AllUsesOfSymbols do + for symbolUse in symbolUseChunk do + cancellationToken |> Option.iter (fun ct -> ct.ThrowIfCancellationRequested()) + + if symbolUse.ItemOccurence <> ItemOccurence.RelatedText then + let symbol = FSharpSymbol.Create(cenv, symbolUse.ItemWithInst.Item) + let inst = symbolUse.ItemWithInst.TyparInstantiation + FSharpSymbolUse(symbolUse.DisplayEnv, symbol, inst, symbolUse.ItemOccurence, symbolUse.Range) + |] member _.ProjectContext = - let tcGlobals, tcImports, thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, ad, _tcAssemblyExpr, _dependencyFiles, projectOptions = getDetails() + let tcGlobals, tcImports, thisCcu, _, _, _, _, _, ad, _, _, projectOptions = + getDetails () + let assemblies = tcImports.GetImportedAssemblies() |> List.map (fun x -> FSharpAssembly(tcGlobals, tcImports, x.FSharpViewOfMetadata)) + FSharpProjectContext(thisCcu, assemblies, ad, projectOptions) member _.DependencyFiles = - let _tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, _ilAssemRef, _ad, _tcAssemblyExpr, dependencyFiles, _projectOptions = getDetails() + let _tcGlobals, _, _, _, _, _, _, _, _, _, dependencyFiles, _ = getDetails () dependencyFiles member _.AssemblyFullName = - let _tcGlobals, _tcImports, _thisCcu, _ccuSig, _tcSymbolUses, _topAttribs, _tcAssemblyData, ilAssemRef, _ad, _tcAssemblyExpr, _dependencyFiles, _projectOptions = getDetails() + let _tcGlobals, _, _, _, _, _, _, ilAssemRef, _, _, _, _ = getDetails () ilAssemRef.QualifiedName - override _.ToString() = "FSharpCheckProjectResults(" + projectFileName + ")" + override _.ToString() = + "FSharpCheckProjectResults(" + projectFileName + ")" -type FsiInteractiveChecker(legacyReferenceResolver, - tcConfig: TcConfig, - tcGlobals: TcGlobals, - tcImports: TcImports, - tcState) = +type FsiInteractiveChecker(legacyReferenceResolver, tcConfig: TcConfig, tcGlobals: TcGlobals, tcImports: TcImports, tcState) = let keepAssemblyContents = false - member _.ParseAndCheckInteraction (sourceText: ISourceText, ?userOpName: string) = + member _.ParseAndCheckInteraction(sourceText: ISourceText, ?userOpName: string) = cancellable { let userOpName = defaultArg userOpName "Unknown" let fileName = Path.Combine(tcConfig.implicitIncludeDir, "stdin.fsx") let suggestNamesForErrors = true // Will always be true, this is just for readability // Note: projectSourceFiles is only used to compute isLastCompiland, and is ignored if Build.IsScript(mainInputFileName) is true (which it is in this case). - let parsingOptions = FSharpParsingOptions.FromTcConfig(tcConfig, [| fileName |], true) - let parseErrors, parsedInput, anyErrors = ParseAndCheckFile.parseFile (sourceText, fileName, parsingOptions, userOpName, suggestNamesForErrors) - let dependencyFiles = [| |] // interactions have no dependencies - let parseResults = FSharpParseFileResults(parseErrors, parsedInput, parseHadErrors = anyErrors, dependencyFiles = dependencyFiles) + let parsingOptions = + FSharpParsingOptions.FromTcConfig(tcConfig, [| fileName |], true) + + let parseErrors, parsedInput, anyErrors = + ParseAndCheckFile.parseFile (sourceText, fileName, parsingOptions, userOpName, suggestNamesForErrors) + + let dependencyFiles = [||] // interactions have no dependencies + + let parseResults = + FSharpParseFileResults(parseErrors, parsedInput, parseHadErrors = anyErrors, dependencyFiles = dependencyFiles) - let backgroundDiagnostics = [| |] + let backgroundDiagnostics = [||] let reduceMemoryUsage = ReduceMemoryFlag.Yes let assumeDotNetFramework = (tcConfig.primaryAssembly = PrimaryAssembly.Mscorlib) - let applyCompilerOptions tcConfigB = + let applyCompilerOptions tcConfigB = let fsiCompilerOptions = CompilerOptions.GetCoreFsiCompilerOptions tcConfigB - CompilerOptions.ParseCompilerOptions (ignore, fsiCompilerOptions, [ ]) + CompilerOptions.ParseCompilerOptions(ignore, fsiCompilerOptions, []) let loadClosure = - LoadClosure.ComputeClosureOfScriptText(legacyReferenceResolver, defaultFSharpBinariesDir, - fileName, sourceText, CodeContext.Editing, - tcConfig.useSimpleResolution, tcConfig.useFsiAuxLib, - tcConfig.useSdkRefs, tcConfig.sdkDirOverride, LexResourceManager(), - applyCompilerOptions, assumeDotNetFramework, - tryGetMetadataSnapshot=(fun _ -> None), - reduceMemoryUsage=reduceMemoryUsage, - dependencyProvider=tcImports.DependencyProvider) + LoadClosure.ComputeClosureOfScriptText( + legacyReferenceResolver, + defaultFSharpBinariesDir, + fileName, + sourceText, + CodeContext.Editing, + tcConfig.useSimpleResolution, + tcConfig.useFsiAuxLib, + tcConfig.useSdkRefs, + tcConfig.sdkDirOverride, + LexResourceManager(), + applyCompilerOptions, + assumeDotNetFramework, + tryGetMetadataSnapshot = (fun _ -> None), + reduceMemoryUsage = reduceMemoryUsage, + dependencyProvider = tcImports.DependencyProvider + ) let projectOptions = { - ProjectFileName="script.fsproj" - ProjectId=None - SourceFiles=[||] - OtherOptions=[||] - ReferencedProjects=[||] - IsIncompleteTypeCheckEnvironment=false - UseScriptResolutionRules =false - LoadTime=DateTime.Now - UnresolvedReferences =None - OriginalLoadReferences = [] - Stamp = None + ProjectFileName = "script.fsproj" + ProjectId = None + SourceFiles = [||] + OtherOptions = [||] + ReferencedProjects = [||] + IsIncompleteTypeCheckEnvironment = false + UseScriptResolutionRules = false + LoadTime = DateTime.Now + UnresolvedReferences = None + OriginalLoadReferences = [] + Stamp = None } let! tcErrors, tcFileInfo = - ParseAndCheckFile.CheckOneFile - (parseResults, sourceText, fileName, projectOptions, projectOptions.ProjectFileName, - tcConfig, tcGlobals, tcImports, tcState, - Map.empty, Some loadClosure, backgroundDiagnostics, - suggestNamesForErrors) + ParseAndCheckFile.CheckOneFile( + parseResults, + sourceText, + fileName, + projectOptions, + projectOptions.ProjectFileName, + tcConfig, + tcGlobals, + tcImports, + tcState, + Map.empty, + Some loadClosure, + backgroundDiagnostics, + suggestNamesForErrors + ) let errors = Array.append parseErrors tcErrors - let typeCheckResults = FSharpCheckFileResults (fileName, errors, Some tcFileInfo, dependencyFiles, None, false) + + let typeCheckResults = + FSharpCheckFileResults(fileName, errors, Some tcFileInfo, dependencyFiles, None, false) + + let details = + (tcGlobals, + tcImports, + tcFileInfo.ThisCcu, + tcFileInfo.CcuSigForFile, + Choice2Of2 tcFileInfo.ScopeSymbolUses, + None, + (fun () -> None), + mkSimpleAssemblyRef "stdin", + tcState.TcEnvFromImpls.AccessRights, + None, + dependencyFiles, + projectOptions) + let projectResults = - FSharpCheckProjectResults (fileName, Some tcConfig, - keepAssemblyContents, errors, - Some(tcGlobals, tcImports, tcFileInfo.ThisCcu, tcFileInfo.CcuSigForFile, - (Choice2Of2 tcFileInfo.ScopeSymbolUses), None, (fun () -> None), mkSimpleAssemblyRef "stdin", - tcState.TcEnvFromImpls.AccessRights, None, dependencyFiles, - projectOptions)) + FSharpCheckProjectResults(fileName, Some tcConfig, keepAssemblyContents, errors, Some details) return parseResults, typeCheckResults, projectResults } /// The result of calling TypeCheckResult including the possibility of abort and background compiler not caught up. -type [] public FSharpCheckFileAnswer = +[] +type public FSharpCheckFileAnswer = /// Aborted because cancellation caused an abandonment of the operation | Aborted diff --git a/src/Compiler/Service/FSharpParseFileResults.fs b/src/Compiler/Service/FSharpParseFileResults.fs index f1f49b911a5..c2ee71a022e 100644 --- a/src/Compiler/Service/FSharpParseFileResults.fs +++ b/src/Compiler/Service/FSharpParseFileResults.fs @@ -6,7 +6,7 @@ open System open System.IO open System.Collections.Generic open System.Diagnostics -open Internal.Utilities.Library +open Internal.Utilities.Library open Internal.Utilities.Library.Extras open FSharp.Compiler.Diagnostics open FSharp.Compiler.EditorServices @@ -21,20 +21,22 @@ module SourceFileImpl = 0 = String.Compare(".fsi", ext, StringComparison.OrdinalIgnoreCase) /// Additional #defines that should be in place when editing a file in a file editor such as VS. - let GetImplicitConditionalDefinesForEditing(isInteractive: bool) = - if isInteractive then ["INTERACTIVE";"EDITING"] // This is still used by the foreground parse - else ["COMPILED";"EDITING"] - + let GetImplicitConditionalDefinesForEditing (isInteractive: bool) = + if isInteractive then + [ "INTERACTIVE"; "EDITING" ] // This is still used by the foreground parse + else + [ "COMPILED"; "EDITING" ] + type CompletionPath = string list * string option // plid * residue [] -type FSharpInheritanceOrigin = +type FSharpInheritanceOrigin = | Class | Interface | Unknown [] -type InheritanceContext = +type InheritanceContext = | Class | Interface | Unknown @@ -46,7 +48,7 @@ type RecordContext = | New of path: CompletionPath [] -type CompletionContext = +type CompletionContext = /// Completion context cannot be determined due to errors | Invalid @@ -74,7 +76,7 @@ type CompletionContext = //---------------------------------------------------------------------------- [] -type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, parseHadErrors: bool, dependencyFiles: string[]) = +type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, parseHadErrors: bool, dependencyFiles: string[]) = member _.Diagnostics = diagnostics @@ -85,15 +87,12 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, member _.TryRangeOfNameOfNearestOuterBindingContainingPos pos = let tryGetIdentRangeFromBinding binding = match binding with - | SynBinding(headPat=headPat) -> + | SynBinding (headPat = headPat) -> match headPat with - | SynPat.LongIdent (longDotId=longIdentWithDots) -> - Some longIdentWithDots.Range - | SynPat.As (rhsPat=SynPat.Named (ident=SynIdent(ident,_); isThisVal=false)) - | SynPat.Named (SynIdent(ident,_), false, _, _) -> - Some ident.idRange - | _ -> - None + | SynPat.LongIdent (longDotId = longIdentWithDots) -> Some longIdentWithDots.Range + | SynPat.As(rhsPat = SynPat.Named (ident = SynIdent (ident, _); isThisVal = false)) + | SynPat.Named (SynIdent (ident, _), false, _, _) -> Some ident.idRange + | _ -> None let rec walkBinding expr workingRange = match expr with @@ -105,81 +104,82 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, else walkBinding expr2 workingRange - - | SynExpr.LetOrUse(bindings=bindings; body=bodyExpr) -> + | SynExpr.LetOrUse (bindings = bindings; body = bodyExpr) -> let potentialNestedRange = bindings |> List.tryFind (fun binding -> rangeContainsPos binding.RangeOfBindingWithRhs pos) |> Option.bind tryGetIdentRangeFromBinding + match potentialNestedRange with - | Some range -> - walkBinding bodyExpr range - | None -> - walkBinding bodyExpr workingRange + | Some range -> walkBinding bodyExpr range + | None -> walkBinding bodyExpr workingRange - - | _ -> - Some workingRange + | _ -> Some workingRange - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - override _.VisitExpr(_, _, defaultTraverse, expr) = - defaultTraverse expr + let visitor = + { new SyntaxVisitorBase<_>() with + override _.VisitExpr(_, _, defaultTraverse, expr) = defaultTraverse expr + + override _.VisitBinding(_path, defaultTraverse, binding) = + match binding with + | SynBinding (valData = SynValData(memberFlags = None); expr = expr) as b when + rangeContainsPos b.RangeOfBindingWithRhs pos + -> + match tryGetIdentRangeFromBinding b with + | Some range -> walkBinding expr range + | None -> None + | _ -> defaultTraverse binding + } + + SyntaxTraversal.Traverse(pos, input, visitor) - override _.VisitBinding(_path, defaultTraverse, binding) = - match binding with - | SynBinding(valData=SynValData (memberFlags=None); expr=expr) as b when rangeContainsPos b.RangeOfBindingWithRhs pos -> - match tryGetIdentRangeFromBinding b with - | Some range -> walkBinding expr range - | None -> None - | _ -> defaultTraverse binding }) - member _.TryIdentOfPipelineContainingPosAndNumArgsApplied pos = - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_, _, defaultTraverse, expr) = - match expr with - | SynExpr.App (_, _, SynExpr.App(_, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ident])), _, _), argExpr, _) when rangeContainsPos argExpr.Range pos -> - match argExpr with - | SynExpr.App(_, _, _, SynExpr.Paren(expr, _, _, _), _) when rangeContainsPos expr.Range pos -> - None - | _ -> - if ident.idText = "op_PipeRight" then - Some (ident, 1) - elif ident.idText = "op_PipeRight2" then - Some (ident, 2) - elif ident.idText = "op_PipeRight3" then - Some (ident, 3) - else - None - | _ -> defaultTraverse expr - }) - + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, _, defaultTraverse, expr) = + match expr with + | SynExpr.App (_, + _, + SynExpr.App (_, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ ident ])), _, _), + argExpr, + _) when rangeContainsPos argExpr.Range pos -> + match argExpr with + | SynExpr.App (_, _, _, SynExpr.Paren (expr, _, _, _), _) when rangeContainsPos expr.Range pos -> None + | _ -> + if ident.idText = "op_PipeRight" then Some(ident, 1) + elif ident.idText = "op_PipeRight2" then Some(ident, 2) + elif ident.idText = "op_PipeRight3" then Some(ident, 3) + else None + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(pos, input, visitor) + member _.IsPosContainedInApplication pos = - let result = - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with + let visitor = + { new SyntaxVisitorBase<_>() with member _.VisitExpr(_, traverseSynExpr, defaultTraverse, expr) = match expr with - | SynExpr.TypeApp (_, _, _, _, _, _, range) when rangeContainsPos range pos -> - Some range - | SynExpr.App(_, _, _, SynExpr.ComputationExpr (_, expr, _), range) when rangeContainsPos range pos -> + | SynExpr.TypeApp (_, _, _, _, _, _, range) when rangeContainsPos range pos -> Some range + | SynExpr.App (_, _, _, SynExpr.ComputationExpr (_, expr, _), range) when rangeContainsPos range pos -> traverseSynExpr expr - | SynExpr.App (_, _, _, _, range) when rangeContainsPos range pos -> - Some range + | SynExpr.App (_, _, _, _, range) when rangeContainsPos range pos -> Some range | _ -> defaultTraverse expr - }) + } + + let result = SyntaxTraversal.Traverse(pos, input, visitor) result.IsSome member _.TryRangeOfFunctionOrMethodBeingApplied pos = let rec getIdentRangeForFuncExprInApp traverseSynExpr expr pos = match expr with | SynExpr.Ident ident -> Some ident.idRange - + | SynExpr.LongIdent (_, _, _, range) -> Some range - | SynExpr.Paren (expr, _, _, range) when rangeContainsPos range pos -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | SynExpr.Paren (expr, _, _, range) when rangeContainsPos range pos -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos - | SynExpr.TypeApp (expr, _, _, _, _, _, _) -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | SynExpr.TypeApp (expr, _, _, _, _, _, _) -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos | SynExpr.App (_, _, funcExpr, argExpr, _) -> match argExpr with @@ -213,7 +213,7 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, | _ -> match funcExpr with | SynExpr.App (_, true, _, _, _) when rangeContainsPos argExpr.Range pos -> - // x |> List.map + // x |> List.map // Don't dive into the funcExpr (the operator expr) // because we dont want to offer sig help for that! getIdentRangeForFuncExprInApp traverseSynExpr argExpr pos @@ -228,17 +228,15 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, else getIdentRangeForFuncExprInApp traverseSynExpr expr2 pos - | SynExpr.LetOrUse (bindings=bindings; body=body; range=range) when rangeContainsPos range pos -> + | SynExpr.LetOrUse (bindings = bindings; body = body; range = range) when rangeContainsPos range pos -> let binding = - bindings - |> List.tryFind (fun x -> rangeContainsPos x.RangeOfBindingWithRhs pos) + bindings |> List.tryFind (fun x -> rangeContainsPos x.RangeOfBindingWithRhs pos) + match binding with - | Some(SynBinding.SynBinding(expr=expr)) -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos - | None -> - getIdentRangeForFuncExprInApp traverseSynExpr body pos + | Some (SynBinding.SynBinding (expr = expr)) -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | None -> getIdentRangeForFuncExprInApp traverseSynExpr body pos - | SynExpr.IfThenElse (ifExpr=ifExpr; thenExpr=thenExpr; elseExpr=elseExpr; range=range) when rangeContainsPos range pos -> + | SynExpr.IfThenElse (ifExpr = ifExpr; thenExpr = thenExpr; elseExpr = elseExpr; range = range) when rangeContainsPos range pos -> if rangeContainsPos ifExpr.Range pos then getIdentRangeForFuncExprInApp traverseSynExpr ifExpr pos elif rangeContainsPos thenExpr.Range pos then @@ -246,168 +244,192 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, else match elseExpr with | None -> None - | Some expr -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | Some expr -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos - | SynExpr.Match (expr=expr; clauses=clauses; range=range) when rangeContainsPos range pos -> + | SynExpr.Match (expr = expr; clauses = clauses; range = range) when rangeContainsPos range pos -> if rangeContainsPos expr.Range pos then getIdentRangeForFuncExprInApp traverseSynExpr expr pos else - let clause = clauses |> List.tryFind (fun clause -> rangeContainsPos clause.Range pos) + let clause = + clauses |> List.tryFind (fun clause -> rangeContainsPos clause.Range pos) + match clause with | None -> None | Some clause -> match clause with - | SynMatchClause.SynMatchClause (whenExpr=whenExprOpt; resultExpr=resultExpr) -> + | SynMatchClause.SynMatchClause (whenExpr = whenExprOpt; resultExpr = resultExpr) -> match whenExprOpt with - | None -> - getIdentRangeForFuncExprInApp traverseSynExpr resultExpr pos + | None -> getIdentRangeForFuncExprInApp traverseSynExpr resultExpr pos | Some whenExpr -> if rangeContainsPos whenExpr.Range pos then getIdentRangeForFuncExprInApp traverseSynExpr whenExpr pos else getIdentRangeForFuncExprInApp traverseSynExpr resultExpr pos - // Ex: C.M(x, y, ...) <--- We want to find where in the tupled application the call is being made - | SynExpr.Tuple(_, exprs, _, tupRange) when rangeContainsPos tupRange pos -> + | SynExpr.Tuple (_, exprs, _, tupRange) when rangeContainsPos tupRange pos -> let expr = exprs |> List.tryFind (fun expr -> rangeContainsPos expr.Range pos) + match expr with | None -> None - | Some expr -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | Some expr -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos // Capture the body of a lambda, often nested in a call to a collection function - | SynExpr.Lambda(body=body) when rangeContainsPos body.Range pos -> - getIdentRangeForFuncExprInApp traverseSynExpr body pos + | SynExpr.Lambda (body = body) when rangeContainsPos body.Range pos -> getIdentRangeForFuncExprInApp traverseSynExpr body pos - | SynExpr.Do(expr, range) when rangeContainsPos range pos -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | SynExpr.Do (expr, range) when rangeContainsPos range pos -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos - | SynExpr.Assert(expr, range) when rangeContainsPos range pos -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | SynExpr.Assert (expr, range) when rangeContainsPos range pos -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos - | SynExpr.ArbitraryAfterError (_debugStr, range) when rangeContainsPos range pos -> - Some range + | SynExpr.ArbitraryAfterError (_debugStr, range) when rangeContainsPos range pos -> Some range - | expr -> - traverseSynExpr expr + | expr -> traverseSynExpr expr - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_, traverseSynExpr, defaultTraverse, expr) = - match expr with - | SynExpr.TypeApp (expr, _, _, _, _, _, range) when rangeContainsPos range pos -> - getIdentRangeForFuncExprInApp traverseSynExpr expr pos - | SynExpr.App (_, _, _funcExpr, _, range) as app when rangeContainsPos range pos -> - getIdentRangeForFuncExprInApp traverseSynExpr app pos - | _ -> defaultTraverse expr - }) + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, traverseSynExpr, defaultTraverse, expr) = + match expr with + | SynExpr.TypeApp (expr, _, _, _, _, _, range) when rangeContainsPos range pos -> + getIdentRangeForFuncExprInApp traverseSynExpr expr pos + | SynExpr.App (_, _, _funcExpr, _, range) as app when rangeContainsPos range pos -> + getIdentRangeForFuncExprInApp traverseSynExpr app pos + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(pos, input, visitor) member _.GetAllArgumentsForFunctionApplicationAtPostion pos = SynExprAppLocationsImpl.getAllCurriedArgsAtPosition pos input member _.TryRangeOfParenEnclosingOpEqualsGreaterUsage opGreaterEqualPos = let (|Ident|_|) ofName = - function | SynExpr.LongIdent(longDotId = SynLongIdent(id = [ident])) when ident.idText = ofName -> Some () - | _ -> None - let (|InfixAppOfOpEqualsGreater|_|) = - function | SynExpr.App(ExprAtomicFlag.NonAtomic, false, SynExpr.App(ExprAtomicFlag.NonAtomic, true, Ident "op_EqualsGreater", actualParamListExpr, _), actualLambdaBodyExpr, _) -> - Some (actualParamListExpr, actualLambdaBodyExpr) - | _ -> None + function + | SynExpr.LongIdent(longDotId = SynLongIdent(id = [ ident ])) when ident.idText = ofName -> Some() + | _ -> None - SyntaxTraversal.Traverse(opGreaterEqualPos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_, _, defaultTraverse, expr) = - match expr with - | SynExpr.Paren(InfixAppOfOpEqualsGreater(lambdaArgs, lambdaBody) as app, _, _, _) -> - Some (app.Range, lambdaArgs.Range, lambdaBody.Range) - | _ -> defaultTraverse expr + let (|InfixAppOfOpEqualsGreater|_|) = + function + | SynExpr.App (ExprAtomicFlag.NonAtomic, + false, + SynExpr.App (ExprAtomicFlag.NonAtomic, true, Ident "op_EqualsGreater", actualParamListExpr, _), + actualLambdaBodyExpr, + _) -> Some(actualParamListExpr, actualLambdaBodyExpr) + | _ -> None + + SyntaxTraversal.Traverse( + opGreaterEqualPos, + input, + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, _, defaultTraverse, expr) = + match expr with + | SynExpr.Paren (InfixAppOfOpEqualsGreater (lambdaArgs, lambdaBody) as app, _, _, _) -> + Some(app.Range, lambdaArgs.Range, lambdaBody.Range) + | _ -> defaultTraverse expr - member _.VisitBinding(_path, defaultTraverse, binding) = - match binding with - | SynBinding(kind=SynBindingKind.Normal; expr=InfixAppOfOpEqualsGreater(lambdaArgs, lambdaBody) as app) -> - Some(app.Range, lambdaArgs.Range, lambdaBody.Range) - | _ -> defaultTraverse binding }) + member _.VisitBinding(_path, defaultTraverse, binding) = + match binding with + | SynBinding (kind = SynBindingKind.Normal; expr = InfixAppOfOpEqualsGreater (lambdaArgs, lambdaBody) as app) -> + Some(app.Range, lambdaArgs.Range, lambdaBody.Range) + | _ -> defaultTraverse binding + } + ) member _.TryRangeOfStringInterpolationContainingPos pos = - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_, _, defaultTraverse, expr) = - match expr with - | SynExpr.InterpolatedString(range = range) when rangeContainsPos range pos -> - Some range - | _ -> defaultTraverse expr }) + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, _, defaultTraverse, expr) = + match expr with + | SynExpr.InterpolatedString (range = range) when rangeContainsPos range pos -> Some range + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(pos, input, visitor) member _.TryRangeOfExprInYieldOrReturn pos = - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, _, defaultTraverse, expr) = - match expr with - | SynExpr.YieldOrReturn(_, expr, range) - | SynExpr.YieldOrReturnFrom(_, expr, range) when rangeContainsPos range pos -> - Some expr.Range - | _ -> defaultTraverse expr }) + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_path, _, defaultTraverse, expr) = + match expr with + | SynExpr.YieldOrReturn (_, expr, range) + | SynExpr.YieldOrReturnFrom (_, expr, range) when rangeContainsPos range pos -> Some expr.Range + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(pos, input, visitor) member _.TryRangeOfRecordExpressionContainingPos pos = - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_, _, defaultTraverse, expr) = - match expr with - | SynExpr.Record(_, _, _, range) when rangeContainsPos range pos -> - Some range - | _ -> defaultTraverse expr }) + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, _, defaultTraverse, expr) = + match expr with + | SynExpr.Record (_, _, _, range) when rangeContainsPos range pos -> Some range + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(pos, input, visitor) member _.TryRangeOfRefCellDereferenceContainingPos expressionPos = - SyntaxTraversal.Traverse(expressionPos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_, _, defaultTraverse, expr) = - match expr with - | SynExpr.App(_, false, SynExpr.LongIdent(longDotId = SynLongIdent(id = [funcIdent])), expr, _) -> - if funcIdent.idText = "op_Dereference" && rangeContainsPos expr.Range expressionPos then - Some funcIdent.idRange - else - None - | _ -> defaultTraverse expr }) + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, _, defaultTraverse, expr) = + match expr with + | SynExpr.App (_, false, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ funcIdent ])), expr, _) -> + if funcIdent.idText = "op_Dereference" && rangeContainsPos expr.Range expressionPos then + Some funcIdent.idRange + else + None + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(expressionPos, input, visitor) member _.TryRangeOfExpressionBeingDereferencedContainingPos expressionPos = - SyntaxTraversal.Traverse(expressionPos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_, _, defaultTraverse, expr) = - match expr with - | SynExpr.App(_, false, SynExpr.LongIdent(longDotId = SynLongIdent(id = [funcIdent])), expr, _) -> - if funcIdent.idText = "op_Dereference" && rangeContainsPos expr.Range expressionPos then - Some expr.Range - else - None - | _ -> defaultTraverse expr }) + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, _, defaultTraverse, expr) = + match expr with + | SynExpr.App (_, false, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ funcIdent ])), expr, _) -> + if funcIdent.idText = "op_Dereference" && rangeContainsPos expr.Range expressionPos then + Some expr.Range + else + None + | _ -> defaultTraverse expr + } - member _.FindParameterLocations pos = - ParameterLocations.Find(pos, input) + SyntaxTraversal.Traverse(expressionPos, input, visitor) + + member _.FindParameterLocations pos = ParameterLocations.Find(pos, input) member _.IsPositionContainedInACurriedParameter pos = - let result = - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = - defaultTraverse(expr) + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = defaultTraverse (expr) - override _.VisitBinding (_path, _, binding) = + override _.VisitBinding(_path, _, binding) = match binding with - | SynBinding(valData=valData; range=range) when rangeContainsPos range pos -> + | SynBinding (valData = valData; range = range) when rangeContainsPos range pos -> let info = valData.SynValInfo.CurriedArgInfos let mutable found = false + for group in info do for arg in group do match arg.Ident with - | Some ident when rangeContainsPos ident.idRange pos -> - found <- true + | Some ident when rangeContainsPos ident.idRange pos -> found <- true | _ -> () + if found then Some range else None - | _ -> - None - }) + | _ -> None + } + + let result = SyntaxTraversal.Traverse(pos, input, visitor) result.IsSome member _.IsTypeAnnotationGivenAtPosition pos = - let walker = + let visitor = { new SyntaxVisitorBase<_>() with member _.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = match expr with - | SynExpr.Typed (_expr, _typeExpr, range) when Position.posEq range.Start pos -> - Some range + | SynExpr.Typed (_expr, _typeExpr, range) when Position.posEq range.Start pos -> Some range | _ -> defaultTraverse expr override _.VisitSimplePats(_path, pats) = @@ -417,405 +439,517 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, let exprFunc pat = match pat with // (s: string) - | SynSimplePat.Typed (_pat, _targetExpr, range) when Position.posEq range.Start pos -> - Some range - | _ -> - None + | SynSimplePat.Typed (_pat, _targetExpr, range) when Position.posEq range.Start pos -> Some range + | _ -> None pats |> List.tryPick exprFunc override _.VisitPat(_path, defaultTraverse, pat) = // (s: string) match pat with - | SynPat.Typed (_pat, _targetType, range) when Position.posEq range.Start pos -> - Some range + | SynPat.Typed (_pat, _targetType, range) when Position.posEq range.Start pos -> Some range | _ -> defaultTraverse pat + override _.VisitBinding(_path, defaultTraverse, binding) = // let x : int = 12 match binding with - | SynBinding(headPat = SynPat.Named (range = patRange); returnInfo = Some (SynBindingReturnInfo(typeName = SynType.LongIdent _))) -> Some patRange + | SynBinding (headPat = SynPat.Named (range = patRange) + returnInfo = Some (SynBindingReturnInfo(typeName = SynType.LongIdent _))) -> Some patRange | _ -> defaultTraverse binding } - let result = SyntaxTraversal.Traverse(pos, input, walker) + + let result = SyntaxTraversal.Traverse(pos, input, visitor) + result.IsSome + + member _.IsBindingALambdaAtPosition pos = + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = defaultTraverse expr + + override _.VisitBinding(_path, defaultTraverse, binding) = + match binding with + | SynBinding.SynBinding (expr = expr; range = range) when Position.posEq range.Start pos -> + match expr with + | SynExpr.Lambda _ -> Some range + | _ -> None + | _ -> defaultTraverse binding + } + + let result = SyntaxTraversal.Traverse(pos, input, visitor) result.IsSome - member _.IsBindingALambdaAtPosition pos = - let result = - SyntaxTraversal.Traverse(pos, input, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = - defaultTraverse expr - - override _.VisitBinding(_path, defaultTraverse, binding) = - match binding with - | SynBinding.SynBinding(expr=expr; range=range) when Position.posEq range.Start pos -> - match expr with - | SynExpr.Lambda _ -> Some range - | _ -> None - | _ -> defaultTraverse binding }) - result.IsSome - /// Get declared items and the selected item at the specified location member _.GetNavigationItemsImpl() = - DiagnosticsScope.Protect range0 - (fun () -> + DiagnosticsScope.Protect + range0 + (fun () -> match input with - | ParsedInput.ImplFile _ as p -> - Navigation.getNavigation p - | ParsedInput.SigFile _ -> - Navigation.empty) - (fun err -> + | ParsedInput.ImplFile _ as p -> Navigation.getNavigation p + | ParsedInput.SigFile _ -> Navigation.empty) + (fun err -> Trace.TraceInformation(sprintf "FCS: recovering from error in GetNavigationItemsImpl: '%s'" err) Navigation.empty) - + member _.ValidateBreakpointLocationImpl pos = - let isMatchRange m = rangeContainsPos m pos || m.StartLine = pos.Line + let isMatchRange m = + rangeContainsPos m pos || m.StartLine = pos.Line // Process let-binding - let findBreakPoints () = - let checkRange m = [ if isMatchRange m && not m.IsSynthetic then yield m ] - let walkBindSeqPt sp = [ match sp with DebugPointAtBinding.Yes m -> yield! checkRange m | _ -> () ] - let walkForSeqPt sp = [ match sp with DebugPointAtFor.Yes m -> yield! checkRange m | _ -> () ] - let walkInOrToSeqPt sp = [ match sp with DebugPointAtInOrTo.Yes m -> yield! checkRange m | _ -> () ] - let walkWhileSeqPt sp = [ match sp with DebugPointAtWhile.Yes m -> yield! checkRange m | _ -> () ] - let walkTrySeqPt sp = [ match sp with DebugPointAtTry.Yes m -> yield! checkRange m | _ -> () ] - let walkWithSeqPt sp = [ match sp with DebugPointAtWith.Yes m -> yield! checkRange m | _ -> () ] - let walkFinallySeqPt sp = [ match sp with DebugPointAtFinally.Yes m -> yield! checkRange m | _ -> () ] - - let rec walkBind (SynBinding(kind=kind; expr=synExpr; debugPoint=spInfo; range=m)) = - [ yield! walkBindSeqPt spInfo - let extendDebugPointForDo = - match kind with - | SynBindingKind.Do -> not (IsControlFlowExpression synExpr) - | _ -> false - - // This extends the range of the implicit debug point for 'do expr' range to include the 'do' - if extendDebugPointForDo then - yield! checkRange m - - let useImplicitDebugPoint = - match spInfo with - | DebugPointAtBinding.Yes _ -> false - | _-> not extendDebugPointForDo - - yield! walkExpr useImplicitDebugPoint synExpr ] - - and walkExprs exprs = - exprs |> List.collect (walkExpr false) - - and walkBinds exprs = - exprs |> List.collect walkBind - - and walkMatchClauses clauses = - [ for SynMatchClause(whenExpr=whenExprOpt; resultExpr=tgtExpr) in clauses do - match whenExprOpt with - | Some whenExpr -> yield! walkExpr false whenExpr + let findBreakPoints () = + let checkRange m = + [ + if isMatchRange m && not m.IsSynthetic then + yield m + ] + + let walkBindSeqPt sp = + [ + match sp with + | DebugPointAtBinding.Yes m -> yield! checkRange m + | _ -> () + ] + + let walkForSeqPt sp = + [ + match sp with + | DebugPointAtFor.Yes m -> yield! checkRange m | _ -> () - yield! walkExpr true tgtExpr ] + ] + + let walkInOrToSeqPt sp = + [ + match sp with + | DebugPointAtInOrTo.Yes m -> yield! checkRange m + | _ -> () + ] + + let walkWhileSeqPt sp = + [ + match sp with + | DebugPointAtWhile.Yes m -> yield! checkRange m + | _ -> () + ] + + let walkTrySeqPt sp = + [ + match sp with + | DebugPointAtTry.Yes m -> yield! checkRange m + | _ -> () + ] + + let walkWithSeqPt sp = + [ + match sp with + | DebugPointAtWith.Yes m -> yield! checkRange m + | _ -> () + ] + + let walkFinallySeqPt sp = + [ + match sp with + | DebugPointAtFinally.Yes m -> yield! checkRange m + | _ -> () + ] + + let rec walkBind (SynBinding (kind = kind; expr = synExpr; debugPoint = spInfo; range = m)) = + [ + yield! walkBindSeqPt spInfo + let extendDebugPointForDo = + match kind with + | SynBindingKind.Do -> not (IsControlFlowExpression synExpr) + | _ -> false + + // This extends the range of the implicit debug point for 'do expr' range to include the 'do' + if extendDebugPointForDo then + yield! checkRange m + + let useImplicitDebugPoint = + match spInfo with + | DebugPointAtBinding.Yes _ -> false + | _ -> not extendDebugPointForDo + + yield! walkExpr useImplicitDebugPoint synExpr + ] + + and walkExprs exprs = exprs |> List.collect (walkExpr false) + + and walkBinds exprs = exprs |> List.collect walkBind + + and walkMatchClauses clauses = + [ + for SynMatchClause (whenExpr = whenExprOpt; resultExpr = tgtExpr) in clauses do + match whenExprOpt with + | Some whenExpr -> yield! walkExpr false whenExpr + | _ -> () + + yield! walkExpr true tgtExpr + ] and walkExprOpt (spImplicit: bool) eOpt = - [ match eOpt with Some e -> yield! walkExpr spImplicit e | _ -> () ] - + [ + match eOpt with + | Some e -> yield! walkExpr spImplicit e + | _ -> () + ] + // Determine the breakpoint locations for an expression. spImplicit indicates we always // emit a breakpoint location for the expression unless it is a syntactic control flow construct and walkExpr spImplicit expr = let m = expr.Range - if not (isMatchRange m) then [] else - [ if spImplicit && not (IsControlFlowExpression expr) then - yield! checkRange m - - match expr with - | SynExpr.ArbitraryAfterError _ - | SynExpr.LongIdent _ - | SynExpr.LibraryOnlyILAssembly _ - | SynExpr.LibraryOnlyStaticOptimization _ - | SynExpr.Null _ - | SynExpr.Ident _ - | SynExpr.ImplicitZero _ - | SynExpr.Const _ - | SynExpr.Dynamic _ -> - () - - | SynExpr.Quote (_, _, e, _, _) - | SynExpr.TypeTest (e, _, _) - | SynExpr.Upcast (e, _, _) - | SynExpr.AddressOf (_, e, _, _) - | SynExpr.ComputationExpr (_, e, _) - | SynExpr.ArrayOrListComputed (_, e, _) - | SynExpr.Typed (e, _, _) - | SynExpr.FromParseError (e, _) - | SynExpr.DiscardAfterMissingQualificationAfterDot (e, _) - | SynExpr.Do (e, _) - | SynExpr.Assert (e, _) - | SynExpr.Fixed (e, _) - | SynExpr.DotGet (e, _, _, _) - | SynExpr.LongIdentSet (_, e, _) - | SynExpr.New (_, _, e, _) - | SynExpr.TypeApp (e, _, _, _, _, _, _) - | SynExpr.LibraryOnlyUnionCaseFieldGet (e, _, _, _) - | SynExpr.Downcast (e, _, _) - | SynExpr.InferredUpcast (e, _) - | SynExpr.InferredDowncast (e, _) - | SynExpr.Lazy (e, _) - | SynExpr.TraitCall (_, _, e, _) - | SynExpr.Paren (e, _, _, _) -> - yield! walkExpr false e - - | SynExpr.InterpolatedString (parts, _, _) -> - yield! walkExprs [ for part in parts do - match part with + + [ + if isMatchRange m then + if spImplicit && not (IsControlFlowExpression expr) then + yield! checkRange m + + match expr with + | SynExpr.ArbitraryAfterError _ + | SynExpr.LongIdent _ + | SynExpr.LibraryOnlyILAssembly _ + | SynExpr.LibraryOnlyStaticOptimization _ + | SynExpr.Null _ + | SynExpr.Ident _ + | SynExpr.ImplicitZero _ + | SynExpr.Const _ + | SynExpr.Dynamic _ -> () + + | SynExpr.Quote (_, _, e, _, _) + | SynExpr.TypeTest (e, _, _) + | SynExpr.Upcast (e, _, _) + | SynExpr.AddressOf (_, e, _, _) + | SynExpr.ComputationExpr (_, e, _) + | SynExpr.ArrayOrListComputed (_, e, _) + | SynExpr.Typed (e, _, _) + | SynExpr.FromParseError (e, _) + | SynExpr.DiscardAfterMissingQualificationAfterDot (e, _) + | SynExpr.Do (e, _) + | SynExpr.Assert (e, _) + | SynExpr.Fixed (e, _) + | SynExpr.DotGet (e, _, _, _) + | SynExpr.LongIdentSet (_, e, _) + | SynExpr.New (_, _, e, _) + | SynExpr.TypeApp (e, _, _, _, _, _, _) + | SynExpr.LibraryOnlyUnionCaseFieldGet (e, _, _, _) + | SynExpr.Downcast (e, _, _) + | SynExpr.InferredUpcast (e, _) + | SynExpr.InferredDowncast (e, _) + | SynExpr.Lazy (e, _) + | SynExpr.TraitCall (_, _, e, _) + | SynExpr.Paren (e, _, _, _) -> yield! walkExpr false e + + | SynExpr.InterpolatedString (parts, _, _) -> + yield! + walkExprs + [ + for part in parts do + match part with | SynInterpolatedStringPart.String _ -> () - | SynInterpolatedStringPart.FillExpr (fillExpr, _) -> yield fillExpr ] - - | SynExpr.DebugPoint (DebugPointAtLeafExpr.Yes m, isControlFlow, innerExpr) -> - yield! checkRange m - yield! walkExpr isControlFlow innerExpr - - | SynExpr.YieldOrReturn (_, e, m) -> - yield! checkRange m - yield! walkExpr false e - - | SynExpr.YieldOrReturnFrom (_, e, _) - | SynExpr.DoBang (e, _) -> - yield! checkRange e.Range - yield! walkExpr false e - - | SynOrElse (e1, e2) - | SynAndAlso (e1, e2) -> - yield! walkExpr true e1 - yield! walkExpr true e2 - - // Always allow breakpoints on input and stages of x |> f1 |> f2 pipelines - | SynPipeRight _ -> - let rec loop e = - seq { - match e with - | SynPipeRight (xExpr, fExpr) -> - yield! checkRange fExpr.Range - yield! walkExpr false fExpr - yield! loop xExpr - | SynPipeRight2 (xExpr1, xExpr2, fExpr) -> - yield! checkRange fExpr.Range - yield! checkRange xExpr1.Range - yield! checkRange xExpr2.Range - yield! walkExpr false xExpr1 - yield! walkExpr false xExpr2 - yield! walkExpr false fExpr - | SynPipeRight3 (xExpr1, xExpr2, xExpr3, fExpr) -> - yield! checkRange fExpr.Range - yield! checkRange xExpr1.Range - yield! checkRange xExpr2.Range - yield! checkRange xExpr3.Range - yield! walkExpr false xExpr1 - yield! walkExpr false xExpr2 - yield! walkExpr false xExpr3 - yield! walkExpr false fExpr - | _ -> - yield! checkRange e.Range - yield! walkExpr false e - } - yield! loop expr - | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) - | SynExpr.DotSet (e1, _, e2, _) - | SynExpr.Set (e1, e2, _) - | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, _, _, e2, _) - | SynExpr.App (_, _, e1, e2, _) -> - yield! walkExpr false e1 - yield! walkExpr false e2 - - | SynExpr.ArrayOrList (_, exprs, _) - | SynExpr.Tuple (_, exprs, _, _) -> - yield! walkExprs exprs - - | SynExpr.Record (_, copyExprOpt, fs, _) -> - match copyExprOpt with - | Some (e, _) -> yield! walkExpr true e - | None -> () - yield! walkExprs (fs |> List.choose (fun (SynExprRecordField(expr=e)) -> e)) - - | SynExpr.AnonRecd (_isStruct, copyExprOpt, fs, _) -> - match copyExprOpt with - | Some (e, _) -> yield! walkExpr true e - | None -> () - yield! walkExprs (fs |> List.map (fun (_, _, e) -> e)) - - | SynExpr.ObjExpr (argOptions=args; bindings=bs; members=ms; extraImpls=is) -> - let bs = unionBindingAndMembers bs ms - match args with - | None -> () - | Some (arg, _) -> yield! walkExpr false arg - yield! walkBinds bs - for SynInterfaceImpl(bindings=bs) in is do yield! walkBinds bs - - | SynExpr.While (spWhile, e1, e2, _) -> - yield! walkWhileSeqPt spWhile - yield! walkExpr false e1 - yield! walkExpr true e2 - - | SynExpr.JoinIn (e1, _range, e2, _range2) -> - yield! walkExpr false e1 - yield! walkExpr false e2 - - | SynExpr.For (forDebugPoint=spFor; toDebugPoint=spTo; identBody=e1; toBody=e2; doBody=e3) -> - yield! walkForSeqPt spFor - yield! walkInOrToSeqPt spTo - yield! walkExpr false e1 - yield! walkExpr true e2 - yield! walkExpr true e3 - - | SynExpr.ForEach (spFor, spIn, _, _, _, e1, e2, _) -> - yield! walkForSeqPt spFor - yield! walkInOrToSeqPt spIn - yield! walkBindSeqPt (DebugPointAtBinding.Yes e1.Range) - yield! walkExpr false e1 - yield! walkExpr true e2 - - | SynExpr.MatchLambda (_isExnMatch, _argm, cl, spBind, _wholem) -> - yield! walkBindSeqPt spBind - for SynMatchClause(whenExpr = whenExpr; resultExpr = resultExpr) in cl do - yield! walkExprOpt true whenExpr - yield! walkExpr true resultExpr - - | SynExpr.Lambda (body = bodyExpr) -> - yield! walkExpr true bodyExpr - - | SynExpr.Match (matchDebugPoint = spBind; expr = inpExpr; clauses=cl) -> - yield! walkBindSeqPt spBind - yield! walkExpr false inpExpr - for SynMatchClause(whenExpr = whenExpr; resultExpr = tgtExpr) in cl do - yield! walkExprOpt true whenExpr - yield! walkExpr true tgtExpr - - | SynExpr.LetOrUse (bindings=binds; body=bodyExpr) -> - yield! walkBinds binds - yield! walkExpr true bodyExpr - - | SynExpr.TryWith (tryExpr=tryExpr; withCases=cl; tryDebugPoint=spTry; withDebugPoint=spWith) -> - yield! walkTrySeqPt spTry - yield! walkWithSeqPt spWith - yield! walkExpr true tryExpr - yield! walkMatchClauses cl - - | SynExpr.TryFinally (tryExpr=e1; finallyExpr=e2; tryDebugPoint=spTry; finallyDebugPoint=spFinally) -> - yield! walkExpr true e1 - yield! walkExpr true e2 - yield! walkTrySeqPt spTry - yield! walkFinallySeqPt spFinally - - | SynExpr.SequentialOrImplicitYield (spSeq, e1, e2, _, _) - | SynExpr.Sequential (spSeq, _, e1, e2, _) -> - yield! walkExpr (match spSeq with DebugPointAtSequential.SuppressExpr | DebugPointAtSequential.SuppressBoth -> false | _ -> true) e1 - yield! walkExpr (match spSeq with DebugPointAtSequential.SuppressStmt | DebugPointAtSequential.SuppressBoth -> false | _ -> true) e2 - - | SynExpr.IfThenElse (ifExpr=e1; thenExpr=e2; elseExpr=e3opt; spIfToThen=spBind) -> - yield! walkBindSeqPt spBind - yield! walkExpr false e1 - yield! walkExpr true e2 - yield! walkExprOpt true e3opt - - | SynExpr.DotIndexedGet (e1, es, _, _) -> - yield! walkExpr false e1 - yield! walkExpr false es - - | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> - match expr1 with Some e -> yield! walkExpr false e | None -> () - match expr2 with Some e -> yield! walkExpr false e | None -> () - - | SynExpr.IndexFromEnd (e, _) -> - yield! walkExpr false e - - | SynExpr.DotIndexedSet (e1, es, e2, _, _, _) -> - yield! walkExpr false e1 - yield! walkExpr false es - yield! walkExpr false e2 - - | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> - yield! walkExpr false e1 - yield! walkExpr false e2 - yield! walkExpr false e3 - - | SynExpr.LetOrUseBang (spBind, _, _, _, rhsExpr, andBangs, bodyExpr, _, _) -> - yield! walkBindSeqPt spBind - yield! walkExpr true rhsExpr - for SynExprAndBang(debugPoint = andBangSpBind; body = eAndBang) in andBangs do - yield! walkBindSeqPt andBangSpBind - yield! walkExpr true eAndBang - yield! walkExpr true bodyExpr - - | SynExpr.MatchBang (matchDebugPoint = spBind; expr = inpExpr; clauses = clauses) -> - yield! walkBindSeqPt spBind - yield! walkExpr false inpExpr - for SynMatchClause(whenExpr = whenExpr; resultExpr = resExpr) in clauses do - yield! walkExprOpt true whenExpr - yield! walkExpr true resExpr ] - + | SynInterpolatedStringPart.FillExpr (fillExpr, _) -> yield fillExpr + ] + + | SynExpr.DebugPoint (DebugPointAtLeafExpr.Yes m, isControlFlow, innerExpr) -> + yield! checkRange m + yield! walkExpr isControlFlow innerExpr + + | SynExpr.YieldOrReturn (_, e, m) -> + yield! checkRange m + yield! walkExpr false e + + | SynExpr.YieldOrReturnFrom (_, e, _) + | SynExpr.DoBang (e, _) -> + yield! checkRange e.Range + yield! walkExpr false e + + | SynOrElse (e1, e2) + | SynAndAlso (e1, e2) -> + yield! walkExpr true e1 + yield! walkExpr true e2 + + // Always allow breakpoints on input and stages of x |> f1 |> f2 pipelines + | SynPipeRight _ -> + let rec loop e = + seq { + match e with + | SynPipeRight (xExpr, fExpr) -> + yield! checkRange fExpr.Range + yield! walkExpr false fExpr + yield! loop xExpr + | SynPipeRight2 (xExpr1, xExpr2, fExpr) -> + yield! checkRange fExpr.Range + yield! checkRange xExpr1.Range + yield! checkRange xExpr2.Range + yield! walkExpr false xExpr1 + yield! walkExpr false xExpr2 + yield! walkExpr false fExpr + | SynPipeRight3 (xExpr1, xExpr2, xExpr3, fExpr) -> + yield! checkRange fExpr.Range + yield! checkRange xExpr1.Range + yield! checkRange xExpr2.Range + yield! checkRange xExpr3.Range + yield! walkExpr false xExpr1 + yield! walkExpr false xExpr2 + yield! walkExpr false xExpr3 + yield! walkExpr false fExpr + | _ -> + yield! checkRange e.Range + yield! walkExpr false e + } + + yield! loop expr + | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) + | SynExpr.DotSet (e1, _, e2, _) + | SynExpr.Set (e1, e2, _) + | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, _, _, e2, _) + | SynExpr.App (_, _, e1, e2, _) -> + yield! walkExpr false e1 + yield! walkExpr false e2 + + | SynExpr.ArrayOrList (_, exprs, _) + | SynExpr.Tuple (_, exprs, _, _) -> yield! walkExprs exprs + + | SynExpr.Record (_, copyExprOpt, fs, _) -> + match copyExprOpt with + | Some (e, _) -> yield! walkExpr true e + | None -> () + + yield! walkExprs (fs |> List.choose (fun (SynExprRecordField (expr = e)) -> e)) + + | SynExpr.AnonRecd (_isStruct, copyExprOpt, fs, _) -> + match copyExprOpt with + | Some (e, _) -> yield! walkExpr true e + | None -> () + + yield! walkExprs (fs |> List.map (fun (_, _, e) -> e)) + + | SynExpr.ObjExpr (argOptions = args; bindings = bs; members = ms; extraImpls = is) -> + let bs = unionBindingAndMembers bs ms + + match args with + | None -> () + | Some (arg, _) -> yield! walkExpr false arg + + yield! walkBinds bs + + for SynInterfaceImpl (bindings = bs) in is do + yield! walkBinds bs + + | SynExpr.While (spWhile, e1, e2, _) -> + yield! walkWhileSeqPt spWhile + yield! walkExpr false e1 + yield! walkExpr true e2 + + | SynExpr.JoinIn (e1, _range, e2, _range2) -> + yield! walkExpr false e1 + yield! walkExpr false e2 + + | SynExpr.For (forDebugPoint = spFor; toDebugPoint = spTo; identBody = e1; toBody = e2; doBody = e3) -> + yield! walkForSeqPt spFor + yield! walkInOrToSeqPt spTo + yield! walkExpr false e1 + yield! walkExpr true e2 + yield! walkExpr true e3 + + | SynExpr.ForEach (spFor, spIn, _, _, _, e1, e2, _) -> + yield! walkForSeqPt spFor + yield! walkInOrToSeqPt spIn + yield! walkBindSeqPt (DebugPointAtBinding.Yes e1.Range) + yield! walkExpr false e1 + yield! walkExpr true e2 + + | SynExpr.MatchLambda (_isExnMatch, _argm, cl, spBind, _wholem) -> + yield! walkBindSeqPt spBind + + for SynMatchClause (whenExpr = whenExpr; resultExpr = resultExpr) in cl do + yield! walkExprOpt true whenExpr + yield! walkExpr true resultExpr + + | SynExpr.Lambda (body = bodyExpr) -> yield! walkExpr true bodyExpr + + | SynExpr.Match (matchDebugPoint = spBind; expr = inpExpr; clauses = cl) -> + yield! walkBindSeqPt spBind + yield! walkExpr false inpExpr + + for SynMatchClause (whenExpr = whenExpr; resultExpr = tgtExpr) in cl do + yield! walkExprOpt true whenExpr + yield! walkExpr true tgtExpr + + | SynExpr.LetOrUse (bindings = binds; body = bodyExpr) -> + yield! walkBinds binds + yield! walkExpr true bodyExpr + + | SynExpr.TryWith (tryExpr = tryExpr; withCases = cl; tryDebugPoint = spTry; withDebugPoint = spWith) -> + yield! walkTrySeqPt spTry + yield! walkWithSeqPt spWith + yield! walkExpr true tryExpr + yield! walkMatchClauses cl + + | SynExpr.TryFinally (tryExpr = e1; finallyExpr = e2; tryDebugPoint = spTry; finallyDebugPoint = spFinally) -> + yield! walkExpr true e1 + yield! walkExpr true e2 + yield! walkTrySeqPt spTry + yield! walkFinallySeqPt spFinally + + | SynExpr.SequentialOrImplicitYield (spSeq, e1, e2, _, _) + | SynExpr.Sequential (spSeq, _, e1, e2, _) -> + let implicit1 = + match spSeq with + | DebugPointAtSequential.SuppressExpr + | DebugPointAtSequential.SuppressBoth -> false + | _ -> true + + yield! walkExpr implicit1 e1 + + let implicit2 = + match spSeq with + | DebugPointAtSequential.SuppressStmt + | DebugPointAtSequential.SuppressBoth -> false + | _ -> true + + yield! walkExpr implicit2 e2 + + | SynExpr.IfThenElse (ifExpr = e1; thenExpr = e2; elseExpr = e3opt; spIfToThen = spBind) -> + yield! walkBindSeqPt spBind + yield! walkExpr false e1 + yield! walkExpr true e2 + yield! walkExprOpt true e3opt + + | SynExpr.DotIndexedGet (e1, es, _, _) -> + yield! walkExpr false e1 + yield! walkExpr false es + + | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> + match expr1 with + | Some e -> yield! walkExpr false e + | None -> () + + match expr2 with + | Some e -> yield! walkExpr false e + | None -> () + + | SynExpr.IndexFromEnd (e, _) -> yield! walkExpr false e + + | SynExpr.DotIndexedSet (e1, es, e2, _, _, _) -> + yield! walkExpr false e1 + yield! walkExpr false es + yield! walkExpr false e2 + + | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> + yield! walkExpr false e1 + yield! walkExpr false e2 + yield! walkExpr false e3 + + | SynExpr.LetOrUseBang (spBind, _, _, _, rhsExpr, andBangs, bodyExpr, _, _) -> + yield! walkBindSeqPt spBind + yield! walkExpr true rhsExpr + + for SynExprAndBang (debugPoint = andBangSpBind; body = eAndBang) in andBangs do + yield! walkBindSeqPt andBangSpBind + yield! walkExpr true eAndBang + + yield! walkExpr true bodyExpr + + | SynExpr.MatchBang (matchDebugPoint = spBind; expr = inpExpr; clauses = clauses) -> + yield! walkBindSeqPt spBind + yield! walkExpr false inpExpr + + for SynMatchClause (whenExpr = whenExpr; resultExpr = resExpr) in clauses do + yield! walkExprOpt true whenExpr + yield! walkExpr true resExpr + ] + // Process a class declaration or F# type declaration - let rec walkTycon (SynTypeDefn(typeRepr=repr; members=membDefns; implicitConstructor=implicitCtor; range=m)) = - if not (isMatchRange m) then [] else - [ for memb in membDefns do yield! walkMember memb - match repr with - | SynTypeDefnRepr.ObjectModel(_, membDefns, _) -> - for memb in membDefns do yield! walkMember memb - | _ -> () - for memb in membDefns do yield! walkMember memb - for memb in Option.toList implicitCtor do yield! walkMember memb] - - // Returns class-members for the right dropdown + let rec walkTycon (SynTypeDefn (typeRepr = repr; members = membDefns; implicitConstructor = implicitCtor; range = m)) = + if not (isMatchRange m) then + [] + else + [ + for memb in membDefns do + yield! walkMember memb + match repr with + | SynTypeDefnRepr.ObjectModel (_, membDefns, _) -> + for memb in membDefns do + yield! walkMember memb + | _ -> () + for memb in membDefns do + yield! walkMember memb + for memb in Option.toList implicitCtor do + yield! walkMember memb + ] + + // Returns class-members for the right dropdown and walkMember memb = - if not (isMatchRange memb.Range) then [] else - [ match memb with - | SynMemberDefn.LetBindings(binds, _, _, _) -> yield! walkBinds binds - | SynMemberDefn.AutoProperty(synExpr=synExpr) -> yield! walkExpr true synExpr - | SynMemberDefn.ImplicitCtor(_, _, _, _, _, m) -> yield! checkRange m - | SynMemberDefn.Member(bind, _) -> yield! walkBind bind - | SynMemberDefn.Interface(members=Some membs) -> for m in membs do yield! walkMember m - | SynMemberDefn.Inherit(_, _, m) -> - // can break on the "inherit" clause - yield! checkRange m - | SynMemberDefn.ImplicitInherit(_, arg, _, m) -> - // can break on the "inherit" clause - yield! checkRange m - yield! walkExpr true arg - | _ -> () ] + if not (isMatchRange memb.Range) then + [] + else + [ + match memb with + | SynMemberDefn.LetBindings (binds, _, _, _) -> yield! walkBinds binds + | SynMemberDefn.AutoProperty (synExpr = synExpr) -> yield! walkExpr true synExpr + | SynMemberDefn.ImplicitCtor (_, _, _, _, _, m) -> yield! checkRange m + | SynMemberDefn.Member (bind, _) -> yield! walkBind bind + | SynMemberDefn.GetSetMember (getBinding, setBinding, _, _) -> + match getBinding, setBinding with + | None, None -> () + | None, Some binding + | Some binding, None -> yield! walkBind binding + | Some getBinding, Some setBinding -> + yield! walkBind getBinding + yield! walkBind setBinding + | SynMemberDefn.Interface(members = Some membs) -> + for m in membs do + yield! walkMember m + | SynMemberDefn.Inherit (_, _, m) -> + // can break on the "inherit" clause + yield! checkRange m + | SynMemberDefn.ImplicitInherit (_, arg, _, m) -> + // can break on the "inherit" clause + yield! checkRange m + yield! walkExpr true arg + | _ -> () + ] // Process declarations nested in a module that should be displayed in the left dropdown - // (such as type declarations, nested modules etc.) - let rec walkDecl decl = - [ match decl with - | SynModuleDecl.Let(_, binds, m) when isMatchRange m -> - yield! walkBinds binds - | SynModuleDecl.Expr(expr, m) when isMatchRange m -> - yield! walkExpr true expr - | SynModuleDecl.ModuleAbbrev _ -> () - | SynModuleDecl.NestedModule(decls=decls; range=m) when isMatchRange m -> - for d in decls do yield! walkDecl d - | SynModuleDecl.Types(tydefs, m) when isMatchRange m -> - for d in tydefs do yield! walkTycon d - | SynModuleDecl.Exception(SynExceptionDefn(SynExceptionDefnRepr _, _, membDefns, _), m) - when isMatchRange m -> - for m in membDefns do yield! walkMember m - | _ -> () ] - - // Collect all the items in a module - let walkModule (SynModuleOrNamespace(decls = decls; range = m)) = - if isMatchRange m then - List.collect walkDecl decls - else - [] - - /// Get information for implementation file + // (such as type declarations, nested modules etc.) + let rec walkDecl decl = + [ + match decl with + | SynModuleDecl.Let (_, binds, m) when isMatchRange m -> yield! walkBinds binds + | SynModuleDecl.Expr (expr, m) when isMatchRange m -> yield! walkExpr true expr + | SynModuleDecl.ModuleAbbrev _ -> () + | SynModuleDecl.NestedModule (decls = decls; range = m) when isMatchRange m -> + for d in decls do + yield! walkDecl d + | SynModuleDecl.Types (tydefs, m) when isMatchRange m -> + for d in tydefs do + yield! walkTycon d + | SynModuleDecl.Exception (SynExceptionDefn (SynExceptionDefnRepr _, _, membDefns, _), m) when isMatchRange m -> + for m in membDefns do + yield! walkMember m + | _ -> () + ] + + // Collect all the items in a module + let walkModule (SynModuleOrNamespace (decls = decls; range = m)) = + if isMatchRange m then List.collect walkDecl decls else [] + + /// Get information for implementation file let walkImplFile (modules: SynModuleOrNamespace list) = List.collect walkModule modules - + match input with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = modules)) -> walkImplFile modules + | ParsedInput.ImplFile (ParsedImplFileInput (modules = modules)) -> walkImplFile modules | _ -> [] - - DiagnosticsScope.Protect range0 - (fun () -> - let locations = findBreakPoints() - + + DiagnosticsScope.Protect + range0 + (fun () -> + let locations = findBreakPoints () + if pos.Column = 0 then // we have a breakpoint that was set with mouse at line start - match locations |> List.filter (fun m -> m.StartLine = m.EndLine && pos.Line = m.StartLine) with + match + locations + |> List.filter (fun m -> m.StartLine = m.EndLine && pos.Line = m.StartLine) + with | [] -> match locations |> List.filter (fun m -> rangeContainsPos m pos) with | [] -> @@ -831,16 +965,16 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, | [] -> Seq.tryHead locations | locationsAfterPos -> Seq.tryHead locationsAfterPos | coveringLocations -> Seq.tryLast coveringLocations) - (fun msg -> + (fun msg -> Trace.TraceInformation(sprintf "FCS: recovering from error in ValidateBreakpointLocationImpl: '%s'" msg) None) - + /// When these files appear or disappear the configuration for the current project is invalidated. member _.DependencyFiles = dependencyFiles member _.FileName = input.FileName - - // Get items for the navigation drop down bar + + // Get items for the navigation drop down bar member scope.GetNavigationItems() = // This does not need to be run on the background thread scope.GetNavigationItemsImpl() @@ -848,4 +982,3 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, member scope.ValidateBreakpointLocation pos = // This does not need to be run on the background thread scope.ValidateBreakpointLocationImpl pos - diff --git a/src/Compiler/Service/FSharpSource.fs b/src/Compiler/Service/FSharpSource.fs index 1f1d12373a9..b7f13801c98 100644 --- a/src/Compiler/Service/FSharpSource.fs +++ b/src/Compiler/Service/FSharpSource.fs @@ -24,9 +24,9 @@ type TextContainer = [] type FSharpSource internal () = - abstract FilePath : string + abstract FilePath: string - abstract TimeStamp : DateTime + abstract TimeStamp: DateTime abstract GetTextContainer: unit -> TextContainer @@ -37,8 +37,7 @@ type private FSharpSourceMemoryMappedFile(filePath: string, timeStamp: DateTime, override _.TimeStamp = timeStamp - override _.GetTextContainer() = - openStream () |> TextContainer.Stream + override _.GetTextContainer() = openStream () |> TextContainer.Stream type private FSharpSourceByteArray(filePath: string, timeStamp: DateTime, bytes: byte[]) = inherit FSharpSource() @@ -57,18 +56,17 @@ type private FSharpSourceFromFile(filePath: string) = override _.TimeStamp = FileSystem.GetLastWriteTimeShim(filePath) - override _.GetTextContainer() = - TextContainer.OnDisk + override _.GetTextContainer() = TextContainer.OnDisk type private FSharpSourceCustom(filePath: string, getTimeStamp, getSourceText) = inherit FSharpSource() override _.FilePath = filePath - override _.TimeStamp = getTimeStamp() + override _.TimeStamp = getTimeStamp () override _.GetTextContainer() = - TextContainer.SourceText(getSourceText()) + TextContainer.SourceText(getSourceText ()) type FSharpSource with @@ -84,9 +82,14 @@ type FSharpSource with // We want to use mmaped documents only when // not running on mono, since its MemoryMappedFile implementation throws when "mapName" is not provided (is null), (see: https://github.com/mono/mono/issues/10245) if runningOnMono then - let bytes = FileSystem.OpenFileForReadShim(filePath, useMemoryMappedFile = false).ReadAllBytes() + let bytes = + FileSystem + .OpenFileForReadShim(filePath, useMemoryMappedFile = false) + .ReadAllBytes() + FSharpSourceByteArray(filePath, timeStamp, bytes) :> FSharpSource else - let openStream = fun () -> - FileSystem.OpenFileForReadShim(filePath, useMemoryMappedFile = true, shouldShadowCopy = true) - FSharpSourceMemoryMappedFile(filePath, timeStamp, openStream) :> FSharpSource \ No newline at end of file + let openStream = + fun () -> FileSystem.OpenFileForReadShim(filePath, useMemoryMappedFile = true, shouldShadowCopy = true) + + FSharpSourceMemoryMappedFile(filePath, timeStamp, openStream) :> FSharpSource diff --git a/src/Compiler/Service/IncrementalBuild.fs b/src/Compiler/Service/IncrementalBuild.fs index c9f7e51675e..6295a9a99a2 100644 --- a/src/Compiler/Service/IncrementalBuild.fs +++ b/src/Compiler/Service/IncrementalBuild.fs @@ -139,11 +139,11 @@ module IncrementalBuildSyntaxTree = use text = source.GetTextContainer() match text with | TextContainer.Stream(stream) -> - ParseOneInputStream(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, (*retryLocked*)false, stream) + ParseOneInputStream(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, false, stream) | TextContainer.SourceText(sourceText) -> ParseOneInputSourceText(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, sourceText) | TextContainer.OnDisk -> - ParseOneInputFile(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, (*retryLocked*)true) + ParseOneInputFile(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, true) fileParsed.Trigger fileName @@ -589,7 +589,7 @@ type BoundModel private (tcConfig: TcConfig, None) /// Global service state -type FrameworkImportsCacheKey = (*resolvedpath*)string list * string * (*TargetFrameworkDirectories*)string list * (*fsharpBinaries*)string * (*langVersion*)decimal +type FrameworkImportsCacheKey = FrameworkImportsCacheKey of resolvedpath: string list * assemblyName: string * targetFrameworkDirectories: string list * fsharpBinaries: string * langVersion: decimal /// Represents a cache of 'framework' references that can be shared between multiple incremental builds type FrameworkImportsCache(size) = @@ -617,7 +617,8 @@ type FrameworkImportsCache(size) = // The data elements in this key are very important. There should be nothing else in the TcConfig that logically affects // the import of a set of framework DLLs into F# CCUs. That is, the F# CCUs that result from a set of DLLs (including // FSharp.Core.dll and mscorlib.dll) must be logically invariant of all the other compiler configuration parameters. - let key = (frameworkDLLsKey, + let key = + FrameworkImportsCacheKey(frameworkDLLsKey, tcConfig.primaryAssembly.Name, tcConfig.GetTargetFrameworkDirectories(), tcConfig.fsharpBinariesDir, diff --git a/src/Compiler/Service/ItemKey.fs b/src/Compiler/Service/ItemKey.fs index 15b56d8287b..d2621715b10 100644 --- a/src/Compiler/Service/ItemKey.fs +++ b/src/Compiler/Service/ItemKey.fs @@ -98,7 +98,8 @@ type ItemKeyStore(mmf: MemoryMappedFile, length) = let rangeBuffer = Array.zeroCreate sizeof let mutable isDisposed = false - let checkDispose() = + + let checkDispose () = if isDisposed then raise (ObjectDisposedException("ItemKeyStore")) @@ -108,13 +109,19 @@ type ItemKeyStore(mmf: MemoryMappedFile, length) = member _.ReadKeyString(reader: byref) = let size = reader.ReadInt32() - let keyString = ReadOnlySpan(reader.CurrentPointer |> NativePtr.toVoidPtr, size) + + let keyString = + ReadOnlySpan(reader.CurrentPointer |> NativePtr.toVoidPtr, size) + reader.Offset <- reader.Offset + size keyString member this.ReadFirstKeyString() = use view = mmf.CreateViewAccessor(0L, length) - let mutable reader = BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) + + let mutable reader = + BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) + this.ReadRange &reader |> ignore let bytes = (this.ReadKeyString &reader).ToArray() ReadOnlySpan.op_Implicit bytes @@ -124,21 +131,26 @@ type ItemKeyStore(mmf: MemoryMappedFile, length) = let builder = ItemKeyStoreBuilder() builder.Write(range0, item) + match builder.TryBuildAndReset() with | None -> Seq.empty - | Some(singleStore : ItemKeyStore) -> + | Some (singleStore: ItemKeyStore) -> let keyString1 = singleStore.ReadFirstKeyString() (singleStore :> IDisposable).Dispose() let results = ResizeArray() use view = mmf.CreateViewAccessor(0L, length) - let mutable reader = BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) + + let mutable reader = + BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) reader.Offset <- 0 + while reader.Offset < reader.Length do let m = this.ReadRange &reader let keyString2 = this.ReadKeyString &reader + if keyString1.SequenceEqual keyString2 then results.Add m @@ -154,20 +166,15 @@ and [] ItemKeyStoreBuilder() = let b = BlobBuilder() - let writeChar (c: char) = - b.WriteUInt16(uint16 c) + let writeChar (c: char) = b.WriteUInt16(uint16 c) - let writeUInt16 (i: uint16) = - b.WriteUInt16 i + let writeUInt16 (i: uint16) = b.WriteUInt16 i - let writeInt32 (i: int) = - b.WriteInt32 i + let writeInt32 (i: int) = b.WriteInt32 i - let writeInt64 (i: int64) = - b.WriteInt64 i + let writeInt64 (i: int64) = b.WriteInt64 i - let writeString (str: string) = - b.WriteUTF16 str + let writeString (str: string) = b.WriteUTF16 str let writeRange (m: range) = let mutable m = m @@ -177,8 +184,7 @@ and [] ItemKeyStoreBuilder() = let writeEntityRef (eref: EntityRef) = writeString ItemKeyTags.entityRef writeString eref.CompiledName - eref.CompilationPath.MangledPath - |> List.iter (fun str -> writeString str) + eref.CompilationPath.MangledPath |> List.iter (fun str -> writeString str) let rec writeILType (ilTy: ILType) = match ilTy with @@ -186,13 +192,12 @@ and [] ItemKeyStoreBuilder() = writeString "!" writeUInt16 n - | ILType.Modified (_, _, ty2) -> - writeILType ty2 + | ILType.Modified (_, _, ty2) -> writeILType ty2 | ILType.Array (ILArrayShape s, ty) -> writeILType ty writeString "[" - writeInt32 (s.Length-1) + writeInt32 (s.Length - 1) writeString "]" | ILType.Value tr @@ -201,11 +206,11 @@ and [] ItemKeyStoreBuilder() = |> List.iter (fun x -> writeString x writeChar '.') + writeChar '.' writeString tr.TypeRef.Name - | ILType.Void -> - writeString "void" + | ILType.Void -> writeString "void" | ILType.Ptr ty -> writeString "ptr<" @@ -218,18 +223,14 @@ and [] ItemKeyStoreBuilder() = writeChar '>' | ILType.FunctionPointer mref -> - mref.ArgTypes - |> List.iter (fun x -> - writeILType x) + mref.ArgTypes |> List.iter (fun x -> writeILType x) writeILType mref.ReturnType let rec writeType isStandalone (ty: TType) = match stripTyparEqns ty with - | TType_forall (_, ty) -> - writeType false ty + | TType_forall (_, ty) -> writeType false ty - | TType_app (tcref, _, _) -> - writeEntityRef tcref + | TType_app (tcref, _, _) -> writeEntityRef tcref | TType_tuple (_, tinst) -> writeString ItemKeyTags.typeTuple @@ -240,22 +241,21 @@ and [] ItemKeyStoreBuilder() = writeString anonInfo.ILTypeRef.BasicQualifiedName tinst |> List.iter (writeType false) - | TType_fun (d, r, _) -> + | TType_fun (domainTy, rangeTy, _) -> writeString ItemKeyTags.typeFunction - writeType false d - writeType false r + writeType false domainTy + writeType false rangeTy | TType_measure ms -> if isStandalone then writeString ItemKeyTags.typeMeasure writeMeasure isStandalone ms - | TType_var (tp, _) -> - writeTypar isStandalone tp + | TType_var (tp, _) -> writeTypar isStandalone tp | TType_ucase (uc, _) -> match uc with - | UnionCaseRef.UnionCaseRef(tcref, nm) -> + | UnionCaseRef.UnionCaseRef (tcref, nm) -> writeString ItemKeyTags.typeUnionCase writeEntityRef tcref writeString nm @@ -265,11 +265,10 @@ and [] ItemKeyStoreBuilder() = | Measure.Var typar -> writeString ItemKeyTags.typeMeasureVar writeTypar isStandalone typar - | Measure.Con tcref -> + | Measure.Const tcref -> writeString ItemKeyTags.typeMeasureCon writeEntityRef tcref - | _ -> - () + | _ -> () and writeTypar (isStandalone: bool) (typar: Typar) = match typar.Solution with @@ -291,11 +290,12 @@ and [] ItemKeyStoreBuilder() = writeString vref.LogicalName writeString ItemKeyTags.parameters writeType false vref.Type + match vref.DeclaringEntity with | ParentNone -> writeChar '%' | Parent eref -> writeEntityRef eref - member _.Write (m: range, item: Item) = + member _.Write(m: range, item: Item) = writeRange m let fixup = b.ReserveBytes 4 |> BlobWriter @@ -307,28 +307,25 @@ and [] ItemKeyStoreBuilder() = if vref.IsPropertyGetterMethod || vref.IsPropertySetterMethod then writeString ItemKeyTags.itemProperty writeString vref.PropertyName + match vref.DeclaringEntity with - | ParentRef.Parent parent -> - writeEntityRef parent - | _ -> - () + | ParentRef.Parent parent -> writeEntityRef parent + | _ -> () else writeValRef vref - | Item.UnionCase(info, _) -> + | Item.UnionCase (info, _) -> writeString ItemKeyTags.typeUnionCase writeEntityRef info.TyconRef writeString info.LogicalName - | Item.ActivePatternResult(info, _, _, _) -> + | Item.ActivePatternResult (info, _, _, _) -> writeString ItemKeyTags.itemActivePattern - info.ActiveTags - |> List.iter writeString + info.ActiveTags |> List.iter writeString | Item.ActivePatternCase elemRef -> writeString ItemKeyTags.itemActivePattern - elemRef.ActivePatternInfo.ActiveTags - |> List.iter writeString + elemRef.ActivePatternInfo.ActiveTags |> List.iter writeString | Item.ExnCase tcref -> writeString ItemKeyTags.itemExnCase @@ -340,13 +337,13 @@ and [] ItemKeyStoreBuilder() = writeString info.LogicalName writeType false info.FieldType - | Item.UnionCaseField(info, fieldIndex) -> + | Item.UnionCaseField (info, fieldIndex) -> writeString ItemKeyTags.typeUnionCase writeEntityRef info.TyconRef writeString info.LogicalName writeInt32 fieldIndex - | Item.AnonRecdField(info, tys, i, _) -> + | Item.AnonRecdField (info, tys, i, _) -> writeString ItemKeyTags.itemAnonymousRecordField writeString info.ILTypeRef.BasicQualifiedName tys |> List.iter (writeType false) @@ -366,32 +363,26 @@ and [] ItemKeyStoreBuilder() = writeString info.EventName writeEntityRef info.DeclaringTyconRef - | Item.Property(nm, infos) -> + | Item.Property (nm, infos) -> writeString ItemKeyTags.itemProperty writeString nm + match infos |> List.tryHead with - | Some info -> - writeEntityRef info.DeclaringTyconRef - | _ -> - () + | Some info -> writeEntityRef info.DeclaringTyconRef + | _ -> () - | Item.TypeVar(_, typar) -> - writeTypar true typar + | Item.TypeVar (_, typar) -> writeTypar true typar - | Item.Types(_, [ty]) -> - writeType true ty + | Item.Types (_, [ ty ]) -> writeType true ty - | Item.UnqualifiedType [tcref] -> - writeEntityRef tcref + | Item.UnqualifiedType [ tcref ] -> writeEntityRef tcref - | Item.MethodGroup(_, [info], _) - | Item.CtorGroup(_, [info]) -> + | Item.MethodGroup (_, [ info ], _) + | Item.CtorGroup (_, [ info ]) -> match info with - | FSMeth(_, _, vref, _) -> - writeValRef vref - | ILMeth(_, info, _) -> - info.ILMethodRef.ArgTypes - |> List.iter writeILType + | FSMeth (_, _, vref, _) -> writeValRef vref + | ILMeth (_, info, _) -> + info.ILMethodRef.ArgTypes |> List.iter writeILType writeILType info.ILMethodRef.ReturnType writeString info.ILName writeType false info.ApparentEnclosingType @@ -400,12 +391,14 @@ and [] ItemKeyStoreBuilder() = writeEntityRef info.DeclaringTyconRef writeString info.LogicalName - | Item.ModuleOrNamespaces [x] -> + | Item.ModuleOrNamespaces [ x ] -> writeString ItemKeyTags.itemModuleOrNamespace + x.CompilationPath.DemangledPath |> List.iter (fun x -> writeString x writeString ".") + writeString x.LogicalName | Item.DelegateCtor ty -> @@ -431,6 +424,7 @@ and [] ItemKeyStoreBuilder() = member _.TryBuildAndReset() = if b.Count > 0 then let length = int64 b.Count + let mmf = let mmf = MemoryMappedFile.CreateNew( @@ -438,7 +432,9 @@ and [] ItemKeyStoreBuilder() = length, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, - HandleInheritability.None) + HandleInheritability.None + ) + use stream = mmf.CreateViewStream(0L, length, MemoryMappedFileAccess.ReadWrite) b.WriteContentTo stream mmf diff --git a/src/Compiler/Service/QuickParse.fs b/src/Compiler/Service/QuickParse.fs index 10c44685120..e40d660bb2f 100644 --- a/src/Compiler/Service/QuickParse.fs +++ b/src/Compiler/Service/QuickParse.fs @@ -10,36 +10,42 @@ open FSharp.Compiler.Tokenization /// Qualified long name. type PartialLongName = { - /// Qualifying idents, prior to the last dot, not including the last part. - QualifyingIdents: string list - - /// Last part of long ident. - PartialIdent: string - - /// The column number at the end of full partial name. - EndColumn: int - - /// Position of the last dot. - LastDotPos: int option + /// Qualifying idents, prior to the last dot, not including the last part. + QualifyingIdents: string list + + /// Last part of long ident. + PartialIdent: string + + /// The column number at the end of full partial name. + EndColumn: int + + /// Position of the last dot. + LastDotPos: int option } - + /// Empty partial long name. - static member Empty(endColumn: int) = { QualifyingIdents = []; PartialIdent = ""; EndColumn = endColumn; LastDotPos = None } + static member Empty(endColumn: int) = + { + QualifyingIdents = [] + PartialIdent = "" + EndColumn = endColumn + LastDotPos = None + } /// Methods for cheaply and inaccurately parsing F#. /// -/// These methods are very old and are mostly to do with extracting "long identifier islands" +/// These methods are very old and are mostly to do with extracting "long identifier islands" /// A.B.C /// from F# source code, an approach taken from pre-F# VS samples for implementing intelliense. /// -/// This code should really no longer be needed since the language service has access to -/// parsed F# source code ASTs. However, the long identifiers are still passed back to GetDeclarations and friends in the +/// This code should really no longer be needed since the language service has access to +/// parsed F# source code ASTs. However, the long identifiers are still passed back to GetDeclarations and friends in the /// F# Compiler Service and it's annoyingly hard to remove their use completely. /// -/// In general it is unlikely much progress will be made by fixing this code - it will be better to +/// In general it is unlikely much progress will be made by fixing this code - it will be better to /// extract more information from the F# ASTs. /// -/// It's also surprising how hard even the job of getting long identifier islands can be. For example the code +/// It's also surprising how hard even the job of getting long identifier islands can be. For example the code /// below is inaccurate for long identifier chains involving ``...`` identifiers. And there are special cases /// for active pattern names and so on. module QuickParse = @@ -49,12 +55,13 @@ module QuickParse = // Adjusts the token tag for the given identifier // - if we're inside active pattern name (at the bar), correct the token TAG to be an identifier - let CorrectIdentifierToken (tokenText: string) (tokenTag: int) = + let CorrectIdentifierToken (tokenText: string) (tokenTag: int) = if tokenText.EndsWithOrdinal("|") then FSharp.Compiler.Parser.tagOfToken (FSharp.Compiler.Parser.token.IDENT tokenText) - else tokenTag + else + tokenTag - let rec isValidStrippedName (name: ReadOnlySpan) idx = + let rec isValidStrippedName (name: ReadOnlySpan) idx = if idx = name.Length then false elif IsIdentifierPartCharacter name[idx] then true else isValidStrippedName name (idx + 1) @@ -63,32 +70,44 @@ module QuickParse = // Extracts the 'core' part without surrounding bars and checks whether it contains some identifier // (Note, this doesn't have to be precise, because this is checked by background compiler, // but it has to be good enough to distinguish operators and active pattern names) - let private isValidActivePatternName (name: string) = - - // Strip the surrounding bars (e.g. from "|xyz|_|") to get "xyz" - match name.StartsWithOrdinal("|"), name.EndsWithOrdinal("|_|"), name.EndsWithOrdinal("|") with - | true, true, _ when name.Length > 4 -> isValidStrippedName (name.AsSpan(1, name.Length - 4)) 0 - | true, _, true when name.Length > 2 -> isValidStrippedName (name.AsSpan(1, name.Length - 2)) 0 - | _ -> false - + let private isValidActivePatternName (name: string) = + + // Strip the surrounding bars (e.g. from "|xyz|_|") to get "xyz" + match name.StartsWithOrdinal("|"), name.EndsWithOrdinal("|_|"), name.EndsWithOrdinal("|") with + | true, true, _ when name.Length > 4 -> isValidStrippedName (name.AsSpan(1, name.Length - 4)) 0 + | true, _, true when name.Length > 2 -> isValidStrippedName (name.AsSpan(1, name.Length - 2)) 0 + | _ -> false + let GetCompleteIdentifierIslandImpl (lineStr: string) (index: int) : (string * int * bool) option = - if index < 0 || isNull lineStr || index >= lineStr.Length then None + if index < 0 || isNull lineStr || index >= lineStr.Length then + None else let fixup = match () with // at a valid position, on a valid character - | _ when (index < lineStr.Length) && (lineStr[index] = '|' || IsIdentifierPartCharacter lineStr[index]) -> Some index + | _ when + (index < lineStr.Length) + && (lineStr[index] = '|' || IsIdentifierPartCharacter lineStr[index]) + -> + Some index | _ -> None // not on a word or '.' - - - let (|Char|_|) p = if p >=0 && p < lineStr.Length then Some(lineStr[p]) else None - let (|IsLongIdentifierPartChar|_|) c = if IsLongIdentifierPartCharacter c then Some () else None - let (|IsIdentifierPartChar|_|) c = if IsIdentifierPartCharacter c then Some () else None + + let (|Char|_|) p = + if p >= 0 && p < lineStr.Length then + Some(lineStr[p]) + else + None + + let (|IsLongIdentifierPartChar|_|) c = + if IsLongIdentifierPartCharacter c then Some() else None + + let (|IsIdentifierPartChar|_|) c = + if IsIdentifierPartCharacter c then Some() else None let rec searchLeft p = match (p - 1), (p - 2) with | Char '|', Char '[' -> p // boundary of array declaration - stop - | Char '|', _ + | Char '|', _ | Char IsLongIdentifierPartChar, _ -> searchLeft (p - 1) // allow normal chars and '.'s | _ -> p @@ -97,36 +116,42 @@ module QuickParse = | Char '|', Char ']' -> p // boundary of array declaration - stop | Char '|', _ | Char IsIdentifierPartChar, _ -> searchRight (p + 1) // allow only normal chars (stop at '.') - | _ -> p - - let tickColsOpt = + | _ -> p + + let tickColsOpt = let rec walkOutsideBackticks i = - if i >= lineStr.Length then None + if i >= lineStr.Length then + None else - match i, i + 1 with - | Char '`', Char '`' -> - // dive into backticked part - // if pos = i then it will be included in backticked range ($``identifier``) - walkInsideBackticks (i + 2) i - | _, _ -> - if i >= index then None - else - // we still not reached position p - continue walking - walkOutsideBackticks (i + 1) - and walkInsideBackticks i start = - if i >= lineStr.Length then None // non-closed backticks + match i, i + 1 with + | Char '`', Char '`' -> + // dive into backticked part + // if pos = i then it will be included in backticked range ($``identifier``) + walkInsideBackticks (i + 2) i + | _, _ -> + if i >= index then + None + else + // we still not reached position p - continue walking + walkOutsideBackticks (i + 1) + + and walkInsideBackticks i start = + if i >= lineStr.Length then + None // non-closed backticks else - match i, i + 1 with - | Char '`', Char '`' -> - // found closing pair of backticks - // if target position is between start and current pos + 1 (entire range of escaped identifier including backticks) - return success - // else climb outside and continue walking - if index >= start && index < (i + 2) then Some (start, i) - else walkOutsideBackticks (i + 2) - | _, _ -> walkInsideBackticks (i + 1) start + match i, i + 1 with + | Char '`', Char '`' -> + // found closing pair of backticks + // if target position is between start and current pos + 1 (entire range of escaped identifier including backticks) - return success + // else climb outside and continue walking + if index >= start && index < (i + 2) then + Some(start, i) + else + walkOutsideBackticks (i + 2) + | _, _ -> walkInsideBackticks (i + 1) start walkOutsideBackticks 0 - + match tickColsOpt with | Some (prevTickTick, idxTickTick) -> // inside ``identifier`` (which can contain any characters!) so we try returning its location @@ -135,14 +160,17 @@ module QuickParse = Some(ident, pos, true) | _ -> // find location of an ordinary identifier - fixup |> Option.bind (fun p -> + fixup + |> Option.bind (fun p -> let l = searchLeft p let r = searchRight p - let ident = lineStr.Substring (l, r - l + 1) - if ident.IndexOf('|') <> -1 && not(isValidActivePatternName(ident)) then None else - let pos = r + MagicalAdjustmentConstant - Some(ident, pos, false) - ) + let ident = lineStr.Substring(l, r - l + 1) + + if ident.IndexOf('|') <> -1 && not (isValidActivePatternName (ident)) then + None + else + let pos = r + MagicalAdjustmentConstant + Some(ident, pos, false)) /// Given a string and a position in that string, find an identifier as /// expected by `GotoDefinition`. This will work when the cursor is @@ -154,7 +182,7 @@ module QuickParse = /// /// In general, only identifiers composed from upper/lower letters and '.' are supported, but there /// are a couple of explicitly handled exceptions to allow some common scenarios: - /// - When the name contains only letters and '|' symbol, it may be an active pattern, so we + /// - When the name contains only letters and '|' symbol, it may be an active pattern, so we /// treat it as a valid identifier - e.g. let ( |Identity| ) a = a /// (but other identifiers that include '|' are not allowed - e.g. '||' operator) /// - It searches for double tick (``) to see if the identifier could be something like ``a b`` @@ -162,200 +190,253 @@ module QuickParse = /// REVIEW: Also support, e.g., operators, performing the necessary mangling. /// (i.e., I would like that the name returned here can be passed as-is /// (post `.`-chopping) to `GetDeclarationLocation.) - /// + /// /// In addition, return the position where a `.` would go if we were making /// a call to `DeclItemsForNamesAtPosition` for intellisense. This will /// allow us to use find the correct qualified items rather than resorting /// to the more expensive and less accurate environment lookup. let GetCompleteIdentifierIsland (tolerateJustAfter: bool) (lineStr: string) (index: int) : (string * int * bool) option = - if String.IsNullOrEmpty lineStr then None - else + if String.IsNullOrEmpty lineStr then + None + else let directResult = GetCompleteIdentifierIslandImpl lineStr index - if tolerateJustAfter && directResult = None then + + if tolerateJustAfter && directResult = None then GetCompleteIdentifierIslandImpl lineStr (index - 1) - else + else directResult let private defaultName = [], "" /// Get the partial long name of the identifier to the left of index. - let GetPartialLongName(lineStr: string, index: int) = - if isNull lineStr then defaultName - elif index < 0 then defaultName - elif index >= lineStr.Length then defaultName + let GetPartialLongName (lineStr: string, index: int) = + if isNull lineStr then + defaultName + elif index < 0 then + defaultName + elif index >= lineStr.Length then + defaultName else let IsIdentifierPartCharacter pos = IsIdentifierPartCharacter lineStr[pos] - let IsLongIdentifierPartCharacter pos = IsLongIdentifierPartCharacter lineStr[pos] + + let IsLongIdentifierPartCharacter pos = + IsLongIdentifierPartCharacter lineStr[pos] + let IsDot pos = lineStr[pos] = '.' - let rec InLeadingIdentifier(pos,right,(prior,residue)) = - let PushName() = ((lineStr.Substring(pos+1,right-pos-1)) :: prior),residue - if pos < 0 then PushName() - elif IsIdentifierPartCharacter pos then InLeadingIdentifier(pos-1,right,(prior,residue)) - elif IsDot pos then InLeadingIdentifier(pos-1,pos,PushName()) - else PushName() - - let rec InName(pos,startResidue,right) = - let NameAndResidue() = - [lineStr.Substring(pos+1,startResidue-pos-1)],(lineStr.Substring(startResidue+1,right-startResidue)) - if pos < 0 then [lineStr.Substring(pos+1,startResidue-pos-1)],(lineStr.Substring(startResidue+1,right-startResidue)) - elif IsIdentifierPartCharacter pos then InName(pos-1,startResidue,right) - elif IsDot pos then InLeadingIdentifier(pos-1,pos,NameAndResidue()) - else NameAndResidue() - - let rec InResidue(pos,right) = - if pos < 0 then [],lineStr.Substring(pos+1,right-pos) - elif IsDot pos then InName(pos-1,pos,right) - elif IsLongIdentifierPartCharacter pos then InResidue(pos-1, right) - else [],lineStr.Substring(pos+1,right-pos) - - let result = InResidue(index,index) + let rec InLeadingIdentifier (pos, right, (prior, residue)) = + let PushName () = + ((lineStr.Substring(pos + 1, right - pos - 1)) :: prior), residue + + if pos < 0 then + PushName() + elif IsIdentifierPartCharacter pos then + InLeadingIdentifier(pos - 1, right, (prior, residue)) + elif IsDot pos then + InLeadingIdentifier(pos - 1, pos, PushName()) + else + PushName() + + let rec InName (pos, startResidue, right) = + let NameAndResidue () = + [ lineStr.Substring(pos + 1, startResidue - pos - 1) ], (lineStr.Substring(startResidue + 1, right - startResidue)) + + if pos < 0 then + [ lineStr.Substring(pos + 1, startResidue - pos - 1) ], (lineStr.Substring(startResidue + 1, right - startResidue)) + elif IsIdentifierPartCharacter pos then + InName(pos - 1, startResidue, right) + elif IsDot pos then + InLeadingIdentifier(pos - 1, pos, NameAndResidue()) + else + NameAndResidue() + + let rec InResidue (pos, right) = + if pos < 0 then + [], lineStr.Substring(pos + 1, right - pos) + elif IsDot pos then + InName(pos - 1, pos, right) + elif IsLongIdentifierPartCharacter pos then + InResidue(pos - 1, right) + else + [], lineStr.Substring(pos + 1, right - pos) + + let result = InResidue(index, index) result - + type private EatCommentCallContext = | SkipWhiteSpaces of ident: string * current: string list * throwAwayNext: bool | StartIdentifier of current: string list * throwAway: bool /// Get the partial long name of the identifier to the left of index. /// For example, for `System.DateTime.Now` it returns PartialLongName ([|"System"; "DateTime"|], "Now", Some 32), where "32" pos of the last dot. - let GetPartialLongNameEx(lineStr: string, index: int) : PartialLongName = - if isNull lineStr then PartialLongName.Empty(index) - elif index < 0 then PartialLongName.Empty(index) - elif index >= lineStr.Length then PartialLongName.Empty(index) + let GetPartialLongNameEx (lineStr: string, index: int) : PartialLongName = + if isNull lineStr then + PartialLongName.Empty(index) + elif index < 0 then + PartialLongName.Empty(index) + elif index >= lineStr.Length then + PartialLongName.Empty(index) else let IsIdentifierPartCharacter pos = IsIdentifierPartCharacter lineStr[pos] let IsIdentifierStartCharacter pos = IsIdentifierPartCharacter pos let IsDot pos = lineStr[pos] = '.' let IsTick pos = lineStr[pos] = '`' - let IsEndOfComment pos = pos < index - 1 && lineStr[pos] = '*' && lineStr[pos + 1] = ')' - let IsStartOfComment pos = pos < index - 1 && lineStr[pos] = '(' && lineStr[pos + 1] = '*' + + let IsEndOfComment pos = + pos < index - 1 && lineStr[pos] = '*' && lineStr[pos + 1] = ')' + + let IsStartOfComment pos = + pos < index - 1 && lineStr[pos] = '(' && lineStr[pos + 1] = '*' + let IsWhitespace pos = Char.IsWhiteSpace(lineStr[pos]) - let rec SkipWhitespaceBeforeDotIdentifier(pos, ident, current, throwAwayNext, lastDotPos) = - if pos > index then PartialLongName.Empty(index) // we're in whitespace after an identifier, if this is where the cursor is, there is no PLID here - elif IsWhitespace pos then SkipWhitespaceBeforeDotIdentifier(pos+1,ident,current,throwAwayNext,lastDotPos) - elif IsDot pos then AtStartOfIdentifier(pos+1,ident :: current,throwAwayNext, Some pos) - elif IsStartOfComment pos then EatComment(1, pos + 1, EatCommentCallContext.SkipWhiteSpaces(ident, current, throwAwayNext), lastDotPos) - else AtStartOfIdentifier(pos,[],false,None) // Throw away what we have and start over. + let rec SkipWhitespaceBeforeDotIdentifier (pos, ident, current, throwAwayNext, lastDotPos) = + if pos > index then + PartialLongName.Empty(index) // we're in whitespace after an identifier, if this is where the cursor is, there is no PLID here + elif IsWhitespace pos then + SkipWhitespaceBeforeDotIdentifier(pos + 1, ident, current, throwAwayNext, lastDotPos) + elif IsDot pos then + AtStartOfIdentifier(pos + 1, ident :: current, throwAwayNext, Some pos) + elif IsStartOfComment pos then + EatComment(1, pos + 1, EatCommentCallContext.SkipWhiteSpaces(ident, current, throwAwayNext), lastDotPos) + else + AtStartOfIdentifier(pos, [], false, None) // Throw away what we have and start over. - and EatComment (nesting, pos, callContext,lastDotPos) = - if pos > index then PartialLongName.Empty(index) else - if IsStartOfComment pos then + and EatComment (nesting, pos, callContext, lastDotPos) = + if pos > index then + PartialLongName.Empty(index) + else if IsStartOfComment pos then // track balance of closing '*)' - EatComment(nesting + 1, pos + 2, callContext,lastDotPos) - else - if IsEndOfComment pos then - if nesting = 1 then + EatComment(nesting + 1, pos + 2, callContext, lastDotPos) + else if IsEndOfComment pos then + if nesting = 1 then // all right, we are at the end of comment, jump outside match callContext with - | EatCommentCallContext.SkipWhiteSpaces(ident, current, throwAway) -> - SkipWhitespaceBeforeDotIdentifier(pos + 2, ident, current, throwAway,lastDotPos) - | EatCommentCallContext.StartIdentifier(current, throwAway) -> - AtStartOfIdentifier(pos + 2, current, throwAway,lastDotPos) - else + | EatCommentCallContext.SkipWhiteSpaces (ident, current, throwAway) -> + SkipWhitespaceBeforeDotIdentifier(pos + 2, ident, current, throwAway, lastDotPos) + | EatCommentCallContext.StartIdentifier (current, throwAway) -> + AtStartOfIdentifier(pos + 2, current, throwAway, lastDotPos) + else // reduce level of nesting and continue EatComment(nesting - 1, pos + 2, callContext, lastDotPos) else // eat next char EatComment(nesting, pos + 1, callContext, lastDotPos) - and InUnquotedIdentifier(left:int,pos:int,current,throwAwayNext,lastDotPos) = - if pos > index then - if throwAwayNext then - PartialLongName.Empty(index) + and InUnquotedIdentifier (left: int, pos: int, current, throwAwayNext, lastDotPos) = + if pos > index then + if throwAwayNext then + PartialLongName.Empty(index) else - { QualifyingIdents = current - PartialIdent = lineStr.Substring(left,pos-left) - EndColumn = index - LastDotPos = lastDotPos } + { + QualifyingIdents = current + PartialIdent = lineStr.Substring(left, pos - left) + EndColumn = index + LastDotPos = lastDotPos + } + else if IsIdentifierPartCharacter pos then + InUnquotedIdentifier(left, pos + 1, current, throwAwayNext, lastDotPos) + elif IsDot pos then + let ident = lineStr.Substring(left, pos - left) + AtStartOfIdentifier(pos + 1, ident :: current, throwAwayNext, Some pos) + elif IsWhitespace pos || IsStartOfComment pos then + let ident = lineStr.Substring(left, pos - left) + SkipWhitespaceBeforeDotIdentifier(pos, ident, current, throwAwayNext, lastDotPos) else - if IsIdentifierPartCharacter pos then InUnquotedIdentifier(left,pos+1,current,throwAwayNext,lastDotPos) - elif IsDot pos then - let ident = lineStr.Substring(left,pos-left) - AtStartOfIdentifier(pos+1,ident :: current,throwAwayNext, Some pos) - elif IsWhitespace pos || IsStartOfComment pos then - let ident = lineStr.Substring(left,pos-left) - SkipWhitespaceBeforeDotIdentifier(pos, ident, current, throwAwayNext, lastDotPos) - else AtStartOfIdentifier(pos,[],false,None) // Throw away what we have and start over. - - and InQuotedIdentifier(left:int,pos:int, current,throwAwayNext,lastDotPos) = - if pos > index then - if throwAwayNext then - PartialLongName.Empty(index) - else - { QualifyingIdents = current - PartialIdent = lineStr.Substring(left,pos-left) - EndColumn = index - LastDotPos = lastDotPos } + AtStartOfIdentifier(pos, [], false, None) // Throw away what we have and start over. + + and InQuotedIdentifier (left: int, pos: int, current, throwAwayNext, lastDotPos) = + if pos > index then + if throwAwayNext then + PartialLongName.Empty(index) + else + { + QualifyingIdents = current + PartialIdent = lineStr.Substring(left, pos - left) + EndColumn = index + LastDotPos = lastDotPos + } else let remainingLength = lineStr.Length - pos - if IsTick pos && remainingLength > 1 && IsTick(pos+1) then - let ident = lineStr.Substring(left, pos-left) - SkipWhitespaceBeforeDotIdentifier(pos+2,ident,current,throwAwayNext,lastDotPos) - else InQuotedIdentifier(left,pos+1,current,throwAwayNext,lastDotPos) - - and AtStartOfIdentifier(pos:int, current, throwAwayNext, lastDotPos: int option) = - if pos > index then - if throwAwayNext then + + if IsTick pos && remainingLength > 1 && IsTick(pos + 1) then + let ident = lineStr.Substring(left, pos - left) + SkipWhitespaceBeforeDotIdentifier(pos + 2, ident, current, throwAwayNext, lastDotPos) + else + InQuotedIdentifier(left, pos + 1, current, throwAwayNext, lastDotPos) + + and AtStartOfIdentifier (pos: int, current, throwAwayNext, lastDotPos: int option) = + if pos > index then + if throwAwayNext then PartialLongName.Empty(index) - else - { QualifyingIdents = current - PartialIdent = "" - EndColumn = index - LastDotPos = lastDotPos } - else - if IsWhitespace pos then AtStartOfIdentifier(pos+1,current,throwAwayNext, lastDotPos) else - let remainingLength = lineStr.Length - pos - if IsTick pos && remainingLength > 1 && IsTick(pos+1) then InQuotedIdentifier(pos+2,pos+2,current,throwAwayNext,lastDotPos) - elif IsStartOfComment pos then EatComment(1, pos + 1, EatCommentCallContext.StartIdentifier(current, throwAwayNext), lastDotPos) - elif IsIdentifierStartCharacter pos then InUnquotedIdentifier(pos,pos+1,current,throwAwayNext,lastDotPos) - elif IsDot pos then - if pos = 0 then - // dot on first char of line, currently treat it like empty identifier to the left - AtStartOfIdentifier(pos+1,"":: current,throwAwayNext, Some pos) - elif not (pos > 0 && (IsIdentifierPartCharacter(pos-1) || IsWhitespace(pos-1))) then - // it's not dots as part.of.a.long.ident, it's e.g. the range operator (..), or some other multi-char operator ending in dot - if lineStr[pos-1] = ')' then - // one very problematic case is someCall(args).Name - // without special logic, we will decide that ). is an operator and parse Name as the plid - // but in fact this is an expression tail, and we don't want a plid, rather we need to use expression typings at that location - // so be sure not to treat the name here as a plid - AtStartOfIdentifier(pos+1,[],true,None) // Throw away what we have, and the next apparent plid, and start over. - else - AtStartOfIdentifier(pos+1,[],false,None) // Throw away what we have and start over. + { + QualifyingIdents = current + PartialIdent = "" + EndColumn = index + LastDotPos = lastDotPos + } + else if IsWhitespace pos then + AtStartOfIdentifier(pos + 1, current, throwAwayNext, lastDotPos) + else + let remainingLength = lineStr.Length - pos + + if IsTick pos && remainingLength > 1 && IsTick(pos + 1) then + InQuotedIdentifier(pos + 2, pos + 2, current, throwAwayNext, lastDotPos) + elif IsStartOfComment pos then + EatComment(1, pos + 1, EatCommentCallContext.StartIdentifier(current, throwAwayNext), lastDotPos) + elif IsIdentifierStartCharacter pos then + InUnquotedIdentifier(pos, pos + 1, current, throwAwayNext, lastDotPos) + elif IsDot pos then + if pos = 0 then + // dot on first char of line, currently treat it like empty identifier to the left + AtStartOfIdentifier(pos + 1, "" :: current, throwAwayNext, Some pos) + elif not (pos > 0 && (IsIdentifierPartCharacter(pos - 1) || IsWhitespace(pos - 1))) then + // it's not dots as part.of.a.long.ident, it's e.g. the range operator (..), or some other multi-char operator ending in dot + if lineStr[pos - 1] = ')' then + // one very problematic case is someCall(args).Name + // without special logic, we will decide that ). is an operator and parse Name as the plid + // but in fact this is an expression tail, and we don't want a plid, rather we need to use expression typings at that location + // so be sure not to treat the name here as a plid + AtStartOfIdentifier(pos + 1, [], true, None) // Throw away what we have, and the next apparent plid, and start over. else - AtStartOfIdentifier(pos+1,"":: current,throwAwayNext, Some pos) - else AtStartOfIdentifier(pos+1,[],throwAwayNext, None) - let partialLongName = AtStartOfIdentifier(0, [], false, None) - + AtStartOfIdentifier(pos + 1, [], false, None) // Throw away what we have and start over. + else + AtStartOfIdentifier(pos + 1, "" :: current, throwAwayNext, Some pos) + else + AtStartOfIdentifier(pos + 1, [], throwAwayNext, None) + + let partialLongName = AtStartOfIdentifier(0, [], false, None) + match List.rev partialLongName.QualifyingIdents with - | s :: _ when s.Length > 0 && Char.IsDigit(s[0]) -> PartialLongName.Empty(index) // "2.0" is not a longId (this might not be right for ``2.0`` but good enough for common case) - | plid -> { partialLongName with QualifyingIdents = plid } - - let TokenNameEquals (tokenInfo: FSharpTokenInfo) (token2: string) = - String.Compare(tokenInfo .TokenName, token2, StringComparison.OrdinalIgnoreCase) = 0 - + | s :: _ when s.Length > 0 && Char.IsDigit(s[0]) -> PartialLongName.Empty(index) // "2.0" is not a longId (this might not be right for ``2.0`` but good enough for common case) + | plid -> + { partialLongName with + QualifyingIdents = plid + } + + let TokenNameEquals (tokenInfo: FSharpTokenInfo) (token2: string) = + String.Compare(tokenInfo.TokenName, token2, StringComparison.OrdinalIgnoreCase) = 0 + // The prefix of the sequence of token names to look for in TestMemberOrOverrideDeclaration, in reverse order - let private expected = [ [|"dot"|]; [|"ident"|]; [|"member"; "override"|] ] + let private expected = [ [| "dot" |]; [| "ident" |]; [| "member"; "override" |] ] /// Tests whether the user is typing something like "member x." or "override (*comment*) x." let TestMemberOrOverrideDeclaration (tokens: FSharpTokenInfo[]) = - let filteredReversed = - tokens + let filteredReversed = + tokens |> Array.filter (fun tok -> // cut out whitespaces\comments\access modifiers - not (TokenNameEquals tok "comment") && - not (TokenNameEquals tok "whitespace") && - not (TokenNameEquals tok "private") && - not (TokenNameEquals tok "internal") && - not (TokenNameEquals tok "public") - ) + not (TokenNameEquals tok "comment") + && not (TokenNameEquals tok "whitespace") + && not (TokenNameEquals tok "private") + && not (TokenNameEquals tok "internal") + && not (TokenNameEquals tok "public")) |> Array.rev - - if filteredReversed.Length < expected.Length then false - else + + if filteredReversed.Length < expected.Length then + false + else // check whether sequences match - (filteredReversed, expected) ||> Seq.forall2 (fun tok expect -> - expect |> Array.exists (TokenNameEquals tok) ) - + (filteredReversed, expected) + ||> Seq.forall2 (fun tok expect -> expect |> Array.exists (TokenNameEquals tok)) diff --git a/src/Compiler/Service/SemanticClassification.fs b/src/Compiler/Service/SemanticClassification.fs index 0cb7f19ba78..fc4f9d21b75 100644 --- a/src/Compiler/Service/SemanticClassification.fs +++ b/src/Compiler/Service/SemanticClassification.fs @@ -5,14 +5,14 @@ namespace FSharp.Compiler.EditorServices open System.Diagnostics open System.Collections.Generic open System.Collections.Immutable -open Internal.Utilities.Library +open Internal.Utilities.Library open FSharp.Compiler.Diagnostics open FSharp.Compiler.Import open FSharp.Compiler.Infos open FSharp.Compiler.DiagnosticsLogger open FSharp.Compiler.NameResolution open FSharp.Compiler.Syntax.PrettyNaming -open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TcGlobals open FSharp.Compiler.Text open FSharp.Compiler.Text.Range open FSharp.Compiler.TypedTree @@ -67,317 +67,336 @@ type SemanticClassificationItem = [] module TcResolutionsExtensions = - let (|CNR|) (cnr:CapturedNameResolution) = + let (|CNR|) (cnr: CapturedNameResolution) = (cnr.Item, cnr.ItemOccurence, cnr.DisplayEnv, cnr.NameResolutionEnv, cnr.AccessorDomain, cnr.Range) type TcResolutions with - member sResolutions.GetSemanticClassification(g: TcGlobals, amap: ImportMap, formatSpecifierLocations: (range * int) [], range: range option) : SemanticClassificationItem [] = - DiagnosticsScope.Protect range0 (fun () -> - let (|LegitTypeOccurence|_|) = function - | ItemOccurence.UseInType - | ItemOccurence.UseInAttribute - | ItemOccurence.Use _ - | ItemOccurence.Binding _ - | ItemOccurence.Pattern _ - | ItemOccurence.Open -> Some() - | _ -> None - - let (|KeywordIntrinsicValue|_|) (vref: ValRef) = - if valRefEq g g.raise_vref vref || - valRefEq g g.reraise_vref vref || - valRefEq g g.typeof_vref vref || - valRefEq g g.typedefof_vref vref || - valRefEq g g.sizeof_vref vref || - valRefEq g g.nameof_vref vref then Some() - else None - - let (|EnumCaseFieldInfo|_|) (rfinfo : RecdFieldInfo) = - match rfinfo.TyconRef.TypeReprInfo with - | TFSharpObjectRepr x -> - match x.fsobjmodel_kind with - | TFSharpEnum -> Some () + + member sResolutions.GetSemanticClassification + ( + g: TcGlobals, + amap: ImportMap, + formatSpecifierLocations: (range * int)[], + range: range option + ) : SemanticClassificationItem[] = + DiagnosticsScope.Protect + range0 + (fun () -> + let (|LegitTypeOccurence|_|) occ = + match occ with + | ItemOccurence.UseInType + | ItemOccurence.UseInAttribute + | ItemOccurence.Use _ + | ItemOccurence.Binding _ + | ItemOccurence.Pattern _ + | ItemOccurence.Open -> Some() + | _ -> None + + let (|KeywordIntrinsicValue|_|) (vref: ValRef) = + if + valRefEq g g.raise_vref vref + || valRefEq g g.reraise_vref vref + || valRefEq g g.typeof_vref vref + || valRefEq g g.typedefof_vref vref + || valRefEq g g.sizeof_vref vref + || valRefEq g g.nameof_vref vref + then + Some() + else + None + + let (|EnumCaseFieldInfo|_|) (rfinfo: RecdFieldInfo) = + match rfinfo.TyconRef.TypeReprInfo with + | TFSharpObjectRepr x -> + match x.fsobjmodel_kind with + | TFSharpEnum -> Some() + | _ -> None | _ -> None - | _ -> None - - // Custome builders like 'async { }' are both Item.Value and Item.CustomBuilder. - // We should prefer the latter, otherwise they would not get classified as CEs. - let takeCustomBuilder (cnrs: CapturedNameResolution[]) = - assert (cnrs.Length > 0) - if cnrs.Length = 1 then - cnrs - elif cnrs.Length = 2 then - match cnrs[0].Item, cnrs[1].Item with - | Item.Value _, Item.CustomBuilder _ -> - [| cnrs[1] |] - | Item.CustomBuilder _, Item.Value _ -> - [| cnrs[0] |] - | _ -> + + // Custome builders like 'async { }' are both Item.Value and Item.CustomBuilder. + // We should prefer the latter, otherwise they would not get classified as CEs. + let takeCustomBuilder (cnrs: CapturedNameResolution[]) = + assert (cnrs.Length > 0) + + if cnrs.Length = 1 then cnrs - else - cnrs - - let resolutions = - match range with - | Some range -> - sResolutions.CapturedNameResolutions.ToArray() - |> Array.filter (fun cnr -> rangeContainsPos range cnr.Range.Start || rangeContainsPos range cnr.Range.End) - |> Array.groupBy (fun cnr -> cnr.Range) - |> Array.map (fun (_, cnrs) -> takeCustomBuilder cnrs) - |> Array.concat - | None -> - sResolutions.CapturedNameResolutions.ToArray() - - let isDisposableTy (ty: TType) = - not (typeEquiv g ty g.system_IDisposable_ty) && - protectAssemblyExplorationNoReraise false false (fun () -> ExistsHeadTypeInEntireHierarchy g amap range0 ty g.tcref_System_IDisposable) - - let isDiscard (str: string) = str.StartsWith("_") - - let isValRefDisposable (vref: ValRef) = - not (isDiscard vref.DisplayName) && - // For values, we actually do want to color things if they literally are IDisposables - protectAssemblyExplorationNoReraise false false (fun () -> ExistsHeadTypeInEntireHierarchy g amap range0 vref.Type g.tcref_System_IDisposable) - - let isStructTyconRef (tyconRef: TyconRef) = - let ty = generalizedTyconRef g tyconRef - let underlyingTy = stripTyEqnsAndMeasureEqns g ty - isStructTy g underlyingTy - - let isValRefMutable (vref: ValRef) = - // Mutable values, ref cells, and non-inref byrefs are mutable. - vref.IsMutable - || isRefCellTy g vref.Type - || (isByrefTy g vref.Type && not (isInByrefTy g vref.Type)) - - let isRecdFieldMutable (rfinfo: RecdFieldInfo) = - (rfinfo.RecdField.IsMutable && rfinfo.LiteralValue.IsNone) - || isRefCellTy g rfinfo.RecdField.FormalType - - let duplicates = HashSet(comparer) - - let results = ImmutableArray.CreateBuilder() - let inline add m (typ: SemanticClassificationType) = - if duplicates.Add m then - results.Add (SemanticClassificationItem((m, typ))) - - resolutions - |> Array.iter (fun cnr -> - match cnr.Item, cnr.ItemOccurence, cnr.DisplayEnv, cnr.NameResolutionEnv, cnr.AccessorDomain, cnr.Range with - | (Item.CustomBuilder _ | Item.CustomOperation _), ItemOccurence.Use, _, _, _, m -> - add m SemanticClassificationType.ComputationExpression - - | Item.Value vref, _, _, _, _, m when isValRefMutable vref -> - add m SemanticClassificationType.MutableVar - - | Item.Value KeywordIntrinsicValue, ItemOccurence.Use, _, _, _, m -> - add m SemanticClassificationType.IntrinsicFunction - - | Item.Value vref, _, _, _, _, m when isForallFunctionTy g vref.Type -> - if isDiscard vref.DisplayName then - add m SemanticClassificationType.Plaintext - elif valRefEq g g.range_op_vref vref || valRefEq g g.range_step_op_vref vref then - add m SemanticClassificationType.Operator - elif vref.IsPropertyGetterMethod || vref.IsPropertySetterMethod then - add m SemanticClassificationType.Property - elif vref.IsMember then - add m SemanticClassificationType.Method - elif IsOperatorDisplayName vref.DisplayName then - add m SemanticClassificationType.Operator + elif cnrs.Length = 2 then + match cnrs[0].Item, cnrs[1].Item with + | Item.Value _, Item.CustomBuilder _ -> [| cnrs[1] |] + | Item.CustomBuilder _, Item.Value _ -> [| cnrs[0] |] + | _ -> cnrs else - add m SemanticClassificationType.Function + cnrs - | Item.Value vref, _, _, _, _, m -> - if isValRefDisposable vref then - if vref.IsCompiledAsTopLevel then - add m SemanticClassificationType.DisposableTopLevelValue + let resolutions = + match range with + | Some range -> + sResolutions.CapturedNameResolutions.ToArray() + |> Array.filter (fun cnr -> rangeContainsPos range cnr.Range.Start || rangeContainsPos range cnr.Range.End) + |> Array.groupBy (fun cnr -> cnr.Range) + |> Array.map (fun (_, cnrs) -> takeCustomBuilder cnrs) + |> Array.concat + | None -> sResolutions.CapturedNameResolutions.ToArray() + + let isDisposableTy (ty: TType) = + not (typeEquiv g ty g.system_IDisposable_ty) + && protectAssemblyExplorationNoReraise false false (fun () -> + ExistsHeadTypeInEntireHierarchy g amap range0 ty g.tcref_System_IDisposable) + + let isDiscard (str: string) = str.StartsWith("_") + + let isValRefDisposable (vref: ValRef) = + not (isDiscard vref.DisplayName) + && + // For values, we actually do want to color things if they literally are IDisposables + protectAssemblyExplorationNoReraise false false (fun () -> + ExistsHeadTypeInEntireHierarchy g amap range0 vref.Type g.tcref_System_IDisposable) + + let isStructTyconRef (tcref: TyconRef) = + let ty = generalizedTyconRef g tcref + let underlyingTy = stripTyEqnsAndMeasureEqns g ty + isStructTy g underlyingTy + + let isValRefMutable (vref: ValRef) = + // Mutable values, ref cells, and non-inref byrefs are mutable. + vref.IsMutable + || isRefCellTy g vref.Type + || (isByrefTy g vref.Type && not (isInByrefTy g vref.Type)) + + let isRecdFieldMutable (rfinfo: RecdFieldInfo) = + (rfinfo.RecdField.IsMutable && rfinfo.LiteralValue.IsNone) + || isRefCellTy g rfinfo.RecdField.FormalType + + let duplicates = HashSet(comparer) + + let results = ImmutableArray.CreateBuilder() + + let inline add m (typ: SemanticClassificationType) = + if duplicates.Add m then + results.Add(SemanticClassificationItem((m, typ))) + + resolutions + |> Array.iter (fun cnr -> + match cnr.Item, cnr.ItemOccurence, cnr.Range with + | (Item.CustomBuilder _ + | Item.CustomOperation _), + ItemOccurence.Use, + m -> add m SemanticClassificationType.ComputationExpression + + | Item.Value vref, _, m when isValRefMutable vref -> add m SemanticClassificationType.MutableVar + + | Item.Value KeywordIntrinsicValue, ItemOccurence.Use, m -> add m SemanticClassificationType.IntrinsicFunction + + | Item.Value vref, _, m when isForallFunctionTy g vref.Type -> + if isDiscard vref.DisplayName then + add m SemanticClassificationType.Plaintext + elif valRefEq g g.range_op_vref vref || valRefEq g g.range_step_op_vref vref then + add m SemanticClassificationType.Operator + elif vref.IsPropertyGetterMethod || vref.IsPropertySetterMethod then + add m SemanticClassificationType.Property + elif vref.IsMember then + add m SemanticClassificationType.Method + elif IsOperatorDisplayName vref.DisplayName then + add m SemanticClassificationType.Operator else - add m SemanticClassificationType.DisposableLocalValue - elif Option.isSome vref.LiteralValue then - add m SemanticClassificationType.Literal - elif not vref.IsCompiledAsTopLevel && not(isDiscard vref.DisplayName) then - add m SemanticClassificationType.LocalValue - else - add m SemanticClassificationType.Value - - | Item.RecdField rfinfo, _, _, _, _, m -> - match rfinfo with - | EnumCaseFieldInfo -> - add m SemanticClassificationType.Enumeration - | _ -> - if isRecdFieldMutable rfinfo then + add m SemanticClassificationType.Function + + | Item.Value vref, _, m -> + if isValRefDisposable vref then + if vref.IsCompiledAsTopLevel then + add m SemanticClassificationType.DisposableTopLevelValue + else + add m SemanticClassificationType.DisposableLocalValue + elif Option.isSome vref.LiteralValue then + add m SemanticClassificationType.Literal + elif not vref.IsCompiledAsTopLevel && not (isDiscard vref.DisplayName) then + add m SemanticClassificationType.LocalValue + else + add m SemanticClassificationType.Value + + | Item.RecdField rfinfo, _, m -> + match rfinfo with + | EnumCaseFieldInfo -> add m SemanticClassificationType.Enumeration + | _ -> + if isRecdFieldMutable rfinfo then + add m SemanticClassificationType.MutableRecordField + elif isFunTy g rfinfo.FieldType then + add m SemanticClassificationType.RecordFieldAsFunction + else + add m SemanticClassificationType.RecordField + + | Item.AnonRecdField (_, tys, idx, m), _, _ -> + let ty = tys[idx] + + // It's not currently possible for anon record fields to be mutable, but they can be ref cells + if isRefCellTy g ty then add m SemanticClassificationType.MutableRecordField - elif isFunTy g rfinfo.FieldType then + elif isFunTy g ty then add m SemanticClassificationType.RecordFieldAsFunction else add m SemanticClassificationType.RecordField - | Item.AnonRecdField(_, tys, idx, m), _, _, _, _, _ -> - let ty = tys[idx] + | Item.Property (_, pinfo :: _), _, m -> + if not pinfo.IsIndexer then + add m SemanticClassificationType.Property + + | Item.CtorGroup (_, minfos), _, m -> + match minfos with + | [] -> add m SemanticClassificationType.ConstructorForReferenceType + | _ -> + if minfos |> List.forall (fun minfo -> isDisposableTy minfo.ApparentEnclosingType) then + add m SemanticClassificationType.DisposableType + elif minfos |> List.forall (fun minfo -> isStructTy g minfo.ApparentEnclosingType) then + add m SemanticClassificationType.ConstructorForValueType + else + add m SemanticClassificationType.ConstructorForReferenceType - // It's not currently possible for anon record fields to be mutable, but they can be ref cells - if isRefCellTy g ty then - add m SemanticClassificationType.MutableRecordField - elif isFunTy g ty then - add m SemanticClassificationType.RecordFieldAsFunction - else - add m SemanticClassificationType.RecordField - - | Item.Property (_, pinfo :: _), _, _, _, _, m -> - if not pinfo.IsIndexer then - add m SemanticClassificationType.Property - - | Item.CtorGroup (_, minfos), _, _, _, _, m -> - match minfos with - | [] -> - add m SemanticClassificationType.ConstructorForReferenceType - | _ -> - if minfos |> List.forall (fun minfo -> isDisposableTy minfo.ApparentEnclosingType) then - add m SemanticClassificationType.DisposableType - elif minfos |> List.forall (fun minfo -> isStructTy g minfo.ApparentEnclosingType) then - add m SemanticClassificationType.ConstructorForValueType - else - add m SemanticClassificationType.ConstructorForReferenceType - - | (Item.DelegateCtor _ | Item.FakeInterfaceCtor _), _, _, _, _, m -> - add m SemanticClassificationType.ConstructorForReferenceType - - | Item.MethodGroup (_, minfos, _), _, _, _, _, m -> - match minfos with - | [] -> - add m SemanticClassificationType.Method - | _ -> - if minfos |> List.forall (fun minfo -> minfo.IsExtensionMember || minfo.IsCSharpStyleExtensionMember) then - add m SemanticClassificationType.ExtensionMethod - else - add m SemanticClassificationType.Method + | Item.DelegateCtor _, _, m -> add m SemanticClassificationType.ConstructorForReferenceType - // Special case measures for struct types - | Item.Types(_, TType_app(tyconRef, TType_measure _ :: _, _) :: _), LegitTypeOccurence, _, _, _, m when isStructTyconRef tyconRef -> - add m SemanticClassificationType.ValueType - - | Item.Types (_, ty :: _), LegitTypeOccurence, _, _, _, m -> - let reprToClassificationType repr tcref = - match repr with - | TFSharpObjectRepr om -> - match om.fsobjmodel_kind with - | TFSharpClass -> SemanticClassificationType.ReferenceType - | TFSharpInterface -> SemanticClassificationType.Interface - | TFSharpStruct -> SemanticClassificationType.ValueType - | TFSharpDelegate _ -> SemanticClassificationType.Delegate - | TFSharpEnum _ -> SemanticClassificationType.Enumeration - | TFSharpRecdRepr _ - | TFSharpUnionRepr _ -> - if isStructTyconRef tcref then - SemanticClassificationType.ValueType - else - SemanticClassificationType.Type - | TILObjectRepr (TILObjectReprData (_, _, td)) -> - if td.IsClass then - SemanticClassificationType.ReferenceType - elif td.IsStruct then - SemanticClassificationType.ValueType - elif td.IsInterface then - SemanticClassificationType.Interface - elif td.IsEnum then - SemanticClassificationType.Enumeration + | Item.FakeInterfaceCtor _, _, m -> add m SemanticClassificationType.ConstructorForReferenceType + + | Item.MethodGroup (_, minfos, _), _, m -> + match minfos with + | [] -> add m SemanticClassificationType.Method + | _ -> + if + minfos + |> List.forall (fun minfo -> minfo.IsExtensionMember || minfo.IsCSharpStyleExtensionMember) + then + add m SemanticClassificationType.ExtensionMethod else - SemanticClassificationType.Delegate - | TAsmRepr _ -> SemanticClassificationType.TypeDef - | TMeasureableRepr _-> SemanticClassificationType.TypeDef + add m SemanticClassificationType.Method + + // Special case measures for struct types + | Item.Types (_, AppTy g (tyconRef, TType_measure _ :: _) :: _), LegitTypeOccurence, m when + isStructTyconRef tyconRef + -> + add m SemanticClassificationType.ValueType + + | Item.Types (_, ty :: _), LegitTypeOccurence, m -> + let reprToClassificationType repr tcref = + match repr with + | TFSharpObjectRepr om -> + match om.fsobjmodel_kind with + | TFSharpClass -> SemanticClassificationType.ReferenceType + | TFSharpInterface -> SemanticClassificationType.Interface + | TFSharpStruct -> SemanticClassificationType.ValueType + | TFSharpDelegate _ -> SemanticClassificationType.Delegate + | TFSharpEnum _ -> SemanticClassificationType.Enumeration + | TFSharpRecdRepr _ + | TFSharpUnionRepr _ -> + if isStructTyconRef tcref then + SemanticClassificationType.ValueType + else + SemanticClassificationType.Type + | TILObjectRepr (TILObjectReprData (_, _, td)) -> + if td.IsClass then + SemanticClassificationType.ReferenceType + elif td.IsStruct then + SemanticClassificationType.ValueType + elif td.IsInterface then + SemanticClassificationType.Interface + elif td.IsEnum then + SemanticClassificationType.Enumeration + else + SemanticClassificationType.Delegate + | TAsmRepr _ -> SemanticClassificationType.TypeDef + | TMeasureableRepr _ -> SemanticClassificationType.TypeDef #if !NO_TYPEPROVIDERS - | TProvidedTypeRepr _-> SemanticClassificationType.TypeDef - | TProvidedNamespaceRepr _-> SemanticClassificationType.TypeDef + | TProvidedTypeRepr _ -> SemanticClassificationType.TypeDef + | TProvidedNamespaceRepr _ -> SemanticClassificationType.TypeDef #endif - | TNoRepr -> SemanticClassificationType.ReferenceType + | TNoRepr -> SemanticClassificationType.ReferenceType - let ty = stripTyEqns g ty - if isDisposableTy ty then - add m SemanticClassificationType.DisposableType - else - match tryTcrefOfAppTy g ty with - | ValueSome tcref -> - add m (reprToClassificationType tcref.TypeReprInfo tcref) - | ValueNone -> - if isStructTupleTy g ty then - add m SemanticClassificationType.ValueType - elif isRefTupleTy g ty then - add m SemanticClassificationType.ReferenceType - elif isForallFunctionTy g ty then - add m SemanticClassificationType.Function - elif isTyparTy g ty then - add m SemanticClassificationType.ValueType - else - add m SemanticClassificationType.TypeDef + let ty = stripTyEqns g ty - | Item.TypeVar _, LegitTypeOccurence, _, _, _, m -> - add m SemanticClassificationType.TypeArgument + if isDisposableTy ty then + add m SemanticClassificationType.DisposableType + else + match tryTcrefOfAppTy g ty with + | ValueSome tcref -> add m (reprToClassificationType tcref.TypeReprInfo tcref) + | ValueNone -> + if isStructTupleTy g ty then + add m SemanticClassificationType.ValueType + elif isRefTupleTy g ty then + add m SemanticClassificationType.ReferenceType + elif isForallFunctionTy g ty then + add m SemanticClassificationType.Function + elif isTyparTy g ty then + add m SemanticClassificationType.ValueType + else + add m SemanticClassificationType.TypeDef + + | Item.TypeVar _, LegitTypeOccurence, m -> add m SemanticClassificationType.TypeArgument + + | Item.ExnCase _, LegitTypeOccurence, m -> add m SemanticClassificationType.Exception + + | Item.ModuleOrNamespaces (modref :: _), LegitTypeOccurence, m -> + if modref.IsNamespace then + add m SemanticClassificationType.Namespace + else + add m SemanticClassificationType.Module - | Item.ExnCase _, LegitTypeOccurence, _, _, _, m -> - add m SemanticClassificationType.Exception + | Item.ActivePatternCase _, _, m -> add m SemanticClassificationType.UnionCase - | Item.ModuleOrNamespaces (modref :: _), LegitTypeOccurence, _, _, _, m -> - if modref.IsNamespace then - add m SemanticClassificationType.Namespace - else - add m SemanticClassificationType.Module + | Item.UnionCase _, _, m -> add m SemanticClassificationType.UnionCase - | (Item.ActivePatternCase _ | Item.UnionCase _ | Item.ActivePatternResult _), _, _, _, _, m -> - add m SemanticClassificationType.UnionCase + | Item.ActivePatternResult _, _, m -> add m SemanticClassificationType.UnionCase - | Item.UnionCaseField _, _, _, _, _, m -> - add m SemanticClassificationType.UnionCaseField + | Item.UnionCaseField _, _, m -> add m SemanticClassificationType.UnionCaseField - | Item.ILField _, _, _, _, _, m -> - add m SemanticClassificationType.Field + | Item.ILField _, _, m -> add m SemanticClassificationType.Field - | Item.Event _, _, _, _, _, m -> - add m SemanticClassificationType.Event + | Item.Event _, _, m -> add m SemanticClassificationType.Event - | (Item.ArgName _ | Item.SetterArg _), _, _, _, _, m -> - add m SemanticClassificationType.NamedArgument + | Item.ArgName _, _, m -> add m SemanticClassificationType.NamedArgument - | Item.SetterArg _, _, _, _, _, m -> - add m SemanticClassificationType.Property + | Item.SetterArg _, _, m -> add m SemanticClassificationType.NamedArgument - | Item.UnqualifiedType (tcref :: _), LegitTypeOccurence, _, _, _, m -> - if tcref.IsEnumTycon || tcref.IsILEnumTycon then - add m SemanticClassificationType.Enumeration - elif tcref.IsFSharpException then - add m SemanticClassificationType.Exception - elif tcref.IsFSharpDelegateTycon then - add m SemanticClassificationType.Delegate - elif tcref.IsFSharpInterfaceTycon then - add m SemanticClassificationType.Interface - elif tcref.IsFSharpStructOrEnumTycon then - add m SemanticClassificationType.ValueType - elif tcref.IsModule then - add m SemanticClassificationType.Module - elif tcref.IsNamespace then - add m SemanticClassificationType.Namespace - elif tcref.IsUnionTycon || tcref.IsRecordTycon then - if isStructTyconRef tcref then - add m SemanticClassificationType.ValueType - else - add m SemanticClassificationType.UnionCase - elif tcref.IsILTycon then - let (TILObjectReprData (_, _, tydef)) = tcref.ILTyconInfo + | Item.SetterArg _, _, m -> add m SemanticClassificationType.Property - if tydef.IsInterface then - add m SemanticClassificationType.Interface - elif tydef.IsDelegate then - add m SemanticClassificationType.Delegate - elif tydef.IsEnum then + | Item.UnqualifiedType (tcref :: _), LegitTypeOccurence, m -> + if tcref.IsEnumTycon || tcref.IsILEnumTycon then add m SemanticClassificationType.Enumeration - elif tydef.IsStruct then + elif tcref.IsFSharpException then + add m SemanticClassificationType.Exception + elif tcref.IsFSharpDelegateTycon then + add m SemanticClassificationType.Delegate + elif tcref.IsFSharpInterfaceTycon then + add m SemanticClassificationType.Interface + elif tcref.IsFSharpStructOrEnumTycon then add m SemanticClassificationType.ValueType - else - add m SemanticClassificationType.ReferenceType - - | _, _, _, _, _, m -> - add m SemanticClassificationType.Plaintext) - results.AddRange(formatSpecifierLocations |> Array.map (fun (m, _) -> SemanticClassificationItem((m, SemanticClassificationType.Printf)))) - results.ToArray() - ) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetSemanticClassification: '%s'" msg) - Array.empty) \ No newline at end of file + elif tcref.IsModule then + add m SemanticClassificationType.Module + elif tcref.IsNamespace then + add m SemanticClassificationType.Namespace + elif tcref.IsUnionTycon || tcref.IsRecordTycon then + if isStructTyconRef tcref then + add m SemanticClassificationType.ValueType + else + add m SemanticClassificationType.UnionCase + elif tcref.IsILTycon then + let (TILObjectReprData (_, _, tydef)) = tcref.ILTyconInfo + + if tydef.IsInterface then + add m SemanticClassificationType.Interface + elif tydef.IsDelegate then + add m SemanticClassificationType.Delegate + elif tydef.IsEnum then + add m SemanticClassificationType.Enumeration + elif tydef.IsStruct then + add m SemanticClassificationType.ValueType + else + add m SemanticClassificationType.ReferenceType + + | _, _, m -> add m SemanticClassificationType.Plaintext) + + let locs = + formatSpecifierLocations + |> Array.map (fun (m, _) -> SemanticClassificationItem((m, SemanticClassificationType.Printf))) + + results.AddRange(locs) + results.ToArray()) + (fun msg -> + Trace.TraceInformation(sprintf "FCS: recovering from error in GetSemanticClassification: '%s'" msg) + Array.empty) diff --git a/src/Compiler/Service/SemanticClassificationKey.fs b/src/Compiler/Service/SemanticClassificationKey.fs index 153c33a5e7a..c6b1279e762 100644 --- a/src/Compiler/Service/SemanticClassificationKey.fs +++ b/src/Compiler/Service/SemanticClassificationKey.fs @@ -22,9 +22,12 @@ type SemanticClassificationView(mmf: MemoryMappedFile, length) = member this.ForEach(f: SemanticClassificationItem -> unit) = use view = mmf.CreateViewAccessor(0L, length) - let mutable reader = BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) + + let mutable reader = + BlobReader(view.SafeMemoryMappedViewHandle.DangerousGetHandle() |> NativePtr.ofNativeInt, int length) reader.Offset <- 0 + while reader.Offset < reader.Length do let item = this.ReadItem(&reader) f item @@ -32,32 +35,34 @@ type SemanticClassificationView(mmf: MemoryMappedFile, length) = [] type SemanticClassificationKeyStore(mmf: MemoryMappedFile, length) = let mutable isDisposed = false - let checkDispose() = + + let checkDispose () = if isDisposed then raise (ObjectDisposedException("SemanticClassificationKeyStore")) member _.GetView() = - checkDispose() + checkDispose () SemanticClassificationView(mmf, length) interface IDisposable with - member _.Dispose() = - isDisposed <- true - mmf.Dispose() + member _.Dispose() = + isDisposed <- true + mmf.Dispose() [] type SemanticClassificationKeyStoreBuilder() = let b = BlobBuilder() - member _.WriteAll (semanticClassification: SemanticClassificationItem[]) = + member _.WriteAll(semanticClassification: SemanticClassificationItem[]) = use ptr = fixed semanticClassification b.WriteBytes(NativePtr.ofNativeInt (NativePtr.toNativeInt ptr), semanticClassification.Length * sizeof) member _.TryBuildAndReset() = if b.Count > 0 then let length = int64 b.Count + let mmf = let mmf = MemoryMappedFile.CreateNew( @@ -65,7 +70,9 @@ type SemanticClassificationKeyStoreBuilder() = length, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, - HandleInheritability.None) + HandleInheritability.None + ) + use stream = mmf.CreateViewStream(0L, length, MemoryMappedFileAccess.ReadWrite) b.WriteContentTo stream mmf diff --git a/src/Compiler/Service/ServiceAnalysis.fs b/src/Compiler/Service/ServiceAnalysis.fs index f1fe59aad2d..38af8f7156c 100644 --- a/src/Compiler/Service/ServiceAnalysis.fs +++ b/src/Compiler/Service/ServiceAnalysis.fs @@ -13,73 +13,84 @@ open FSharp.Compiler.Text.Range module UnusedOpens = - let symbolHash = HashIdentity.FromFunctions (fun (x: FSharpSymbol) -> x.GetEffectivelySameAsHash()) (fun x y -> x.IsEffectivelySameAs(y)) + let symbolHash = + HashIdentity.FromFunctions (fun (x: FSharpSymbol) -> x.GetEffectivelySameAsHash()) (fun x y -> x.IsEffectivelySameAs(y)) /// Represents one namespace or module opened by an 'open' statement - type OpenedModule(entity: FSharpEntity, isNestedAutoOpen: bool) = + type OpenedModule(entity: FSharpEntity, isNestedAutoOpen: bool) = /// Compute an indexed table of the set of symbols revealed by 'open', on-demand - let revealedSymbols : Lazy> = - lazy - let symbols = - [| for ent in entity.NestedEntities do - yield ent :> FSharpSymbol - - if ent.IsFSharpRecord then - for rf in ent.FSharpFields do - yield rf :> FSharpSymbol - - if ent.IsFSharpUnion && not (ent.HasAttribute()) then - for unionCase in ent.UnionCases do - yield unionCase :> FSharpSymbol - - if ent.HasAttribute() then - for fv in ent.MembersFunctionsAndValues do - // fv.IsExtensionMember is always false for C# extension methods returning by `MembersFunctionsAndValues`, - // so we have to check Extension attribute instead. - // (note: fv.IsExtensionMember has proper value for symbols returning by GetAllUsesOfAllSymbolsInFile though) - if fv.HasAttribute() then - yield fv :> FSharpSymbol - - for apCase in entity.ActivePatternCases do - yield apCase :> FSharpSymbol - - // The IsNamespace and IsFSharpModule cases are handled by looking at DeclaringEntity below - if not entity.IsNamespace && not entity.IsFSharpModule then - for fv in entity.MembersFunctionsAndValues do - yield fv :> FSharpSymbol |] - - HashSet<_>(symbols, symbolHash) + let revealedSymbols: Lazy> = + lazy + let symbols: FSharpSymbol[] = + [| + for ent in entity.NestedEntities do + ent + + if ent.IsFSharpRecord then + for rf in ent.FSharpFields do + rf + + if ent.IsFSharpUnion && not (ent.HasAttribute()) then + for unionCase in ent.UnionCases do + unionCase + + if ent.HasAttribute() then + for fv in ent.MembersFunctionsAndValues do + // fv.IsExtensionMember is always false for C# extension methods returning by `MembersFunctionsAndValues`, + // so we have to check Extension attribute instead. + // (note: fv.IsExtensionMember has proper value for symbols returning by GetAllUsesOfAllSymbolsInFile though) + if fv.HasAttribute() then + fv + + for apCase in entity.ActivePatternCases do + apCase + + // The IsNamespace and IsFSharpModule cases are handled by looking at DeclaringEntity below + if not entity.IsNamespace && not entity.IsFSharpModule then + for fv in entity.MembersFunctionsAndValues do + fv + |] + + HashSet<_>(symbols, symbolHash) member _.Entity = entity member _.IsNestedAutoOpen = isNestedAutoOpen member _.RevealedSymbolsContains(symbol) = revealedSymbols.Force().Contains symbol - type OpenedModuleGroup = - { OpenedModules: OpenedModule [] } - - static member Create (modul: FSharpEntity) = + type OpenedModuleGroup = + { + OpenedModules: OpenedModule[] + } + + static member Create(modul: FSharpEntity) = let rec getModuleAndItsAutoOpens (isNestedAutoOpen: bool) (modul: FSharpEntity) = [| - yield OpenedModule (modul, isNestedAutoOpen) + yield OpenedModule(modul, isNestedAutoOpen) for ent in modul.NestedEntities do if ent.IsFSharpModule && ent.HasAttribute() then - yield! getModuleAndItsAutoOpens true ent |] - { OpenedModules = getModuleAndItsAutoOpens false modul } + yield! getModuleAndItsAutoOpens true ent + |] + + { + OpenedModules = getModuleAndItsAutoOpens false modul + } /// Represents a single open statement type OpenStatement = - { /// All namespaces, modules and types which this open declaration effectively opens, including the AutoOpen ones - OpenedGroups: OpenedModuleGroup list + { + /// All namespaces, modules and types which this open declaration effectively opens, including the AutoOpen ones + OpenedGroups: OpenedModuleGroup list - /// The range of open statement itself - Range: range + /// The range of open statement itself + Range: range - /// The scope on which this open declaration is applied - AppliedScope: range } + /// The scope on which this open declaration is applied + AppliedScope: range + } /// Gets the open statements, their scopes and their resolutions - let getOpenStatements (openDeclarations: FSharpOpenDeclaration[]) : OpenStatement[] = + let getOpenStatements (openDeclarations: FSharpOpenDeclaration[]) : OpenStatement[] = openDeclarations |> Array.choose (fun openDecl -> if openDecl.IsOwnNamespace then @@ -87,59 +98,65 @@ module UnusedOpens = else match openDecl.LongId, openDecl.Range with | firstId :: _, Some range -> - if firstId.idText = MangledGlobalName then + if firstId.idText = MangledGlobalName then None else - let openedModulesAndTypes = List.concat [openDecl.Modules; openDecl.Types |> List.map(fun ty -> ty.TypeDefinition)] - Some { OpenedGroups = openedModulesAndTypes |> List.map OpenedModuleGroup.Create - Range = range - AppliedScope = openDecl.AppliedScope } + let openedModulesAndTypes = + List.concat [ openDecl.Modules; openDecl.Types |> List.map (fun ty -> ty.TypeDefinition) ] + + Some + { + OpenedGroups = openedModulesAndTypes |> List.map OpenedModuleGroup.Create + Range = range + AppliedScope = openDecl.AppliedScope + } | _ -> None) /// Only consider symbol uses which are the first part of a long ident, i.e. with no qualifying identifiers let filterSymbolUses (getSourceLineStr: int -> string) (symbolUses: seq) = symbolUses - |> Seq.filter(fun (su: FSharpSymbolUse) -> + |> Seq.filter (fun (su: FSharpSymbolUse) -> match su.Symbol with - | :? FSharpMemberOrFunctionOrValue as fv when fv.IsExtensionMember -> + | :? FSharpMemberOrFunctionOrValue as fv when fv.IsExtensionMember -> // Extension members should be taken into account even though they have a prefix (as they do most of the time) true - | :? FSharpMemberOrFunctionOrValue as fv when not fv.IsModuleValueOrMember -> + | :? FSharpMemberOrFunctionOrValue as fv when not fv.IsModuleValueOrMember -> // Local values can be ignored false - | :? FSharpMemberOrFunctionOrValue when su.IsFromDefinition -> + | :? FSharpMemberOrFunctionOrValue when su.IsFromDefinition -> // Value definitions should be ignored false - | :? FSharpGenericParameter -> + | :? FSharpGenericParameter -> // Generic parameters can be ignored, they never come into scope via 'open' false - | :? FSharpUnionCase when su.IsFromDefinition -> - false + | :? FSharpUnionCase when su.IsFromDefinition -> false - | :? FSharpField as field when - field.DeclaringEntity.IsSome && field.DeclaringEntity.Value.IsFSharpRecord -> + | :? FSharpField as field when field.DeclaringEntity.IsSome && field.DeclaringEntity.Value.IsFSharpRecord -> // Record fields are used in name resolution true - | :? FSharpField as field when field.IsUnionCaseField -> - false + | :? FSharpField as field when field.IsUnionCaseField -> false | _ -> // For the rest of symbols we pick only those which are the first part of a long ident, because it's they which are // contained in opened namespaces / modules. For example, we pick `IO` from long ident `IO.File.OpenWrite` because // it's `open System` which really brings it into scope. - let partialName = QuickParse.GetPartialLongNameEx (getSourceLineStr su.Range.StartLine, su.Range.EndColumn - 1) + let partialName = + QuickParse.GetPartialLongNameEx(getSourceLineStr su.Range.StartLine, su.Range.EndColumn - 1) + List.isEmpty partialName.QualifyingIdents) |> Array.ofSeq /// Split symbol uses into cases that are easy to handle (via DeclaringEntity) and those that don't have a good DeclaringEntity - let splitSymbolUses (symbolUses: FSharpSymbolUse[]) = - symbolUses |> Array.partition (fun symbolUse -> + let splitSymbolUses (symbolUses: FSharpSymbolUse[]) = + symbolUses + |> Array.partition (fun symbolUse -> let symbol = symbolUse.Symbol + match symbol with | :? FSharpMemberOrFunctionOrValue as f -> match f.DeclaringEntity with @@ -151,79 +168,126 @@ module UnusedOpens = /// in the scope of the 'open' is from that module. /// /// Performance will be roughly NumberOfOpenStatements x NumberOfSymbolUses - let isOpenStatementUsed (symbolUses2: FSharpSymbolUse[]) (symbolUsesRangesByDeclaringEntity: Dictionary) - (usedModules: Dictionary) (openStatement: OpenStatement) = + let isOpenStatementUsed + (symbolUses2: FSharpSymbolUse[]) + (symbolUsesRangesByDeclaringEntity: Dictionary) + (usedModules: Dictionary) + (openStatement: OpenStatement) + = // Don't re-check modules whose symbols are already known to have been used let openedGroupsToExamine = - openStatement.OpenedGroups |> List.choose (fun openedGroup -> + openStatement.OpenedGroups + |> List.choose (fun openedGroup -> let openedEntitiesToExamine = - openedGroup.OpenedModules + openedGroup.OpenedModules |> Array.filter (fun openedEntity -> - not (usedModules.BagExistsValueForKey(openedEntity.Entity, fun scope -> rangeContainsRange scope openStatement.AppliedScope))) - + not ( + usedModules.BagExistsValueForKey( + openedEntity.Entity, + fun scope -> rangeContainsRange scope openStatement.AppliedScope + ) + )) + match openedEntitiesToExamine with | [||] -> None - | _ when openedEntitiesToExamine |> Array.exists (fun x -> not x.IsNestedAutoOpen) -> Some { OpenedModules = openedEntitiesToExamine } + | _ when openedEntitiesToExamine |> Array.exists (fun x -> not x.IsNestedAutoOpen) -> + Some + { + OpenedModules = openedEntitiesToExamine + } | _ -> None) // Find the opened groups that are used by some symbol use - let newlyUsedOpenedGroups = - openedGroupsToExamine |> List.filter (fun openedGroup -> - openedGroup.OpenedModules |> Array.exists (fun openedEntity -> - symbolUsesRangesByDeclaringEntity.BagExistsValueForKey(openedEntity.Entity, fun symbolUseRange -> - rangeContainsRange openStatement.AppliedScope symbolUseRange && - Position.posGt symbolUseRange.Start openStatement.Range.End) || - - symbolUses2 |> Array.exists (fun symbolUse -> - rangeContainsRange openStatement.AppliedScope symbolUse.Range && - Position.posGt symbolUse.Range.Start openStatement.Range.End && - openedEntity.RevealedSymbolsContains symbolUse.Symbol))) + let newlyUsedOpenedGroups = + openedGroupsToExamine + |> List.filter (fun openedGroup -> + openedGroup.OpenedModules + |> Array.exists (fun openedEntity -> + symbolUsesRangesByDeclaringEntity.BagExistsValueForKey( + openedEntity.Entity, + fun symbolUseRange -> + rangeContainsRange openStatement.AppliedScope symbolUseRange + && Position.posGt symbolUseRange.Start openStatement.Range.End + ) + || + + symbolUses2 + |> Array.exists (fun symbolUse -> + rangeContainsRange openStatement.AppliedScope symbolUse.Range + && Position.posGt symbolUse.Range.Start openStatement.Range.End + && openedEntity.RevealedSymbolsContains symbolUse.Symbol))) // Return them as interim used entities - let newlyOpenedModules = newlyUsedOpenedGroups |> List.collect (fun openedGroup -> openedGroup.OpenedModules |> List.ofArray) + let newlyOpenedModules = + newlyUsedOpenedGroups + |> List.collect (fun openedGroup -> openedGroup.OpenedModules |> List.ofArray) + for openedModule in newlyOpenedModules do let scopes = match usedModules.TryGetValue openedModule.Entity with | true, scopes -> openStatement.AppliedScope :: scopes - | _ -> [openStatement.AppliedScope] + | _ -> [ openStatement.AppliedScope ] + usedModules[openedModule.Entity] <- scopes + not newlyOpenedModules.IsEmpty - + /// Incrementally filter out the open statements one by one. Filter those whose contents are referred to somewhere in the symbol uses. /// Async to allow cancellation. - let rec filterOpenStatementsIncremental symbolUses2 (symbolUsesRangesByDeclaringEntity: Dictionary) (openStatements: OpenStatement list) - (usedModules: Dictionary) acc = - async { + let rec filterOpenStatementsIncremental + symbolUses2 + (symbolUsesRangesByDeclaringEntity: Dictionary) + (openStatements: OpenStatement list) + (usedModules: Dictionary) + acc + = + async { match openStatements with | openStatement :: rest -> if isOpenStatementUsed symbolUses2 symbolUsesRangesByDeclaringEntity usedModules openStatement then return! filterOpenStatementsIncremental symbolUses2 symbolUsesRangesByDeclaringEntity rest usedModules acc else // The open statement has not been used, include it in the results - return! filterOpenStatementsIncremental symbolUses2 symbolUsesRangesByDeclaringEntity rest usedModules (openStatement :: acc) + return! + filterOpenStatementsIncremental + symbolUses2 + symbolUsesRangesByDeclaringEntity + rest + usedModules + (openStatement :: acc) | [] -> return List.rev acc } - let entityHash = HashIdentity.FromFunctions (fun (x: FSharpEntity) -> x.GetEffectivelySameAsHash()) (fun x y -> x.IsEffectivelySameAs(y)) + let entityHash = + HashIdentity.FromFunctions (fun (x: FSharpEntity) -> x.GetEffectivelySameAsHash()) (fun x y -> x.IsEffectivelySameAs(y)) /// Filter out the open statements whose contents are referred to somewhere in the symbol uses. /// Async to allow cancellation. let filterOpenStatements (symbolUses1: FSharpSymbolUse[], symbolUses2: FSharpSymbolUse[]) openStatements = async { - // the key is a namespace or module, the value is a list of FSharpSymbolUse range of symbols defined in the - // namespace or module. So, it's just symbol uses ranges grouped by namespace or module where they are _defined_. - let symbolUsesRangesByDeclaringEntity = Dictionary(entityHash) + // the key is a namespace or module, the value is a list of FSharpSymbolUse range of symbols defined in the + // namespace or module. So, it's just symbol uses ranges grouped by namespace or module where they are _defined_. + let symbolUsesRangesByDeclaringEntity = + Dictionary(entityHash) + for symbolUse in symbolUses1 do match symbolUse.Symbol with | :? FSharpMemberOrFunctionOrValue as f -> match f.DeclaringEntity with - | Some entity when entity.IsNamespace || entity.IsFSharpModule -> + | Some entity when entity.IsNamespace || entity.IsFSharpModule -> symbolUsesRangesByDeclaringEntity.BagAdd(entity, symbolUse.Range) | _ -> () | _ -> () - let! results = filterOpenStatementsIncremental symbolUses2 symbolUsesRangesByDeclaringEntity (List.ofArray openStatements) (Dictionary(entityHash)) [] + let! results = + filterOpenStatementsIncremental + symbolUses2 + symbolUsesRangesByDeclaringEntity + (List.ofArray openStatements) + (Dictionary(entityHash)) + [] + return results |> List.map (fun os -> os.Range) } @@ -238,20 +302,18 @@ module UnusedOpens = let openStatements = getOpenStatements checkFileResults.OpenDeclarations return! filterOpenStatements symbolUses openStatements } - -module SimplifyNames = - type SimplifiableRange = - { - Range: range - RelativeName: string - } - let getPlidLength (plid: string list) = (plid |> List.sumBy String.length) + plid.Length +module SimplifyNames = + type SimplifiableRange = { Range: range; RelativeName: string } + + let getPlidLength (plid: string list) = + (plid |> List.sumBy String.length) + plid.Length let getSimplifiableNames (checkFileResults: FSharpCheckFileResults, getSourceLineStr: int -> string) = async { let result = ResizeArray() let! ct = Async.CancellationToken + let symbolUses = checkFileResults.GetAllUsesOfAllSymbolsInFile(ct) |> Seq.choose (fun symbolUse -> @@ -260,63 +322,94 @@ module SimplifyNames = else let lineStr = getSourceLineStr symbolUse.Range.StartLine // for `System.DateTime.Now` it returns ([|"System"; "DateTime"|], "Now") - let partialName = QuickParse.GetPartialLongNameEx(lineStr, symbolUse.Range.EndColumn - 1) + let partialName = + QuickParse.GetPartialLongNameEx(lineStr, symbolUse.Range.EndColumn - 1) // `symbolUse.Range.Start` does not point to the start of plid, it points to start of `name`, // so we have to calculate plid's start ourselves. - let plidStartCol = symbolUse.Range.EndColumn - partialName.PartialIdent.Length - (getPlidLength partialName.QualifyingIdents) + let plidStartCol = + symbolUse.Range.EndColumn + - partialName.PartialIdent.Length + - (getPlidLength partialName.QualifyingIdents) + if partialName.PartialIdent = "" || List.isEmpty partialName.QualifyingIdents then None else - Some (symbolUse, partialName.QualifyingIdents, plidStartCol, partialName.PartialIdent)) + Some(symbolUse, partialName.QualifyingIdents, plidStartCol, partialName.PartialIdent)) |> Seq.groupBy (fun (symbolUse, _, plidStartCol, _) -> symbolUse.Range.StartLine, plidStartCol) |> Seq.map (fun (_, xs) -> xs |> Seq.maxBy (fun (symbolUse, _, _, _) -> symbolUse.Range.EndColumn)) for symbolUse, plid, plidStartCol, name in symbolUses do let posAtStartOfName = let r = symbolUse.Range - if r.StartLine = r.EndLine then Position.mkPos r.StartLine (r.EndColumn - name.Length) - else r.Start + + if r.StartLine = r.EndLine then + Position.mkPos r.StartLine (r.EndColumn - name.Length) + else + r.Start let getNecessaryPlid (plid: string list) : string list = let rec loop (rest: string list) (current: string list) = match rest with | [] -> current | headIdent :: restPlid -> - let res = checkFileResults.IsRelativeNameResolvableFromSymbol(posAtStartOfName, current, symbolUse.Symbol) - if res then current - else loop restPlid (headIdent :: current) + let res = + checkFileResults.IsRelativeNameResolvableFromSymbol(posAtStartOfName, current, symbolUse.Symbol) + + if res then + current + else + loop restPlid (headIdent :: current) + loop (List.rev plid) [] - - let necessaryPlid = getNecessaryPlid plid - + + let necessaryPlid = getNecessaryPlid plid + match necessaryPlid with | necessaryPlid when necessaryPlid = plid -> () | necessaryPlid -> let r = symbolUse.Range - let necessaryPlidStartCol = r.EndColumn - name.Length - (getPlidLength necessaryPlid) - - let unnecessaryRange = + + let necessaryPlidStartCol = + r.EndColumn - name.Length - (getPlidLength necessaryPlid) + + let unnecessaryRange = mkRange r.FileName (Position.mkPos r.StartLine plidStartCol) (Position.mkPos r.EndLine necessaryPlidStartCol) - + let relativeName = (String.concat "." plid) + "." + name - result.Add({Range = unnecessaryRange; RelativeName = relativeName}) + + result.Add( + { + Range = unnecessaryRange + RelativeName = relativeName + } + ) return (result :> seq<_>) } -module UnusedDeclarations = +module UnusedDeclarations = let isPotentiallyUnusedDeclaration (symbol: FSharpSymbol) : bool = match symbol with // Determining that a record, DU or module is used anywhere requires inspecting all their enclosed entities (fields, cases and func / vals) // for usages, which is too expensive to do. Hence we never gray them out. - | :? FSharpEntity as e when e.IsFSharpRecord || e.IsFSharpUnion || e.IsInterface || e.IsFSharpModule || e.IsClass || e.IsNamespace -> false + | :? FSharpEntity as e when + e.IsFSharpRecord + || e.IsFSharpUnion + || e.IsInterface + || e.IsFSharpModule + || e.IsClass + || e.IsNamespace + -> + false // FCS returns inconsistent results for override members; we're skipping these symbols. - | :? FSharpMemberOrFunctionOrValue as f when - f.IsOverrideOrExplicitInterfaceImplementation || - f.IsBaseValue || - f.IsConstructor -> false + | :? FSharpMemberOrFunctionOrValue as f when + f.IsOverrideOrExplicitInterfaceImplementation + || f.IsBaseValue + || f.IsConstructor + -> + false // Usage of DU case parameters does not give any meaningful feedback; we never gray them out. | :? FSharpParameter -> false @@ -324,31 +417,37 @@ module UnusedDeclarations = let getUnusedDeclarationRanges (symbolsUses: seq) (isScript: bool) = let usages = - let usages = + let usages = symbolsUses - |> Seq.choose (fun su -> if not su.IsFromDefinition then su.Symbol.DeclarationLocation else None) + |> Seq.choose (fun su -> + if not su.IsFromDefinition then + su.Symbol.DeclarationLocation + else + None) + HashSet(usages) symbolsUses |> Seq.distinctBy (fun su -> su.Range) // Account for "hidden" uses, like a val in a member val definition. These aren't relevant - |> Seq.choose(fun (su: FSharpSymbolUse) -> - if su.IsFromDefinition && - su.Symbol.DeclarationLocation.IsSome && - (isScript || su.IsPrivateToFile) && - not (su.Symbol.DisplayName.StartsWith "_") && - isPotentiallyUnusedDeclaration su.Symbol + |> Seq.choose (fun (su: FSharpSymbolUse) -> + if + su.IsFromDefinition + && su.Symbol.DeclarationLocation.IsSome + && (isScript || su.IsPrivateToFile) + && not (su.Symbol.DisplayName.StartsWith "_") + && isPotentiallyUnusedDeclaration su.Symbol then - Some (su, usages.Contains su.Symbol.DeclarationLocation.Value) + Some(su, usages.Contains su.Symbol.DeclarationLocation.Value) else None) |> Seq.groupBy (fun (defSu, _) -> defSu.Range) |> Seq.filter (fun (_, defSus) -> defSus |> Seq.forall (fun (_, isUsed) -> not isUsed)) |> Seq.map (fun (m, _) -> m) - - let getUnusedDeclarations(checkFileResults: FSharpCheckFileResults, isScriptFile: bool) = + + let getUnusedDeclarations (checkFileResults: FSharpCheckFileResults, isScriptFile: bool) = async { let! ct = Async.CancellationToken let allSymbolUsesInFile = checkFileResults.GetAllUsesOfAllSymbolsInFile(ct) let unusedRanges = getUnusedDeclarationRanges allSymbolUsesInFile isScriptFile return unusedRanges - } \ No newline at end of file + } diff --git a/src/Compiler/Service/ServiceCompilerDiagnostics.fs b/src/Compiler/Service/ServiceCompilerDiagnostics.fs index dcfed426252..bc54a3f5f75 100644 --- a/src/Compiler/Service/ServiceCompilerDiagnostics.fs +++ b/src/Compiler/Service/ServiceCompilerDiagnostics.fs @@ -7,20 +7,21 @@ open FSharp.Compiler.DiagnosticResolutionHints [] type FSharpDiagnosticKind = | AddIndexerDot - | ReplaceWithSuggestion of suggestion:string + | ReplaceWithSuggestion of suggestion: string [] module CompilerDiagnostics = let GetErrorMessage diagnosticKind = match diagnosticKind with - | FSharpDiagnosticKind.AddIndexerDot -> FSComp.SR.addIndexerDot() - | FSharpDiagnosticKind.ReplaceWithSuggestion s -> FSComp.SR.replaceWithSuggestion(s) + | FSharpDiagnosticKind.AddIndexerDot -> FSComp.SR.addIndexerDot () + | FSharpDiagnosticKind.ReplaceWithSuggestion s -> FSComp.SR.replaceWithSuggestion (s) let GetSuggestedNames (suggestionsF: FSharp.Compiler.DiagnosticsLogger.Suggestions) (unresolvedIdentifier: string) = let buffer = SuggestionBuffer(unresolvedIdentifier) + if buffer.Disabled then Seq.empty else suggestionsF buffer.Add - buffer :> seq \ No newline at end of file + buffer :> seq diff --git a/src/Compiler/Service/ServiceConstants.fs b/src/Compiler/Service/ServiceConstants.fs index 97b6a16d228..5a1e180d440 100644 --- a/src/Compiler/Service/ServiceConstants.fs +++ b/src/Compiler/Service/ServiceConstants.fs @@ -25,4 +25,4 @@ type FSharpGlyph = | Variable | ExtensionMethod | Error - | TypeParameter \ No newline at end of file + | TypeParameter diff --git a/src/Compiler/Service/ServiceDeclarationLists.fs b/src/Compiler/Service/ServiceDeclarationLists.fs index 82fc0afae36..30d024d646a 100644 --- a/src/Compiler/Service/ServiceDeclarationLists.fs +++ b/src/Compiler/Service/ServiceDeclarationLists.fs @@ -197,15 +197,15 @@ module DeclarationListHelpers = | Item.ActivePatternCase apref -> let v = apref.ActivePatternVal // Format the type parameters to get e.g. ('a -> 'a) rather than ('?1234 -> '?1234) - let tau = v.TauType + let vTauTy = v.TauType // REVIEW: use _cxs here - let (prettyTyparInst, ptau), _cxs = PrettyTypes.PrettifyInstAndType denv.g (item.TyparInstantiation, tau) + let (prettyTyparInst, prettyTy), _cxs = PrettyTypes.PrettifyInstAndType denv.g (item.TyparInstantiation, vTauTy) let remarks = OutputFullName displayFullName pubpathOfValRef fullDisplayTextOfValRefAsLayout v let layout = wordL (tagText (FSComp.SR.typeInfoActiveRecognizer())) ^^ wordL (tagActivePatternCase apref.Name |> mkNav v.DefinitionRange) ^^ RightL.colon ^^ - NicePrint.layoutType denv ptau + NicePrint.layoutType denv prettyTy let tpsL = FormatTyparMapping denv prettyTyparInst @@ -292,7 +292,7 @@ module DeclarationListHelpers = // .NET events | Item.Event einfo -> - let eventTy = PropTypOfEventInfo infoReader m AccessibleFromSomewhere einfo + let eventTy = PropTypeOfEventInfo infoReader m AccessibleFromSomewhere einfo let eventTy, _cxs = PrettyTypes.PrettifyType g eventTy let layout = wordL (tagText (FSComp.SR.typeInfoEvent())) ^^ @@ -353,11 +353,11 @@ module DeclarationListHelpers = ToolTipElement.Single(layout, xml) // The 'fake' representation of constructors of .NET delegate types - | Item.DelegateCtor delty -> - let delty, _cxs = PrettyTypes.PrettifyType g delty - let (SigOfFunctionForDelegate(_, _, _, delFuncTy)) = GetSigOfFunctionForDelegate infoReader delty m AccessibleFromSomewhere + | Item.DelegateCtor delTy -> + let delTy, _cxs = PrettyTypes.PrettifyType g delTy + let (SigOfFunctionForDelegate(_, _, _, delFuncTy)) = GetSigOfFunctionForDelegate infoReader delTy m AccessibleFromSomewhere let layout = - NicePrint.layoutTyconRef denv (tcrefOfAppTy g delty) ^^ + NicePrint.layoutTyconRef denv (tcrefOfAppTy g delTy) ^^ LeftL.leftParen ^^ NicePrint.layoutType denv delFuncTy ^^ RightL.rightParen @@ -484,16 +484,16 @@ type MethodGroupItemParameter(name: string, canonicalTypeTextForSorting: string, module internal DescriptionListsImpl = let isFunction g ty = - let _, tau = tryDestForallTy g ty - isFunTy g tau + let _, tauTy = tryDestForallTy g ty + isFunTy g tauTy - let printCanonicalizedTypeName g (denv:DisplayEnv) tau = + let printCanonicalizedTypeName g (denv:DisplayEnv) tauTy = // get rid of F# abbreviations and such - let strippedType = stripTyEqnsWrtErasure EraseAll g tau + let strippedTy = stripTyEqnsWrtErasure EraseAll g tauTy // pretend no namespaces are open let denv = denv.SetOpenPaths([]) // now printing will see a .NET-like canonical representation, that is good for sorting overloads into a reasonable order (see bug 94520) - NicePrint.stringOfTy denv strippedType + NicePrint.stringOfTy denv strippedTy let PrettyParamOfRecdField g denv (f: RecdField) = let display = NicePrint.prettyLayoutOfType denv f.FormalType @@ -566,12 +566,12 @@ module internal DescriptionListsImpl = // Remake the params using the prettified versions let prettyParams = - (paramInfo, prettyParamTys, prettyParamTysL) |||> List.map3 (fun (nm, isOptArg, paramPrefix) tau tyL -> + (paramInfo, prettyParamTys, prettyParamTysL) |||> List.map3 (fun (nm, isOptArg, paramPrefix) tauTy tyL -> let display = paramPrefix ^^ tyL let display = toArray display MethodGroupItemParameter( name = nm, - canonicalTypeTextForSorting = printCanonicalizedTypeName g denv tau, + canonicalTypeTextForSorting = printCanonicalizedTypeName g denv tauTy, display = display, isOptional=isOptArg )) @@ -587,11 +587,11 @@ module internal DescriptionListsImpl = // Remake the params using the prettified versions let parameters = (prettyParamTys, prettyParamTysL) - ||> List.map2 (fun tau tyL -> + ||> List.map2 (fun paramTy tyL -> let display = toArray tyL MethodGroupItemParameter( name = "", - canonicalTypeTextForSorting = printCanonicalizedTypeName g denv tau, + canonicalTypeTextForSorting = printCanonicalizedTypeName g denv paramTy, display = display, isOptional=false )) @@ -635,17 +635,18 @@ module internal DescriptionListsImpl = let denv = { SimplerDisplayEnv denv with useColonForReturnType=true} match item.Item with | Item.Value vref -> + let getPrettyParamsOfTypes() = - let tau = vref.TauType - match tryDestFunTy denv.g tau with - | ValueSome(arg, rtau) -> + let vTauTy = vref.TauType + match tryDestFunTy denv.g vTauTy with + | ValueSome(arg, retTy) -> let args = tryDestRefTupleTy denv.g arg - let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfTypes g denv item.TyparInstantiation args rtau + let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfTypes g denv item.TyparInstantiation args retTy // FUTURE: prettyTyparInst is the pretty version of the known instantiations of type parameters in the output. It could be returned // for display as part of the method group prettyParams, prettyRetTyL | _ -> - let _prettyTyparInst, prettyTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInstantiation [] tau + let _prettyTyparInst, prettyTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInstantiation [] vTauTy [], prettyTyL match vref.ValReprInfo with @@ -675,7 +676,7 @@ module internal DescriptionListsImpl = // Adjust the return type so it only strips the first argument let curriedRetTy = match tryDestFunTy denv.g vref.TauType with - | ValueSome(_, rtau) -> rtau + | ValueSome(_, retTy) -> retTy | _ -> lastRetTy let _prettyTyparInst, prettyFirstCurriedParams, prettyCurriedRetTyL, prettyConstraintsL = PrettyParamsOfParamDatas g denv item.TyparInstantiation firstCurriedParamDatas curriedRetTy @@ -695,8 +696,8 @@ module internal DescriptionListsImpl = | Item.ActivePatternCase(apref) -> let v = apref.ActivePatternVal - let tau = v.TauType - let args, resTy = stripFunTy denv.g tau + let vTauTy = v.TauType + let args, resTy = stripFunTy denv.g vTauTy let apinfo = Option.get (TryGetActivePatternInfo v) let aparity = apinfo.Names.Length @@ -726,7 +727,7 @@ module internal DescriptionListsImpl = [], prettyRetTyL | Item.Event einfo -> - let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInstantiation [] (PropTypOfEventInfo infoReader m AccessibleFromSomewhere einfo) + let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInstantiation [] (PropTypeOfEventInfo infoReader m AccessibleFromSomewhere einfo) [], prettyRetTyL | Item.Property(_, pinfo :: _) -> @@ -775,11 +776,11 @@ module internal DescriptionListsImpl = let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInstantiation [] ty [], prettyRetTyL - | Item.DelegateCtor delty -> - let (SigOfFunctionForDelegate(_, _, _, delFuncTy)) = GetSigOfFunctionForDelegate infoReader delty m AccessibleFromSomewhere + | Item.DelegateCtor delTy -> + let (SigOfFunctionForDelegate(_, _, _, delFuncTy)) = GetSigOfFunctionForDelegate infoReader delTy m AccessibleFromSomewhere // No need to pass more generic type information in here since the instanitations have already been applied - let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfParamDatas g denv item.TyparInstantiation [ParamData(false, false, false, NotOptional, NoCallerInfo, None, ReflectedArgInfo.None, delFuncTy)] delty + let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfParamDatas g denv item.TyparInstantiation [ParamData(false, false, false, NotOptional, NoCallerInfo, None, ReflectedArgInfo.None, delFuncTy)] delTy // FUTURE: prettyTyparInst is the pretty version of the known instantiations of type parameters in the output. It could be returned // for display as part of the method group diff --git a/src/Compiler/Service/ServiceInterfaceStubGenerator.fs b/src/Compiler/Service/ServiceInterfaceStubGenerator.fs index 5e0c8256018..410d02dc786 100644 --- a/src/Compiler/Service/ServiceInterfaceStubGenerator.fs +++ b/src/Compiler/Service/ServiceInterfaceStubGenerator.fs @@ -4,7 +4,7 @@ namespace FSharp.Compiler.EditorServices open System open System.Diagnostics -open Internal.Utilities.Library +open Internal.Utilities.Library open FSharp.Compiler.CodeAnalysis open FSharp.Compiler.Symbols open FSharp.Compiler.Syntax @@ -22,30 +22,25 @@ module internal CodeGenerationUtils = let stringWriter = new StringWriter() let indentWriter = new IndentedTextWriter(stringWriter, " ") - member _.Write(s: string) = - indentWriter.Write("{0}", s) + member _.Write(s: string) = indentWriter.Write("{0}", s) - member _.Write(s: string, [] objs: obj []) = - indentWriter.Write(s, objs) + member _.Write(s: string, [] objs: obj[]) = indentWriter.Write(s, objs) - member _.WriteLine(s: string) = - indentWriter.WriteLine("{0}", s) + member _.WriteLine(s: string) = indentWriter.WriteLine("{0}", s) - member _.WriteLine(s: string, [] objs: obj []) = - indentWriter.WriteLine(s, objs) + member _.WriteLine(s: string, [] objs: obj[]) = indentWriter.WriteLine(s, objs) member x.WriteBlankLines count = for _ in 0 .. count - 1 do x.WriteLine "" - member _.Indent i = + member _.Indent i = indentWriter.Indent <- indentWriter.Indent + i - member _.Unindent i = + 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() = @@ -53,11 +48,10 @@ module internal CodeGenerationUtils = indentWriter.Dispose() /// An recursive pattern that collect all sequential expressions to avoid StackOverflowException - let rec (|Sequentials|_|) = function - | SynExpr.Sequential (_, _, e, Sequentials es, _) -> - Some(e :: es) - | SynExpr.Sequential (_, _, e1, e2, _) -> - Some [e1; e2] + let rec (|Sequentials|_|) = + function + | SynExpr.Sequential (_, _, e, Sequentials es, _) -> Some(e :: es) + | SynExpr.Sequential (_, _, e1, e2, _) -> Some [ e1; e2 ] | _ -> None /// Represent environment where a captured identifier should be renamed @@ -72,25 +66,32 @@ module internal CodeGenerationUtils = | _ -> let nm = String.lowerCaseFirstChar nm let nm, index = String.extractTrailingIndex nm - + let index, namesWithIndices = match namesWithIndices |> Map.tryFind nm, index with | Some indexes, index -> let rec getAvailableIndex idx = - if indexes |> Set.contains idx then + if indexes |> Set.contains idx then getAvailableIndex (idx + 1) - else idx + else + idx + let index = index |> Option.defaultValue 1 |> getAvailableIndex Some index, namesWithIndices |> Map.add nm (indexes |> Set.add index) - | None, Some index -> Some index, namesWithIndices |> Map.add nm (Set.ofList [index]) + | None, Some index -> Some index, namesWithIndices |> Map.add nm (Set.ofList [ index ]) | None, None -> None, namesWithIndices |> Map.add nm Set.empty - let nm = + let nm = match index with | Some index -> sprintf "%s%d" nm index | None -> nm - - let nm = if Set.contains nm keywordSet then sprintf "``%s``" nm else nm + + let nm = + if Set.contains nm keywordSet then + sprintf "``%s``" nm + else + nm + nm, namesWithIndices /// Capture information about an interface in ASTs @@ -101,69 +102,56 @@ type InterfaceData = member x.Range = match x with - | InterfaceData.Interface(ty, _) -> - ty.Range - | InterfaceData.ObjExpr(ty, _) -> - ty.Range + | InterfaceData.Interface (ty, _) -> ty.Range + | InterfaceData.ObjExpr (ty, _) -> ty.Range - member x.TypeParameters = + member x.TypeParameters = match x with - | InterfaceData.Interface(StripParenTypes ty, _) - | InterfaceData.ObjExpr(StripParenTypes ty, _) -> - let rec (|RationalConst|) = function - | SynRationalConst.Integer i -> - string i - | SynRationalConst.Rational(numerator, denominator, _) -> - sprintf "(%i/%i)" numerator denominator - | SynRationalConst.Negate (RationalConst s) -> - sprintf "- %s" s - - let rec (|TypeIdent|_|) = function - | SynType.Var(SynTypar(s, req, _), _) -> + | InterfaceData.Interface (StripParenTypes ty, _) + | InterfaceData.ObjExpr (StripParenTypes ty, _) -> + let rec (|RationalConst|) = + function + | SynRationalConst.Integer i -> string i + | SynRationalConst.Rational (numerator, denominator, _) -> sprintf "(%i/%i)" numerator denominator + | SynRationalConst.Negate (RationalConst s) -> sprintf "- %s" s + + let rec (|TypeIdent|_|) = + function + | SynType.Var (SynTypar (s, req, _), _) -> match req with - | TyparStaticReq.None -> - Some ("'" + s.idText) - | TyparStaticReq.HeadType -> - Some ("^" + s.idText) - | SynType.LongIdent(SynLongIdent(xs, _, _)) -> - xs |> Seq.map (fun x -> x.idText) |> String.concat "." |> Some - | SynType.App(t, _, ts, _, _, isPostfix, _) -> + | TyparStaticReq.None -> Some("'" + s.idText) + | TyparStaticReq.HeadType -> Some("^" + s.idText) + | SynType.LongIdent (SynLongIdent (xs, _, _)) -> xs |> Seq.map (fun x -> x.idText) |> String.concat "." |> Some + | SynType.App (t, _, ts, _, _, isPostfix, _) -> match t, ts with | TypeIdent typeName, [] -> Some typeName - | TypeIdent typeName, [TypeIdent typeArg] -> - if isPostfix then - Some (sprintf "%s %s" typeArg typeName) + | TypeIdent typeName, [ TypeIdent typeArg ] -> + if isPostfix then + Some(sprintf "%s %s" typeArg typeName) else - Some (sprintf "%s<%s>" typeName typeArg) - | TypeIdent typeName, _ -> + Some(sprintf "%s<%s>" typeName typeArg) + | TypeIdent typeName, _ -> let typeArgs = ts |> Seq.choose (|TypeIdent|_|) |> String.concat ", " - if isPostfix then - Some (sprintf "(%s) %s" typeArgs typeName) + + if isPostfix then + Some(sprintf "(%s) %s" typeArgs typeName) else Some(sprintf "%s<%s>" typeName typeArgs) | _ -> //debug "Unsupported case with %A and %A" t ts None - | SynType.Anon _ -> - Some "_" - | SynType.AnonRecd (_, ts, _) -> - Some (ts |> Seq.choose (snd >> (|TypeIdent|_|)) |> String.concat "; ") - | SynType.Array(dimension, TypeIdent typeName, _) -> - Some (sprintf "%s [%s]" typeName (String(',', dimension-1))) - | SynType.MeasurePower(TypeIdent typeName, RationalConst power, _) -> - Some (sprintf "%s^%s" typeName power) - | SynType.MeasureDivide(TypeIdent numerator, TypeIdent denominator, _) -> - Some (sprintf "%s/%s" numerator denominator) - | SynType.Paren(TypeIdent typeName, _) -> - Some typeName - | _ -> - None + | SynType.Anon _ -> Some "_" + | SynType.AnonRecd (_, ts, _) -> Some(ts |> Seq.choose (snd >> (|TypeIdent|_|)) |> String.concat "; ") + | SynType.Array (dimension, TypeIdent typeName, _) -> Some(sprintf "%s [%s]" typeName (String(',', dimension - 1))) + | SynType.MeasurePower (TypeIdent typeName, RationalConst power, _) -> Some(sprintf "%s^%s" typeName power) + | SynType.MeasureDivide (TypeIdent numerator, TypeIdent denominator, _) -> Some(sprintf "%s/%s" numerator denominator) + | SynType.Paren (TypeIdent typeName, _) -> Some typeName + | _ -> None + match ty with - | SynType.App(_, _, ts, _, _, _, _) - | SynType.LongIdentApp(_, _, _, ts, _, _, _) -> - ts |> Seq.choose (|TypeIdent|_|) |> Seq.toArray - | _ -> - [||] + | SynType.App (_, _, ts, _, _, _, _) + | SynType.LongIdentApp (_, _, _, ts, _, _, _) -> ts |> Seq.choose (|TypeIdent|_|) |> Seq.toArray + | _ -> [||] module InterfaceStubGenerator = [] @@ -184,73 +172,88 @@ module InterfaceStubGenerator = ObjectIdent: string /// A list of lines represents skeleton of each member - MethodBody: string [] + MethodBody: string[] /// Context in order to display types in the short form DisplayContext: FSharpDisplayContext } - // Adapt from MetadataFormat module in FSharp.Formatting + // Adapt from MetadataFormat module in FSharp.Formatting - let internal (|AllAndLast|_|) (xs: 'T list) = + let internal (|AllAndLast|_|) (xs: 'T list) = match xs with - | [] -> - None - | _ -> + | [] -> None + | _ -> let revd = List.rev xs - Some (List.rev revd.Tail, revd.Head) + Some(List.rev revd.Tail, revd.Head) let internal getTypeParameterName (typar: FSharpGenericParameter) = (if typar.IsSolveAtCompileTime then "^" else "'") + typar.Name - let internal bracket (str: string) = + let internal bracket (str: string) = if str.Contains(" ") then "(" + str + ")" else str let internal formatType ctx (ty: FSharpType) = - let genericDefinition = ty.Instantiate(Seq.toList ctx.ArgInstantiations).Format(ctx.DisplayContext) + let genericDefinition = + ty.Instantiate(Seq.toList ctx.ArgInstantiations).Format(ctx.DisplayContext) + (genericDefinition, ctx.TypeInstantations) ||> Map.fold (fun s k v -> s.Replace(k, v)) - // Format each argument, including its name and type - let internal formatArgUsage ctx hasTypeAnnotation (namesWithIndices: Map>) (arg: FSharpParameter) = - let nm = - match arg.Name with + // Format each argument, including its name and type + let internal formatArgUsage ctx hasTypeAnnotation (namesWithIndices: Map>) (arg: FSharpParameter) = + let nm = + match arg.Name with | None -> - if arg.Type.HasTypeDefinition && arg.Type.TypeDefinition.CompiledName = "unit" && arg.Type.TypeDefinition.Namespace = Some "Microsoft.FSharp.Core" then "()" - else sprintf "arg%d" (namesWithIndices |> Map.toSeq |> Seq.map snd |> Seq.sumBy Set.count |> max 1) + if + arg.Type.HasTypeDefinition + && arg.Type.TypeDefinition.CompiledName = "unit" + && arg.Type.TypeDefinition.Namespace = Some "Microsoft.FSharp.Core" + then + "()" + else + sprintf "arg%d" (namesWithIndices |> Map.toSeq |> Seq.map snd |> Seq.sumBy Set.count |> max 1) | Some x -> x - + let nm, namesWithIndices = normalizeArgName namesWithIndices nm - + // Detect an optional argument let isOptionalArg = arg.HasAttribute() let argName = if isOptionalArg then "?" + nm else nm - (if hasTypeAnnotation && argName <> "()" then - argName + ": " + formatType ctx arg.Type - else argName), + + (if hasTypeAnnotation && argName <> "()" then + argName + ": " + formatType ctx arg.Type + else + argName), namesWithIndices let internal formatArgsUsage ctx hasTypeAnnotation (v: FSharpMemberOrFunctionOrValue) args = let isItemIndexer = (v.IsInstanceMember && v.DisplayName = "Item") let unit, argSep, tupSep = "()", " ", ", " + let args, namesWithIndices = args - |> List.fold (fun (argsSoFar: string list list, namesWithIndices) args -> - let argsSoFar', namesWithIndices = - args - |> List.fold (fun (acc: string list, allNames) arg -> - let name, allNames = formatArgUsage ctx hasTypeAnnotation allNames arg - name :: acc, allNames) ([], namesWithIndices) - List.rev argsSoFar' :: argsSoFar, namesWithIndices) + |> List.fold + (fun (argsSoFar: string list list, namesWithIndices) args -> + let argsSoFar', namesWithIndices = + args + |> List.fold + (fun (acc: string list, allNames) arg -> + let name, allNames = formatArgUsage ctx hasTypeAnnotation allNames arg + name :: acc, allNames) + ([], namesWithIndices) + + List.rev argsSoFar' :: argsSoFar, namesWithIndices) ([], Map.ofList [ ctx.ObjectIdent, Set.empty ]) + let argText = args |> List.rev - |> List.map (function - | [] -> unit - | [arg] when arg = unit -> unit - | [arg] when not v.IsMember || isItemIndexer -> arg + |> List.map (function + | [] -> unit + | [ arg ] when arg = unit -> unit + | [ arg ] when not v.IsMember || isItemIndexer -> arg | args when isItemIndexer -> String.concat tupSep args | args -> bracket (String.concat tupSep args)) |> String.concat argSep @@ -263,131 +266,176 @@ module InterfaceStubGenerator = | Member of FSharpMemberOrFunctionOrValue let internal getArgTypes (ctx: Context) (v: FSharpMemberOrFunctionOrValue) = - let argInfos = v.CurriedParameterGroups |> Seq.map Seq.toList |> Seq.toList - + let argInfos = v.CurriedParameterGroups |> Seq.map Seq.toList |> Seq.toList + let retType = v.ReturnParameter.Type - let argInfos, retType = + let argInfos, retType = match argInfos, v.IsPropertyGetterMethod, v.IsPropertySetterMethod with - | [ AllAndLast(args, last) ], _, true -> [ args ], Some last.Type - | [[]], true, _ -> [], Some retType + | [ AllAndLast (args, last) ], _, true -> [ args ], Some last.Type + | [ [] ], true, _ -> [], Some retType | _, _, _ -> argInfos, Some retType - let retType = + let retType = match retType with | Some ty -> let coreType = formatType ctx ty + if v.IsEvent then - let isEventHandler = - ty.BaseType - |> Option.bind (fun t -> + let isEventHandler = + ty.BaseType + |> Option.bind (fun t -> if t.HasTypeDefinition then t.TypeDefinition.TryGetFullName() - else None) + else + None) |> Option.exists ((=) "System.MulticastDelegate") - if isEventHandler then sprintf "IEvent<%s, _>" coreType else coreType - else coreType - | None -> - "unit" - + + if isEventHandler then + sprintf "IEvent<%s, _>" coreType + else + coreType + else + coreType + | None -> "unit" + argInfos, retType /// Convert a getter/setter to its canonical form let internal normalizePropertyName (v: FSharpMemberOrFunctionOrValue) = let displayName = v.DisplayName - if (v.IsPropertyGetterMethod && displayName.StartsWithOrdinal("get_")) || - (v.IsPropertySetterMethod && displayName.StartsWithOrdinal("set_")) then + + if + (v.IsPropertyGetterMethod && displayName.StartsWithOrdinal("get_")) + || (v.IsPropertySetterMethod && displayName.StartsWithOrdinal("set_")) + then displayName[4..] - else displayName + else + displayName let internal isEventMember (m: FSharpMemberOrFunctionOrValue) = m.IsEvent || m.HasAttribute() - - let internal formatMember (ctx: Context) m verboseMode = - let getParamArgs (argInfos: FSharpParameter list list) (ctx: Context) (v: FSharpMemberOrFunctionOrValue) = + + let internal formatMember (ctx: Context) m verboseMode = + let getParamArgs (argInfos: FSharpParameter list list) (ctx: Context) (v: FSharpMemberOrFunctionOrValue) = let args, namesWithIndices = match argInfos with - | [[x]] when v.IsPropertyGetterMethod && x.Name.IsNone - && x.Type.TypeDefinition.CompiledName = "unit" - && x.Type.TypeDefinition.Namespace = Some "Microsoft.FSharp.Core" -> - "", Map.ofList [ctx.ObjectIdent, Set.empty] - | _ -> formatArgsUsage ctx verboseMode v argInfos - - let argText = - if String.IsNullOrWhiteSpace(args) then "" - elif args.StartsWithOrdinal("(") then args - elif v.CurriedParameterGroups.Count > 1 && (not verboseMode) then " " + args - else sprintf "(%s)" args + | [ [ x ] ] when + v.IsPropertyGetterMethod + && x.Name.IsNone + && x.Type.TypeDefinition.CompiledName = "unit" + && x.Type.TypeDefinition.Namespace = Some "Microsoft.FSharp.Core" + -> + "", Map.ofList [ ctx.ObjectIdent, Set.empty ] + | _ -> formatArgsUsage ctx verboseMode v argInfos + + let argText = + if String.IsNullOrWhiteSpace(args) then + "" + elif args.StartsWithOrdinal("(") then + args + elif v.CurriedParameterGroups.Count > 1 && (not verboseMode) then + " " + args + else + sprintf "(%s)" args + argText, namesWithIndices - let preprocess (ctx: Context) (v: FSharpMemberOrFunctionOrValue) = - let buildUsage argInfos = + let preprocess (ctx: Context) (v: FSharpMemberOrFunctionOrValue) = + let buildUsage argInfos = let parArgs, _ = getParamArgs argInfos ctx v + match v.IsMember, v.IsInstanceMember, v.LogicalName, v.DisplayName with // Constructors | _, _, ".ctor", _ -> "new" + parArgs // Properties (skipping arguments) - | _, true, _, name when v.IsPropertyGetterMethod || v.IsPropertySetterMethod -> - if name.StartsWithOrdinal("get_") || name.StartsWithOrdinal("set_") then name[4..] else name + | _, true, _, name when v.IsPropertyGetterMethod || v.IsPropertySetterMethod -> + if name.StartsWithOrdinal("get_") || name.StartsWithOrdinal("set_") then + name[4..] + else + name // Ordinary instance members | _, true, _, name -> name + parArgs // Ordinary functions or values - | false, _, _, name when - not (v.ApparentEnclosingEntity.HasAttribute()) -> + | false, _, _, name when not (v.ApparentEnclosingEntity.HasAttribute()) -> name + " " + parArgs // Ordinary static members or things (?) that require fully qualified access | _, _, _, name -> name + parArgs let modifiers = - [ if v.InlineAnnotation = FSharpInlineAnnotation.AlwaysInline then yield "inline" - if v.Accessibility.IsInternal then yield "internal" ] + [ + if v.InlineAnnotation = FSharpInlineAnnotation.AlwaysInline then + yield "inline" + if v.Accessibility.IsInternal then + yield "internal" + ] let argInfos, retType = getArgTypes ctx v let usage = buildUsage argInfos usage, modifiers, argInfos, retType // A couple of helper methods for emitting close declarations of members and stub method bodies. - let closeDeclaration (returnType:string) (writer:ColumnIndentedTextWriter) = - if verboseMode then writer.Write(": {0}", returnType) + let closeDeclaration (returnType: string) (writer: ColumnIndentedTextWriter) = + if verboseMode then + writer.Write(": {0}", returnType) + writer.Write(" = ", returnType) - if verboseMode then writer.WriteLine("") - let writeImplementation (ctx:Context) (writer:ColumnIndentedTextWriter) = + + if verboseMode then + writer.WriteLine("") + + let writeImplementation (ctx: Context) (writer: ColumnIndentedTextWriter) = match verboseMode, ctx.MethodBody with | false, [| singleLine |] -> writer.WriteLine(singleLine) | _, lines -> writer.Indent ctx.Indentation + for line in lines do writer.WriteLine(line) + writer.Unindent ctx.Indentation match m with - | MemberInfo.PropertyGetSet(getter, setter) -> + | MemberInfo.PropertyGetSet (getter, setter) -> let usage, modifiers, getterArgInfos, retType = preprocess ctx getter let closeDeclaration = closeDeclaration retType let writeImplementation = writeImplementation ctx let _, _, setterArgInfos, _ = preprocess ctx setter let writer = ctx.Writer writer.Write("member ") + for modifier in modifiers do writer.Write("{0} ", modifier) + writer.Write("{0}.", ctx.ObjectIdent) // Try to print getters and setters on the same identifier writer.WriteLine(usage) writer.Indent ctx.Indentation + match getParamArgs getterArgInfos ctx getter with - | "", _ | "()", _ -> writer.Write("with get ()") + | "", _ + | "()", _ -> writer.Write("with get ()") | args, _ -> writer.Write("with get {0}", args) + writer |> closeDeclaration writer |> writeImplementation + match getParamArgs setterArgInfos ctx setter with - | "", _ | "()", _ -> - if verboseMode then writer.WriteLine("and set (v: {0}): unit = ", retType) - else writer.Write("and set v = ") + | "", _ + | "()", _ -> + if verboseMode then + writer.WriteLine("and set (v: {0}): unit = ", retType) + else + writer.Write("and set v = ") | args, namesWithIndices -> let valueArgName, _ = normalizeArgName namesWithIndices "v" - if verboseMode then writer.WriteLine("and set {0} ({1}: {2}): unit = ", args, valueArgName, retType) - else writer.Write("and set {0} {1} = ", args, valueArgName) + + if verboseMode then + writer.WriteLine("and set {0} ({1}: {2}): unit = ", args, valueArgName, retType) + else + writer.Write("and set {0} {1} = ", args, valueArgName) + writer |> writeImplementation writer.Unindent ctx.Indentation @@ -396,13 +444,17 @@ module InterfaceStubGenerator = let closeDeclaration = closeDeclaration retType let writeImplementation = writeImplementation ctx let writer = ctx.Writer + if isEventMember v then writer.WriteLine("[]") + writer.Write("member ") + for modifier in modifiers do writer.Write("{0} ", modifier) + writer.Write("{0}.", ctx.ObjectIdent) - + if v.IsEvent then writer.Write(usage) writer |> closeDeclaration @@ -410,23 +462,32 @@ module InterfaceStubGenerator = elif v.IsPropertySetterMethod then writer.WriteLine(usage) writer.Indent ctx.Indentation + match getParamArgs argInfos ctx v with - | "", _ | "()", _ -> - writer.WriteLine("with set (v: {0}): unit = ", retType) + | "", _ + | "()", _ -> writer.WriteLine("with set (v: {0}): unit = ", retType) | args, namesWithIndices -> let valueArgName, _ = normalizeArgName namesWithIndices "v" writer.Write("with set {0} ({1}", args, valueArgName) - if verboseMode then writer.Write(": {0}): unit", retType) - else writer.Write(")") + + if verboseMode then + writer.Write(": {0}): unit", retType) + else + writer.Write(")") + writer.Write(" = ") - if verboseMode then writer.WriteLine("") + + if verboseMode then + writer.WriteLine("") writer |> writeImplementation writer.Unindent ctx.Indentation elif v.IsPropertyGetterMethod then writer.Write(usage) + match getParamArgs argInfos ctx v with - | "", _ | "()", _ -> + | "", _ + | "()", _ -> // Use the short-hand notation for getters without arguments writer |> closeDeclaration writer |> writeImplementation @@ -445,19 +506,20 @@ module InterfaceStubGenerator = let rec internal getNonAbbreviatedType (ty: FSharpType) = if ty.HasTypeDefinition && ty.TypeDefinition.IsFSharpAbbreviation then getNonAbbreviatedType ty.AbbreviatedType - else ty + else + ty // Sometimes interface members are stored in the form of `IInterface<'T> -> ...`, // so we need to get the 2nd generic argument let internal (|MemberFunctionType|_|) (ty: FSharpType) = if ty.IsFunctionType && ty.GenericArguments.Count = 2 then Some ty.GenericArguments[1] - else None + else + None let internal (|TypeOfMember|_|) (m: FSharpMemberOrFunctionOrValue) = match m.FullTypeSafe with - | Some (MemberFunctionType ty) when m.IsProperty && m.DeclaringEntity.IsSome && m.DeclaringEntity.Value.IsFSharp -> - Some ty + | Some (MemberFunctionType ty) when m.IsProperty && m.DeclaringEntity.IsSome && m.DeclaringEntity.Value.IsFSharp -> Some ty | Some ty -> Some ty | None -> None @@ -467,19 +529,21 @@ module InterfaceStubGenerator = if ty.IsFunctionType && ty.GenericArguments.Count = 2 then let retType = ty.GenericArguments[0] let argType = ty.GenericArguments[1] + if argType.GenericArguments.Count = 2 then - Some (argType.GenericArguments[0], retType) - else None - else None - | _ -> - None + Some(argType.GenericArguments[0], retType) + else + None + else + None + | _ -> None - let internal removeWhitespace (str: string) = - str.Replace(" ", "") + let internal removeWhitespace (str: string) = str.Replace(" ", "") /// Filter out duplicated interfaces in inheritance chain - let rec internal getInterfaces (e: FSharpEntity) = - seq { for iface in e.AllInterfaces -> + let rec internal getInterfaces (e: FSharpEntity) = + seq { + for iface in e.AllInterfaces -> let ty = getNonAbbreviatedType iface // Argument should be kept lazy so that it is only evaluated when instantiating a new type ty.TypeDefinition, Seq.zip ty.TypeDefinition.GenericParameters ty.GenericArguments @@ -487,138 +551,180 @@ module InterfaceStubGenerator = |> Seq.distinct /// Get members in the decreasing order of inheritance chain - let GetInterfaceMembers (entity: FSharpEntity) = + let GetInterfaceMembers (entity: FSharpEntity) = seq { for iface, instantiations in getInterfaces entity do - yield! iface.TryGetMembersFunctionsAndValues() - |> Seq.choose (fun m -> - // Use this hack when FCS doesn't return enough information on .NET properties and events - if m.IsProperty || m.IsEventAddMethod || m.IsEventRemoveMethod then - None - else Some (m, instantiations)) - } + yield! + iface.TryGetMembersFunctionsAndValues() + |> Seq.choose (fun m -> + // Use this hack when FCS doesn't return enough information on .NET properties and events + if m.IsProperty || m.IsEventAddMethod || m.IsEventRemoveMethod then + None + else + Some(m, instantiations)) + } /// Check whether an interface is empty let HasNoInterfaceMember entity = GetInterfaceMembers entity |> Seq.isEmpty - let internal (|LongIdentPattern|_|) = function - | SynPat.LongIdent(longDotId=SynLongIdent(xs, _, _)) -> -// let (name, range) = xs |> List.map (fun x -> x.idText, x.idRange) |> List.last + let internal (|LongIdentPattern|_|) = + function + | SynPat.LongIdent(longDotId = SynLongIdent (xs, _, _)) -> + // let (name, range) = xs |> List.map (fun x -> x.idText, x.idRange) |> List.last let last = List.last xs Some(last.idText, last.idRange) - | _ -> - None + | _ -> None // Get name and associated range of a member // On merged properties (consisting both getters and setters), they have the same range values, // so we use 'get_' and 'set_' prefix to ensure corresponding symbols are retrieved correctly. - let internal (|MemberNameAndRange|_|) = function - | SynBinding(valData=SynValData(memberFlags=Some mf); headPat=LongIdentPattern(name, range)) when mf.MemberKind = SynMemberKind.PropertyGet -> - if name.StartsWithOrdinal("get_") then Some(name, range) else Some("get_" + name, range) - | SynBinding(valData=SynValData(memberFlags=Some mf); headPat=LongIdentPattern(name, range)) when mf.MemberKind = SynMemberKind.PropertySet -> - if name.StartsWithOrdinal("set_") then Some(name, range) else Some("set_" + name, range) - | SynBinding(headPat=LongIdentPattern(name, range)) -> - Some(name, range) - | _ -> - None + let internal (|MemberNameAndRange|_|) = + function + | SynBinding (valData = SynValData(memberFlags = Some mf); headPat = LongIdentPattern (name, range)) when + mf.MemberKind = SynMemberKind.PropertyGet + -> + if name.StartsWithOrdinal("get_") then + Some(name, range) + else + Some("get_" + name, range) + | SynBinding (valData = SynValData(memberFlags = Some mf); headPat = LongIdentPattern (name, range)) when + mf.MemberKind = SynMemberKind.PropertySet + -> + if name.StartsWithOrdinal("set_") then + Some(name, range) + else + Some("set_" + name, range) + | SynBinding(headPat = LongIdentPattern (name, range)) -> Some(name, range) + | _ -> None /// Get associated member names and ranges /// In case of properties, intrinsic ranges might not be correct for the purpose of getting /// positions of 'member', which indicate the indentation for generating new members - let GetMemberNameAndRanges interfaceData = + let GetMemberNameAndRanges interfaceData = match interfaceData with - | InterfaceData.Interface(_, None) -> - [] - | InterfaceData.Interface(_, Some memberDefns) -> + | InterfaceData.Interface (_, None) -> [] + | InterfaceData.Interface (_, Some memberDefns) -> memberDefns - |> Seq.choose (function SynMemberDefn.Member(binding, _) -> Some binding | _ -> None) + |> Seq.collect (function + | SynMemberDefn.Member (binding, _) -> [ binding ] + | SynMemberDefn.GetSetMember (Some getBinding, Some setBinding, _, _) -> [ getBinding; setBinding ] + | SynMemberDefn.GetSetMember (Some binding, None, _, _) + | SynMemberDefn.GetSetMember (None, Some binding, _, _) -> [ binding ] + | _ -> []) |> Seq.choose (|MemberNameAndRange|_|) |> Seq.toList - | InterfaceData.ObjExpr(_, bindings) -> - List.choose (|MemberNameAndRange|_|) bindings + | InterfaceData.ObjExpr (_, bindings) -> List.choose (|MemberNameAndRange|_|) bindings let internal normalizeEventName (m: FSharpMemberOrFunctionOrValue) = let name = m.DisplayName + if name.StartsWithOrdinal("add_") then name[4..] - elif name.StartsWithOrdinal("remove_") then name[7..] + elif name.StartsWithOrdinal("remove_") then name[7..] else name - /// Ideally this info should be returned in error symbols from FCS. + /// Ideally this info should be returned in error symbols from FCS. /// Because it isn't, we implement a crude way of getting member signatures: /// (1) Crack ASTs to get member names and their associated ranges /// (2) Check symbols of those members based on ranges - /// (3) If any symbol found, capture its member signature - let GetImplementedMemberSignatures (getMemberByLocation: string * range -> FSharpSymbolUse option) displayContext interfaceData = - let formatMemberSignature (symbolUse: FSharpSymbolUse) = + /// (3) If any symbol found, capture its member signature + let GetImplementedMemberSignatures (getMemberByLocation: string * range -> FSharpSymbolUse option) displayContext interfaceData = + let formatMemberSignature (symbolUse: FSharpSymbolUse) = match symbolUse.Symbol with | :? FSharpMemberOrFunctionOrValue as m -> match m.FullTypeSafe with | Some _ when isEventMember m -> // Events don't have overloads so we use only display names for comparison let signature = normalizeEventName m - Some [signature] + Some [ signature ] | Some ty -> - let signature = removeWhitespace (sprintf "%s:%s" m.DisplayName (ty.Format(displayContext))) - Some [signature] - | None -> - None + let signature = + removeWhitespace (sprintf "%s:%s" m.DisplayName (ty.Format(displayContext))) + + Some [ signature ] + | None -> None | _ -> //fail "Should only accept symbol uses of members." None + async { - let symbolUses = + let symbolUses = GetMemberNameAndRanges interfaceData |> List.toArray |> Array.map getMemberByLocation - return symbolUses |> Array.choose (Option.bind formatMemberSignature >> Option.map String.Concat) - |> Set.ofArray + + return + symbolUses + |> Array.choose (Option.bind formatMemberSignature >> Option.map String.Concat) + |> Set.ofArray } /// Check whether an entity is an interface or type abbreviation of an interface let rec IsInterface (entity: FSharpEntity) = - entity.IsInterface || (entity.IsFSharpAbbreviation && IsInterface entity.AbbreviatedType.TypeDefinition) + entity.IsInterface + || (entity.IsFSharpAbbreviation && IsInterface entity.AbbreviatedType.TypeDefinition) /// Generate stub implementation of an interface at a start column - let FormatInterface startColumn indentation (typeInstances: string []) objectIdent - (methodBody: string) (displayContext: FSharpDisplayContext) excludedMemberSignatures - (e: FSharpEntity) verboseMode = + let FormatInterface + startColumn + indentation + (typeInstances: string[]) + objectIdent + (methodBody: string) + (displayContext: FSharpDisplayContext) + excludedMemberSignatures + (e: FSharpEntity) + verboseMode + = Debug.Assert(IsInterface e, "The entity should be an interface.") let lines = String.getLines methodBody use writer = new ColumnIndentedTextWriter() let typeParams = Seq.map getTypeParameterName e.GenericParameters - let instantiations = + + let instantiations = let insts = Seq.zip typeParams typeInstances // Filter out useless instances (when it is replaced by the same name or by wildcard) - |> Seq.filter(fun (t1, t2) -> t1 <> t2 && t2 <> "_") + |> Seq.filter (fun (t1, t2) -> t1 <> t2 && t2 <> "_") |> Map.ofSeq - // A simple hack to handle instantiation of type alias + // A simple hack to handle instantiation of type alias if e.IsFSharpAbbreviation then let ty = getNonAbbreviatedType e.AbbreviatedType - (ty.TypeDefinition.GenericParameters |> Seq.map getTypeParameterName, - ty.GenericArguments |> Seq.map (fun ty -> ty.Format(displayContext))) + + (ty.TypeDefinition.GenericParameters |> Seq.map getTypeParameterName, + ty.GenericArguments |> Seq.map (fun ty -> ty.Format(displayContext))) ||> Seq.zip |> Seq.fold (fun acc (x, y) -> Map.add x y acc) insts - else insts - let ctx = { Writer = writer; TypeInstantations = instantiations; ArgInstantiations = Seq.empty; - Indentation = indentation; ObjectIdent = objectIdent; MethodBody = lines; DisplayContext = displayContext } + else + insts + + let ctx = + { + Writer = writer + TypeInstantations = instantiations + ArgInstantiations = Seq.empty + Indentation = indentation + ObjectIdent = objectIdent + MethodBody = lines + DisplayContext = displayContext + } + let missingMembers = GetInterfaceMembers e - |> Seq.groupBy (fun (m, insts) -> + |> Seq.groupBy (fun (m, insts) -> match m with - | _ when isEventMember m -> - Some (normalizeEventName m) + | _ when isEventMember m -> Some(normalizeEventName m) | TypeOfMember ty -> - let signature = removeWhitespace (sprintf "%s:%s" m.DisplayName (formatType { ctx with ArgInstantiations = insts } ty)) - Some signature - | _ -> + let signature = + removeWhitespace (sprintf "%s:%s" m.DisplayName (formatType { ctx with ArgInstantiations = insts } ty)) + + Some signature + | _ -> //debug "FullType throws exceptions due to bugs in FCS." None) - |> Seq.collect (fun (signature, members) -> + |> Seq.collect (fun (signature, members) -> match signature with - | None -> - members + | None -> members | Some signature when not (Set.contains signature excludedMemberSignatures) -> // Return the first member from a group of members for a particular signature Seq.truncate 1 members @@ -630,15 +736,17 @@ module InterfaceStubGenerator = else writer.Indent startColumn writer.WriteLine("") + let duplicatedMembers = missingMembers - |> Seq.countBy(fun (m, insts) -> m.DisplayName, insts |> Seq.length) + |> Seq.countBy (fun (m, insts) -> m.DisplayName, insts |> Seq.length) |> Seq.filter (snd >> (<) 1) |> Seq.map (fst >> fst) |> Set.ofSeq let getReturnType v = snd (getArgTypes ctx v) - let rec formatMembers (members : (FSharpMemberOrFunctionOrValue * _) list) = + + let rec formatMembers (members: (FSharpMemberOrFunctionOrValue * _) list) = match members with // Since there is no unified source of information for properties, // we try to merge getters and setters when they seem to match. @@ -646,9 +754,11 @@ module InterfaceStubGenerator = // They belong to the same property if names and return types are the same | (getter as first, insts) :: (setter, _) :: otherMembers | (setter as first, _) :: (getter, insts) :: otherMembers when - getter.IsPropertyGetterMethod && setter.IsPropertySetterMethod && - normalizePropertyName getter = normalizePropertyName setter && - getReturnType getter = getReturnType setter -> + getter.IsPropertyGetterMethod + && setter.IsPropertySetterMethod + && normalizePropertyName getter = normalizePropertyName setter + && getReturnType getter = getReturnType setter + -> let useVerboseMode = verboseMode || duplicatedMembers.Contains first.DisplayName formatMember { ctx with ArgInstantiations = insts } (MemberInfo.PropertyGetSet(getter, setter)) useVerboseMode formatMembers otherMembers @@ -659,65 +769,56 @@ module InterfaceStubGenerator = | [] -> () missingMembers - |> Seq.sortBy (fun (m, _) -> + |> Seq.sortBy (fun (m, _) -> // Sort by normalized name and return type so that getters and setters of the same properties // are guaranteed to be neighboring. normalizePropertyName m, getReturnType m) |> Seq.toList |> formatMembers + writer.Dump() /// Find corresponding interface declaration at a given position let TryFindInterfaceDeclaration (pos: pos) (parsedInput: ParsedInput) = - let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.tryPick walkSynModuleOrNamespace moduleOrNamespaceList - and walkSynModuleOrNamespace(SynModuleOrNamespace(decls = decls; range = range)) = + and walkSynModuleOrNamespace (SynModuleOrNamespace (decls = decls; range = range)) = if not <| rangeContainsPos range pos then None else List.tryPick walkSynModuleDecl decls - and walkSynModuleDecl(decl: SynModuleDecl) = + and walkSynModuleDecl (decl: SynModuleDecl) = if not <| rangeContainsPos decl.Range pos then None else match decl with - | SynModuleDecl.Exception(SynExceptionDefn(_, _, synMembers, _), _) -> - List.tryPick walkSynMemberDefn synMembers - | SynModuleDecl.Let(_isRecursive, bindings, _range) -> - List.tryPick walkBinding bindings - | SynModuleDecl.ModuleAbbrev(_lhs, _rhs, _range) -> - None - | SynModuleDecl.NamespaceFragment(fragment) -> - walkSynModuleOrNamespace fragment - | SynModuleDecl.NestedModule(decls = modules) -> - List.tryPick walkSynModuleDecl modules - | SynModuleDecl.Types(typeDefs, _range) -> - List.tryPick walkSynTypeDefn typeDefs - | SynModuleDecl.Expr (expr, _) -> - walkExpr expr + | SynModuleDecl.Exception (SynExceptionDefn (_, _, synMembers, _), _) -> List.tryPick walkSynMemberDefn synMembers + | SynModuleDecl.Let (_isRecursive, bindings, _range) -> List.tryPick walkBinding bindings + | SynModuleDecl.ModuleAbbrev (_lhs, _rhs, _range) -> None + | SynModuleDecl.NamespaceFragment (fragment) -> walkSynModuleOrNamespace fragment + | SynModuleDecl.NestedModule (decls = modules) -> List.tryPick walkSynModuleDecl modules + | SynModuleDecl.Types (typeDefs, _range) -> List.tryPick walkSynTypeDefn typeDefs + | SynModuleDecl.Expr (expr, _) -> walkExpr expr | SynModuleDecl.Attributes _ | SynModuleDecl.HashDirective _ - | SynModuleDecl.Open _ -> - None + | SynModuleDecl.Open _ -> None - and walkSynTypeDefn(SynTypeDefn(typeRepr=representation; members=members; range=range)) = + and walkSynTypeDefn (SynTypeDefn (typeRepr = representation; members = members; range = range)) = if not <| rangeContainsPos range pos then None else walkSynTypeDefnRepr representation - |> Option.orElse (List.tryPick walkSynMemberDefn members) + |> Option.orElse (List.tryPick walkSynMemberDefn members) - and walkSynTypeDefnRepr(typeDefnRepr: SynTypeDefnRepr) = + and walkSynTypeDefnRepr (typeDefnRepr: SynTypeDefnRepr) = if not <| rangeContainsPos typeDefnRepr.Range pos then None else match typeDefnRepr with - | SynTypeDefnRepr.ObjectModel(_kind, members, _range) -> - List.tryPick walkSynMemberDefn members - | SynTypeDefnRepr.Simple(_repr, _range) -> - None + | SynTypeDefnRepr.ObjectModel (_kind, members, _range) -> List.tryPick walkSynMemberDefn members + | SynTypeDefnRepr.Simple (_repr, _range) -> None | SynTypeDefnRepr.Exception _ -> None and walkSynMemberDefn (memberDefn: SynMemberDefn) = @@ -725,210 +826,175 @@ module InterfaceStubGenerator = None else match memberDefn with - | SynMemberDefn.AbstractSlot(_synValSig, _memberFlags, _range) -> - None - | SynMemberDefn.AutoProperty(synExpr=expr) -> - walkExpr expr - | SynMemberDefn.Interface(interfaceType=interfaceType; members=members) -> + | SynMemberDefn.AbstractSlot (_synValSig, _memberFlags, _range) -> None + | SynMemberDefn.AutoProperty (synExpr = expr) -> walkExpr expr + | SynMemberDefn.Interface (interfaceType = interfaceType; members = members) -> if rangeContainsPos interfaceType.Range pos then Some(InterfaceData.Interface(interfaceType, members)) else Option.bind (List.tryPick walkSynMemberDefn) members - | SynMemberDefn.Member(binding, _range) -> - walkBinding binding - | SynMemberDefn.NestedType(typeDef, _access, _range) -> - walkSynTypeDefn typeDef - | SynMemberDefn.ValField(_field, _range) -> - None - | SynMemberDefn.LetBindings(bindings, _isStatic, _isRec, _range) -> - List.tryPick walkBinding bindings + | SynMemberDefn.Member (binding, _range) -> walkBinding binding + | SynMemberDefn.GetSetMember (getBinding, setBinding, _, _) -> + match getBinding, setBinding with + | None, None -> None + | Some binding, None + | None, Some binding -> walkBinding binding + | Some getBinding, Some setBinding -> walkBinding getBinding |> Option.orElseWith (fun () -> walkBinding setBinding) + | SynMemberDefn.NestedType (typeDef, _access, _range) -> walkSynTypeDefn typeDef + | SynMemberDefn.ValField (_field, _range) -> None + | SynMemberDefn.LetBindings (bindings, _isStatic, _isRec, _range) -> List.tryPick walkBinding bindings | SynMemberDefn.Open _ | SynMemberDefn.ImplicitCtor _ | SynMemberDefn.Inherit _ -> None | SynMemberDefn.ImplicitInherit (_, expr, _, _) -> walkExpr expr - and walkBinding (SynBinding(expr=expr)) = - walkExpr expr + and walkBinding (SynBinding (expr = expr)) = walkExpr expr and walkExpr expr = - if not <| rangeContainsPos expr.Range pos then + if not <| rangeContainsPos expr.Range pos then None else match expr with - | SynExpr.Quote (synExpr1, _, synExpr2, _, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.Quote (synExpr1, _, synExpr2, _, _range) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.Const (_synConst, _range) -> - None + | SynExpr.Const (_synConst, _range) -> None - | SynExpr.Paren (synExpr, _, _, _parenRange) -> - walkExpr synExpr - | SynExpr.Typed (synExpr, _synType, _range) -> - walkExpr synExpr + | SynExpr.Paren (synExpr, _, _, _parenRange) -> walkExpr synExpr + | SynExpr.Typed (synExpr, _synType, _range) -> walkExpr synExpr | SynExpr.Tuple (_, synExprList, _, _range) - | SynExpr.ArrayOrList (_, synExprList, _range) -> - List.tryPick walkExpr synExprList + | SynExpr.ArrayOrList (_, synExprList, _range) -> List.tryPick walkExpr synExprList - | SynExpr.Record (_inheritOpt, _copyOpt, fields, _range) -> - List.tryPick (fun (SynExprRecordField(expr=e)) -> Option.bind walkExpr e) fields + | SynExpr.Record (_inheritOpt, _copyOpt, fields, _range) -> + List.tryPick (fun (SynExprRecordField (expr = e)) -> Option.bind walkExpr e) fields - | SynExpr.New (_, _synType, synExpr, _range) -> - walkExpr synExpr + | SynExpr.New (_, _synType, synExpr, _range) -> walkExpr synExpr - | SynExpr.ObjExpr (objType=ty; argOptions=baseCallOpt; bindings=binds; members=ms; extraImpls=ifaces) -> + | SynExpr.ObjExpr (objType = ty; argOptions = baseCallOpt; bindings = binds; members = ms; extraImpls = ifaces) -> let binds = unionBindingAndMembers binds ms + match baseCallOpt with - | None -> + | None -> if rangeContainsPos ty.Range pos then - Some (InterfaceData.ObjExpr(ty, binds)) + Some(InterfaceData.ObjExpr(ty, binds)) else - ifaces |> List.tryPick (fun (SynInterfaceImpl(interfaceTy=ty; bindings=binds; range=range)) -> - if rangeContainsPos range pos then - Some (InterfaceData.ObjExpr(ty, binds)) - else None) - | Some _ -> + ifaces + |> List.tryPick (fun (SynInterfaceImpl (interfaceTy = ty; bindings = binds; range = range)) -> + if rangeContainsPos range pos then + Some(InterfaceData.ObjExpr(ty, binds)) + else + None) + | Some _ -> // Ignore object expressions of normal objects None - | SynExpr.While (_spWhile, synExpr1, synExpr2, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.While (_spWhile, synExpr1, synExpr2, _range) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.ForEach (_spFor, _spIn, _seqExprOnly, _isFromSource, _synPat, synExpr1, synExpr2, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.ForEach (_spFor, _spIn, _seqExprOnly, _isFromSource, _synPat, synExpr1, synExpr2, _range) -> + List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.For (identBody=synExpr1; toBody=synExpr2; doBody=synExpr3) -> - List.tryPick walkExpr [synExpr1; synExpr2; synExpr3] + | SynExpr.For (identBody = synExpr1; toBody = synExpr2; doBody = synExpr3) -> + List.tryPick walkExpr [ synExpr1; synExpr2; synExpr3 ] - | SynExpr.ArrayOrListComputed (_, synExpr, _range) -> - walkExpr synExpr + | SynExpr.ArrayOrListComputed (_, synExpr, _range) -> walkExpr synExpr - | SynExpr.ComputationExpr (_, synExpr, _range) -> - walkExpr synExpr + | SynExpr.ComputationExpr (_, synExpr, _range) -> walkExpr synExpr - | SynExpr.Lambda (body=synExpr) -> - walkExpr synExpr + | SynExpr.Lambda (body = synExpr) -> walkExpr synExpr - | SynExpr.MatchLambda (_isExnMatch, _argm, synMatchClauseList, _spBind, _wholem) -> - synMatchClauseList |> List.tryPick (fun (SynMatchClause(resultExpr = e)) -> walkExpr e) + | SynExpr.MatchLambda (_isExnMatch, _argm, synMatchClauseList, _spBind, _wholem) -> + synMatchClauseList + |> List.tryPick (fun (SynMatchClause (resultExpr = e)) -> walkExpr e) - | SynExpr.Match (expr=synExpr; clauses=synMatchClauseList) -> + | SynExpr.Match (expr = synExpr; clauses = synMatchClauseList) -> walkExpr synExpr - |> Option.orElse (synMatchClauseList |> List.tryPick (fun (SynMatchClause(resultExpr = e)) -> walkExpr e)) + |> Option.orElse ( + synMatchClauseList + |> List.tryPick (fun (SynMatchClause (resultExpr = e)) -> walkExpr e) + ) - | SynExpr.Lazy (synExpr, _range) -> - walkExpr synExpr + | SynExpr.Lazy (synExpr, _range) -> walkExpr synExpr - | SynExpr.Do (synExpr, _range) -> - walkExpr synExpr + | SynExpr.Do (synExpr, _range) -> walkExpr synExpr - | SynExpr.Assert (synExpr, _range) -> - walkExpr synExpr + | SynExpr.Assert (synExpr, _range) -> walkExpr synExpr - | SynExpr.App (_exprAtomicFlag, _isInfix, synExpr1, synExpr2, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.App (_exprAtomicFlag, _isInfix, synExpr1, synExpr2, _range) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> - walkExpr synExpr + | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> walkExpr synExpr - | SynExpr.LetOrUse (bindings=synBindingList; body=synExpr) -> + | SynExpr.LetOrUse (bindings = synBindingList; body = synExpr) -> Option.orElse (List.tryPick walkBinding synBindingList) (walkExpr synExpr) - | SynExpr.TryWith (tryExpr=synExpr) -> - walkExpr synExpr + | SynExpr.TryWith (tryExpr = synExpr) -> walkExpr synExpr - | SynExpr.TryFinally (tryExpr=synExpr1; finallyExpr=synExpr2) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.TryFinally (tryExpr = synExpr1; finallyExpr = synExpr2) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | Sequentials exprs -> - List.tryPick walkExpr exprs + | Sequentials exprs -> List.tryPick walkExpr exprs - | SynExpr.IfThenElse (ifExpr=synExpr1; thenExpr=synExpr2; elseExpr=synExprOpt) -> + | SynExpr.IfThenElse (ifExpr = synExpr1; thenExpr = synExpr2; elseExpr = synExprOpt) -> match synExprOpt with - | Some synExpr3 -> - List.tryPick walkExpr [synExpr1; synExpr2; synExpr3] - | None -> - List.tryPick walkExpr [synExpr1; synExpr2] + | Some synExpr3 -> List.tryPick walkExpr [ synExpr1; synExpr2; synExpr3 ] + | None -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.Ident _ident -> - None + | SynExpr.Ident _ident -> None - | SynExpr.LongIdent (_, _longIdent, _altNameRefCell, _range) -> - None + | SynExpr.LongIdent (_, _longIdent, _altNameRefCell, _range) -> None - | SynExpr.LongIdentSet (_longIdent, synExpr, _range) -> - walkExpr synExpr + | SynExpr.LongIdentSet (_longIdent, synExpr, _range) -> walkExpr synExpr - | SynExpr.DotGet (synExpr, _dotm, _longIdent, _range) -> - walkExpr synExpr + | SynExpr.DotGet (synExpr, _dotm, _longIdent, _range) -> walkExpr synExpr - | SynExpr.DotSet (synExpr1, _longIdent, synExpr2, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.DotSet (synExpr1, _longIdent, synExpr2, _range) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.Set (synExpr1, synExpr2, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.Set (synExpr1, synExpr2, _range) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.DotIndexedGet (synExpr, indexArgs, _range, _range2) -> - Option.orElse (walkExpr synExpr) (walkExpr indexArgs) + | SynExpr.DotIndexedGet (synExpr, indexArgs, _range, _range2) -> Option.orElse (walkExpr synExpr) (walkExpr indexArgs) - | SynExpr.DotIndexedSet (synExpr1, indexArgs, synExpr2, _, _range, _range2) -> - [ synExpr1; indexArgs; synExpr2 ] - |> List.tryPick walkExpr + | SynExpr.DotIndexedSet (synExpr1, indexArgs, synExpr2, _, _range, _range2) -> + [ synExpr1; indexArgs; synExpr2 ] |> List.tryPick walkExpr - | SynExpr.JoinIn (synExpr1, _range, synExpr2, _range2) -> - List.tryPick walkExpr [synExpr1; synExpr2] - | SynExpr.NamedIndexedPropertySet (_longIdent, synExpr1, synExpr2, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2] + | SynExpr.JoinIn (synExpr1, _range, synExpr2, _range2) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] + | SynExpr.NamedIndexedPropertySet (_longIdent, synExpr1, synExpr2, _range) -> List.tryPick walkExpr [ synExpr1; synExpr2 ] - | SynExpr.DotNamedIndexedPropertySet (synExpr1, _longIdent, synExpr2, synExpr3, _range) -> - List.tryPick walkExpr [synExpr1; synExpr2; synExpr3] + | SynExpr.DotNamedIndexedPropertySet (synExpr1, _longIdent, synExpr2, synExpr3, _range) -> + List.tryPick walkExpr [ synExpr1; synExpr2; synExpr3 ] | SynExpr.TypeTest (synExpr, _synType, _range) | SynExpr.Upcast (synExpr, _synType, _range) - | SynExpr.Downcast (synExpr, _synType, _range) -> - walkExpr synExpr + | SynExpr.Downcast (synExpr, _synType, _range) -> walkExpr synExpr | SynExpr.InferredUpcast (synExpr, _range) - | SynExpr.InferredDowncast (synExpr, _range) -> - walkExpr synExpr - | SynExpr.AddressOf (_, synExpr, _range, _range2) -> - walkExpr synExpr - | SynExpr.TraitCall (_synTyparList, _synMemberSig, synExpr, _range) -> - walkExpr synExpr + | SynExpr.InferredDowncast (synExpr, _range) -> walkExpr synExpr + | SynExpr.AddressOf (_, synExpr, _range, _range2) -> walkExpr synExpr + | SynExpr.TraitCall (_synTyparList, _synMemberSig, synExpr, _range) -> walkExpr synExpr | SynExpr.Null _range - | SynExpr.ImplicitZero _range -> - None + | SynExpr.ImplicitZero _range -> None | SynExpr.YieldOrReturn (_, synExpr, _range) - | SynExpr.YieldOrReturnFrom (_, synExpr, _range) - | SynExpr.DoBang (synExpr, _range) -> - walkExpr synExpr + | SynExpr.YieldOrReturnFrom (_, synExpr, _range) + | SynExpr.DoBang (synExpr, _range) -> walkExpr synExpr - | SynExpr.LetOrUseBang (rhs=synExpr1; andBangs=synExprAndBangs; body=synExpr2) -> + | SynExpr.LetOrUseBang (rhs = synExpr1; andBangs = synExprAndBangs; body = synExpr2) -> [ yield synExpr1 - for SynExprAndBang(body=eAndBang) in synExprAndBangs do + for SynExprAndBang (body = eAndBang) in synExprAndBangs do yield eAndBang yield synExpr2 ] |> List.tryPick walkExpr | SynExpr.LibraryOnlyILAssembly _ - | SynExpr.LibraryOnlyStaticOptimization _ + | SynExpr.LibraryOnlyStaticOptimization _ | SynExpr.LibraryOnlyUnionCaseFieldGet _ - | SynExpr.LibraryOnlyUnionCaseFieldSet _ -> - None - | SynExpr.ArbitraryAfterError (_debugStr, _range) -> - None + | SynExpr.LibraryOnlyUnionCaseFieldSet _ -> None + | SynExpr.ArbitraryAfterError (_debugStr, _range) -> None | SynExpr.FromParseError (synExpr, _range) - | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _range) -> - walkExpr synExpr + | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _range) -> walkExpr synExpr | _ -> None match parsedInput with - | ParsedInput.SigFile _input -> - None - | ParsedInput.ImplFile input -> - walkImplFileInput input + | ParsedInput.SigFile _input -> None + | ParsedInput.ImplFile input -> walkImplFileInput input diff --git a/src/Compiler/Service/ServiceLexing.fs b/src/Compiler/Service/ServiceLexing.fs index e3e5aa58280..9f14d717af2 100644 --- a/src/Compiler/Service/ServiceLexing.fs +++ b/src/Compiler/Service/ServiceLexing.fs @@ -24,15 +24,20 @@ open FSharp.Compiler.Text.Range module FSharpTokenTag = let Identifier = tagOfToken (IDENT "a") - let String = tagOfToken (STRING ("a", SynStringKind.Regular, LexCont.Default)) + let String = tagOfToken (STRING("a", SynStringKind.Regular, LexCont.Default)) let IDENT = tagOfToken (IDENT "a") let HASH_IDENT = tagOfToken (HASH_IDENT "a") let STRING = String - let INTERP_STRING_BEGIN_END = tagOfToken (INTERP_STRING_BEGIN_END ("a", SynStringKind.Regular, LexCont.Default)) - let INTERP_STRING_BEGIN_PART = tagOfToken (INTERP_STRING_BEGIN_PART ("a", SynStringKind.Regular, LexCont.Default)) - let INTERP_STRING_PART = tagOfToken (INTERP_STRING_PART ("a", LexCont.Default)) - let INTERP_STRING_END = tagOfToken (INTERP_STRING_END ("a", LexCont.Default)) + + let INTERP_STRING_BEGIN_END = + tagOfToken (INTERP_STRING_BEGIN_END("a", SynStringKind.Regular, LexCont.Default)) + + let INTERP_STRING_BEGIN_PART = + tagOfToken (INTERP_STRING_BEGIN_PART("a", SynStringKind.Regular, LexCont.Default)) + + let INTERP_STRING_PART = tagOfToken (INTERP_STRING_PART("a", LexCont.Default)) + let INTERP_STRING_END = tagOfToken (INTERP_STRING_END("a", LexCont.Default)) let LPAREN = tagOfToken LPAREN let RPAREN = tagOfToken RPAREN let LBRACK = tagOfToken LBRACK @@ -90,7 +95,6 @@ module FSharpTokenTag = let WITH = tagOfToken WITH let OWITH = tagOfToken OWITH - /// This corresponds to a token categorization originally used in Visual Studio 2003. /// /// NOTE: This corresponds to a token categorization originally used in Visual Studio 2003 and the original Babel source code. @@ -116,15 +120,14 @@ type FSharpTokenColorKind = /// It is not clear it is a primary logical classification that should be being used in the /// more recent language service work. type FSharpTokenTriggerClass = - | None = 0x00000000 + | None = 0x00000000 | MemberSelect = 0x00000001 - | MatchBraces = 0x00000002 + | MatchBraces = 0x00000002 | ChoiceSelect = 0x00000004 - | MethodTip = 0x000000F0 - | ParamStart = 0x00000010 - | ParamNext = 0x00000020 - | ParamEnd = 0x00000040 - + | MethodTip = 0x000000F0 + | ParamStart = 0x00000010 + | ParamNext = 0x00000020 + | ParamEnd = 0x00000040 /// This corresponds to a token categorization originally used in Visual Studio 2003. /// @@ -132,29 +135,30 @@ type FSharpTokenTriggerClass = /// It is not clear it is a primary logical classification that should be being used in the /// more recent language service work. type FSharpTokenCharKind = - | Default = 0x00000000 - | Text = 0x00000000 - | Keyword = 0x00000001 - | Identifier = 0x00000002 - | String = 0x00000003 - | Literal = 0x00000004 - | Operator = 0x00000005 - | Delimiter = 0x00000006 - | WhiteSpace = 0x00000008 + | Default = 0x00000000 + | Text = 0x00000000 + | Keyword = 0x00000001 + | Identifier = 0x00000002 + | String = 0x00000003 + | Literal = 0x00000004 + | Operator = 0x00000005 + | Delimiter = 0x00000006 + | WhiteSpace = 0x00000008 | LineComment = 0x00000009 - | Comment = 0x0000000A - + | Comment = 0x0000000A /// Information about a particular token from the tokenizer -type FSharpTokenInfo = { - LeftColumn: int - RightColumn: int - ColorClass: FSharpTokenColorKind - CharClass: FSharpTokenCharKind - FSharpTokenTriggerClass: FSharpTokenTriggerClass - Tag: int - TokenName: string - FullMatchedLength: int } +type FSharpTokenInfo = + { + LeftColumn: int + RightColumn: int + ColorClass: FSharpTokenColorKind + CharClass: FSharpTokenCharKind + FSharpTokenTriggerClass: FSharpTokenTriggerClass + Tag: int + TokenName: string + FullMatchedLength: int + } //---------------------------------------------------------------------------- // Babel flags @@ -174,37 +178,61 @@ module internal TokenClassifications = System.Diagnostics.Debug.Assert(false, "BUG: Received zero length IDENT token.") // This is related to 4783. Recover by treating as lower case identifier. (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + else if Char.ToUpperInvariant s[0] = s[0] then + (FSharpTokenColorKind.UpperIdentifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) else - if Char.ToUpperInvariant s[0] = s[0] then - (FSharpTokenColorKind.UpperIdentifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) - else - (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) // 'in' when used in a 'join' in a query expression - | JOIN_IN -> - (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + | JOIN_IN -> (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) | DECIMAL _ - | BIGNUM _ | INT8 _ | UINT8 _ | INT16 _ | UINT16 _ | INT32 _ | UINT32 _ | INT64 _ | UINT64 _ - | UNATIVEINT _ | NATIVEINT _ | IEEE32 _ | IEEE64 _ -> - (FSharpTokenColorKind.Number, FSharpTokenCharKind.Literal, FSharpTokenTriggerClass.None) + | BIGNUM _ + | INT8 _ + | UINT8 _ + | INT16 _ + | UINT16 _ + | INT32 _ + | UINT32 _ + | INT64 _ + | UINT64 _ + | UNATIVEINT _ + | NATIVEINT _ + | IEEE32 _ + | IEEE64 _ -> (FSharpTokenColorKind.Number, FSharpTokenCharKind.Literal, FSharpTokenTriggerClass.None) | INT32_DOT_DOT _ -> - // This will color the whole "1.." expression in a 'number' color - // (this isn't entirely correct, but it'll work for now - see bug 3727) + // This will color the whole "1.." expression in a 'number' color + // (this isn't entirely correct, but it'll work for now - see bug 3727) (FSharpTokenColorKind.Number, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) - | INFIX_STAR_DIV_MOD_OP ("mod" | "land" | "lor" | "lxor") - | INFIX_STAR_STAR_OP ("lsl" | "lsr" | "asr") -> - (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | INFIX_STAR_DIV_MOD_OP ("mod" + | "land" + | "lor" + | "lxor") + | INFIX_STAR_STAR_OP ("lsl" + | "lsr" + | "asr") -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | LPAREN_STAR_RPAREN - | DOLLAR | COLON_GREATER | COLON_COLON - | PERCENT_OP _ | PLUS_MINUS_OP _ | PREFIX_OP _ | COLON_QMARK_GREATER - | AMP | AMP_AMP | BAR_BAR | QMARK | QMARK_QMARK | COLON_QMARK + | DOLLAR + | COLON_GREATER + | COLON_COLON + | PERCENT_OP _ + | PLUS_MINUS_OP _ + | PREFIX_OP _ + | COLON_QMARK_GREATER + | AMP + | AMP_AMP + | BAR_BAR + | QMARK + | QMARK_QMARK + | COLON_QMARK | HIGH_PRECEDENCE_TYAPP - | COLON_EQUALS | EQUALS | RQUOTE_DOT _ - | MINUS | ADJACENT_PREFIX_OP _ -> - (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) + | COLON_EQUALS + | EQUALS + | RQUOTE_DOT _ + | MINUS + | ADJACENT_PREFIX_OP _ -> (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) | INFIX_COMPARE_OP _ // This is a whole family: .< .> .= .!= .$ | FUNKY_OPERATOR_NAME _ // This is another whole family, including: .[] and .() @@ -213,115 +241,204 @@ module internal TokenClassifications = | INFIX_AMP_OP _ | INFIX_BAR_OP _ | INFIX_STAR_DIV_MOD_OP _ - | INFIX_AMP_OP _ -> - (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) + | INFIX_AMP_OP _ -> (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) - | DOT_DOT | DOT_DOT_HAT -> - (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.MemberSelect) + | DOT_DOT + | DOT_DOT_HAT -> (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.MemberSelect) - | COMMA -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamNext) + | COMMA -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamNext) - | DOT -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MemberSelect) + | DOT -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MemberSelect) | BAR -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None (* FSharpTokenTriggerClass.ChoiceSelect *)) + (FSharpTokenColorKind.Punctuation, + FSharpTokenCharKind.Delimiter, + FSharpTokenTriggerClass.None (* FSharpTokenTriggerClass.ChoiceSelect *) ) - | HASH | STAR | SEMICOLON | SEMICOLON_SEMICOLON | COLON -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None) + | HASH + | STAR + | SEMICOLON + | SEMICOLON_SEMICOLON + | COLON -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None) - | QUOTE | UNDERSCORE - | INFIX_AT_HAT_OP _ -> - (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) + | QUOTE + | UNDERSCORE + | INFIX_AT_HAT_OP _ -> (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) - | LESS _ -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamStart) // for type provider static arguments + | LESS _ -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamStart) // for type provider static arguments - | GREATER _ -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamEnd) // for type provider static arguments + | GREATER _ -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamEnd) // for type provider static arguments | LPAREN -> // We need 'ParamStart' to trigger the 'GetDeclarations' method to show param info automatically // this is needed even if we don't use MPF for determining information about params - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamStart ||| FSharpTokenTriggerClass.MatchBraces) - - | RPAREN | RPAREN_COMING_SOON | RPAREN_IS_HERE -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamEnd ||| FSharpTokenTriggerClass.MatchBraces) - - | LBRACK_LESS -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) - - | LQUOTE _ | LBRACK | LBRACE _ | LBRACK_BAR | LBRACE_BAR -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) - - | GREATER_RBRACK | GREATER_BAR_RBRACK -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) - - | RQUOTE _ | RBRACK | RBRACE _ | RBRACE_COMING_SOON | RBRACE_IS_HERE | BAR_RBRACK | BAR_RBRACE -> - (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) - - | PUBLIC | PRIVATE | INTERNAL | BASE | GLOBAL - | CONSTRAINT | INSTANCE | DELEGATE | INHERIT|CONSTRUCTOR|DEFAULT|OVERRIDE|ABSTRACT|CLASS - | MEMBER | STATIC | NAMESPACE - | OASSERT | OLAZY | ODECLEND | OBLOCKSEP | OEND | OBLOCKBEGIN | ORIGHT_BLOCK_END - | OBLOCKEND | OBLOCKEND_COMING_SOON | OBLOCKEND_IS_HERE | OTHEN | OELSE | OLET _ - | OBINDER _ | OAND_BANG _ | BINDER _ | ODO | OWITH | OFUNCTION | OFUN | ORESET | ODUMMY _ | DO_BANG - | ODO_BANG | YIELD _ | YIELD_BANG _ | OINTERFACE_MEMBER - | ELIF | RARROW | LARROW | SIG | STRUCT - | UPCAST | DOWNCAST | NULL | RESERVED | MODULE | AND | AS | ASSERT | ASR - | DOWNTO | EXCEPTION | FALSE | FOR | FUN | FUNCTION - | FINALLY | LAZY | MATCH | MATCH_BANG | MUTABLE | NEW | OF | OPEN | OR | VOID | EXTERN - | INTERFACE | REC | TO | TRUE | TRY | TYPE | VAL | INLINE | WHEN | WHILE | WITH - | IF | THEN | ELSE | DO | DONE | LET _ | AND_BANG _ | IN | CONST - | HIGH_PRECEDENCE_PAREN_APP | FIXED + (FSharpTokenColorKind.Punctuation, + FSharpTokenCharKind.Delimiter, + FSharpTokenTriggerClass.ParamStart ||| FSharpTokenTriggerClass.MatchBraces) + + | RPAREN + | RPAREN_COMING_SOON + | RPAREN_IS_HERE -> + (FSharpTokenColorKind.Punctuation, + FSharpTokenCharKind.Delimiter, + FSharpTokenTriggerClass.ParamEnd ||| FSharpTokenTriggerClass.MatchBraces) + + | LBRACK_LESS -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None) + + | LQUOTE _ + | LBRACK + | LBRACE _ + | LBRACK_BAR + | LBRACE_BAR -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces) + + | GREATER_RBRACK + | GREATER_BAR_RBRACK -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None) + + | RQUOTE _ + | RBRACK + | RBRACE _ + | RBRACE_COMING_SOON + | RBRACE_IS_HERE + | BAR_RBRACK + | BAR_RBRACE -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces) + + | PUBLIC + | PRIVATE + | INTERNAL + | BASE + | GLOBAL + | CONSTRAINT + | INSTANCE + | DELEGATE + | INHERIT + | CONSTRUCTOR + | DEFAULT + | OVERRIDE + | ABSTRACT + | CLASS + | MEMBER + | STATIC + | NAMESPACE + | OASSERT + | OLAZY + | ODECLEND + | OBLOCKSEP + | OEND + | OBLOCKBEGIN + | ORIGHT_BLOCK_END + | OBLOCKEND + | OBLOCKEND_COMING_SOON + | OBLOCKEND_IS_HERE + | OTHEN + | OELSE + | OLET _ + | OBINDER _ + | OAND_BANG _ + | BINDER _ + | ODO + | OWITH + | OFUNCTION + | OFUN + | ORESET + | ODUMMY _ + | DO_BANG + | ODO_BANG + | YIELD _ + | YIELD_BANG _ + | OINTERFACE_MEMBER + | ELIF + | RARROW + | LARROW + | SIG + | STRUCT + | UPCAST + | DOWNCAST + | NULL + | RESERVED + | MODULE + | AND + | AS + | ASSERT + | ASR + | DOWNTO + | EXCEPTION + | FALSE + | FOR + | FUN + | FUNCTION + | FINALLY + | LAZY + | MATCH + | MATCH_BANG + | MUTABLE + | NEW + | OF + | OPEN + | OR + | VOID + | EXTERN + | INTERFACE + | REC + | TO + | TRUE + | TRY + | TYPE + | VAL + | INLINE + | WHEN + | WHILE + | WITH + | IF + | THEN + | ELSE + | DO + | DONE + | LET _ + | AND_BANG _ + | IN + | CONST + | HIGH_PRECEDENCE_PAREN_APP + | FIXED | HIGH_PRECEDENCE_BRACK_APP - | TYPE_COMING_SOON | TYPE_IS_HERE | MODULE_COMING_SOON | MODULE_IS_HERE -> - (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | TYPE_COMING_SOON + | TYPE_IS_HERE + | MODULE_COMING_SOON + | MODULE_IS_HERE -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) - | BEGIN -> - (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | BEGIN -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) - | END -> - (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | END -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | HASH_LIGHT _ | HASH_LINE _ | HASH_IF _ | HASH_ELSE _ - | HASH_ENDIF _ -> - (FSharpTokenColorKind.PreprocessorKeyword, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) - - | INACTIVECODE _ -> - (FSharpTokenColorKind.InactiveCode, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) + | HASH_ENDIF _ -> (FSharpTokenColorKind.PreprocessorKeyword, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) + | INACTIVECODE _ -> (FSharpTokenColorKind.InactiveCode, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) | LEX_FAILURE _ - | WHITESPACE _ -> - (FSharpTokenColorKind.Default, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) + | WHITESPACE _ -> (FSharpTokenColorKind.Default, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) - | COMMENT _ -> - (FSharpTokenColorKind.Comment, FSharpTokenCharKind.Comment, FSharpTokenTriggerClass.None) + | COMMENT _ -> (FSharpTokenColorKind.Comment, FSharpTokenCharKind.Comment, FSharpTokenTriggerClass.None) - | LINE_COMMENT _ -> - (FSharpTokenColorKind.Comment, FSharpTokenCharKind.LineComment, FSharpTokenTriggerClass.None) + | LINE_COMMENT _ -> (FSharpTokenColorKind.Comment, FSharpTokenCharKind.LineComment, FSharpTokenTriggerClass.None) - | KEYWORD_STRING _ -> - (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) + | KEYWORD_STRING _ -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | STRING_TEXT _ | INTERP_STRING_BEGIN_END _ | INTERP_STRING_BEGIN_PART _ | INTERP_STRING_PART _ | INTERP_STRING_END _ - | BYTEARRAY _ | STRING _ - | CHAR _ -> - (FSharpTokenColorKind.String, FSharpTokenCharKind.String, FSharpTokenTriggerClass.None) + | BYTEARRAY _ + | STRING _ + | CHAR _ -> (FSharpTokenColorKind.String, FSharpTokenCharKind.String, FSharpTokenTriggerClass.None) | EOF _ -> failwith "tokenInfo" module internal TestExpose = - let TokenInfo tok = TokenClassifications.tokenInfo tok + let TokenInfo tok = TokenClassifications.tokenInfo tok /// Lexer states are encoded to/from integers. Typically one lexer state is /// keep at the end of each line in an IDE service. IDE services are sometimes highly limited in the @@ -332,22 +449,22 @@ module internal TestExpose = /// or accurate error messages from lexing for mismtached #if are not supported. [] type FSharpTokenizerLexState = - { PosBits: int64 - OtherBits: int64 } + { + PosBits: int64 + OtherBits: int64 + } static member Initial = { PosBits = 0L; OtherBits = 0L } - member this.Equals (other: FSharpTokenizerLexState) = - (this.PosBits = other.PosBits) && - (this.OtherBits = other.OtherBits) + member this.Equals(other: FSharpTokenizerLexState) = + (this.PosBits = other.PosBits) && (this.OtherBits = other.OtherBits) - override this.Equals (obj: obj) = + override this.Equals(obj: obj) = match obj with | :? FSharpTokenizerLexState as other -> this.Equals other | _ -> false - override this.GetHashCode () = - hash this.PosBits + hash this.OtherBits + override this.GetHashCode() = hash this.PosBits + hash this.OtherBits type FSharpTokenizerColorState = | Token = 1 @@ -365,31 +482,30 @@ type FSharpTokenizerColorState = | TripleQuoteStringInComment = 14 | InitialState = 0 - module internal LexerStateEncoding = let computeNextLexState token (prevLexcont: LexerContinuation) = - match token with - | HASH_LINE cont - | HASH_LIGHT cont - | HASH_IF(_, _, cont) - | HASH_ELSE(_, _, cont) - | HASH_ENDIF(_, _, cont) - | INACTIVECODE cont - | WHITESPACE cont - | COMMENT cont - | LINE_COMMENT cont - | STRING_TEXT cont - | EOF cont - | INTERP_STRING_BEGIN_PART (_, _, cont) - | INTERP_STRING_PART (_, cont) - | INTERP_STRING_BEGIN_END (_, _, cont) - | INTERP_STRING_END (_, cont) - | LBRACE cont - | RBRACE cont - | BYTEARRAY (_, _, cont) - | STRING (_, _, cont) -> cont - | _ -> prevLexcont + match token with + | HASH_LINE cont + | HASH_LIGHT cont + | HASH_IF (_, _, cont) + | HASH_ELSE (_, _, cont) + | HASH_ENDIF (_, _, cont) + | INACTIVECODE cont + | WHITESPACE cont + | COMMENT cont + | LINE_COMMENT cont + | STRING_TEXT cont + | EOF cont + | INTERP_STRING_BEGIN_PART (_, _, cont) + | INTERP_STRING_PART (_, cont) + | INTERP_STRING_BEGIN_END (_, _, cont) + | INTERP_STRING_END (_, cont) + | LBRACE cont + | RBRACE cont + | BYTEARRAY (_, _, cont) + | STRING (_, _, cont) -> cont + | _ -> prevLexcont // Note that this will discard all lexcont state, including the ifdefStack. let revertToDefaultLexCont = LexCont.Default @@ -398,32 +514,51 @@ module internal LexerStateEncoding = let ncommentsNumBits = 4 let hardwhiteNumBits = 1 let ifdefstackCountNumBits = 8 - let ifdefstackNumBits = 24 // 0 means if, 1 means else + let ifdefstackNumBits = 24 // 0 means if, 1 means else let stringKindBits = 3 let nestingBits = 12 - let _ = assert (lexstateNumBits - + ncommentsNumBits - + hardwhiteNumBits - + ifdefstackCountNumBits - + ifdefstackNumBits - + stringKindBits - + nestingBits <= 64) - - let lexstateStart = 0 - let ncommentsStart = lexstateNumBits - let hardwhitePosStart = lexstateNumBits+ncommentsNumBits - let ifdefstackCountStart = lexstateNumBits+ncommentsNumBits+hardwhiteNumBits - let ifdefstackStart = lexstateNumBits+ncommentsNumBits+hardwhiteNumBits+ifdefstackCountNumBits - let stringKindStart = lexstateNumBits+ncommentsNumBits+hardwhiteNumBits+ifdefstackCountNumBits+ifdefstackNumBits - let nestingStart = lexstateNumBits+ncommentsNumBits+hardwhiteNumBits+ifdefstackCountNumBits+ifdefstackNumBits+stringKindBits - - let lexstateMask = Bits.mask64 lexstateStart lexstateNumBits - let ncommentsMask = Bits.mask64 ncommentsStart ncommentsNumBits - let hardwhitePosMask = Bits.mask64 hardwhitePosStart hardwhiteNumBits - let ifdefstackCountMask = Bits.mask64 ifdefstackCountStart ifdefstackCountNumBits - let ifdefstackMask = Bits.mask64 ifdefstackStart ifdefstackNumBits - let stringKindMask = Bits.mask64 stringKindStart stringKindBits - let nestingMask = Bits.mask64 nestingStart nestingBits + + let _ = + assert + (lexstateNumBits + + ncommentsNumBits + + hardwhiteNumBits + + ifdefstackCountNumBits + + ifdefstackNumBits + + stringKindBits + + nestingBits + <= 64) + + let lexstateStart = 0 + let ncommentsStart = lexstateNumBits + let hardwhitePosStart = lexstateNumBits + ncommentsNumBits + let ifdefstackCountStart = lexstateNumBits + ncommentsNumBits + hardwhiteNumBits + + let ifdefstackStart = + lexstateNumBits + ncommentsNumBits + hardwhiteNumBits + ifdefstackCountNumBits + + let stringKindStart = + lexstateNumBits + + ncommentsNumBits + + hardwhiteNumBits + + ifdefstackCountNumBits + + ifdefstackNumBits + + let nestingStart = + lexstateNumBits + + ncommentsNumBits + + hardwhiteNumBits + + ifdefstackCountNumBits + + ifdefstackNumBits + + stringKindBits + + let lexstateMask = Bits.mask64 lexstateStart lexstateNumBits + let ncommentsMask = Bits.mask64 ncommentsStart ncommentsNumBits + let hardwhitePosMask = Bits.mask64 hardwhitePosStart hardwhiteNumBits + let ifdefstackCountMask = Bits.mask64 ifdefstackCountStart ifdefstackCountNumBits + let ifdefstackMask = Bits.mask64 ifdefstackStart ifdefstackNumBits + let stringKindMask = Bits.mask64 stringKindStart stringKindBits + let nestingMask = Bits.mask64 nestingStart nestingBits let bitOfBool b = if b then 1 else 0 let boolOfBit n = (n = 1L) @@ -445,38 +580,52 @@ module internal LexerStateEncoding = | 0 -> LexerStringStyle.SingleQuote | 1 -> LexerStringStyle.Verbatim | 2 -> LexerStringStyle.TripleQuote - | _ -> assert false; LexerStringStyle.SingleQuote - - let encodeLexCont (colorState: FSharpTokenizerColorState, numComments, b: pos, ifdefStack, light, stringKind: LexerStringKind, stringNest) = + | _ -> + assert false + LexerStringStyle.SingleQuote + + let encodeLexCont + ( + colorState: FSharpTokenizerColorState, + numComments, + b: pos, + ifdefStack, + light, + stringKind: LexerStringKind, + stringNest + ) = let mutable ifdefStackCount = 0 let mutable ifdefStackBits = 0 + for ifOrElse in ifdefStack do match ifOrElse with | IfDefIf, _ -> () - | IfDefElse, _ -> - ifdefStackBits <- (ifdefStackBits ||| (1 <<< ifdefStackCount)) + | IfDefElse, _ -> ifdefStackBits <- (ifdefStackBits ||| (1 <<< ifdefStackCount)) + ifdefStackCount <- ifdefStackCount + 1 let stringKindValue = - (if stringKind.IsByteString then 0b100 else 0) ||| - (if stringKind.IsInterpolated then 0b010 else 0) ||| - (if stringKind.IsInterpolatedFirst then 0b001 else 0) + (if stringKind.IsByteString then 0b100 else 0) + ||| (if stringKind.IsInterpolated then 0b010 else 0) + ||| (if stringKind.IsInterpolatedFirst then 0b001 else 0) let nestingValue = let tag1, i1, kind1, rest = match stringNest with | [] -> false, 0, 0, [] - | (i1, kind1, _)::rest -> true, i1, encodeStringStyle kind1, rest + | (i1, kind1, _) :: rest -> true, i1, encodeStringStyle kind1, rest + let tag2, i2, kind2 = match rest with | [] -> false, 0, 0 - | (i2, kind2, _)::_ -> true, i2, encodeStringStyle kind2 - (if tag1 then 0b100000000000 else 0) ||| - (if tag2 then 0b010000000000 else 0) ||| - ((i1 <<< 7) &&& 0b001110000000) ||| - ((i2 <<< 4) &&& 0b000001110000) ||| - ((kind1 <<< 2) &&& 0b000000001100) ||| - ((kind2 <<< 0) &&& 0b000000000011) + | (i2, kind2, _) :: _ -> true, i2, encodeStringStyle kind2 + + (if tag1 then 0b100000000000 else 0) + ||| (if tag2 then 0b010000000000 else 0) + ||| ((i1 <<< 7) &&& 0b001110000000) + ||| ((i2 <<< 4) &&& 0b000001110000) + ||| ((kind1 <<< 2) &&& 0b000000001100) + ||| ((kind2 <<< 0) &&& 0b000000000011) let bits = lexStateOfColorState colorState @@ -487,9 +636,10 @@ module internal LexerStateEncoding = ||| ((int64 stringKindValue <<< stringKindStart) &&& stringKindMask) ||| ((int64 nestingValue <<< nestingStart) &&& nestingMask) - { PosBits = b.Encoding - OtherBits = bits } - + { + PosBits = b.Encoding + OtherBits = bits + } let decodeLexCont (state: FSharpTokenizerLexState) = let mutable ifDefs = [] @@ -499,35 +649,44 @@ module internal LexerStateEncoding = let ncomments = int32 ((bits &&& ncommentsMask) >>> ncommentsStart) let pos = pos.Decode state.PosBits - let ifdefStackCount = int32 ((bits &&& ifdefstackCountMask) >>> ifdefstackCountStart) - if ifdefStackCount>0 then + let ifdefStackCount = + int32 ((bits &&& ifdefstackCountMask) >>> ifdefstackCountStart) + + if ifdefStackCount > 0 then let ifdefStack = int32 ((bits &&& ifdefstackMask) >>> ifdefstackStart) + for i in 1..ifdefStackCount do - let bit = ifdefStackCount-i + let bit = ifdefStackCount - i let mask = 1 <<< bit let ifDef = (if ifdefStack &&& mask = 0 then IfDefIf else IfDefElse) ifDefs <- (ifDef, range0) :: ifDefs let stringKindValue = int32 ((bits &&& stringKindMask) >>> stringKindStart) - let stringKind : LexerStringKind = - { IsByteString = ((stringKindValue &&& 0b100) = 0b100) - IsInterpolated = ((stringKindValue &&& 0b010) = 0b010) - IsInterpolatedFirst = ((stringKindValue &&& 0b001) = 0b001) } + + let stringKind: LexerStringKind = + { + IsByteString = ((stringKindValue &&& 0b100) = 0b100) + IsInterpolated = ((stringKindValue &&& 0b010) = 0b010) + IsInterpolatedFirst = ((stringKindValue &&& 0b001) = 0b001) + } let hardwhite = boolOfBit ((bits &&& hardwhitePosMask) >>> hardwhitePosStart) let nestingValue = int32 ((bits &&& nestingMask) >>> nestingStart) - let stringNest : LexerInterpolatedStringNesting = - let tag1 = ((nestingValue &&& 0b100000000000) = 0b100000000000) - let tag2 = ((nestingValue &&& 0b010000000000) = 0b010000000000) - let i1 = ((nestingValue &&& 0b001110000000) >>> 7) - let i2 = ((nestingValue &&& 0b000001110000) >>> 4) + + let stringNest: LexerInterpolatedStringNesting = + let tag1 = ((nestingValue &&& 0b100000000000) = 0b100000000000) + let tag2 = ((nestingValue &&& 0b010000000000) = 0b010000000000) + let i1 = ((nestingValue &&& 0b001110000000) >>> 7) + let i2 = ((nestingValue &&& 0b000001110000) >>> 4) let kind1 = ((nestingValue &&& 0b000000001100) >>> 2) let kind2 = ((nestingValue &&& 0b000000000011) >>> 0) - [ if tag1 then - i1, decodeStringStyle kind1, range0 - if tag2 then - i2, decodeStringStyle kind2, range0 + + [ + if tag1 then + i1, decodeStringStyle kind1, range0 + if tag2 then + i2, decodeStringStyle kind2, range0 ] (colorState, ncomments, pos, ifDefs, hardwhite, stringKind, stringNest) @@ -537,65 +696,112 @@ module internal LexerStateEncoding = | LexCont.Token (ifdefs, stringNest) -> encodeLexCont (FSharpTokenizerColorState.Token, 0L, pos0, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) | LexCont.IfDefSkip (ifdefs, stringNest, n, m) -> - encodeLexCont (FSharpTokenizerColorState.IfDefSkip, int64 n, m.Start, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) - | LexCont.EndLine(ifdefs, stringNest, econt) -> + encodeLexCont ( + FSharpTokenizerColorState.IfDefSkip, + int64 n, + m.Start, + ifdefs, + indentationSyntaxStatus, + LexerStringKind.String, + stringNest + ) + | LexCont.EndLine (ifdefs, stringNest, econt) -> match econt with - | LexerEndlineContinuation.Skip(n, m) -> - encodeLexCont (FSharpTokenizerColorState.EndLineThenSkip, int64 n, m.Start, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) + | LexerEndlineContinuation.Skip (n, m) -> + encodeLexCont ( + FSharpTokenizerColorState.EndLineThenSkip, + int64 n, + m.Start, + ifdefs, + indentationSyntaxStatus, + LexerStringKind.String, + stringNest + ) | LexerEndlineContinuation.Token -> - encodeLexCont (FSharpTokenizerColorState.EndLineThenToken, 0L, pos0, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) + encodeLexCont ( + FSharpTokenizerColorState.EndLineThenToken, + 0L, + pos0, + ifdefs, + indentationSyntaxStatus, + LexerStringKind.String, + stringNest + ) | LexCont.String (ifdefs, stringNest, style, kind, m) -> let state = match style with | LexerStringStyle.SingleQuote -> FSharpTokenizerColorState.String | LexerStringStyle.Verbatim -> FSharpTokenizerColorState.VerbatimString | LexerStringStyle.TripleQuote -> FSharpTokenizerColorState.TripleQuoteString + encodeLexCont (state, 0L, m.Start, ifdefs, indentationSyntaxStatus, kind, stringNest) | LexCont.Comment (ifdefs, stringNest, n, m) -> - encodeLexCont (FSharpTokenizerColorState.Comment, int64 n, m.Start, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) + encodeLexCont ( + FSharpTokenizerColorState.Comment, + int64 n, + m.Start, + ifdefs, + indentationSyntaxStatus, + LexerStringKind.String, + stringNest + ) | LexCont.SingleLineComment (ifdefs, stringNest, n, m) -> - encodeLexCont (FSharpTokenizerColorState.SingleLineComment, int64 n, m.Start, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) + encodeLexCont ( + FSharpTokenizerColorState.SingleLineComment, + int64 n, + m.Start, + ifdefs, + indentationSyntaxStatus, + LexerStringKind.String, + stringNest + ) | LexCont.StringInComment (ifdefs, stringNest, style, n, m) -> let state = match style with | LexerStringStyle.SingleQuote -> FSharpTokenizerColorState.StringInComment | LexerStringStyle.Verbatim -> FSharpTokenizerColorState.VerbatimStringInComment | LexerStringStyle.TripleQuote -> FSharpTokenizerColorState.TripleQuoteStringInComment + encodeLexCont (state, int64 n, m.Start, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) | LexCont.MLOnly (ifdefs, stringNest, m) -> - encodeLexCont (FSharpTokenizerColorState.CamlOnly, 0L, m.Start, ifdefs, indentationSyntaxStatus, LexerStringKind.String, stringNest) + encodeLexCont ( + FSharpTokenizerColorState.CamlOnly, + 0L, + m.Start, + ifdefs, + indentationSyntaxStatus, + LexerStringKind.String, + stringNest + ) let decodeLexInt (state: FSharpTokenizerLexState) = - let tag, n1, p1, ifdefs, lightSyntaxStatusInitial, stringKind, stringNest = decodeLexCont state + let tag, n1, p1, ifdefs, lightSyntaxStatusInitial, stringKind, stringNest = + decodeLexCont state + let lexcont = match tag with - | FSharpTokenizerColorState.Token -> - LexCont.Token (ifdefs, stringNest) - | FSharpTokenizerColorState.IfDefSkip -> - LexCont.IfDefSkip (ifdefs, stringNest, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.Token -> LexCont.Token(ifdefs, stringNest) + | FSharpTokenizerColorState.IfDefSkip -> LexCont.IfDefSkip(ifdefs, stringNest, n1, mkRange "file" p1 p1) | FSharpTokenizerColorState.String -> - LexCont.String (ifdefs, stringNest, LexerStringStyle.SingleQuote, stringKind, mkRange "file" p1 p1) - | FSharpTokenizerColorState.Comment -> - LexCont.Comment (ifdefs, stringNest, n1, mkRange "file" p1 p1) - | FSharpTokenizerColorState.SingleLineComment -> - LexCont.SingleLineComment (ifdefs, stringNest, n1, mkRange "file" p1 p1) + LexCont.String(ifdefs, stringNest, LexerStringStyle.SingleQuote, stringKind, mkRange "file" p1 p1) + | FSharpTokenizerColorState.Comment -> LexCont.Comment(ifdefs, stringNest, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.SingleLineComment -> LexCont.SingleLineComment(ifdefs, stringNest, n1, mkRange "file" p1 p1) | FSharpTokenizerColorState.StringInComment -> - LexCont.StringInComment (ifdefs, stringNest, LexerStringStyle.SingleQuote, n1, mkRange "file" p1 p1) + LexCont.StringInComment(ifdefs, stringNest, LexerStringStyle.SingleQuote, n1, mkRange "file" p1 p1) | FSharpTokenizerColorState.VerbatimStringInComment -> - LexCont.StringInComment (ifdefs, stringNest, LexerStringStyle.Verbatim, n1, mkRange "file" p1 p1) + LexCont.StringInComment(ifdefs, stringNest, LexerStringStyle.Verbatim, n1, mkRange "file" p1 p1) | FSharpTokenizerColorState.TripleQuoteStringInComment -> - LexCont.StringInComment (ifdefs, stringNest, LexerStringStyle.TripleQuote, n1, mkRange "file" p1 p1) - | FSharpTokenizerColorState.CamlOnly -> - LexCont.MLOnly (ifdefs, stringNest, mkRange "file" p1 p1) + LexCont.StringInComment(ifdefs, stringNest, LexerStringStyle.TripleQuote, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.CamlOnly -> LexCont.MLOnly(ifdefs, stringNest, mkRange "file" p1 p1) | FSharpTokenizerColorState.VerbatimString -> - LexCont.String (ifdefs, stringNest, LexerStringStyle.Verbatim, stringKind, mkRange "file" p1 p1) + LexCont.String(ifdefs, stringNest, LexerStringStyle.Verbatim, stringKind, mkRange "file" p1 p1) | FSharpTokenizerColorState.TripleQuoteString -> - LexCont.String (ifdefs, stringNest, LexerStringStyle.TripleQuote, stringKind, mkRange "file" p1 p1) + LexCont.String(ifdefs, stringNest, LexerStringStyle.TripleQuote, stringKind, mkRange "file" p1 p1) | FSharpTokenizerColorState.EndLineThenSkip -> LexCont.EndLine(ifdefs, stringNest, LexerEndlineContinuation.Skip(n1, mkRange "file" p1 p1)) - | FSharpTokenizerColorState.EndLineThenToken -> - LexCont.EndLine(ifdefs, stringNest, LexerEndlineContinuation.Token) - | _ -> LexCont.Token ([], stringNest) + | FSharpTokenizerColorState.EndLineThenToken -> LexCont.EndLine(ifdefs, stringNest, LexerEndlineContinuation.Token) + | _ -> LexCont.Token([], stringNest) + lightSyntaxStatusInitial, lexcont //---------------------------------------------------------------------------- @@ -608,17 +814,14 @@ type SingleLineTokenState = | BeforeHash = 0 | NoFurtherMatchPossible = 1 - /// Split a line into tokens and attach information about the tokens. This information is used by Visual Studio. [] -type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, - maxLength: int option, - fileName: string option, - lexargs: LexArgs) = +type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, maxLength: int option, fileName: string option, lexargs: LexArgs) = - let skip = false // don't skip whitespace in the lexer + let skip = false // don't skip whitespace in the lexer let mutable singleLineTokenState = SingleLineTokenState.BeforeHash + let fsx = match fileName with | None -> false @@ -636,8 +839,11 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, // Process: anywhite* # let processDirective (str: string) directiveLength delay cont = let hashIdx = str.IndexOf("#", StringComparison.Ordinal) - if (hashIdx <> 0) then delay(WHITESPACE cont, 0, hashIdx - 1) - delay(HASH_IF(range0, "", cont), hashIdx, hashIdx + directiveLength) + + if (hashIdx <> 0) then + delay (WHITESPACE cont, 0, hashIdx - 1) + + delay (HASH_IF(range0, "", cont), hashIdx, hashIdx + directiveLength) hashIdx + directiveLength + 1 // Process: anywhite* ("//" [^'\n''\r']*)? @@ -645,15 +851,21 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, let rest = str.Substring(offset, str.Length - offset) let comment = rest.IndexOf('/') let spaceLength = if comment = -1 then rest.Length else comment - if (spaceLength > 0) then delay(WHITESPACE cont, offset, offset + spaceLength - 1) - if (comment <> -1) then delay(COMMENT cont, offset + comment, offset + rest.Length - 1) + + if (spaceLength > 0) then + delay (WHITESPACE cont, offset, offset + spaceLength - 1) + + if (comment <> -1) then + delay (COMMENT cont, offset + comment, offset + rest.Length - 1) // Split a directive line from lexer into tokens usable in VS let processDirectiveLine ofs f = let delayed = ResizeArray<_>() - f (fun (tok, s, e) -> delayed.Add (tok, s + ofs, e + ofs) ) + f (fun (tok, s, e) -> delayed.Add(tok, s + ofs, e + ofs)) // delay all the tokens and return the remaining one - for i = delayed.Count - 1 downto 1 do delayToken delayed[i] + for i = delayed.Count - 1 downto 1 do + delayToken delayed[i] + delayed[0] // Split the following line: @@ -663,12 +875,13 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, // Process: anywhite* "#else" / anywhite* "#endif" let offset = processDirective str length delay cont // Process: anywhite* ("//" [^'\n''\r']*)? - processWhiteAndComment str offset delay cont ) + processWhiteAndComment str offset delay cont) // Split the following line: // anywhite* "#if" anywhite+ ident anywhite* ("//" [^'\n''\r']*)? let processHashIfLine ofs (str: string) cont = let With n m = if (n < 0) then m else n + processDirectiveLine ofs (fun delay -> // Process: anywhite* "#if" let offset = processDirective str 2 delay cont @@ -677,16 +890,18 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, let w = str.Substring offset let r = w.TrimStart [| ' '; '\t' |] r, w.Length - r.Length + let beforeIdent = offset + spaces let identLength = With (rest.IndexOfAny([| '/'; '\t'; ' ' |])) rest.Length - delay(WHITESPACE cont, offset, beforeIdent - 1) - delay(IDENT(rest.Substring(0, identLength)), beforeIdent, beforeIdent + identLength - 1) + delay (WHITESPACE cont, offset, beforeIdent - 1) + delay (IDENT(rest.Substring(0, identLength)), beforeIdent, beforeIdent + identLength - 1) // Process: anywhite* ("//" [^'\n''\r']*)? let offset = beforeIdent + identLength - processWhiteAndComment str offset delay cont ) + processWhiteAndComment str offset delay cont) // Set up the initial file position - do match fileName with + do + match fileName with | None -> lexbuf.EndPos <- Internal.Utilities.Text.Lexing.Position.Empty | Some value -> resetLexbufPos value lexbuf @@ -718,6 +933,7 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, lexargs.stringNest <- stringNest use buf = ByteBuffer.Create Lexer.StringCapacity let args = (buf, LexerStringFinisher.Default, m, kind, lexargs) + match style with | LexerStringStyle.SingleQuote -> Lexer.singleQuoteString args skip lexbuf | LexerStringStyle.Verbatim -> Lexer.verbatimString args skip lexbuf @@ -737,6 +953,7 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, | LexCont.StringInComment (ifdefs, stringNest, style, n, m) -> lexargs.ifdefStack <- ifdefs lexargs.stringNest <- stringNest + match style with | LexerStringStyle.SingleQuote -> Lexer.stringInComment n m lexargs skip lexbuf | LexerStringStyle.Verbatim -> Lexer.verbatimStringInComment n m lexargs skip lexbuf @@ -747,14 +964,16 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, lexargs.stringNest <- stringNest Lexer.mlOnly m lexargs skip lexbuf - let columnsOfCurrentToken() = + let columnsOfCurrentToken () = let leftp = lexbuf.StartPos let rightp = lexbuf.EndPos let leftc = leftp.Column + let rightc = match maxLength with | Some mx when rightp.Line > leftp.Line -> mx | _ -> rightp.Column + let rightc = rightc - 1 struct (leftc, rightc) @@ -767,78 +986,80 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, else // Choose which lexer entry point to call and call it let token = callLexCont lexcont indentationSyntaxStatus skip - let struct (leftc, rightc) = columnsOfCurrentToken() + let struct (leftc, rightc) = columnsOfCurrentToken () // Splits tokens like ">." into multiple tokens - this duplicates behavior from the 'lexfilter' // which cannot be (easily) used from the language service. The rules here are not always valid, // because sometimes token shouldn't be split. However it is just for colorization & // for VS (which needs to recognize when user types "."). match token with - | HASH_IF (m, lineStr, cont) when lineStr <> "" -> - false, processHashIfLine m.StartColumn lineStr cont - | HASH_ELSE (m, lineStr, cont) when lineStr <> "" -> - false, processHashEndElse m.StartColumn lineStr 4 cont - | HASH_ENDIF (m, lineStr, cont) when lineStr <> "" -> - false, processHashEndElse m.StartColumn lineStr 5 cont - | HASH_IDENT(ident) -> - delayToken(IDENT ident, leftc + 1, rightc) + | HASH_IF (m, lineStr, cont) when lineStr <> "" -> false, processHashIfLine m.StartColumn lineStr cont + | HASH_ELSE (m, lineStr, cont) when lineStr <> "" -> false, processHashEndElse m.StartColumn lineStr 4 cont + | HASH_ENDIF (m, lineStr, cont) when lineStr <> "" -> false, processHashEndElse m.StartColumn lineStr 5 cont + | HASH_IDENT (ident) -> + delayToken (IDENT ident, leftc + 1, rightc) false, (HASH, leftc, leftc) | RQUOTE_DOT (s, raw) -> - delayToken(DOT, rightc, rightc) - false, (RQUOTE (s, raw), leftc, rightc - 1) - | INFIX_COMPARE_OP (LexFilter.TyparsCloseOp(greaters, afterOp) as opstr) -> + delayToken (DOT, rightc, rightc) + false, (RQUOTE(s, raw), leftc, rightc - 1) + | INFIX_COMPARE_OP (LexFilter.TyparsCloseOp (greaters, afterOp) as opstr) -> match afterOp with | None -> () - | Some tok -> delayToken(tok, leftc + greaters.Length, rightc) + | Some tok -> delayToken (tok, leftc + greaters.Length, rightc) + for i = greaters.Length - 1 downto 1 do - delayToken(greaters[i] false, leftc + i, rightc - opstr.Length + i + 1) - false, (greaters[0] false, leftc, rightc - opstr.Length + 1) + delayToken (greaters[i]false, leftc + i, rightc - opstr.Length + i + 1) + + false, (greaters[0]false, leftc, rightc - opstr.Length + 1) // break up any operators that start with '.' so that we can get auto-popup-completion for e.g. "x.+1" when typing the dot | INFIX_STAR_STAR_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_STAR_STAR_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (INFIX_STAR_STAR_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | PLUS_MINUS_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(PLUS_MINUS_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (PLUS_MINUS_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | INFIX_COMPARE_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_COMPARE_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (INFIX_COMPARE_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | INFIX_AT_HAT_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_AT_HAT_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (INFIX_AT_HAT_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | INFIX_BAR_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_BAR_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (INFIX_BAR_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | PREFIX_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(PREFIX_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (PREFIX_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | INFIX_STAR_DIV_MOD_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_STAR_DIV_MOD_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (INFIX_STAR_DIV_MOD_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | INFIX_AMP_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(INFIX_AMP_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (INFIX_AMP_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | ADJACENT_PREFIX_OP opstr when opstr.StartsWithOrdinal(".") -> - delayToken(ADJACENT_PREFIX_OP(opstr.Substring 1), leftc+1, rightc) + delayToken (ADJACENT_PREFIX_OP(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | FUNKY_OPERATOR_NAME opstr when opstr.StartsWithOrdinal(".") -> - delayToken(FUNKY_OPERATOR_NAME(opstr.Substring 1), leftc+1, rightc) + delayToken (FUNKY_OPERATOR_NAME(opstr.Substring 1), leftc + 1, rightc) false, (DOT, leftc, leftc) | _ -> false, (token, leftc, rightc) with _ -> false, (EOF LexerStateEncoding.revertToDefaultLexCont, 0, 0) // Scan a token starting with the given lexer state - member x.ScanToken (lexState: FSharpTokenizerLexState) : FSharpTokenInfo option * FSharpTokenizerLexState = + member x.ScanToken(lexState: FSharpTokenizerLexState) : FSharpTokenInfo option * FSharpTokenizerLexState = use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse - use unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind (fun _ -> DiscardErrorsLogger) + use unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind(fun _ -> DiscardErrorsLogger) let indentationSyntaxStatus, lexcont = LexerStateEncoding.decodeLexInt lexState - let indentationSyntaxStatus = IndentationAwareSyntaxStatus(indentationSyntaxStatus, false) + + let indentationSyntaxStatus = + IndentationAwareSyntaxStatus(indentationSyntaxStatus, false) // Grab a token - let isCached, (token, leftc, rightc) = getTokenWithPosition lexcont indentationSyntaxStatus + let isCached, (token, leftc, rightc) = + getTokenWithPosition lexcont indentationSyntaxStatus // Check for end-of-string and failure let tokenDataOption, lexcontFinal, tokenTag = @@ -846,43 +1067,52 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, | EOF lexcont -> // End of text! No more tokens. None, lexcont, 0 - | LEX_FAILURE _ -> - None, LexerStateEncoding.revertToDefaultLexCont, 0 + | LEX_FAILURE _ -> None, LexerStateEncoding.revertToDefaultLexCont, 0 | _ -> // Get the information about the token let colorClass, charClass, triggerClass = TokenClassifications.tokenInfo token let lexcontFinal = // If we're using token from cache, we don't move forward with lexing - if isCached then lexcont - else LexerStateEncoding.computeNextLexState token lexcont + if isCached then + lexcont + else + LexerStateEncoding.computeNextLexState token lexcont let tokenTag = tagOfToken token let tokenName = token_to_string token - let fullMatchedLength = lexbuf.EndPos.AbsoluteOffset - lexbuf.StartPos.AbsoluteOffset + let fullMatchedLength = + lexbuf.EndPos.AbsoluteOffset - lexbuf.StartPos.AbsoluteOffset let tokenData = - { TokenName = tokenName - LeftColumn=leftc - RightColumn=rightc - ColorClass=colorClass - CharClass=charClass - FSharpTokenTriggerClass=triggerClass - Tag=tokenTag - FullMatchedLength=fullMatchedLength} + { + TokenName = tokenName + LeftColumn = leftc + RightColumn = rightc + ColorClass = colorClass + CharClass = charClass + FSharpTokenTriggerClass = triggerClass + Tag = tokenTag + FullMatchedLength = fullMatchedLength + } + Some tokenData, lexcontFinal, tokenTag // Check for patterns like #-IDENT and see if they look like meta commands for .fsx files. If they do then merge them into a single token. let tokenDataOption, lexintFinal = - let lexintFinal = LexerStateEncoding.encodeLexInt indentationSyntaxStatus.Status lexcontFinal + let lexintFinal = + LexerStateEncoding.encodeLexInt indentationSyntaxStatus.Status lexcontFinal + match tokenDataOption, singleLineTokenState, tokenTagToTokenId tokenTag with | Some tokenData, SingleLineTokenState.BeforeHash, TOKEN_HASH -> // Don't allow further matches. singleLineTokenState <- SingleLineTokenState.NoFurtherMatchPossible // Peek at the next token - let isCached, (nextToken, _, rightc) = getTokenWithPosition lexcont indentationSyntaxStatus + let isCached, (nextToken, _, rightc) = + getTokenWithPosition lexcont indentationSyntaxStatus + match nextToken with | IDENT possibleMetaCommand -> match fsx, possibleMetaCommand with @@ -907,9 +1137,23 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, // These are for script and non-script | _, "nowarn" -> // Merge both tokens into one. - let lexcontFinal = if isCached then lexcont else LexerStateEncoding.computeNextLexState token lexcont - let tokenData = {tokenData with RightColumn=rightc;ColorClass=FSharpTokenColorKind.PreprocessorKeyword;CharClass=FSharpTokenCharKind.Keyword;FSharpTokenTriggerClass=FSharpTokenTriggerClass.None} - let lexintFinal = LexerStateEncoding.encodeLexInt indentationSyntaxStatus.Status lexcontFinal + let lexcontFinal = + if isCached then + lexcont + else + LexerStateEncoding.computeNextLexState token lexcont + + let tokenData = + { tokenData with + RightColumn = rightc + ColorClass = FSharpTokenColorKind.PreprocessorKeyword + CharClass = FSharpTokenCharKind.Keyword + FSharpTokenTriggerClass = FSharpTokenTriggerClass.None + } + + let lexintFinal = + LexerStateEncoding.encodeLexInt indentationSyntaxStatus.Status lexcontFinal + Some tokenData, lexintFinal | _ -> tokenDataOption, lexintFinal | _ -> tokenDataOption, lexintFinal @@ -926,7 +1170,10 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, LexerStateEncoding.colorStateOfLexState lexState static member LexStateOfColorState(colorState: FSharpTokenizerColorState) = - { PosBits = 0L; OtherBits = LexerStateEncoding.lexStateOfColorState colorState } + { + PosBits = 0L + OtherBits = LexerStateEncoding.lexStateOfColorState colorState + } [] type FSharpSourceTokenizer(conditionalDefines: string list, fileName: string option) = @@ -936,23 +1183,38 @@ type FSharpSourceTokenizer(conditionalDefines: string list, fileName: string opt let lexResourceManager = LexResourceManager() - let lexargs = mkLexargs(conditionalDefines, IndentationAwareSyntaxStatus(true, false), lexResourceManager, [], DiscardErrorsLogger, PathMap.empty) + let lexargs = + mkLexargs ( + conditionalDefines, + IndentationAwareSyntaxStatus(true, false), + lexResourceManager, + [], + DiscardErrorsLogger, + PathMap.empty + ) member _.CreateLineTokenizer(lineText: string) = - let lexbuf = UnicodeLexing.StringAsLexbuf(reportLibraryOnlyFeatures, langVersion, lineText) + let lexbuf = + UnicodeLexing.StringAsLexbuf(reportLibraryOnlyFeatures, langVersion, lineText) + FSharpLineTokenizer(lexbuf, Some lineText.Length, fileName, lexargs) member _.CreateBufferTokenizer bufferFiller = - let lexbuf = UnicodeLexing.FunctionAsLexbuf(reportLibraryOnlyFeatures, langVersion, bufferFiller) + let lexbuf = + UnicodeLexing.FunctionAsLexbuf(reportLibraryOnlyFeatures, langVersion, bufferFiller) + FSharpLineTokenizer(lexbuf, None, fileName, lexargs) module FSharpKeywords = - let DoesIdentifierNeedBackticks s = PrettyNaming.DoesIdentifierNeedBackticks s + let DoesIdentifierNeedBackticks s = + PrettyNaming.DoesIdentifierNeedBackticks s - let AddBackticksToIdentifierIfNeeded s = PrettyNaming.AddBackticksToIdentifierIfNeeded s + let AddBackticksToIdentifierIfNeeded s = + PrettyNaming.AddBackticksToIdentifierIfNeeded s - let NormalizeIdentifierBackticks s = PrettyNaming.NormalizeIdentifierBackticks s + let NormalizeIdentifierBackticks s = + PrettyNaming.NormalizeIdentifierBackticks s let KeywordsWithDescription = PrettyNaming.keywordsWithDescription @@ -960,12 +1222,12 @@ module FSharpKeywords = [] type FSharpLexerFlags = - | Default = 0x11011 - | LightSyntaxOn = 0x00001 - | Compiling = 0x00010 - | CompilingFSharpCore = 0x00110 - | SkipTrivia = 0x01000 - | UseLexFilter = 0x10000 + | Default = 0x11011 + | LightSyntaxOn = 0x00001 + | Compiling = 0x00010 + | CompilingFSharpCore = 0x00110 + | SkipTrivia = 0x01000 + | UseLexFilter = 0x10000 [] type FSharpTokenKind = @@ -1160,13 +1422,13 @@ type FSharpTokenKind = | InfixLxor | InfixMod -[] +[] type FSharpToken = val private tok: token val private tokRange: range - new (tok, tokRange) = { tok = tok; tokRange = tokRange } + new(tok, tokRange) = { tok = tok; tokRange = tokRange } member this.Range = this.tokRange @@ -1190,137 +1452,137 @@ type FSharpToken = | INACTIVECODE _ -> FSharpTokenKind.InactiveCode | LINE_COMMENT _ -> FSharpTokenKind.LineCommentTrivia | STRING_TEXT _ -> FSharpTokenKind.StringText - | FIXED -> FSharpTokenKind.Fixed - | OINTERFACE_MEMBER -> FSharpTokenKind.OffsideInterfaceMember - | OBLOCKEND -> FSharpTokenKind.OffsideBlockEnd - | ORIGHT_BLOCK_END -> FSharpTokenKind.OffsideRightBlockEnd - | ODECLEND -> FSharpTokenKind.OffsideDeclEnd - | OEND -> FSharpTokenKind.OffsideEnd - | OBLOCKSEP -> FSharpTokenKind.OffsideBlockSep - | OBLOCKBEGIN -> FSharpTokenKind.OffsideBlockBegin - | ORESET -> FSharpTokenKind.OffsideReset - | OFUN -> FSharpTokenKind.OffsideFun - | OFUNCTION -> FSharpTokenKind.OffsideFunction - | OWITH -> FSharpTokenKind.OffsideWith - | OELSE -> FSharpTokenKind.OffsideElse - | OTHEN -> FSharpTokenKind.OffsideThen - | ODO_BANG -> FSharpTokenKind.OffsideDoBang - | ODO -> FSharpTokenKind.OffsideDo + | FIXED -> FSharpTokenKind.Fixed + | OINTERFACE_MEMBER -> FSharpTokenKind.OffsideInterfaceMember + | OBLOCKEND -> FSharpTokenKind.OffsideBlockEnd + | ORIGHT_BLOCK_END -> FSharpTokenKind.OffsideRightBlockEnd + | ODECLEND -> FSharpTokenKind.OffsideDeclEnd + | OEND -> FSharpTokenKind.OffsideEnd + | OBLOCKSEP -> FSharpTokenKind.OffsideBlockSep + | OBLOCKBEGIN -> FSharpTokenKind.OffsideBlockBegin + | ORESET -> FSharpTokenKind.OffsideReset + | OFUN -> FSharpTokenKind.OffsideFun + | OFUNCTION -> FSharpTokenKind.OffsideFunction + | OWITH -> FSharpTokenKind.OffsideWith + | OELSE -> FSharpTokenKind.OffsideElse + | OTHEN -> FSharpTokenKind.OffsideThen + | ODO_BANG -> FSharpTokenKind.OffsideDoBang + | ODO -> FSharpTokenKind.OffsideDo | OBINDER _ -> FSharpTokenKind.OffsideBinder | OLET _ -> FSharpTokenKind.OffsideLet - | HIGH_PRECEDENCE_TYAPP -> FSharpTokenKind.HighPrecedenceTypeApp - | HIGH_PRECEDENCE_PAREN_APP -> FSharpTokenKind.HighPrecedenceParenthesisApp - | HIGH_PRECEDENCE_BRACK_APP -> FSharpTokenKind.HighPrecedenceBracketApp - | EXTERN -> FSharpTokenKind.Extern - | VOID -> FSharpTokenKind.Void - | PUBLIC -> FSharpTokenKind.Public - | PRIVATE -> FSharpTokenKind.Private - | INTERNAL -> FSharpTokenKind.Internal - | GLOBAL -> FSharpTokenKind.Global - | STATIC -> FSharpTokenKind.Static - | MEMBER -> FSharpTokenKind.Member - | CLASS -> FSharpTokenKind.Class - | ABSTRACT -> FSharpTokenKind.Abstract - | OVERRIDE -> FSharpTokenKind.Override - | DEFAULT -> FSharpTokenKind.Default - | CONSTRUCTOR -> FSharpTokenKind.Constructor - | INHERIT -> FSharpTokenKind.Inherit - | GREATER_RBRACK -> FSharpTokenKind.GreaterRightBracket - | STRUCT -> FSharpTokenKind.Struct - | SIG -> FSharpTokenKind.Sig - | BAR -> FSharpTokenKind.Bar - | RBRACK -> FSharpTokenKind.RightBracket + | HIGH_PRECEDENCE_TYAPP -> FSharpTokenKind.HighPrecedenceTypeApp + | HIGH_PRECEDENCE_PAREN_APP -> FSharpTokenKind.HighPrecedenceParenthesisApp + | HIGH_PRECEDENCE_BRACK_APP -> FSharpTokenKind.HighPrecedenceBracketApp + | EXTERN -> FSharpTokenKind.Extern + | VOID -> FSharpTokenKind.Void + | PUBLIC -> FSharpTokenKind.Public + | PRIVATE -> FSharpTokenKind.Private + | INTERNAL -> FSharpTokenKind.Internal + | GLOBAL -> FSharpTokenKind.Global + | STATIC -> FSharpTokenKind.Static + | MEMBER -> FSharpTokenKind.Member + | CLASS -> FSharpTokenKind.Class + | ABSTRACT -> FSharpTokenKind.Abstract + | OVERRIDE -> FSharpTokenKind.Override + | DEFAULT -> FSharpTokenKind.Default + | CONSTRUCTOR -> FSharpTokenKind.Constructor + | INHERIT -> FSharpTokenKind.Inherit + | GREATER_RBRACK -> FSharpTokenKind.GreaterRightBracket + | STRUCT -> FSharpTokenKind.Struct + | SIG -> FSharpTokenKind.Sig + | BAR -> FSharpTokenKind.Bar + | RBRACK -> FSharpTokenKind.RightBracket | RBRACE _ -> FSharpTokenKind.RightBrace - | MINUS -> FSharpTokenKind.Minus - | DOLLAR -> FSharpTokenKind.Dollar - | BAR_RBRACK -> FSharpTokenKind.BarRightBracket - | BAR_RBRACE -> FSharpTokenKind.BarRightBrace - | UNDERSCORE -> FSharpTokenKind.Underscore - | SEMICOLON_SEMICOLON -> FSharpTokenKind.SemicolonSemicolon - | LARROW -> FSharpTokenKind.LeftArrow - | EQUALS -> FSharpTokenKind.Equals - | LBRACK -> FSharpTokenKind.LeftBracket - | LBRACK_BAR -> FSharpTokenKind.LeftBracketBar - | LBRACE_BAR -> FSharpTokenKind.LeftBraceBar - | LBRACK_LESS -> FSharpTokenKind.LeftBracketLess + | MINUS -> FSharpTokenKind.Minus + | DOLLAR -> FSharpTokenKind.Dollar + | BAR_RBRACK -> FSharpTokenKind.BarRightBracket + | BAR_RBRACE -> FSharpTokenKind.BarRightBrace + | UNDERSCORE -> FSharpTokenKind.Underscore + | SEMICOLON_SEMICOLON -> FSharpTokenKind.SemicolonSemicolon + | LARROW -> FSharpTokenKind.LeftArrow + | EQUALS -> FSharpTokenKind.Equals + | LBRACK -> FSharpTokenKind.LeftBracket + | LBRACK_BAR -> FSharpTokenKind.LeftBracketBar + | LBRACE_BAR -> FSharpTokenKind.LeftBraceBar + | LBRACK_LESS -> FSharpTokenKind.LeftBracketLess | LBRACE _ -> FSharpTokenKind.LeftBrace - | QMARK -> FSharpTokenKind.QuestionMark - | QMARK_QMARK -> FSharpTokenKind.QuestionMarkQuestionMark - | DOT -> FSharpTokenKind.Dot - | COLON -> FSharpTokenKind.Colon - | COLON_COLON -> FSharpTokenKind.ColonColon - | COLON_GREATER -> FSharpTokenKind.ColonGreater - | COLON_QMARK_GREATER -> FSharpTokenKind.ColonQuestionMarkGreater - | COLON_QMARK -> FSharpTokenKind.ColonQuestionMark - | COLON_EQUALS -> FSharpTokenKind.ColonEquals - | SEMICOLON -> FSharpTokenKind.SemicolonSemicolon - | WHEN -> FSharpTokenKind.When - | WHILE -> FSharpTokenKind.While - | WITH -> FSharpTokenKind.With - | HASH -> FSharpTokenKind.Hash - | AMP -> FSharpTokenKind.Ampersand - | AMP_AMP -> FSharpTokenKind.AmpersandAmpersand - | QUOTE -> FSharpTokenKind.RightQuote - | LPAREN -> FSharpTokenKind.LeftParenthesis - | RPAREN -> FSharpTokenKind.RightParenthesis - | STAR -> FSharpTokenKind.Star - | COMMA -> FSharpTokenKind.Comma - | RARROW -> FSharpTokenKind.RightArrow - | GREATER_BAR_RBRACK -> FSharpTokenKind.GreaterBarRightBracket - | LPAREN_STAR_RPAREN -> FSharpTokenKind.LeftParenthesisStarRightParenthesis - | OPEN -> FSharpTokenKind.Open - | OR -> FSharpTokenKind.Or - | REC -> FSharpTokenKind.Rec - | THEN -> FSharpTokenKind.Then - | TO -> FSharpTokenKind.To - | TRUE -> FSharpTokenKind.True - | TRY -> FSharpTokenKind.Try - | TYPE -> FSharpTokenKind.Type - | VAL -> FSharpTokenKind.Val - | INLINE -> FSharpTokenKind.Inline - | INTERFACE -> FSharpTokenKind.Interface - | INSTANCE -> FSharpTokenKind.Instance - | CONST -> FSharpTokenKind.Const - | LAZY -> FSharpTokenKind.Lazy - | OLAZY -> FSharpTokenKind.OffsideLazy - | MATCH -> FSharpTokenKind.Match - | MATCH_BANG -> FSharpTokenKind.MatchBang - | MUTABLE -> FSharpTokenKind.Mutable - | NEW -> FSharpTokenKind.New - | OF -> FSharpTokenKind.Of - | EXCEPTION -> FSharpTokenKind.Exception - | FALSE -> FSharpTokenKind.False - | FOR -> FSharpTokenKind.For - | FUN -> FSharpTokenKind.Fun - | FUNCTION -> FSharpTokenKind.Function - | IF -> FSharpTokenKind.If - | IN -> FSharpTokenKind.In - | JOIN_IN -> FSharpTokenKind.JoinIn - | FINALLY -> FSharpTokenKind.Finally - | DO_BANG -> FSharpTokenKind.DoBang - | AND -> FSharpTokenKind.And - | AS -> FSharpTokenKind.As - | ASSERT -> FSharpTokenKind.Assert - | OASSERT -> FSharpTokenKind.OffsideAssert - | BEGIN -> FSharpTokenKind.Begin - | DO -> FSharpTokenKind.Do - | DONE -> FSharpTokenKind.Done - | DOWNTO -> FSharpTokenKind.DownTo - | ELSE -> FSharpTokenKind.Else - | ELIF -> FSharpTokenKind.Elif - | END -> FSharpTokenKind.End - | DOT_DOT -> FSharpTokenKind.DotDot - | DOT_DOT_HAT -> FSharpTokenKind.DotDotHat - | BAR_BAR -> FSharpTokenKind.BarBar - | UPCAST -> FSharpTokenKind.Upcast - | DOWNCAST -> FSharpTokenKind.Downcast - | NULL -> FSharpTokenKind.Null - | RESERVED -> FSharpTokenKind.Reserved - | MODULE -> FSharpTokenKind.Module - | NAMESPACE -> FSharpTokenKind.Namespace - | DELEGATE -> FSharpTokenKind.Delegate - | CONSTRAINT -> FSharpTokenKind.Constraint - | BASE -> FSharpTokenKind.Base + | QMARK -> FSharpTokenKind.QuestionMark + | QMARK_QMARK -> FSharpTokenKind.QuestionMarkQuestionMark + | DOT -> FSharpTokenKind.Dot + | COLON -> FSharpTokenKind.Colon + | COLON_COLON -> FSharpTokenKind.ColonColon + | COLON_GREATER -> FSharpTokenKind.ColonGreater + | COLON_QMARK_GREATER -> FSharpTokenKind.ColonQuestionMarkGreater + | COLON_QMARK -> FSharpTokenKind.ColonQuestionMark + | COLON_EQUALS -> FSharpTokenKind.ColonEquals + | SEMICOLON -> FSharpTokenKind.SemicolonSemicolon + | WHEN -> FSharpTokenKind.When + | WHILE -> FSharpTokenKind.While + | WITH -> FSharpTokenKind.With + | HASH -> FSharpTokenKind.Hash + | AMP -> FSharpTokenKind.Ampersand + | AMP_AMP -> FSharpTokenKind.AmpersandAmpersand + | QUOTE -> FSharpTokenKind.RightQuote + | LPAREN -> FSharpTokenKind.LeftParenthesis + | RPAREN -> FSharpTokenKind.RightParenthesis + | STAR -> FSharpTokenKind.Star + | COMMA -> FSharpTokenKind.Comma + | RARROW -> FSharpTokenKind.RightArrow + | GREATER_BAR_RBRACK -> FSharpTokenKind.GreaterBarRightBracket + | LPAREN_STAR_RPAREN -> FSharpTokenKind.LeftParenthesisStarRightParenthesis + | OPEN -> FSharpTokenKind.Open + | OR -> FSharpTokenKind.Or + | REC -> FSharpTokenKind.Rec + | THEN -> FSharpTokenKind.Then + | TO -> FSharpTokenKind.To + | TRUE -> FSharpTokenKind.True + | TRY -> FSharpTokenKind.Try + | TYPE -> FSharpTokenKind.Type + | VAL -> FSharpTokenKind.Val + | INLINE -> FSharpTokenKind.Inline + | INTERFACE -> FSharpTokenKind.Interface + | INSTANCE -> FSharpTokenKind.Instance + | CONST -> FSharpTokenKind.Const + | LAZY -> FSharpTokenKind.Lazy + | OLAZY -> FSharpTokenKind.OffsideLazy + | MATCH -> FSharpTokenKind.Match + | MATCH_BANG -> FSharpTokenKind.MatchBang + | MUTABLE -> FSharpTokenKind.Mutable + | NEW -> FSharpTokenKind.New + | OF -> FSharpTokenKind.Of + | EXCEPTION -> FSharpTokenKind.Exception + | FALSE -> FSharpTokenKind.False + | FOR -> FSharpTokenKind.For + | FUN -> FSharpTokenKind.Fun + | FUNCTION -> FSharpTokenKind.Function + | IF -> FSharpTokenKind.If + | IN -> FSharpTokenKind.In + | JOIN_IN -> FSharpTokenKind.JoinIn + | FINALLY -> FSharpTokenKind.Finally + | DO_BANG -> FSharpTokenKind.DoBang + | AND -> FSharpTokenKind.And + | AS -> FSharpTokenKind.As + | ASSERT -> FSharpTokenKind.Assert + | OASSERT -> FSharpTokenKind.OffsideAssert + | BEGIN -> FSharpTokenKind.Begin + | DO -> FSharpTokenKind.Do + | DONE -> FSharpTokenKind.Done + | DOWNTO -> FSharpTokenKind.DownTo + | ELSE -> FSharpTokenKind.Else + | ELIF -> FSharpTokenKind.Elif + | END -> FSharpTokenKind.End + | DOT_DOT -> FSharpTokenKind.DotDot + | DOT_DOT_HAT -> FSharpTokenKind.DotDotHat + | BAR_BAR -> FSharpTokenKind.BarBar + | UPCAST -> FSharpTokenKind.Upcast + | DOWNCAST -> FSharpTokenKind.Downcast + | NULL -> FSharpTokenKind.Null + | RESERVED -> FSharpTokenKind.Reserved + | MODULE -> FSharpTokenKind.Module + | NAMESPACE -> FSharpTokenKind.Namespace + | DELEGATE -> FSharpTokenKind.Delegate + | CONSTRAINT -> FSharpTokenKind.Constraint + | BASE -> FSharpTokenKind.Base | LQUOTE _ -> FSharpTokenKind.LeftQuote | RQUOTE _ -> FSharpTokenKind.RightQuote | RQUOTE_DOT _ -> FSharpTokenKind.RightQuoteDot @@ -1521,40 +1783,81 @@ type FSharpToken = [] module FSharpLexerImpl = - let lexWithDiagnosticsLogger (text: ISourceText) conditionalDefines (flags: FSharpLexerFlags) reportLibraryOnlyFeatures langVersion diagnosticsLogger onToken pathMap (ct: CancellationToken) = - let canSkipTrivia = (flags &&& FSharpLexerFlags.SkipTrivia) = FSharpLexerFlags.SkipTrivia - let isLightSyntaxOn = (flags &&& FSharpLexerFlags.LightSyntaxOn) = FSharpLexerFlags.LightSyntaxOn - let isCompiling = (flags &&& FSharpLexerFlags.Compiling) = FSharpLexerFlags.Compiling - let isCompilingFSharpCore = (flags &&& FSharpLexerFlags.CompilingFSharpCore) = FSharpLexerFlags.CompilingFSharpCore - let canUseLexFilter = (flags &&& FSharpLexerFlags.UseLexFilter) = FSharpLexerFlags.UseLexFilter - - let lexbuf = UnicodeLexing.SourceTextAsLexbuf(reportLibraryOnlyFeatures, langVersion, text) + let lexWithDiagnosticsLogger + (text: ISourceText) + conditionalDefines + (flags: FSharpLexerFlags) + reportLibraryOnlyFeatures + langVersion + diagnosticsLogger + onToken + pathMap + (ct: CancellationToken) + = + let canSkipTrivia = + (flags &&& FSharpLexerFlags.SkipTrivia) = FSharpLexerFlags.SkipTrivia + + let isLightSyntaxOn = + (flags &&& FSharpLexerFlags.LightSyntaxOn) = FSharpLexerFlags.LightSyntaxOn + + let isCompiling = + (flags &&& FSharpLexerFlags.Compiling) = FSharpLexerFlags.Compiling + + let isCompilingFSharpCore = + (flags &&& FSharpLexerFlags.CompilingFSharpCore) = FSharpLexerFlags.CompilingFSharpCore + + let canUseLexFilter = + (flags &&& FSharpLexerFlags.UseLexFilter) = FSharpLexerFlags.UseLexFilter + + let lexbuf = + UnicodeLexing.SourceTextAsLexbuf(reportLibraryOnlyFeatures, langVersion, text) + let indentationSyntaxStatus = IndentationAwareSyntaxStatus(isLightSyntaxOn, true) - let lexargs = mkLexargs (conditionalDefines, indentationSyntaxStatus, LexResourceManager(0), [], diagnosticsLogger, pathMap) - let lexargs = { lexargs with applyLineDirectives = isCompiling } + + let lexargs = + mkLexargs (conditionalDefines, indentationSyntaxStatus, LexResourceManager(0), [], diagnosticsLogger, pathMap) + + let lexargs = + { lexargs with + applyLineDirectives = isCompiling + } let getNextToken = let lexer = Lexer.token lexargs canSkipTrivia if canUseLexFilter then - let lexFilter = LexFilter.LexFilter(lexargs.indentationSyntaxStatus, isCompilingFSharpCore, lexer, lexbuf) + let lexFilter = + LexFilter.LexFilter(lexargs.indentationSyntaxStatus, isCompilingFSharpCore, lexer, lexbuf) + (fun _ -> lexFilter.GetToken()) else lexer use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse - use _unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind (fun _ -> DiscardErrorsLogger) + use _unwindEL = PushDiagnosticsLoggerPhaseUntilUnwind(fun _ -> DiscardErrorsLogger) resetLexbufPos "" lexbuf + while not lexbuf.IsPastEndOfStream do - ct.ThrowIfCancellationRequested () + ct.ThrowIfCancellationRequested() onToken (getNextToken lexbuf) lexbuf.LexemeRange let lex text conditionalDefines flags reportLibraryOnlyFeatures langVersion lexCallback pathMap ct = - let diagnosticsLogger = CompilationDiagnosticLogger("Lexer", FSharpDiagnosticOptions.Default) - lexWithDiagnosticsLogger text conditionalDefines flags reportLibraryOnlyFeatures langVersion diagnosticsLogger lexCallback pathMap ct - -[] + let diagnosticsLogger = + CompilationDiagnosticLogger("Lexer", FSharpDiagnosticOptions.Default) + + lexWithDiagnosticsLogger + text + conditionalDefines + flags + reportLibraryOnlyFeatures + langVersion + diagnosticsLogger + lexCallback + pathMap + ct + +[] type FSharpLexer = static member Tokenize(text: ISourceText, tokenCallback, ?langVersion, ?filePath: string, ?conditionalDefines, ?flags, ?pathMap, ?ct) = @@ -1570,10 +1873,11 @@ type FSharpLexer = ||> Seq.fold (fun state pair -> state |> PathMap.addMapping pair.Key pair.Value) let onToken tok m = - let fsTok = FSharpToken(tok, m) - match fsTok.Kind with - | FSharpTokenKind.None -> () - | _ -> tokenCallback fsTok + let fsTok = FSharpToken(tok, m) + + match fsTok.Kind with + | FSharpTokenKind.None -> () + | _ -> tokenCallback fsTok let reportLibraryOnlyFeatures = true lex text conditionalDefines flags reportLibraryOnlyFeatures langVersion onToken pathMap ct diff --git a/src/Compiler/Service/ServiceLexing.fsi b/src/Compiler/Service/ServiceLexing.fsi index 5e2e5a9732d..df1dfdde294 100755 --- a/src/Compiler/Service/ServiceLexing.fsi +++ b/src/Compiler/Service/ServiceLexing.fsi @@ -6,6 +6,7 @@ open System open System.Threading open FSharp.Compiler open FSharp.Compiler.Text + #nowarn "57" /// Represents encoded information for the end-of-line continuation of lexing diff --git a/src/Compiler/Service/ServiceNavigation.fs b/src/Compiler/Service/ServiceNavigation.fs index de3b0bece2c..0751225c890 100755 --- a/src/Compiler/Service/ServiceNavigation.fs +++ b/src/Compiler/Service/ServiceNavigation.fs @@ -40,39 +40,62 @@ type NavigationEntityKind = /// Represents an item to be displayed in the navigation bar [] -type NavigationItem(uniqueName: string, name: string, kind: NavigationItemKind, glyph: FSharpGlyph, range: range, - bodyRange: range, singleTopLevel: bool, enclosingEntityKind: NavigationEntityKind, isAbstract: bool, access: SynAccess option) = - +type NavigationItem + ( + uniqueName: string, + name: string, + kind: NavigationItemKind, + glyph: FSharpGlyph, + range: range, + bodyRange: range, + singleTopLevel: bool, + enclosingEntityKind: NavigationEntityKind, + isAbstract: bool, + access: SynAccess option + ) = + member _.bodyRange = bodyRange + member _.UniqueName = uniqueName + member _.Name = name + member _.Glyph = glyph + member _.Kind = kind + member _.Range = range - member _.BodyRange = bodyRange + + member _.BodyRange = bodyRange + member _.IsSingleTopLevel = singleTopLevel + member _.EnclosingEntityKind = enclosingEntityKind + member _.IsAbstract = isAbstract - + member _.Access = access - + member _.WithUniqueName(uniqueName: string) = - NavigationItem(uniqueName, name, kind, glyph, range, bodyRange, singleTopLevel, enclosingEntityKind, isAbstract, access) - static member Create(name: string, kind, glyph: FSharpGlyph, range: range, bodyRange: range, singleTopLevel: bool, enclosingEntityKind, isAbstract, access: SynAccess option) = - NavigationItem("", name, kind, glyph, range, bodyRange, singleTopLevel, enclosingEntityKind, isAbstract, access) + NavigationItem(uniqueName, name, kind, glyph, range, bodyRange, singleTopLevel, enclosingEntityKind, isAbstract, access) + + static member Create(name, kind, glyph, range, bodyRange, singleTopLevel, enclosingEntityKind, isAbstract, access) = + NavigationItem("", name, kind, glyph, range, bodyRange, singleTopLevel, enclosingEntityKind, isAbstract, access) /// Represents top-level declarations (that should be in the type drop-down) /// with nested declarations (that can be shown in the member drop-down) [] -type NavigationTopLevelDeclaration = - { Declaration: NavigationItem - Nested: NavigationItem[] } - +type NavigationTopLevelDeclaration = + { + Declaration: NavigationItem + Nested: NavigationItem[] + } + /// Represents result of 'GetNavigationItems' operation - this contains /// all the members and currently selected indices. First level correspond to /// types & modules and second level are methods etc. [] -type NavigationItems(declarations:NavigationTopLevelDeclaration[]) = +type NavigationItems(declarations: NavigationTopLevelDeclaration[]) = member _.Declarations = declarations module NavigationImpl = @@ -80,384 +103,557 @@ module NavigationImpl = if equals r1 range.Zero then r2 elif equals r2 range.Zero then r1 else unionRanges r1 r2 - - let rangeOfDecls2 f decls = - match decls |> List.map (f >> (fun (d:NavigationItem) -> d.bodyRange)) with + + let rangeOfDecls2 f decls = + match decls |> List.map (f >> (fun (d: NavigationItem) -> d.bodyRange)) with | hd :: tl -> tl |> List.fold unionRangesChecked hd | [] -> range.Zero - + let rangeOfDecls = rangeOfDecls2 fst - let moduleRange (idm:range) others = - unionRangesChecked idm.EndRange (rangeOfDecls2 (fun (a, _, _) -> a) others) - + let moduleRange (idm: range) others = + unionRangesChecked idm.EndRange (rangeOfDecls2 (fun (a, _, _) -> a) others) + let fldspecRange fldspec = - match fldspec with - | SynUnionCaseKind.Fields(flds) -> flds |> List.fold (fun st (SynField(_, _, _, _, _, _, _, m)) -> unionRangesChecked m st) range.Zero - | SynUnionCaseKind.FullType(ty, _) -> ty.Range - - let bodyRange mb decls = - unionRangesChecked (rangeOfDecls decls) mb - - /// Get information for implementation file + match fldspec with + | SynUnionCaseKind.Fields (flds) -> + flds + |> List.fold (fun st (SynField (_, _, _, _, _, _, _, m)) -> unionRangesChecked m st) range.Zero + | SynUnionCaseKind.FullType (ty, _) -> ty.Range + + let bodyRange mBody decls = + unionRangesChecked (rangeOfDecls decls) mBody + + /// Get information for implementation file let getNavigationFromImplFile (modules: SynModuleOrNamespace list) = // Map for dealing with name conflicts let names = Dictionary() - let addItemName name = + let addItemName name = let count = match names.TryGetValue name with | true, count -> count + 1 | _ -> 1 + names[name] <- count count - - let uniqueName name idx = + + let uniqueName name idx = let total = names[name] sprintf "%s_%d_of_%d" name idx total - // Create declaration (for the left dropdown) - let createDeclLid(baseName, lid, kind, baseGlyph, m, bodym, nested, enclosingEntityKind, isAbstract, access) = - let name = (if baseName <> "" then baseName + "." else "") + (textOfLid lid) - NavigationItem.Create - (name, kind, baseGlyph, m, bodym, false, enclosingEntityKind, isAbstract, access), (addItemName name), nested - - let createDecl(baseName, id:Ident, kind, baseGlyph, m, bodym, nested, enclosingEntityKind, isAbstract, access) = + // Create declaration (for the left dropdown) + let createDeclLid (baseName, lid, kind, baseGlyph, m, mBody, nested, enclosingEntityKind, access) = + let name = (if baseName <> "" then baseName + "." else "") + textOfLid lid + let item = NavigationItem.Create(name, kind, baseGlyph, m, mBody, false, enclosingEntityKind, false, access) + item, addItemName name, nested + + let createDecl (baseName, id: Ident, kind, baseGlyph, m, mBody, nested, enclosingEntityKind, isAbstract, access) = let name = (if baseName <> "" then baseName + "." else "") + id.idText - NavigationItem.Create - (name, kind, baseGlyph, m, bodym, false, enclosingEntityKind, isAbstract, access), (addItemName name), nested - + let item = NavigationItem.Create(name, kind, baseGlyph, m, mBody, false, enclosingEntityKind, isAbstract, access) + item, addItemName name, nested + + let createTypeDecl (baseName, lid, baseGlyph, m, mBody, nested, enclosingEntityKind, access) = + createDeclLid (baseName, lid, NavigationItemKind.Type, baseGlyph, m, mBody, nested, enclosingEntityKind, access) + // Create member-kind-of-thing for the right dropdown - let createMemberLid(lid, kind, baseGlyph, m, enclosingEntityKind, isAbstract, access) = - NavigationItem.Create(textOfLid lid, kind, baseGlyph, m, m, false, enclosingEntityKind, isAbstract, access), (addItemName(textOfLid lid)) + let createMemberLid (lid, kind, baseGlyph, m, enclosingEntityKind, isAbstract, access) = + let item = NavigationItem.Create(textOfLid lid, kind, baseGlyph, m, m, false, enclosingEntityKind, isAbstract, access) + item, addItemName (textOfLid lid) - let createMember(id:Ident, kind, baseGlyph, m, enclosingEntityKind, isAbstract, access) = - NavigationItem.Create(id.idText, kind, baseGlyph, m, m, false, enclosingEntityKind, isAbstract, access), (addItemName(id.idText)) + let createMember (id: Ident, kind, baseGlyph, m, enclosingEntityKind, isAbstract, access) = + let item = NavigationItem.Create(id.idText, kind, baseGlyph, m, m, false, enclosingEntityKind, isAbstract, access) + item, addItemName (id.idText) // Process let-binding - let processBinding isMember enclosingEntityKind isAbstract (SynBinding(valData=SynValData(memberOpt, _, _); headPat=synPat; expr=synExpr)) = - let m = - match synExpr with + let processBinding isMember enclosingEntityKind isAbstract synBinding = + let (SynBinding (valData = valData; headPat = synPat; expr = synExpr)) = synBinding + let (SynValData (memberOpt, _, _)) = valData + + let m = + match synExpr with | SynExpr.Typed (e, _, _) -> e.Range // fix range for properties with type annotations | _ -> synExpr.Range match synPat, memberOpt with - | SynPat.LongIdent(longDotId=SynLongIdent(lid,_,_); accessibility=access), Some(flags) when isMember -> + | SynPat.LongIdent (longDotId = SynLongIdent (lid, _, _); accessibility = access), Some (flags) when isMember -> let icon, kind = - match flags.MemberKind with - | SynMemberKind.ClassConstructor - | SynMemberKind.Constructor - | SynMemberKind.Member -> - (if flags.IsOverrideOrExplicitImpl then FSharpGlyph.OverridenMethod else FSharpGlyph.Method), NavigationItemKind.Method - | SynMemberKind.PropertyGetSet - | SynMemberKind.PropertySet - | SynMemberKind.PropertyGet -> FSharpGlyph.Property, NavigationItemKind.Property - let lidShow, rangeMerge = - match lid with - | _thisVar :: nm :: _ -> (List.tail lid, nm.idRange) - | hd :: _ -> (lid, hd.idRange) - | _ -> (lid, m) - [ createMemberLid(lidShow, kind, icon, unionRanges rangeMerge m, enclosingEntityKind, isAbstract, access) ] - | SynPat.LongIdent(longDotId=SynLongIdent(lid,_,_); accessibility=access), _ -> - [ createMemberLid(lid, NavigationItemKind.Field, FSharpGlyph.Field, unionRanges (List.head lid).idRange m, enclosingEntityKind, isAbstract, access) ] - | SynPat.Named (SynIdent(id,_), _, access, _), _ | SynPat.As(_, SynPat.Named (SynIdent(id,_), _, access, _), _), _ -> + match flags.MemberKind with + | SynMemberKind.ClassConstructor + | SynMemberKind.Constructor + | SynMemberKind.Member -> + let glyph = + if flags.IsOverrideOrExplicitImpl then + FSharpGlyph.OverridenMethod + else + FSharpGlyph.Method + + glyph, NavigationItemKind.Method + | SynMemberKind.PropertyGetSet + | SynMemberKind.PropertySet + | SynMemberKind.PropertyGet -> FSharpGlyph.Property, NavigationItemKind.Property + + let lidShow, rangeMerge = + match lid with + | _thisVar :: nm :: _ -> (List.tail lid, nm.idRange) + | hd :: _ -> (lid, hd.idRange) + | _ -> (lid, m) + + let m = unionRanges rangeMerge m + + [ + createMemberLid (lidShow, kind, icon, m, enclosingEntityKind, isAbstract, access) + ] + + | SynPat.LongIdent (longDotId = SynLongIdent (lid, _, _); accessibility = access), _ -> + let m = unionRanges (List.head lid).idRange m + + [ + createMemberLid (lid, NavigationItemKind.Field, FSharpGlyph.Field, m, enclosingEntityKind, isAbstract, access) + ] + + | SynPat.Named (SynIdent (id, _), _, access, _), _ + | SynPat.As (_, SynPat.Named (SynIdent (id, _), _, access, _), _), _ -> let glyph = if isMember then FSharpGlyph.Method else FSharpGlyph.Field - [ createMember(id, NavigationItemKind.Field, glyph, unionRanges id.idRange m, enclosingEntityKind, isAbstract, access) ] + let m = unionRanges id.idRange m + + [ + createMember (id, NavigationItemKind.Field, glyph, m, enclosingEntityKind, isAbstract, access) + ] | _ -> [] - + // Process a class declaration or F# type declaration - let rec processExnDefnRepr baseName nested (SynExceptionDefnRepr(_, SynUnionCase(ident=SynIdent(id,_); caseType=fldspec), _, _, access, m)) = - // Exception declaration - [ createDecl(baseName, id, NavigationItemKind.Exception, FSharpGlyph.Exception, m, fldspecRange fldspec, nested, NavigationEntityKind.Exception, false, access) ] + let rec processExnDefnRepr baseName nested synExnRepr = + let (SynExceptionDefnRepr (_, ucase, _, _, access, m)) = synExnRepr + let (SynUnionCase (ident = SynIdent (id, _); caseType = fldspec)) = ucase + let mBody = fldspecRange fldspec + + [ + createDecl (baseName, id, NavigationItemKind.Exception, FSharpGlyph.Exception, m, mBody, nested, NavigationEntityKind.Exception, false, access) + ] // Process a class declaration or F# type declaration - and processExnDefn baseName (SynExceptionDefn(repr, _, membDefns, _)) = + and processExnDefn baseName synExnDefn = + let (SynExceptionDefn (repr, _, membDefns, _)) = synExnDefn let nested = processMembers membDefns NavigationEntityKind.Exception |> snd processExnDefnRepr baseName nested repr - and processTycon baseName (SynTypeDefn(typeInfo=SynComponentInfo(longId=lid; accessibility=access); typeRepr=repr; members=membDefns; range=m)) = + and processTycon baseName synTypeDefn = + let (SynTypeDefn (typeInfo = typeInfo; typeRepr = repr; members = membDefns; range = m)) = synTypeDefn + let (SynComponentInfo (longId = lid; accessibility = access)) = typeInfo + let topMembers = processMembers membDefns NavigationEntityKind.Class |> snd + match repr with | SynTypeDefnRepr.Exception repr -> processExnDefnRepr baseName [] repr - | SynTypeDefnRepr.ObjectModel(_, membDefns, mb) -> + + | SynTypeDefnRepr.ObjectModel (_, membDefns, mBody) -> // F# class declaration let members = processMembers membDefns NavigationEntityKind.Class |> snd - let nested = members@topMembers - ([ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Class, m, bodyRange mb nested, nested, NavigationEntityKind.Class, false, access) ]: (NavigationItem * int * _) list) - | SynTypeDefnRepr.Simple(simple, _) -> + let nested = members @ topMembers + let mBody = bodyRange mBody nested + + [ + createTypeDecl (baseName, lid, FSharpGlyph.Class, m, mBody, nested, NavigationEntityKind.Class, access) + ] + + | SynTypeDefnRepr.Simple (simple, _) -> // F# type declaration match simple with - | SynTypeDefnSimpleRepr.Union(_, cases, mb) -> - let cases = - [ for SynUnionCase(ident=SynIdent(id,_); caseType=fldspec) in cases -> - createMember(id, NavigationItemKind.Other, FSharpGlyph.Struct, unionRanges (fldspecRange fldspec) id.idRange, NavigationEntityKind.Union, false, access) ] - let nested = cases@topMembers - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Union, m, bodyRange mb nested, nested, NavigationEntityKind.Union, false, access) ] - | SynTypeDefnSimpleRepr.Enum(cases, mb) -> - let cases = - [ for SynEnumCase(ident=SynIdent(id,_); range=m) in cases -> - createMember(id, NavigationItemKind.Field, FSharpGlyph.EnumMember, m, NavigationEntityKind.Enum, false, access) ] - let nested = cases@topMembers - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Enum, m, bodyRange mb nested, nested, NavigationEntityKind.Enum, false, access) ] - | SynTypeDefnSimpleRepr.Record(_, fields, mb) -> - let fields = - [ for SynField(_, _, id, _, _, _, _, m) in fields do - match id with - | Some ident -> - yield createMember(ident, NavigationItemKind.Field, FSharpGlyph.Field, m, NavigationEntityKind.Record, false, access) - | _ -> - () ] - let nested = fields@topMembers - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Type, m, bodyRange mb nested, nested, NavigationEntityKind.Record, false, access) ] - | SynTypeDefnSimpleRepr.TypeAbbrev(_, _, mb) -> - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Typedef, m, bodyRange mb topMembers, topMembers, NavigationEntityKind.Class, false, access) ] - - //| SynTypeDefnSimpleRepr.General of TyconKind * (SynType * Range * ident option) list * (valSpfn * MemberFlags) list * fieldDecls * bool * bool * Range + | SynTypeDefnSimpleRepr.Union (_, cases, mBody) -> + let cases = + [ + for SynUnionCase (ident = SynIdent (id, _); caseType = fldspec) in cases -> + let mBody = unionRanges (fldspecRange fldspec) id.idRange + createMember (id, NavigationItemKind.Other, FSharpGlyph.Struct, mBody, NavigationEntityKind.Union, false, access) + ] + + let nested = cases @ topMembers + let mBody = bodyRange mBody nested + + [ + createTypeDecl (baseName, lid, FSharpGlyph.Union, m, mBody, nested, NavigationEntityKind.Union, access) + ] + + | SynTypeDefnSimpleRepr.Enum (cases, mBody) -> + let cases = + [ + for SynEnumCase (ident = SynIdent (id, _); range = m) in cases -> + createMember (id, NavigationItemKind.Field, FSharpGlyph.EnumMember, m, NavigationEntityKind.Enum, false, access) + ] + + let nested = cases @ topMembers + let mBody = bodyRange mBody nested + + [ + createTypeDecl (baseName, lid, FSharpGlyph.Enum, m, mBody, nested, NavigationEntityKind.Enum, access) + ] + + | SynTypeDefnSimpleRepr.Record (_, fields, mBody) -> + let fields = + [ + for SynField (_, _, id, _, _, _, _, m) in fields do + match id with + | Some ident -> yield createMember (ident, NavigationItemKind.Field, FSharpGlyph.Field, m, NavigationEntityKind.Record, false, access) + | _ -> () + ] + + let nested = fields @ topMembers + let mBody = bodyRange mBody nested + + [ + createTypeDecl (baseName, lid, FSharpGlyph.Type, m, mBody, nested, NavigationEntityKind.Record, access) + ] + + | SynTypeDefnSimpleRepr.TypeAbbrev (_, _, mBody) -> + let mBody = bodyRange mBody topMembers + + [ + createTypeDecl (baseName, lid, FSharpGlyph.Typedef, m, mBody, topMembers, NavigationEntityKind.Class, access) + ] + + //| SynTypeDefnSimpleRepr.General of TyconKind * (SynType * Range * ident option) list * (valSpfn * MemberFlags) list * fieldDecls * bool * bool * Range //| SynTypeDefnSimpleRepr.LibraryOnlyILAssembly of ILType * Range //| TyconCore_repr_hidden of Range - | _ -> [] - - // Returns class-members for the right dropdown - and processMembers members enclosingEntityKind = - let members = - members - |> List.groupBy (fun x -> x.Range) - |> List.map (fun (range, members) -> - range, - (match members with - | [memb] -> - match memb with - | SynMemberDefn.LetBindings(binds, _, _, _) -> List.collect (processBinding false enclosingEntityKind false) binds - | SynMemberDefn.Member(bind, _) -> processBinding true enclosingEntityKind false bind - | SynMemberDefn.ValField(SynField(_, _, Some(rcid), _, _, _, access, range), _) -> - [ createMember(rcid, NavigationItemKind.Field, FSharpGlyph.Field, range, enclosingEntityKind, false, access) ] - | SynMemberDefn.AutoProperty(ident=id; accessibility=access) -> - [ createMember(id, NavigationItemKind.Field, FSharpGlyph.Field, id.idRange, enclosingEntityKind, false, access) ] - | SynMemberDefn.AbstractSlot(SynValSig(ident=SynIdent(id,_); synType=ty; accessibility=access), _, _) -> - [ createMember(id, NavigationItemKind.Method, FSharpGlyph.OverridenMethod, ty.Range, enclosingEntityKind, true, access) ] - | SynMemberDefn.NestedType _ -> failwith "tycon as member????" //processTycon tycon - | SynMemberDefn.Interface(members=Some(membs)) -> - processMembers membs enclosingEntityKind |> snd - | _ -> [] - // can happen if one is a getter and one is a setter - | [SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(longDotId=lid1; extraId=Some(info1))) as binding1) - SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(longDotId=lid2; extraId=Some(info2))) as binding2)] -> - // ensure same long id - assert((lid1.LongIdent,lid2.LongIdent) ||> List.forall2 (fun x y -> x.idText = y.idText)) - // ensure one is getter, other is setter - assert((info1.idText = "set" && info2.idText = "get") || - (info2.idText = "set" && info1.idText = "get")) - // both binding1 and binding2 have same range, so just try the first one, else try the second one - match processBinding true enclosingEntityKind false binding1 with - | [] -> processBinding true enclosingEntityKind false binding2 - | x -> x - | _ -> [])) - - (members |> Seq.map fst |> Seq.fold unionRangesChecked range.Zero), - (members |> List.collect snd) + | _ -> [] + + // Returns class-members for the right dropdown + and processMembers members enclosingEntityKind = + let members = + members + |> List.map (fun md -> + md.Range, + (match md with + | SynMemberDefn.LetBindings (binds, _, _, _) -> List.collect (processBinding false enclosingEntityKind false) binds + | SynMemberDefn.GetSetMember (Some bind, None, _, _) + | SynMemberDefn.GetSetMember (None, Some bind, _, _) + | SynMemberDefn.Member (bind, _) -> processBinding true enclosingEntityKind false bind + | SynMemberDefn.ValField (SynField (_, _, Some (rcid), _, _, _, access, range), _) -> + [ + createMember (rcid, NavigationItemKind.Field, FSharpGlyph.Field, range, enclosingEntityKind, false, access) + ] + | SynMemberDefn.AutoProperty (ident = id; accessibility = access) -> + [ + createMember (id, NavigationItemKind.Field, FSharpGlyph.Field, id.idRange, enclosingEntityKind, false, access) + ] + | SynMemberDefn.AbstractSlot (SynValSig (ident = SynIdent (id, _); synType = ty; accessibility = access), _, _) -> + [ + createMember (id, NavigationItemKind.Method, FSharpGlyph.OverridenMethod, ty.Range, enclosingEntityKind, true, access) + ] + | SynMemberDefn.NestedType _ -> failwith "tycon as member????" //processTycon tycon + | SynMemberDefn.Interface(members = Some (membs)) -> processMembers membs enclosingEntityKind |> snd + | SynMemberDefn.GetSetMember (Some getBinding, Some setBinding, _, _) -> + [ + yield! processBinding true enclosingEntityKind false getBinding + yield! processBinding true enclosingEntityKind false setBinding + ] + | _ -> [])) + + let m2 = members |> Seq.map fst |> Seq.fold unionRangesChecked range.Zero + let items = members |> List.collect snd + m2, items // Process declarations in a module that belong to the right drop-down (let bindings) - let processNestedDeclarations decls = decls |> List.collect (function - | SynModuleDecl.Let(_, binds, _) -> List.collect (processBinding false NavigationEntityKind.Module false) binds - | _ -> []) + let processNestedDeclarations decls = + [ + for decl in decls do + match decl with + | SynModuleDecl.Let (_, binds, _) -> + for bind in binds do + yield! processBinding false NavigationEntityKind.Module false bind + | _ -> () + ] // Process declarations nested in a module that should be displayed in the left dropdown - // (such as type declarations, nested modules etc.) - let rec processNavigationTopLevelDeclarations(baseName, decls) = decls |> List.collect (function - | SynModuleDecl.ModuleAbbrev(id, lid, m) -> - [ createDecl(baseName, id, NavigationItemKind.Module, FSharpGlyph.Module, m, rangeOfLid lid, [], NavigationEntityKind.Namespace, false, None) ] - - | SynModuleDecl.NestedModule(moduleInfo=SynComponentInfo(longId=lid; accessibility=access); decls=decls; range=m) -> - // Find let bindings (for the right dropdown) - let nested = processNestedDeclarations(decls) - let newBaseName = (if (baseName = "") then "" else baseName+".") + (textOfLid lid) - - // Get nested modules and types (for the left dropdown) - let other = processNavigationTopLevelDeclarations(newBaseName, decls) - createDeclLid(baseName, lid, NavigationItemKind.Module, FSharpGlyph.Module, m, unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid lid) other), nested, NavigationEntityKind.Module, false, access) :: other - - | SynModuleDecl.Types(tydefs, _) -> tydefs |> List.collect (processTycon baseName) - | SynModuleDecl.Exception (defn,_) -> processExnDefn baseName defn - | _ -> []) - - // Collect all the items - let items = + // (such as type declarations, nested modules etc.) + let rec processNavigationTopLevelDeclarations (baseName, decls) = + [ + for decl in decls do + match decl with + | SynModuleDecl.ModuleAbbrev (id, lid, m) -> + let mBody = rangeOfLid lid + createDecl (baseName, id, NavigationItemKind.Module, FSharpGlyph.Module, m, mBody, [], NavigationEntityKind.Namespace, false, None) + + | SynModuleDecl.NestedModule (moduleInfo = SynComponentInfo (longId = lid; accessibility = access); decls = decls; range = m) -> + // Find let bindings (for the right dropdown) + let nested = processNestedDeclarations (decls) + let newBaseName = (if (baseName = "") then "" else baseName + ".") + (textOfLid lid) + let other = processNavigationTopLevelDeclarations (newBaseName, decls) + + let mBody = unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid lid) other) + createDeclLid (baseName, lid, NavigationItemKind.Module, FSharpGlyph.Module, m, mBody, nested, NavigationEntityKind.Module, access) + // Get nested modules and types (for the left dropdown) + yield! other + + | SynModuleDecl.Types (tydefs, _) -> + for tydef in tydefs do + yield! processTycon baseName tydef + | SynModuleDecl.Exception (defn, _) -> yield! processExnDefn baseName defn + | _ -> () + ] + + // Collect all the items + let items = // Show base name for this module only if it's not the root one let singleTopLevel = (modules.Length = 1) - modules |> List.collect (fun (SynModuleOrNamespace(id, _isRec, kind, decls, _, _, access, m, _)) -> - let baseName = if (not singleTopLevel) then textOfLid id else "" - // Find let bindings (for the right dropdown) - let nested = processNestedDeclarations(decls) - // Get nested modules and types (for the left dropdown) - let other = processNavigationTopLevelDeclarations(baseName, decls) - - // Create explicitly - it can be 'single top level' thing that is hidden - match id with - | [] -> other - | _ -> - let decl = - NavigationItem.Create - (textOfLid id, (if kind.IsModule then NavigationItemKind.ModuleFile else NavigationItemKind.Namespace), - FSharpGlyph.Module, m, - unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid id) other), - singleTopLevel, NavigationEntityKind.Module, false, access), (addItemName(textOfLid id)), nested - decl :: other) - - let items = - items - |> Array.ofList - |> Array.map (fun (d, idx, nest) -> - let nest = nest |> Array.ofList |> Array.map (fun (decl, idx) -> decl.WithUniqueName(uniqueName d.Name idx)) - nest |> Array.sortInPlaceWith (fun a b -> compare a.Name b.Name) - { Declaration = d.WithUniqueName(uniqueName d.Name idx); Nested = nest } ) - items |> Array.sortInPlaceWith (fun a b -> compare a.Declaration.Name b.Declaration.Name) + + [ + for modul in modules do + let (SynModuleOrNamespace (id, _isRec, kind, decls, _, _, access, m, _)) = modul + let baseName = if (not singleTopLevel) then textOfLid id else "" + // Find let bindings (for the right dropdown) + let nested = processNestedDeclarations (decls) + // Get nested modules and types (for the left dropdown) + let other = processNavigationTopLevelDeclarations (baseName, decls) + + // Create explicitly - it can be 'single top level' thing that is hidden + if not (List.isEmpty id) then + let kind = + if kind.IsModule then + NavigationItemKind.ModuleFile + else + NavigationItemKind.Namespace + + let mBody = unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid id) other) + let nm = textOfLid id + + let item = + NavigationItem.Create(nm, kind, FSharpGlyph.Module, m, mBody, singleTopLevel, NavigationEntityKind.Module, false, access) + + let decl = (item, addItemName (nm), nested) + decl + + yield! other + ] + + let items = + [| + for (d, idx, nested) in items do + let nested = + nested + |> Array.ofList + |> Array.map (fun (decl, idx) -> decl.WithUniqueName(uniqueName d.Name idx)) + + nested |> Array.sortInPlaceWith (fun a b -> compare a.Name b.Name) + + { + Declaration = d.WithUniqueName(uniqueName d.Name idx) + Nested = nested + } + |] + + items + |> Array.sortInPlaceWith (fun a b -> compare a.Declaration.Name b.Declaration.Name) + NavigationItems(items) - /// Get information for signature file + /// Get information for signature file let getNavigationFromSigFile (modules: SynModuleOrNamespaceSig list) = // Map for dealing with name conflicts - let mutable nameMap = Map.empty - let addItemName name = + let mutable nameMap = Map.empty + + let addItemName name = let count = defaultArg (nameMap |> Map.tryFind name) 0 nameMap <- (Map.add name (count + 1) nameMap) (count + 1) - let uniqueName name idx = + + let uniqueName name idx = let total = Map.find name nameMap sprintf "%s_%d_of_%d" name idx total - // Create declaration (for the left dropdown) - let createDeclLid(baseName, lid, kind, baseGlyph, m, bodym, nested, enclosingEntityKind, isAbstract, access) = + // Create declaration (for the left dropdown) + let createDeclLid (baseName, lid, kind, baseGlyph, m, mBody, nested, enclosingEntityKind, access) = let name = (if baseName <> "" then baseName + "." else "") + (textOfLid lid) - NavigationItem.Create - (name, kind, baseGlyph, m, bodym, false, enclosingEntityKind, isAbstract, access), (addItemName name), nested - - let createDecl(baseName, id:Ident, kind, baseGlyph, m, bodym, nested, enclosingEntityKind, isAbstract, access) = + let item = NavigationItem.Create(name, kind, baseGlyph, m, mBody, false, enclosingEntityKind, false, access) + item, addItemName name, nested + + let createTypeDecl (baseName, lid, baseGlyph, m, mBody, nested, enclosingEntityKind, access) = + createDeclLid (baseName, lid, NavigationItemKind.Type, baseGlyph, m, mBody, nested, enclosingEntityKind, access) + + let createDecl (baseName, id: Ident, kind, baseGlyph, m, mBody, nested, enclosingEntityKind, isAbstract, access) = let name = (if baseName <> "" then baseName + "." else "") + id.idText - NavigationItem.Create - (name, kind, baseGlyph, m, bodym, false, enclosingEntityKind, isAbstract, access), (addItemName name), nested - - let createMember(id:Ident, kind, baseGlyph, m, enclosingEntityKind, isAbstract, access) = - NavigationItem.Create(id.idText, kind, baseGlyph, m, m, false, enclosingEntityKind, isAbstract, access), (addItemName(id.idText)) - - let rec processExnRepr baseName nested (SynExceptionDefnRepr(_, SynUnionCase(ident=SynIdent(id,_); caseType=fldspec), _, _, access, m)) = - // Exception declaration - [ createDecl(baseName, id, NavigationItemKind.Exception, FSharpGlyph.Exception, m, fldspecRange fldspec, nested, NavigationEntityKind.Exception, false, access) ] - - and processExnSig baseName (SynExceptionSig(exnRepr=repr; members=memberSigs)) = + let item = NavigationItem.Create(name, kind, baseGlyph, m, mBody, false, enclosingEntityKind, isAbstract, access) + item, addItemName name, nested + + let createMember (id: Ident, kind, baseGlyph, m, enclosingEntityKind, isAbstract, access) = + let item = NavigationItem.Create(id.idText, kind, baseGlyph, m, m, false, enclosingEntityKind, isAbstract, access) + item, addItemName (id.idText) + + let rec processExnRepr baseName nested inp = + let (SynExceptionDefnRepr (_, SynUnionCase (ident = SynIdent (id, _); caseType = fldspec), _, _, access, m)) = inp + let mBody = fldspecRange fldspec + + [ + createDecl (baseName, id, NavigationItemKind.Exception, FSharpGlyph.Exception, m, mBody, nested, NavigationEntityKind.Exception, false, access) + ] + + and processExnSig baseName inp = + let (SynExceptionSig (exnRepr = repr; members = memberSigs)) = inp let nested = processSigMembers memberSigs processExnRepr baseName nested repr - and processTycon baseName (SynTypeDefnSig(typeInfo=SynComponentInfo(longId=lid; accessibility=access); typeRepr=repr; members=membDefns; range=m)) = + and processTycon baseName inp = + let (SynTypeDefnSig (typeInfo = SynComponentInfo (longId = lid; accessibility = access); typeRepr = repr; members = membDefns; range = m)) = + inp + let topMembers = processSigMembers membDefns - match repr with - | SynTypeDefnSigRepr.Exception repr -> processExnRepr baseName [] repr - | SynTypeDefnSigRepr.ObjectModel(_, membDefns, mb) -> - // F# class declaration - let members = processSigMembers membDefns - let nested = members @ topMembers - ([ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Class, m, bodyRange mb nested, nested, NavigationEntityKind.Class, false, access) ]: (NavigationItem * int * _) list) - | SynTypeDefnSigRepr.Simple(simple, _) -> - // F# type declaration - match simple with - | SynTypeDefnSimpleRepr.Union(_, cases, mb) -> - let cases = - [ for SynUnionCase(ident=SynIdent(id,_); caseType=fldspec) in cases -> - createMember(id, NavigationItemKind.Other, FSharpGlyph.Struct, unionRanges (fldspecRange fldspec) id.idRange, NavigationEntityKind.Union, false, access) ] - let nested = cases@topMembers - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Union, m, bodyRange mb nested, nested, NavigationEntityKind.Union, false, access) ] - | SynTypeDefnSimpleRepr.Enum(cases, mb) -> - let cases = - [ for SynEnumCase(ident = SynIdent(id,_); range = m) in cases -> - createMember(id, NavigationItemKind.Field, FSharpGlyph.EnumMember, m, NavigationEntityKind.Enum, false, access) ] - let nested = cases@topMembers - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Enum, m, bodyRange mb nested, nested, NavigationEntityKind.Enum, false, access) ] - | SynTypeDefnSimpleRepr.Record(_, fields, mb) -> - let fields = - [ for SynField(_, _, id, _, _, _, _, m) in fields do - match id with - | Some ident -> - yield createMember(ident, NavigationItemKind.Field, FSharpGlyph.Field, m, NavigationEntityKind.Record, false, access) - | _ -> - () ] - let nested = fields@topMembers - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Type, m, bodyRange mb nested, nested, NavigationEntityKind.Record, false, access) ] - | SynTypeDefnSimpleRepr.TypeAbbrev(_, _, mb) -> - [ createDeclLid(baseName, lid, NavigationItemKind.Type, FSharpGlyph.Typedef, m, bodyRange mb topMembers, topMembers, NavigationEntityKind.Class, false, access) ] - - //| SynTypeDefnSimpleRepr.General of TyconKind * (SynType * range * ident option) list * (valSpfn * MemberFlags) list * fieldDecls * bool * bool * range - //| SynTypeDefnSimpleRepr.LibraryOnlyILAssembly of ILType * range - //| TyconCore_repr_hidden of range - | _ -> [] - - and processSigMembers (members: SynMemberSig list) = - [ for memb in members do - match memb with - | SynMemberSig.Member(SynValSig.SynValSig(ident=SynIdent(id,_); accessibility=access; range=m), _, _) -> - yield createMember(id, NavigationItemKind.Method, FSharpGlyph.Method, m, NavigationEntityKind.Class, false, access) - | SynMemberSig.ValField(SynField(_, _, Some(rcid), ty, _, _, access, _), _) -> - yield createMember(rcid, NavigationItemKind.Field, FSharpGlyph.Field, ty.Range, NavigationEntityKind.Class, false, access) - | _ -> () ] + + [ + match repr with + | SynTypeDefnSigRepr.Exception repr -> yield! processExnRepr baseName [] repr + | SynTypeDefnSigRepr.ObjectModel (_, membDefns, mBody) -> + // F# class declaration + let members = processSigMembers membDefns + let nested = members @ topMembers + let mBody = bodyRange mBody nested + createTypeDecl (baseName, lid, FSharpGlyph.Class, m, mBody, nested, NavigationEntityKind.Class, access) + | SynTypeDefnSigRepr.Simple (simple, _) -> + // F# type declaration + match simple with + | SynTypeDefnSimpleRepr.Union (_, cases, mBody) -> + let cases = + [ + for SynUnionCase (ident = SynIdent (id, _); caseType = fldspec) in cases -> + let m = unionRanges (fldspecRange fldspec) id.idRange + createMember (id, NavigationItemKind.Other, FSharpGlyph.Struct, m, NavigationEntityKind.Union, false, access) + ] + + let nested = cases @ topMembers + let mBody = bodyRange mBody nested + createTypeDecl (baseName, lid, FSharpGlyph.Union, m, mBody, nested, NavigationEntityKind.Union, access) + | SynTypeDefnSimpleRepr.Enum (cases, mBody) -> + let cases = + [ + for SynEnumCase (ident = SynIdent (id, _); range = m) in cases -> + createMember (id, NavigationItemKind.Field, FSharpGlyph.EnumMember, m, NavigationEntityKind.Enum, false, access) + ] + + let nested = cases @ topMembers + let mBody = bodyRange mBody nested + createTypeDecl (baseName, lid, FSharpGlyph.Enum, m, mBody, nested, NavigationEntityKind.Enum, access) + | SynTypeDefnSimpleRepr.Record (_, fields, mBody) -> + let fields = + [ + for SynField (_, _, id, _, _, _, _, m) in fields do + match id with + | Some ident -> yield createMember (ident, NavigationItemKind.Field, FSharpGlyph.Field, m, NavigationEntityKind.Record, false, access) + | _ -> () + ] + + let nested = fields @ topMembers + let mBody = bodyRange mBody nested + createTypeDecl (baseName, lid, FSharpGlyph.Type, m, mBody, nested, NavigationEntityKind.Record, access) + | SynTypeDefnSimpleRepr.TypeAbbrev (_, _, mBody) -> + let mBody = bodyRange mBody topMembers + createTypeDecl (baseName, lid, FSharpGlyph.Typedef, m, mBody, topMembers, NavigationEntityKind.Class, access) + + //| SynTypeDefnSimpleRepr.General of TyconKind * (SynType * range * ident option) list * (valSpfn * MemberFlags) list * fieldDecls * bool * bool * range + //| SynTypeDefnSimpleRepr.LibraryOnlyILAssembly of ILType * range + //| TyconCore_repr_hidden of range + | _ -> () + ] + + and processSigMembers (members: SynMemberSig list) = + [ + for memb in members do + match memb with + | SynMemberSig.Member (SynValSig.SynValSig (ident = SynIdent (id, _); accessibility = access; range = m), _, _) -> + createMember (id, NavigationItemKind.Method, FSharpGlyph.Method, m, NavigationEntityKind.Class, false, access) + | SynMemberSig.ValField (SynField (_, _, Some (rcid), ty, _, _, access, _), _) -> + createMember (rcid, NavigationItemKind.Field, FSharpGlyph.Field, ty.Range, NavigationEntityKind.Class, false, access) + | _ -> () + ] // Process declarations in a module that belong to the right drop-down (let bindings) let processNestedSigDeclarations decls = - decls |> List.collect (fun decl -> - match decl with - | SynModuleSigDecl.Val(SynValSig.SynValSig(ident=SynIdent(id,_); accessibility=access; range=m), _) -> - [ createMember(id, NavigationItemKind.Method, FSharpGlyph.Method, m, NavigationEntityKind.Module, false, access) ] - | _ -> [] ) + [ + for decl in decls do + match decl with + | SynModuleSigDecl.Val (SynValSig.SynValSig (ident = SynIdent (id, _); accessibility = access; range = m), _) -> + createMember (id, NavigationItemKind.Method, FSharpGlyph.Method, m, NavigationEntityKind.Module, false, access) + | _ -> () + ] // Process declarations nested in a module that should be displayed in the left dropdown - // (such as type declarations, nested modules etc.) - let rec processNavigationTopLevelSigDeclarations(baseName, decls) = - decls |> List.collect (fun decl -> - match decl with - | SynModuleSigDecl.ModuleAbbrev(id, lid, m) -> - [ createDecl(baseName, id, NavigationItemKind.Module, FSharpGlyph.Module, m, rangeOfLid lid, [], NavigationEntityKind.Module, false, None) ] - - | SynModuleSigDecl.NestedModule(moduleInfo=SynComponentInfo(longId=lid; accessibility=access); moduleDecls=decls; range=m) -> - // Find let bindings (for the right dropdown) - let nested = processNestedSigDeclarations(decls) - let newBaseName = (if baseName = "" then "" else baseName + ".") + (textOfLid lid) - - // Get nested modules and types (for the left dropdown) - let other = processNavigationTopLevelSigDeclarations(newBaseName, decls) - createDeclLid(baseName, lid, NavigationItemKind.Module, FSharpGlyph.Module, m, unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid lid) other), nested, NavigationEntityKind.Module, false, access) :: other - - | SynModuleSigDecl.Types(tydefs, _) -> tydefs |> List.collect (processTycon baseName) - | SynModuleSigDecl.Exception (defn,_) -> processExnSig baseName defn - | _ -> []) - - // Collect all the items - let items = + // (such as type declarations, nested modules etc.) + let rec processNavigationTopLevelSigDeclarations (baseName, decls) = + [ + for decl in decls do + match decl with + | SynModuleSigDecl.ModuleAbbrev (id, lid, m) -> + let mBody = rangeOfLid lid + createDecl (baseName, id, NavigationItemKind.Module, FSharpGlyph.Module, m, mBody, [], NavigationEntityKind.Module, false, None) + + | SynModuleSigDecl.NestedModule (moduleInfo = SynComponentInfo (longId = lid; accessibility = access); moduleDecls = decls; range = m) -> + // Find let bindings (for the right dropdown) + let nested = processNestedSigDeclarations (decls) + let newBaseName = (if baseName = "" then "" else baseName + ".") + (textOfLid lid) + let other = processNavigationTopLevelSigDeclarations (newBaseName, decls) + + // Get nested modules and types (for the left dropdown) + let mBody = unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid lid) other) + createDeclLid (baseName, lid, NavigationItemKind.Module, FSharpGlyph.Module, m, mBody, nested, NavigationEntityKind.Module, access) + yield! other + + | SynModuleSigDecl.Types (tydefs, _) -> + for tydef in tydefs do + yield! processTycon baseName tydef + | SynModuleSigDecl.Exception (defn, _) -> yield! processExnSig baseName defn + | _ -> () + ] + + // Collect all the items + let items = // Show base name for this module only if it's not the root one let singleTopLevel = (modules.Length = 1) - modules |> List.collect (fun modulSig -> - let (SynModuleOrNamespaceSig(id, _isRec, kind, decls, _, _, access, m, _)) = modulSig - let baseName = if (not singleTopLevel) then textOfLid id else "" - // Find let bindings (for the right dropdown) - let nested = processNestedSigDeclarations(decls) - // Get nested modules and types (for the left dropdown) - let other = processNavigationTopLevelSigDeclarations(baseName, decls) - - // Create explicitly - it can be 'single top level' thing that is hidden - let decl = - NavigationItem.Create - (textOfLid id, (if kind.IsModule then NavigationItemKind.ModuleFile else NavigationItemKind.Namespace), - FSharpGlyph.Module, m, - unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid id) other), - singleTopLevel, NavigationEntityKind.Module, false, access), (addItemName(textOfLid id)), nested - decl :: other) - - let items = - items - |> Array.ofList - |> Array.map (fun (d, idx, nest) -> - let nest = nest |> Array.ofList |> Array.map (fun (decl, idx) -> decl.WithUniqueName(uniqueName d.Name idx)) - nest |> Array.sortInPlaceWith (fun a b -> compare a.Name b.Name) - let nest = nest |> Array.distinctBy (fun x -> x.Range, x.BodyRange, x.Name, x.Kind) - - { Declaration = d.WithUniqueName(uniqueName d.Name idx); Nested = nest } ) - items |> Array.sortInPlaceWith (fun a b -> compare a.Declaration.Name b.Declaration.Name) + + [ + for modulSig in modules do + let (SynModuleOrNamespaceSig (id, _isRec, kind, decls, _, _, access, m, _)) = modulSig + let baseName = if (not singleTopLevel) then textOfLid id else "" + // Find let bindings (for the right dropdown) + let nested = processNestedSigDeclarations (decls) + // Get nested modules and types (for the left dropdown) + let other = processNavigationTopLevelSigDeclarations (baseName, decls) + + // Create explicitly - it can be 'single top level' thing that is hidden + let kind = + if kind.IsModule then + NavigationItemKind.ModuleFile + else + NavigationItemKind.Namespace + + let mBody = unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid id) other) + + let item = + NavigationItem.Create(textOfLid id, kind, FSharpGlyph.Module, m, mBody, singleTopLevel, NavigationEntityKind.Module, false, access) + + let decl = (item, addItemName (textOfLid id), nested) + decl + yield! other + ] + + let items = + [| + for (d, idx, nested) in items do + let nested = + nested + |> Array.ofList + |> Array.map (fun (decl, idx) -> decl.WithUniqueName(uniqueName d.Name idx)) + + nested |> Array.sortInPlaceWith (fun a b -> compare a.Name b.Name) + + let nested = nested |> Array.distinctBy (fun x -> x.Range, x.BodyRange, x.Name, x.Kind) + + { + Declaration = d.WithUniqueName(uniqueName d.Name idx) + Nested = nested + } + |] + + items + |> Array.sortInPlaceWith (fun a b -> compare a.Declaration.Name b.Declaration.Name) + NavigationItems(items) [] @@ -482,8 +678,9 @@ type NavigableItemKind = | Member | EnumCase | UnionCase + override x.ToString() = sprintf "%+A" x - + [] type NavigableContainerType = | File @@ -493,71 +690,96 @@ type NavigableContainerType = | Exception type NavigableContainer = - { Type: NavigableContainerType - Name: string } - -type NavigableItem = - { Name: string - Range: range - IsSignature: bool - Kind: NavigableItemKind - Container: NavigableContainer } - + { + Type: NavigableContainerType + Name: string + } + +type NavigableItem = + { + Name: string + Range: range + IsSignature: bool + Kind: NavigableItemKind + Container: NavigableContainer + } + [] module NavigateTo = - let GetNavigableItems (parsedInput: ParsedInput) : NavigableItem [] = - let rec lastInLid (lid: LongIdent) = + let GetNavigableItems (parsedInput: ParsedInput) : NavigableItem[] = + let rec lastInLid (lid: LongIdent) = match lid with - | [x] -> Some x + | [ x ] -> Some x | _ :: xs -> lastInLid xs | _ -> None // empty lid is possible in case of broken ast - let formatLongIdent (lid: LongIdent) = lid |> List.map (fun id -> id.idText) |> String.concat "." + let formatLongIdent (lid: LongIdent) = + lid |> List.map (fun id -> id.idText) |> String.concat "." + let result = ResizeArray() - - let addIdent kind (id: Ident) (isSignature: bool) (container: NavigableContainer) = + + let addIdent kind (id: Ident) (isSignature: bool) (container: NavigableContainer) = if not (String.IsNullOrEmpty id.idText) then - let item = - { Name = id.idText - Range = id.idRange - IsSignature = isSignature - Kind = kind - Container = container } + let item = + { + Name = id.idText + Range = id.idRange + IsSignature = isSignature + Kind = kind + Container = container + } + result.Add item - - let addModule lid isSig container = + + let addModule lid isSig container = match lastInLid lid with | Some id -> addIdent NavigableItemKind.Module id isSig container | _ -> () - + let addModuleAbbreviation (id: Ident) isSig container = addIdent NavigableItemKind.ModuleAbbreviation id isSig container - - let addExceptionRepr (SynExceptionDefnRepr(_, SynUnionCase(ident=SynIdent(id,_)), _, _, _, _)) isSig container = + + let addExceptionRepr exnRepr isSig container = + let (SynExceptionDefnRepr (_, SynUnionCase(ident = SynIdent (id, _)), _, _, _, _)) = exnRepr addIdent NavigableItemKind.Exception id isSig container - { Type = NavigableContainerType.Exception; Name = id.idText } - - let addComponentInfo containerType kind (SynComponentInfo(_, _, _, lid, _, _, _, _)) isSig container = + + { + Type = NavigableContainerType.Exception + Name = id.idText + } + + let addComponentInfo containerType kind info isSig container = + let (SynComponentInfo (_, _, _, lid, _, _, _, _)) = info + match lastInLid lid with | Some id -> addIdent kind id isSig container | _ -> () - { Type = containerType; Name = formatLongIdent lid } - - let addValSig kind (SynValSig(ident=SynIdent(id,_))) isSig container = + + { + Type = containerType + Name = formatLongIdent lid + } + + let addValSig kind synValSig isSig container = + let (SynValSig(ident = SynIdent (id, _))) = synValSig addIdent kind id isSig container - - let addField(SynField(_, _, id, _, _, _, _, _)) isSig container = + + let addField synField isSig container = + let (SynField (_, _, id, _, _, _, _, _)) = synField + match id with | Some id -> addIdent NavigableItemKind.Field id isSig container | _ -> () - - let addEnumCase(SynEnumCase(ident=SynIdent(id,_))) isSig = + + let addEnumCase inp isSig = + let (SynEnumCase(ident = SynIdent (id, _))) = inp addIdent NavigableItemKind.EnumCase id isSig - - let addUnionCase(SynUnionCase(ident=SynIdent(id,_))) isSig container = + + let addUnionCase synUnionCase isSig container = + let (SynUnionCase(ident = SynIdent (id, _))) = synUnionCase addIdent NavigableItemKind.UnionCase id isSig container - - let mapMemberKind mk = + + let mapMemberKind mk = match mk with | SynMemberKind.ClassConstructor // ? | SynMemberKind.Constructor -> NavigableItemKind.Constructor @@ -565,9 +787,11 @@ module NavigateTo = | SynMemberKind.PropertySet | SynMemberKind.PropertyGetSet -> NavigableItemKind.Property | SynMemberKind.Member -> NavigableItemKind.Member - - let addBinding (SynBinding(valData=valData; headPat=headPat)) itemKind container = - let (SynValData(memberFlagsOpt, _, _)) = valData + + let addBinding synBinding itemKind container = + let (SynBinding (valData = valData; headPat = headPat)) = synBinding + let (SynValData (memberFlagsOpt, _, _)) = valData + let kind = match itemKind with | Some x -> x @@ -575,145 +799,177 @@ module NavigateTo = match memberFlagsOpt with | Some mf -> mapMemberKind mf.MemberKind | _ -> NavigableItemKind.ModuleValue - + match headPat with - | SynPat.LongIdent(longDotId=SynLongIdent([_; id], _,_)) -> + | SynPat.LongIdent(longDotId = SynLongIdent ([ _; id ], _, _)) -> // instance members addIdent kind id false container - | SynPat.LongIdent(longDotId=SynLongIdent([id], _,_)) -> + | SynPat.LongIdent(longDotId = SynLongIdent ([ id ], _, _)) -> // functions addIdent kind id false container - | SynPat.Named (SynIdent(id,_), _, _, _) | SynPat.As(_, SynPat.Named (SynIdent(id,_), _, _, _), _) -> + | SynPat.Named (SynIdent (id, _), _, _, _) + | SynPat.As (_, SynPat.Named (SynIdent (id, _), _, _, _), _) -> // values addIdent kind id false container | _ -> () - - let addMember valSig (memberFlags: SynMemberFlags) isSig container = + + let addMember valSig (memberFlags: SynMemberFlags) isSig container = let ctor = mapMemberKind memberFlags.MemberKind addValSig ctor valSig isSig container - - let rec walkSigFileInput (ParsedSigFileInput (fileName = fileName; modules = moduleOrNamespaceList)) = + + let rec walkSigFileInput (inp: ParsedSigFileInput) = + let (ParsedSigFileInput (fileName = fileName; modules = moduleOrNamespaceList)) = inp + for item in moduleOrNamespaceList do - walkSynModuleOrNamespaceSig item { Type = NavigableContainerType.File; Name = fileName } - - and walkSynModuleOrNamespaceSig (SynModuleOrNamespaceSig(longId = lid; kind = kind; decls = decls)) container = + walkSynModuleOrNamespaceSig + item + { + Type = NavigableContainerType.File + Name = fileName + } + + and walkSynModuleOrNamespaceSig (inp: SynModuleOrNamespaceSig) container = + let (SynModuleOrNamespaceSig (longId = lid; kind = kind; decls = decls)) = inp let isModule = kind.IsModule + if isModule then addModule lid true container - let container = - { Type = if isModule then NavigableContainerType.Module else NavigableContainerType.Namespace - Name = formatLongIdent lid } + + let container = + { + Type = + if isModule then + NavigableContainerType.Module + else + NavigableContainerType.Namespace + Name = formatLongIdent lid + } + for decl in decls do walkSynModuleSigDecl decl container - - and walkSynModuleSigDecl(decl: SynModuleSigDecl) container = + + and walkSynModuleSigDecl (decl: SynModuleSigDecl) container = match decl with - | SynModuleSigDecl.ModuleAbbrev(lhs, _, _range) -> - addModuleAbbreviation lhs true container - | SynModuleSigDecl.Exception(exnSig=SynExceptionSig(exnRepr=representation)) -> - addExceptionRepr representation true container |> ignore - | SynModuleSigDecl.NamespaceFragment fragment -> - walkSynModuleOrNamespaceSig fragment container - | SynModuleSigDecl.NestedModule(moduleInfo=componentInfo; moduleDecls=nestedDecls) -> + | SynModuleSigDecl.ModuleAbbrev (lhs, _, _range) -> addModuleAbbreviation lhs true container + | SynModuleSigDecl.Exception(exnSig = SynExceptionSig (exnRepr = representation)) -> addExceptionRepr representation true container |> ignore + | SynModuleSigDecl.NamespaceFragment fragment -> walkSynModuleOrNamespaceSig fragment container + | SynModuleSigDecl.NestedModule (moduleInfo = componentInfo; moduleDecls = nestedDecls) -> let container = addComponentInfo NavigableContainerType.Module NavigableItemKind.Module componentInfo true container + for decl in nestedDecls do walkSynModuleSigDecl decl container - | SynModuleSigDecl.Types(types, _) -> + | SynModuleSigDecl.Types (types, _) -> for ty in types do walkSynTypeDefnSig ty container - | SynModuleSigDecl.Val(valSig, _range) -> - addValSig NavigableItemKind.ModuleValue valSig true container + | SynModuleSigDecl.Val (valSig, _range) -> addValSig NavigableItemKind.ModuleValue valSig true container | SynModuleSigDecl.HashDirective _ | SynModuleSigDecl.Open _ -> () - - and walkSynTypeDefnSig (SynTypeDefnSig(typeInfo=componentInfo; typeRepr=repr; members=members)) container = + + and walkSynTypeDefnSig (inp: SynTypeDefnSig) container = + let (SynTypeDefnSig (typeInfo = componentInfo; typeRepr = repr; members = members)) = inp let container = addComponentInfo NavigableContainerType.Type NavigableItemKind.Type componentInfo true container + for m in members do walkSynMemberSig m container + match repr with - | SynTypeDefnSigRepr.ObjectModel(_, membersSigs, _) -> + | SynTypeDefnSigRepr.ObjectModel (_, membersSigs, _) -> for m in membersSigs do walkSynMemberSig m container - | SynTypeDefnSigRepr.Simple(repr, _) -> - walkSynTypeDefnSimpleRepr repr true container + | SynTypeDefnSigRepr.Simple (repr, _) -> walkSynTypeDefnSimpleRepr repr true container | SynTypeDefnSigRepr.Exception _ -> () - - and walkSynMemberSig (synMemberSig: SynMemberSig) container = + + and walkSynMemberSig (synMemberSig: SynMemberSig) container = match synMemberSig with - | SynMemberSig.Member(valSig, memberFlags, _) -> - addMember valSig memberFlags true container - | SynMemberSig.ValField(synField, _) -> - addField synField true container - | SynMemberSig.NestedType(synTypeDef, _) -> - walkSynTypeDefnSig synTypeDef container + | SynMemberSig.Member (valSig, memberFlags, _) -> addMember valSig memberFlags true container + | SynMemberSig.ValField (synField, _) -> addField synField true container + | SynMemberSig.NestedType (synTypeDef, _) -> walkSynTypeDefnSig synTypeDef container | SynMemberSig.Inherit _ | SynMemberSig.Interface _ -> () - - and walkImplFileInput (ParsedImplFileInput (fileName = fileName; modules = moduleOrNamespaceList)) = - let container = { Type = NavigableContainerType.File; Name = fileName } + + and walkImplFileInput (inp: ParsedImplFileInput) = + let (ParsedImplFileInput (fileName = fileName; modules = moduleOrNamespaceList)) = inp + + let container = + { + Type = NavigableContainerType.File + Name = fileName + } + for item in moduleOrNamespaceList do walkSynModuleOrNamespace item container - - and walkSynModuleOrNamespace(SynModuleOrNamespace(longId = lid; kind = kind; decls = decls)) container = + + and walkSynModuleOrNamespace inp container = + let (SynModuleOrNamespace (longId = lid; kind = kind; decls = decls)) = inp let isModule = kind.IsModule + if isModule then addModule lid false container - let container = - { Type = if isModule then NavigableContainerType.Module else NavigableContainerType.Namespace - Name = formatLongIdent lid } + + let container = + { + Type = + if isModule then + NavigableContainerType.Module + else + NavigableContainerType.Namespace + Name = formatLongIdent lid + } + for decl in decls do walkSynModuleDecl decl container - - and walkSynModuleDecl(decl: SynModuleDecl) container = + + and walkSynModuleDecl (decl: SynModuleDecl) container = match decl with - | SynModuleDecl.Exception(SynExceptionDefn(repr, _, synMembers, _), _) -> + | SynModuleDecl.Exception (SynExceptionDefn (repr, _, synMembers, _), _) -> let container = addExceptionRepr repr false container + for m in synMembers do walkSynMemberDefn m container - | SynModuleDecl.Let(_, bindings, _) -> + | SynModuleDecl.Let (_, bindings, _) -> for binding in bindings do addBinding binding None container - | SynModuleDecl.ModuleAbbrev(lhs, _, _) -> - addModuleAbbreviation lhs false container - | SynModuleDecl.NamespaceFragment(fragment) -> - walkSynModuleOrNamespace fragment container - | SynModuleDecl.NestedModule(moduleInfo=componentInfo; decls=modules) -> + | SynModuleDecl.ModuleAbbrev (lhs, _, _) -> addModuleAbbreviation lhs false container + | SynModuleDecl.NamespaceFragment (fragment) -> walkSynModuleOrNamespace fragment container + | SynModuleDecl.NestedModule (moduleInfo = componentInfo; decls = modules) -> let container = addComponentInfo NavigableContainerType.Module NavigableItemKind.Module componentInfo false container + for m in modules do walkSynModuleDecl m container - | SynModuleDecl.Types(typeDefs, _range) -> + | SynModuleDecl.Types (typeDefs, _range) -> for t in typeDefs do walkSynTypeDefn t container | SynModuleDecl.Attributes _ | SynModuleDecl.Expr _ | SynModuleDecl.HashDirective _ | SynModuleDecl.Open _ -> () - - and walkSynTypeDefn(SynTypeDefn(typeInfo=componentInfo; typeRepr=representation; members=members)) container = + + and walkSynTypeDefn inp container = + let (SynTypeDefn (typeInfo = componentInfo; typeRepr = representation; members = members)) = inp let container = addComponentInfo NavigableContainerType.Type NavigableItemKind.Type componentInfo false container walkSynTypeDefnRepr representation container + for m in members do walkSynMemberDefn m container - - and walkSynTypeDefnRepr(typeDefnRepr: SynTypeDefnRepr) container = + + and walkSynTypeDefnRepr (typeDefnRepr: SynTypeDefnRepr) container = match typeDefnRepr with - | SynTypeDefnRepr.ObjectModel(_, members, _) -> + | SynTypeDefnRepr.ObjectModel (_, members, _) -> for m in members do walkSynMemberDefn m container - | SynTypeDefnRepr.Simple(repr, _) -> - walkSynTypeDefnSimpleRepr repr false container + | SynTypeDefnRepr.Simple (repr, _) -> walkSynTypeDefnSimpleRepr repr false container | SynTypeDefnRepr.Exception _ -> () - - and walkSynTypeDefnSimpleRepr(repr: SynTypeDefnSimpleRepr) isSig container = + + and walkSynTypeDefnSimpleRepr (repr: SynTypeDefnSimpleRepr) isSig container = match repr with - | SynTypeDefnSimpleRepr.Enum(enumCases, _) -> + | SynTypeDefnSimpleRepr.Enum (enumCases, _) -> for c in enumCases do addEnumCase c isSig container - | SynTypeDefnSimpleRepr.Record(_, fields, _) -> + | SynTypeDefnSimpleRepr.Record (_, fields, _) -> for f in fields do // TODO: add specific case for record field? addField f isSig container - | SynTypeDefnSimpleRepr.Union(_, unionCases, _) -> + | SynTypeDefnSimpleRepr.Union (_, unionCases, _) -> for uc in unionCases do addUnionCase uc isSig container | SynTypeDefnSimpleRepr.General _ @@ -721,27 +977,26 @@ module NavigateTo = | SynTypeDefnSimpleRepr.None _ | SynTypeDefnSimpleRepr.TypeAbbrev _ | SynTypeDefnSimpleRepr.Exception _ -> () - + and walkSynMemberDefn (memberDefn: SynMemberDefn) container = match memberDefn with - | SynMemberDefn.AbstractSlot(synValSig, memberFlags, _) -> - addMember synValSig memberFlags false container - | SynMemberDefn.AutoProperty(ident=id) -> - addIdent NavigableItemKind.Property id false container - | SynMemberDefn.Interface(members=members) -> + | SynMemberDefn.AbstractSlot (synValSig, memberFlags, _) -> addMember synValSig memberFlags false container + | SynMemberDefn.AutoProperty (ident = id) -> addIdent NavigableItemKind.Property id false container + | SynMemberDefn.Interface (members = members) -> match members with | Some members -> for m in members do walkSynMemberDefn m container | None -> () - | SynMemberDefn.Member(binding, _) -> - addBinding binding None container - | SynMemberDefn.NestedType(typeDef, _, _) -> - walkSynTypeDefn typeDef container - | SynMemberDefn.ValField(field, _) -> - addField field false container - | SynMemberDefn.LetBindings (bindings, _, _, _) -> - bindings |> List.iter (fun binding -> addBinding binding (Some NavigableItemKind.Field) container) + | SynMemberDefn.Member (binding, _) -> addBinding binding None container + | SynMemberDefn.GetSetMember (getBinding, setBinding, _, _) -> + Option.iter (fun b -> addBinding b None container) getBinding + Option.iter (fun b -> addBinding b None container) setBinding + | SynMemberDefn.NestedType (typeDef, _, _) -> walkSynTypeDefn typeDef container + | SynMemberDefn.ValField (field, _) -> addField field false container + | SynMemberDefn.LetBindings (bindings, _, _, _) -> + bindings + |> List.iter (fun binding -> addBinding binding (Some NavigableItemKind.Field) container) | SynMemberDefn.Open _ | SynMemberDefn.ImplicitInherit _ | SynMemberDefn.Inherit _ @@ -750,6 +1005,5 @@ module NavigateTo = match parsedInput with | ParsedInput.SigFile input -> walkSigFileInput input | ParsedInput.ImplFile input -> walkImplFileInput input - - result.ToArray() + result.ToArray() diff --git a/src/Compiler/Service/ServiceParamInfoLocations.fs b/src/Compiler/Service/ServiceParamInfoLocations.fs index 8d1f8e93d23..b757120b628 100755 --- a/src/Compiler/Service/ServiceParamInfoLocations.fs +++ b/src/Compiler/Service/ServiceParamInfoLocations.fs @@ -8,7 +8,11 @@ open FSharp.Compiler.Text.Range open FSharp.Compiler.Syntax open FSharp.Compiler.SyntaxTreeOps -type TupledArgumentLocation = { IsNamedArgument: bool; ArgumentRange: range } +type TupledArgumentLocation = + { + IsNamedArgument: bool + ArgumentRange: range + } [] type ParameterLocations @@ -16,7 +20,7 @@ type ParameterLocations longId: string list, longIdRange: range, openParenLocation: pos, - argRanges: TupledArgumentLocation list, + argRanges: TupledArgumentLocation list, tupleEndLocations: pos list, isThereACloseParen: bool, namedParamNames: string option list @@ -24,6 +28,7 @@ type ParameterLocations let tupleEndLocations = Array.ofList tupleEndLocations let namedParamNames = Array.ofList namedParamNames + let namedParamNames = if (tupleEndLocations.Length = namedParamNames.Length) then namedParamNames @@ -32,9 +37,9 @@ type ParameterLocations // this is ok, but later code in the UI layer will expect these lengths to match // so just fill in a blank named param to represent the final missing param // (compare to f( or f(42, where the parser injects a fake "AbrExpr" to represent the missing argument) - assert(tupleEndLocations.Length = namedParamNames.Length + 1) - [| yield! namedParamNames; yield None |] // None is representation of a non-named param - + assert (tupleEndLocations.Length = namedParamNames.Length + 1) + [| yield! namedParamNames; yield None |] // None is representation of a non-named param + member _.LongId = longId member _.LongIdStartLocation = longIdRange.Start @@ -66,53 +71,72 @@ module internal ParameterLocationsImpl = let rec digOutIdentFromFuncExpr synExpr = // we found it, dig out ident match synExpr with - | SynExpr.Ident id -> Some ([id.idText], id.idRange) - | SynExpr.LongIdent(_, SynLongIdent([id], [], [ Some _ ]), _, _) -> Some ([id.idText], id.idRange) - | SynExpr.LongIdent (_, SynLongIdent(lid, _, _), _, lidRange) - | SynExpr.DotGet (_, _, SynLongIdent(lid, _, _), lidRange) -> Some (pathOfLid lid, lidRange) - | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> digOutIdentFromFuncExpr synExpr - | SynExpr.Paren(expr = expr) -> digOutIdentFromFuncExpr expr + | SynExpr.Ident id -> Some([ id.idText ], id.idRange) + | SynExpr.LongIdent (_, SynLongIdent ([ id ], [], [ Some _ ]), _, _) -> Some([ id.idText ], id.idRange) + | SynExpr.LongIdent (_, SynLongIdent (lid, _, _), _, mLongId) + | SynExpr.DotGet (_, _, SynLongIdent (lid, _, _), mLongId) -> Some(pathOfLid lid, mLongId) + | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> digOutIdentFromFuncExpr synExpr + | SynExpr.Paren (expr = expr) -> digOutIdentFromFuncExpr expr | _ -> None - type FindResult = - | Found of openParen: pos * argRanges: TupledArgumentLocation list * commasAndCloseParen: (pos * string option) list * hasClosedParen: bool + type FindResult = + | Found of + openParen: pos * + argRanges: TupledArgumentLocation list * + commasAndCloseParen: (pos * string option) list * + hasClosedParen: bool | NotFound let digOutIdentFromStaticArg (StripParenTypes synType) = - match synType with - | SynType.StaticConstantNamed(SynType.LongIdent(SynLongIdent([id], _, _)), _, _) -> Some id.idText - | SynType.LongIdent(SynLongIdent([id], _, _)) -> Some id.idText // NOTE: again, not a static constant, but may be a prefix of a Named in incomplete code + match synType with + | SynType.StaticConstantNamed (SynType.LongIdent (SynLongIdent ([ id ], _, _)), _, _) -> Some id.idText + | SynType.LongIdent (SynLongIdent ([ id ], _, _)) -> Some id.idText // NOTE: again, not a static constant, but may be a prefix of a Named in incomplete code | _ -> None let getNamedParamName e = match e with // f(x=4) - | SynExpr.App (ExprAtomicFlag.NonAtomic, _, - SynExpr.App (ExprAtomicFlag.NonAtomic, true, - SynExpr.LongIdent(longDotId = SynLongIdent(id = [op])), - SynExpr.Ident n, - _range), - _, _) when op.idText="op_Equality" -> Some n.idText + | SynExpr.App (ExprAtomicFlag.NonAtomic, + _, + SynExpr.App (ExprAtomicFlag.NonAtomic, + true, + SynExpr.LongIdent(longDotId = SynLongIdent(id = [ op ])), + SynExpr.Ident n, + _range), + _, + _) when op.idText = "op_Equality" -> Some n.idText // f(?x=4) - | SynExpr.App (ExprAtomicFlag.NonAtomic, _, - SynExpr.App (ExprAtomicFlag.NonAtomic, true, - SynExpr.LongIdent(longDotId = SynLongIdent(id = [op])), - SynExpr.LongIdent (true(*isOptional*), SynLongIdent([n], _, _), _ref, _lidrange), _range), - _, _) when op.idText="op_Equality" -> Some n.idText + | SynExpr.App (ExprAtomicFlag.NonAtomic, + _, + SynExpr.App (ExprAtomicFlag.NonAtomic, + true, + SynExpr.LongIdent(longDotId = SynLongIdent(id = [ op ])), + SynExpr.LongIdent (true, SynLongIdent ([ n ], _, _), _ref, _lidrange), + _range), + _, + _) when op.idText = "op_Equality" -> Some n.idText | _ -> None let getTypeName synType = match synType with - | SynType.LongIdent(SynLongIdent(ids, _, _)) -> ids |> pathOfLid - | _ -> [""] // TODO type name for other cases, see also unit test named "ParameterInfo.LocationOfParams.AfterQuicklyTyping.CallConstructorViaLongId.Bug94333" + | SynType.LongIdent (SynLongIdent (ids, _, _)) -> ids |> pathOfLid + | _ -> [ "" ] // TODO type name for other cases, see also unit test named "ParameterInfo.LocationOfParams.AfterQuicklyTyping.CallConstructorViaLongId.Bug94333" - let handleSingleArg traverseSynExpr (pos, synExpr, parenRange, rpRangeOpt : _ option) = + let handleSingleArg traverseSynExpr (pos, synExpr, parenRange, rpRangeOpt: _ option) = let inner = traverseSynExpr synExpr + match inner with | None -> if SyntaxTraversal.rangeContainsPosLeftEdgeExclusiveAndRightEdgeInclusive parenRange pos then - let argRanges = [{ IsNamedArgument = (getNamedParamName synExpr).IsSome; ArgumentRange = synExpr.Range }] - Found (parenRange.Start, argRanges, [(parenRange.End, getNamedParamName synExpr)], rpRangeOpt.IsSome), None + let argRanges = + [ + { + IsNamedArgument = (getNamedParamName synExpr).IsSome + ArgumentRange = synExpr.Range + } + ] + + Found(parenRange.Start, argRanges, [ (parenRange.End, getNamedParamName synExpr) ], rpRangeOpt.IsSome), None else NotFound, None | _ -> NotFound, None @@ -120,241 +144,353 @@ module internal ParameterLocationsImpl = // This method returns a tuple, where the second element is // Some(cache) if the implementation called 'traverseSynExpr expr', then 'cache' is the result of that call // None otherwise - // so that callers can avoid recomputing 'traverseSynExpr expr' if it's already been done. This is very important for perf, + // so that callers can avoid recomputing 'traverseSynExpr expr' if it's already been done. This is very important for perf, // see bug 345385. let rec searchSynArgExpr traverseSynExpr pos expr = - match expr with - | SynExprParen(SynExpr.Tuple (false, synExprList, commaRanges, _tupleRange) as synExpr, _lpRange, rpRangeOpt, parenRange) -> // tuple argument + match expr with + | SynExprParen (SynExpr.Tuple (false, synExprList, commaRanges, _tupleRange) as synExpr, _lpRange, rpRangeOpt, parenRange) -> // tuple argument let inner = traverseSynExpr synExpr + match inner with | None -> if SyntaxTraversal.rangeContainsPosLeftEdgeExclusiveAndRightEdgeInclusive parenRange pos then // argRange, isNamed let argRanges = synExprList - |> List.map (fun e -> { IsNamedArgument = (getNamedParamName e).IsSome; ArgumentRange = e.Range }) - let commasAndCloseParen = ((synExprList, commaRanges@[parenRange]) ||> List.map2 (fun e c -> c.End, getNamedParamName e)) - let r = Found (parenRange.Start, argRanges, commasAndCloseParen, rpRangeOpt.IsSome) + |> List.map (fun e -> + { + IsNamedArgument = (getNamedParamName e).IsSome + ArgumentRange = e.Range + }) + + let commasAndCloseParen = + ((synExprList, commaRanges @ [ parenRange ]) + ||> List.map2 (fun e c -> c.End, getNamedParamName e)) + + let r = Found(parenRange.Start, argRanges, commasAndCloseParen, rpRangeOpt.IsSome) r, None else NotFound, None | _ -> NotFound, None - | SynExprParen(SynExprParen(SynExpr.Tuple (false, _, _, _), _, _, _) as synExpr, _, rpRangeOpt, parenRange) -> // f((x, y)) is special, single tuple arg + | SynExprParen (SynExprParen (SynExpr.Tuple (false, _, _, _), _, _, _) as synExpr, _, rpRangeOpt, parenRange) -> // f((x, y)) is special, single tuple arg handleSingleArg traverseSynExpr (pos, synExpr, parenRange, rpRangeOpt) // dig into multiple parens - | SynExprParen(SynExprParen(_, _, _, _) as synExpr, _, _, _parenRange) -> + | SynExprParen (SynExprParen (_, _, _, _) as synExpr, _, _, _parenRange) -> let r, _cacheOpt = searchSynArgExpr traverseSynExpr pos synExpr r, None - | SynExprParen(synExpr, _lpRange, rpRangeOpt, parenRange) -> // single argument + | SynExprParen (synExpr, _lpRange, rpRangeOpt, parenRange) -> // single argument handleSingleArg traverseSynExpr (pos, synExpr, parenRange, rpRangeOpt) | SynExpr.ArbitraryAfterError (_debugStr, range) -> // single argument when e.g. after open paren you hit EOF if SyntaxTraversal.rangeContainsPosEdgesExclusive range pos then - let r = Found (range.Start, [], [(range.End, None)], false) + let r = Found(range.Start, [], [ (range.End, None) ], false) r, None else NotFound, None | SynExpr.Const (SynConst.Unit, unitRange) -> if SyntaxTraversal.rangeContainsPosEdgesExclusive unitRange pos then - let r = Found (unitRange.Start, [], [(unitRange.End, None)], true) + let r = Found(unitRange.Start, [], [ (unitRange.End, None) ], true) r, None else NotFound, None - | e -> + | e -> let inner = traverseSynExpr e + match inner with | None -> if SyntaxTraversal.rangeContainsPosEdgesExclusive e.Range pos then // any other expression doesn't start with parens, so if it was the target of an App, then it must be a single argument e.g. "f x" - Found (e.Range.Start, [], [ (e.Range.End, None) ], false), Some inner + Found(e.Range.Start, [], [ (e.Range.End, None) ], false), Some inner else NotFound, Some inner | _ -> NotFound, Some inner let (|StaticParameters|_|) pos (StripParenTypes synType) = match synType with - | SynType.App(StripParenTypes (SynType.LongIdent(SynLongIdent(lid, _, _) as lidwd)), Some(openm), args, commas, closemOpt, _pf, wholem) -> + | SynType.App (StripParenTypes (SynType.LongIdent (SynLongIdent (lid, _, _) as lidwd)), + Some mLess, + args, + commas, + mGreaterOpt, + _pf, + wholem) -> let lidm = lidwd.Range - let betweenTheBrackets = mkRange wholem.FileName openm.Start wholem.End - if SyntaxTraversal.rangeContainsPosEdgesExclusive betweenTheBrackets pos && args |> List.forall isStaticArg then + let betweenTheBrackets = mkRange wholem.FileName mLess.Start wholem.End + + if + SyntaxTraversal.rangeContainsPosEdgesExclusive betweenTheBrackets pos + && args |> List.forall isStaticArg + then let commasAndCloseParen = [ for c in commas -> c.End ] @ [ wholem.End ] - Some (ParameterLocations(pathOfLid lid, lidm, openm.Start, [], commasAndCloseParen, closemOpt.IsSome, args |> List.map digOutIdentFromStaticArg)) + + Some( + ParameterLocations( + pathOfLid lid, + lidm, + mLess.Start, + [], + commasAndCloseParen, + mGreaterOpt.IsSome, + args |> List.map digOutIdentFromStaticArg + ) + ) else None - | _ -> - None - - let traverseInput(pos, parseTree) = - SyntaxTraversal.Traverse(pos, parseTree, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = - let expr = expr // fix debug locals - match expr with - - // new LID(...) and error recovery of these - | SynExpr.New (_, synType, synExpr, _) -> - let constrArgsResult, cacheOpt = searchSynArgExpr traverseSynExpr pos synExpr - match constrArgsResult, cacheOpt with - | Found(parenLoc, argRanges, commasAndCloseParen, isThereACloseParen), _ -> - let typeName = getTypeName synType - Some (ParameterLocations(typeName, synType.Range, parenLoc, argRanges, commasAndCloseParen |> List.map fst, isThereACloseParen, commasAndCloseParen |> List.map snd)) - | NotFound, Some cache -> - cache - | _ -> - match synType with - | StaticParameters pos loc -> Some loc - | _ -> traverseSynExpr synExpr - - // EXPR< = error recovery of a form of half-written TypeApp - | SynExpr.App (_, _, SynExpr.App (_, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [op])), synExpr, openm), SynExpr.ArbitraryAfterError _, wholem) when op.idText = "op_LessThan" -> - // Look in the function expression - let fResult = traverseSynExpr synExpr - match fResult with - | Some _ -> fResult - | _ -> - let typeArgsm = mkRange openm.FileName openm.Start wholem.End - if SyntaxTraversal.rangeContainsPosEdgesExclusive typeArgsm pos then - // We found it, dig out ident - match digOutIdentFromFuncExpr synExpr with - | Some(lid, lidRange) -> Some (ParameterLocations(lid, lidRange, op.idRange.Start, [], [ wholem.End ], false, [])) - | None -> None - else - None - - // EXPR EXPR2 - | SynExpr.App (_exprAtomicFlag, isInfix, synExpr, synExpr2, _range) -> - // Look in the function expression - let fResult = traverseSynExpr synExpr - match fResult with - | Some _ -> fResult - | _ -> - // Search the argument - let xResult, cacheOpt = searchSynArgExpr traverseSynExpr pos synExpr2 - match xResult, cacheOpt with - | Found(parenLoc, argRanges, commasAndCloseParen, isThereACloseParen), _ -> - // We found it, dig out ident - match digOutIdentFromFuncExpr synExpr with - | Some(lid, lidRange) -> - assert(isInfix = (posLt parenLoc lidRange.End)) - if isInfix then - // This seems to be an infix operator, since the start of the argument is a position earlier than the end of the long-id being applied to it. - // For now, we don't support infix operators. + | _ -> None + + let traverseInput (pos, parseTree) = + SyntaxTraversal.Traverse( + pos, + parseTree, + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = + let expr = expr // fix debug locals + + match expr with + + // new LID(...) and error recovery of these + | SynExpr.New (_, synType, synExpr, _) -> + let constrArgsResult, cacheOpt = searchSynArgExpr traverseSynExpr pos synExpr + + match constrArgsResult, cacheOpt with + | Found (parenLoc, argRanges, commasAndCloseParen, isThereACloseParen), _ -> + let typeName = getTypeName synType + + Some( + ParameterLocations( + typeName, + synType.Range, + parenLoc, + argRanges, + commasAndCloseParen |> List.map fst, + isThereACloseParen, + commasAndCloseParen |> List.map snd + ) + ) + | NotFound, Some cache -> cache + | _ -> + match synType with + | StaticParameters pos loc -> Some loc + | _ -> traverseSynExpr synExpr + + // EXPR< = error recovery of a form of half-written TypeApp + | SynExpr.App (_, + _, + SynExpr.App (_, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ op ])), synExpr, mLess), + SynExpr.ArbitraryAfterError _, + wholem) when op.idText = "op_LessThan" -> + // Look in the function expression + let fResult = traverseSynExpr synExpr + + match fResult with + | Some _ -> fResult + | _ -> + let typeArgsm = mkRange mLess.FileName mLess.Start wholem.End + + if SyntaxTraversal.rangeContainsPosEdgesExclusive typeArgsm pos then + // We found it, dig out ident + match digOutIdentFromFuncExpr synExpr with + | Some (lid, mLongId) -> + Some(ParameterLocations(lid, mLongId, op.idRange.Start, [], [ wholem.End ], false, [])) + | None -> None + else None + + // EXPR EXPR2 + | SynExpr.App (_exprAtomicFlag, isInfix, synExpr, synExpr2, _range) -> + // Look in the function expression + let fResult = traverseSynExpr synExpr + + match fResult with + | Some _ -> fResult + | _ -> + // Search the argument + let xResult, cacheOpt = searchSynArgExpr traverseSynExpr pos synExpr2 + + match xResult, cacheOpt with + | Found (parenLoc, argRanges, commasAndCloseParen, isThereACloseParen), _ -> + // We found it, dig out ident + match digOutIdentFromFuncExpr synExpr with + | Some (lid, mLongId) -> + assert (isInfix = (posLt parenLoc mLongId.End)) + + if isInfix then + // This seems to be an infix operator, since the start of the argument is a position earlier than the end of the long-id being applied to it. + // For now, we don't support infix operators. + None + else + Some( + ParameterLocations( + lid, + mLongId, + parenLoc, + argRanges, + commasAndCloseParen |> List.map fst, + isThereACloseParen, + commasAndCloseParen |> List.map snd + ) + ) + | None -> None + | NotFound, Some cache -> cache + | _ -> traverseSynExpr synExpr2 + + // ID and error recovery of these + | SynExpr.TypeApp (synExpr, mLess, tyArgs, commas, mGreaterOpt, _, wholem) -> + match traverseSynExpr synExpr with + | Some _ as r -> r + | None -> + let typeArgsm = mkRange mLess.FileName mLess.Start wholem.End + + if + SyntaxTraversal.rangeContainsPosEdgesExclusive typeArgsm pos + && tyArgs |> List.forall isStaticArg + then + let commasAndCloseParen = [ for c in commas -> c.End ] @ [ wholem.End ] + + let argRanges = + tyArgs + |> List.map (fun tyarg -> + { + IsNamedArgument = false + ArgumentRange = tyarg.Range + }) + + let r = + ParameterLocations( + [ "dummy" ], + synExpr.Range, + mLess.Start, + argRanges, + commasAndCloseParen, + mGreaterOpt.IsSome, + tyArgs |> List.map digOutIdentFromStaticArg + ) + + Some r else - Some (ParameterLocations(lid, lidRange, parenLoc, argRanges, commasAndCloseParen |> List.map fst, isThereACloseParen, commasAndCloseParen |> List.map snd)) - | None -> None - | NotFound, Some cache -> cache - | _ -> traverseSynExpr synExpr2 - - // ID and error recovery of these - | SynExpr.TypeApp (synExpr, openm, tyArgs, commas, closemOpt, _, wholem) -> - match traverseSynExpr synExpr with - | Some _ as r -> r - | None -> - let typeArgsm = mkRange openm.FileName openm.Start wholem.End - if SyntaxTraversal.rangeContainsPosEdgesExclusive typeArgsm pos && tyArgs |> List.forall isStaticArg then - let commasAndCloseParen = [ for c in commas -> c.End ] @ [ wholem.End ] - let argRanges = tyArgs |> List.map (fun tyarg -> { IsNamedArgument = false; ArgumentRange = tyarg.Range }) - let r = ParameterLocations(["dummy"], synExpr.Range, openm.Start, argRanges, commasAndCloseParen, closemOpt.IsSome, tyArgs |> List.map digOutIdentFromStaticArg) - Some r - else - None - - | _ -> defaultTraverse expr - - member _.VisitTypeAbbrev(_path, tyAbbrevRhs, _m) = - match tyAbbrevRhs with - | StaticParameters pos loc -> Some loc - | _ -> None - - member _.VisitImplicitInherit(_path, defaultTraverse, ty, expr, m) = - match defaultTraverse expr with - | Some _ as r -> r - | None -> - let inheritm = mkRange m.FileName m.Start m.End - if SyntaxTraversal.rangeContainsPosEdgesExclusive inheritm pos then - // inherit ty(expr) --- treat it like an application (constructor call) - let xResult, _cacheOpt = searchSynArgExpr defaultTraverse pos expr - match xResult with - | Found(parenLoc, argRanges, commasAndCloseParen, isThereACloseParen) -> - // we found it, dig out ident - let typeName = getTypeName ty - let r = ParameterLocations(typeName, ty.Range, parenLoc, argRanges, commasAndCloseParen |> List.map fst, isThereACloseParen, commasAndCloseParen |> List.map snd) - Some r - | NotFound -> None - else None - }) - -type ParameterLocations with + None + + | _ -> defaultTraverse expr + + member _.VisitTypeAbbrev(_path, tyAbbrevRhs, _m) = + match tyAbbrevRhs with + | StaticParameters pos loc -> Some loc + | _ -> None + + member _.VisitImplicitInherit(_path, defaultTraverse, ty, expr, m) = + match defaultTraverse expr with + | Some _ as r -> r + | None -> + let inheritm = mkRange m.FileName m.Start m.End + + if SyntaxTraversal.rangeContainsPosEdgesExclusive inheritm pos then + // inherit ty(expr) --- treat it like an application (constructor call) + let xResult, _cacheOpt = searchSynArgExpr defaultTraverse pos expr + + match xResult with + | Found (parenLoc, argRanges, commasAndCloseParen, isThereACloseParen) -> + // we found it, dig out ident + let typeName = getTypeName ty + + let r = + ParameterLocations( + typeName, + ty.Range, + parenLoc, + argRanges, + commasAndCloseParen |> List.map fst, + isThereACloseParen, + commasAndCloseParen |> List.map snd + ) + + Some r + | NotFound -> None + else + None + } + ) + +type ParameterLocations with + static member Find(pos, parseTree) = - match traverseInput(pos, parseTree) with - | Some nwpl as r -> + match traverseInput (pos, parseTree) with + | Some nwpl as r -> #if DEBUG - let ranges = nwpl.LongIdStartLocation :: nwpl.LongIdEndLocation :: nwpl.OpenParenLocation :: (nwpl.TupleEndLocations |> Array.toList) - let sorted = ranges |> List.sortWith (fun a b -> posOrder.Compare(a, b)) |> Seq.toList - assert(ranges = sorted) + let ranges = + nwpl.LongIdStartLocation + :: nwpl.LongIdEndLocation + :: nwpl.OpenParenLocation :: (nwpl.TupleEndLocations |> Array.toList) + + let sorted = + ranges |> List.sortWith (fun a b -> posOrder.Compare(a, b)) |> Seq.toList + + assert (ranges = sorted) #else ignore nwpl -#endif +#endif r | _ -> None module internal SynExprAppLocationsImpl = let rec private searchSynArgExpr traverseSynExpr expr ranges = match expr with - | SynExpr.Const(SynConst.Unit, _) -> - None, None + | SynExpr.Const (SynConst.Unit, _) -> None, None - | SynExpr.Paren(SynExpr.Tuple (_, exprs, _commas, _tupRange), _, _, _parenRange) -> + | SynExpr.Paren (SynExpr.Tuple (_, exprs, _commas, _tupRange), _, _, _parenRange) -> let rec loop (exprs: SynExpr list) ranges = match exprs with | [] -> ranges - | h::t -> - loop t (h.Range :: ranges) + | h :: t -> loop t (h.Range :: ranges) let res = loop exprs ranges Some res, None - | SynExpr.Paren(SynExpr.Paren _ as synExpr, _, _, _parenRange) -> + | SynExpr.Paren (SynExpr.Paren _ as synExpr, _, _, _parenRange) -> let r, _cacheOpt = searchSynArgExpr traverseSynExpr synExpr ranges r, None - | SynExpr.Paren(SynExpr.App (_, _isInfix, _, _, _range), _, _, parenRange) -> - Some (parenRange :: ranges), None + | SynExpr.Paren (SynExpr.App (_, _isInfix, _, _, _range), _, _, parenRange) -> Some(parenRange :: ranges), None - | e -> + | e -> let inner = traverseSynExpr e + match inner with - | None -> - Some (e.Range :: ranges), Some inner + | None -> Some(e.Range :: ranges), Some inner | _ -> None, Some inner let getAllCurriedArgsAtPosition pos parseTree = - SyntaxTraversal.Traverse(pos, parseTree, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = - match expr with - | SynExpr.App (_exprAtomicFlag, _isInfix, funcExpr, argExpr, range) when posEq pos range.Start -> - let isInfixFuncExpr = - match funcExpr with - | SynExpr.App (_, isInfix, _, _, _) -> isInfix - | _ -> false - - if isInfixFuncExpr then - traverseSynExpr funcExpr - else - let workingRanges = - match traverseSynExpr funcExpr with - | Some ranges -> ranges - | None -> [] - - let xResult, cacheOpt = searchSynArgExpr traverseSynExpr argExpr workingRanges - match xResult, cacheOpt with - | Some ranges, _ -> Some ranges - | None, Some cache -> cache - | _ -> traverseSynExpr argExpr - | _ -> defaultTraverse expr }) + SyntaxTraversal.Traverse( + pos, + parseTree, + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = + match expr with + | SynExpr.App (_exprAtomicFlag, _isInfix, funcExpr, argExpr, range) when posEq pos range.Start -> + let isInfixFuncExpr = + match funcExpr with + | SynExpr.App (_, isInfix, _, _, _) -> isInfix + | _ -> false + + if isInfixFuncExpr then + traverseSynExpr funcExpr + else + let workingRanges = + match traverseSynExpr funcExpr with + | Some ranges -> ranges + | None -> [] + + let xResult, cacheOpt = searchSynArgExpr traverseSynExpr argExpr workingRanges + + match xResult, cacheOpt with + | Some ranges, _ -> Some ranges + | None, Some cache -> cache + | _ -> traverseSynExpr argExpr + | _ -> defaultTraverse expr + } + ) |> Option.map List.rev diff --git a/src/Compiler/Service/ServiceParseTreeWalk.fs b/src/Compiler/Service/ServiceParseTreeWalk.fs index 4fc616925e6..e2eedc9ba47 100755 --- a/src/Compiler/Service/ServiceParseTreeWalk.fs +++ b/src/Compiler/Service/ServiceParseTreeWalk.fs @@ -15,7 +15,7 @@ open FSharp.Compiler.Text.Range /// used to track route during traversal AST [] -type SyntaxNode = +type SyntaxNode = | SynPat of SynPat | SynType of SynType | SynExpr of SynExpr @@ -30,116 +30,151 @@ type SyntaxVisitorPath = SyntaxNode list [] type SyntaxVisitorBase<'T>() = - abstract VisitExpr: path: SyntaxVisitorPath * traverseSynExpr: (SynExpr -> 'T option) * defaultTraverse: (SynExpr -> 'T option) * synExpr: SynExpr -> 'T option - default _.VisitExpr(path: SyntaxVisitorPath, traverseSynExpr: SynExpr -> 'T option, defaultTraverse: SynExpr -> 'T option, synExpr: SynExpr) = + abstract VisitExpr: + path: SyntaxVisitorPath * traverseSynExpr: (SynExpr -> 'T option) * defaultTraverse: (SynExpr -> 'T option) * synExpr: SynExpr -> + 'T option + + default _.VisitExpr + ( + path: SyntaxVisitorPath, + traverseSynExpr: SynExpr -> 'T option, + defaultTraverse: SynExpr -> 'T option, + synExpr: SynExpr + ) = ignore (path, traverseSynExpr, defaultTraverse, synExpr) None /// VisitTypeAbbrev(ty,m), defaults to ignoring this leaf of the AST abstract VisitTypeAbbrev: path: SyntaxVisitorPath * synType: SynType * range: range -> 'T option + default _.VisitTypeAbbrev(path, synType, range) = ignore (path, synType, range) None /// VisitImplicitInherit(defaultTraverse,ty,expr,m), defaults to just visiting expr - abstract VisitImplicitInherit: path: SyntaxVisitorPath * defaultTraverse: (SynExpr -> 'T option) * inheritedType: SynType * synArgs: SynExpr * range: range -> 'T option + abstract VisitImplicitInherit: + path: SyntaxVisitorPath * defaultTraverse: (SynExpr -> 'T option) * inheritedType: SynType * synArgs: SynExpr * range: range -> + 'T option + default _.VisitImplicitInherit(path, defaultTraverse, inheritedType, synArgs, range) = ignore (path, inheritedType, range) defaultTraverse synArgs /// VisitModuleDecl allows overriding module declaration behavior - abstract VisitModuleDecl: path: SyntaxVisitorPath * defaultTraverse: (SynModuleDecl -> 'T option) * synModuleDecl: SynModuleDecl -> 'T option + abstract VisitModuleDecl: + path: SyntaxVisitorPath * defaultTraverse: (SynModuleDecl -> 'T option) * synModuleDecl: SynModuleDecl -> 'T option + default _.VisitModuleDecl(path, defaultTraverse, synModuleDecl) = ignore path defaultTraverse synModuleDecl /// VisitBinding allows overriding binding behavior (note: by default it would defaultTraverse expression) abstract VisitBinding: path: SyntaxVisitorPath * defaultTraverse: (SynBinding -> 'T option) * synBinding: SynBinding -> 'T option + default _.VisitBinding(path, defaultTraverse, synBinding) = ignore path defaultTraverse synBinding /// VisitMatchClause allows overriding clause behavior (note: by default it would defaultTraverse expression) - abstract VisitMatchClause: path: SyntaxVisitorPath * defaultTraverse: (SynMatchClause -> 'T option) * matchClause: SynMatchClause -> 'T option + abstract VisitMatchClause: + path: SyntaxVisitorPath * defaultTraverse: (SynMatchClause -> 'T option) * matchClause: SynMatchClause -> 'T option + default _.VisitMatchClause(path, defaultTraverse, matchClause) = ignore path defaultTraverse matchClause /// VisitInheritSynMemberDefn allows overriding inherit behavior (by default do nothing) - abstract VisitInheritSynMemberDefn: path: SyntaxVisitorPath * componentInfo: SynComponentInfo * typeDefnKind: SynTypeDefnKind * SynType * SynMemberDefns * range -> 'T option + abstract VisitInheritSynMemberDefn: + path: SyntaxVisitorPath * componentInfo: SynComponentInfo * typeDefnKind: SynTypeDefnKind * SynType * SynMemberDefns * range -> + 'T option + default _.VisitInheritSynMemberDefn(path, componentInfo, typeDefnKind, synType, members, range) = ignore (path, componentInfo, typeDefnKind, synType, members, range) None /// VisitRecordDefn allows overriding behavior when visiting record definitions (by default do nothing) abstract VisitRecordDefn: path: SyntaxVisitorPath * fields: SynField list * range -> 'T option + default _.VisitRecordDefn(path, fields, range) = ignore (path, fields, range) None /// VisitUnionDefn allows overriding behavior when visiting union definitions (by default do nothing) abstract VisitUnionDefn: path: SyntaxVisitorPath * cases: SynUnionCase list * range -> 'T option + default _.VisitUnionDefn(path, cases, range) = ignore (path, cases, range) None /// VisitEnumDefn allows overriding behavior when visiting enum definitions (by default do nothing) abstract VisitEnumDefn: path: SyntaxVisitorPath * cases: SynEnumCase list * range -> 'T option + default _.VisitEnumDefn(path, cases, range) = ignore (path, cases, range) None /// VisitInterfaceSynMemberDefnType allows overriding behavior for visiting interface member in types (by default - do nothing) abstract VisitInterfaceSynMemberDefnType: path: SyntaxVisitorPath * synType: SynType -> 'T option + default _.VisitInterfaceSynMemberDefnType(path, synType) = ignore (path, synType) None /// VisitRecordField allows overriding behavior when visiting l.h.s. of constructed record instances abstract VisitRecordField: path: SyntaxVisitorPath * copyOpt: SynExpr option * recordField: SynLongIdent option -> 'T option - default _.VisitRecordField (path, copyOpt, recordField) = + + default _.VisitRecordField(path, copyOpt, recordField) = ignore (path, copyOpt, recordField) None /// VisitHashDirective allows overriding behavior when visiting hash directives in FSX scripts, like #r, #load and #I. abstract VisitHashDirective: path: SyntaxVisitorPath * hashDirective: ParsedHashDirective * range: range -> 'T option - default _.VisitHashDirective (path, hashDirective, range) = + + default _.VisitHashDirective(path, hashDirective, range) = ignore (path, hashDirective, range) None /// VisitModuleOrNamespace allows overriding behavior when visiting module or namespaces abstract VisitModuleOrNamespace: path: SyntaxVisitorPath * synModuleOrNamespace: SynModuleOrNamespace -> 'T option - default _.VisitModuleOrNamespace (path, synModuleOrNamespace) = + + default _.VisitModuleOrNamespace(path, synModuleOrNamespace) = ignore (path, synModuleOrNamespace) None - /// VisitComponentInfo allows overriding behavior when visiting type component infos + /// VisitComponentInfo allows overriding behavior when visiting type component infos abstract VisitComponentInfo: path: SyntaxVisitorPath * synComponentInfo: SynComponentInfo -> 'T option - default _.VisitComponentInfo (path, synComponentInfo) = + + default _.VisitComponentInfo(path, synComponentInfo) = ignore (path, synComponentInfo) None /// VisitLetOrUse allows overriding behavior when visiting module or local let or use bindings - abstract VisitLetOrUse: path: SyntaxVisitorPath * isRecursive: bool * defaultTraverse: (SynBinding -> 'T option) * bindings: SynBinding list * range: range -> 'T option - default _.VisitLetOrUse (path, isRecursive, defaultTraverse, bindings, range) = + abstract VisitLetOrUse: + path: SyntaxVisitorPath * isRecursive: bool * defaultTraverse: (SynBinding -> 'T option) * bindings: SynBinding list * range: range -> + 'T option + + default _.VisitLetOrUse(path, isRecursive, defaultTraverse, bindings, range) = ignore (path, isRecursive, defaultTraverse, bindings, range) None /// VisitType allows overriding behavior when visiting simple pats abstract VisitSimplePats: path: SyntaxVisitorPath * synPats: SynSimplePat list -> 'T option - default _.VisitSimplePats (path, synPats) = + + default _.VisitSimplePats(path, synPats) = ignore (path, synPats) None /// VisitPat allows overriding behavior when visiting patterns abstract VisitPat: path: SyntaxVisitorPath * defaultTraverse: (SynPat -> 'T option) * synPat: SynPat -> 'T option - default _.VisitPat (path, defaultTraverse, synPat) = + + default _.VisitPat(path, defaultTraverse, synPat) = ignore path defaultTraverse synPat /// VisitType allows overriding behavior when visiting type hints (x: ..., etc.) abstract VisitType: path: SyntaxVisitorPath * defaultTraverse: (SynType -> 'T option) * synType: SynType -> 'T option - default _.VisitType (path, defaultTraverse, synType) = + + default _.VisitType(path, defaultTraverse, synType) = ignore path defaultTraverse synType @@ -147,128 +182,166 @@ type SyntaxVisitorBase<'T>() = module SyntaxTraversal = // treat ranges as though they are half-open: [,) - let rangeContainsPosLeftEdgeInclusive (m1:range) p = + let rangeContainsPosLeftEdgeInclusive (m1: range) p = if posEq m1.Start m1.End then // the parser doesn't produce zero-width ranges, except in one case, for e.g. a block of lets that lacks a body // we treat the range [n,n) as containing position n - posGeq p m1.Start && - posGeq m1.End p + posGeq p m1.Start && posGeq m1.End p else - posGeq p m1.Start && // [ - posGt m1.End p // ) + posGeq p m1.Start + && // [ + posGt m1.End p // ) // treat ranges as though they are fully open: (,) - let rangeContainsPosEdgesExclusive (m1:range) p = posGt p m1.Start && posGt m1.End p + let rangeContainsPosEdgesExclusive (m1: range) p = posGt p m1.Start && posGt m1.End p - let rangeContainsPosLeftEdgeExclusiveAndRightEdgeInclusive (m1:range) p = posGt p m1.Start && posGeq m1.End p + let rangeContainsPosLeftEdgeExclusiveAndRightEdgeInclusive (m1: range) p = posGt p m1.Start && posGeq m1.End p - let dive node range project = - range,(fun() -> project node) + let dive node range project = range, (fun () -> project node) - let pick pos (outerRange:range) (debugObj:obj) (diveResults: (range * _) list) = + let pick pos (outerRange: range) (debugObj: obj) (diveResults: (range * _) list) = match diveResults with | [] -> None | _ -> - let isOrdered = + let isOrdered = #if DEBUG - // ranges in a dive-and-pick group should be ordered - diveResults |> Seq.pairwise |> Seq.forall (fun ((r1,_),(r2,_)) -> posGeq r2.Start r1.End) + // ranges in a dive-and-pick group should be ordered + diveResults + |> Seq.pairwise + |> Seq.forall (fun ((r1, _), (r2, _)) -> posGeq r2.Start r1.End) #else - true + true #endif - if not isOrdered then - let s = sprintf "ServiceParseTreeWalk: not isOrdered: %A" (diveResults |> List.map (fun (r,_) -> r.ToShortString())) - ignore s + if not isOrdered then + let s = + sprintf "ServiceParseTreeWalk: not isOrdered: %A" (diveResults |> List.map (fun (r, _) -> r.ToShortString())) + + ignore s //System.Diagnostics.Debug.Assert(false, s) - let outerContainsInner = + let outerContainsInner = #if DEBUG - // ranges in a dive-and-pick group should be "under" the thing that contains them - let innerTotalRange = diveResults |> List.map fst |> List.reduce unionRanges - rangeContainsRange outerRange innerTotalRange + // ranges in a dive-and-pick group should be "under" the thing that contains them + let innerTotalRange = diveResults |> List.map fst |> List.reduce unionRanges + rangeContainsRange outerRange innerTotalRange #else - ignore(outerRange) - true + ignore (outerRange) + true #endif - if not outerContainsInner then - let s = sprintf "ServiceParseTreeWalk: not outerContainsInner: %A : %A" (outerRange.ToShortString()) (diveResults |> List.map (fun (r,_) -> r.ToShortString())) - ignore s + if not outerContainsInner then + let s = + sprintf + "ServiceParseTreeWalk: not outerContainsInner: %A : %A" + (outerRange.ToShortString()) + (diveResults |> List.map (fun (r, _) -> r.ToShortString())) + + ignore s //System.Diagnostics.Debug.Assert(false, s) - let isZeroWidth(r:range) = - posEq r.Start r.End // the parser inserts some zero-width elements to represent the completions of incomplete constructs, but we should never 'dive' into them, since they don't represent actual user code - match List.choose (fun (r,f) -> if rangeContainsPosLeftEdgeInclusive r pos && not(isZeroWidth r) then Some(f) else None) diveResults with - | [] -> - // No entity's range contained the desired position. However the ranges in the parse tree only span actual characters present in the file. - // The cursor may be at whitespace between entities or after everything, so find the nearest entity with the range left of the position. - let mutable e = diveResults.Head - for r in diveResults do - if posGt pos (fst r).Start then - e <- r - snd(e)() - | [x] -> x() - | _ -> + let isZeroWidth (r: range) = posEq r.Start r.End // the parser inserts some zero-width elements to represent the completions of incomplete constructs, but we should never 'dive' into them, since they don't represent actual user code + + match + List.choose + (fun (r, f) -> + if rangeContainsPosLeftEdgeInclusive r pos && not (isZeroWidth r) then + Some(f) + else + None) + diveResults + with + | [] -> + // No entity's range contained the desired position. However the ranges in the parse tree only span actual characters present in the file. + // The cursor may be at whitespace between entities or after everything, so find the nearest entity with the range left of the position. + let mutable e = diveResults.Head + + for r in diveResults do + if posGt pos (fst r).Start then + e <- r + + snd (e) () + | [ x ] -> x () + | _ -> #if DEBUG - assert false - failwithf "multiple disjoint AST node ranges claimed to contain (%A) from %+A" pos debugObj + assert false + failwithf "multiple disjoint AST node ranges claimed to contain (%A) from %+A" pos debugObj #else - ignore debugObj - None + ignore debugObj + None #endif /// traverse an implementation file walking all the way down to SynExpr or TypeAbbrev at a particular location /// - let Traverse(pos:pos, parseTree, visitor:SyntaxVisitorBase<'T>) = + let Traverse (pos: pos, parseTree, visitor: SyntaxVisitorBase<'T>) = let pick x = pick pos x - let rec traverseSynModuleDecl origPath (decl:SynModuleDecl) = + + let rec traverseSynModuleDecl origPath (decl: SynModuleDecl) = let pick = pick decl.Range - let defaultTraverse m = + + let defaultTraverse m = let path = SyntaxNode.SynModule m :: origPath + match m with - | SynModuleDecl.ModuleAbbrev(_ident, _longIdent, _range) -> None - | SynModuleDecl.NestedModule(decls=synModuleDecls) -> synModuleDecls |> List.map (fun x -> dive x x.Range (traverseSynModuleDecl path)) |> pick decl - | SynModuleDecl.Let(isRecursive, synBindingList, range) -> + | SynModuleDecl.ModuleAbbrev (_ident, _longIdent, _range) -> None + | SynModuleDecl.NestedModule (decls = synModuleDecls) -> + synModuleDecls + |> List.map (fun x -> dive x x.Range (traverseSynModuleDecl path)) + |> pick decl + | SynModuleDecl.Let (isRecursive, synBindingList, range) -> match visitor.VisitLetOrUse(path, isRecursive, traverseSynBinding path, synBindingList, range) with | Some x -> Some x - | None -> synBindingList |> List.map (fun x -> dive x x.RangeOfBindingWithRhs (traverseSynBinding path)) |> pick decl - | SynModuleDecl.Expr(synExpr, _range) -> traverseSynExpr path synExpr - | SynModuleDecl.Types(synTypeDefnList, _range) -> synTypeDefnList |> List.map (fun x -> dive x x.Range (traverseSynTypeDefn path)) |> pick decl - | SynModuleDecl.Exception(_synExceptionDefn, _range) -> None - | SynModuleDecl.Open(_target, _range) -> None - | SynModuleDecl.Attributes(_synAttributes, _range) -> None - | SynModuleDecl.HashDirective(parsedHashDirective, range) -> visitor.VisitHashDirective (path, parsedHashDirective, range) - | SynModuleDecl.NamespaceFragment(synModuleOrNamespace) -> traverseSynModuleOrNamespace path synModuleOrNamespace + | None -> + synBindingList + |> List.map (fun x -> dive x x.RangeOfBindingWithRhs (traverseSynBinding path)) + |> pick decl + | SynModuleDecl.Expr (synExpr, _range) -> traverseSynExpr path synExpr + | SynModuleDecl.Types (synTypeDefnList, _range) -> + synTypeDefnList + |> List.map (fun x -> dive x x.Range (traverseSynTypeDefn path)) + |> pick decl + | SynModuleDecl.Exception (_synExceptionDefn, _range) -> None + | SynModuleDecl.Open (_target, _range) -> None + | SynModuleDecl.Attributes (_synAttributes, _range) -> None + | SynModuleDecl.HashDirective (parsedHashDirective, range) -> visitor.VisitHashDirective(path, parsedHashDirective, range) + | SynModuleDecl.NamespaceFragment (synModuleOrNamespace) -> traverseSynModuleOrNamespace path synModuleOrNamespace + visitor.VisitModuleDecl(origPath, defaultTraverse, decl) - and traverseSynModuleOrNamespace origPath (SynModuleOrNamespace(decls = synModuleDecls; range = range) as mors) = + and traverseSynModuleOrNamespace origPath (SynModuleOrNamespace (decls = synModuleDecls; range = range) as mors) = match visitor.VisitModuleOrNamespace(origPath, mors) with | Some x -> Some x | None -> let path = SyntaxNode.SynModuleOrNamespace mors :: origPath - synModuleDecls |> List.map (fun x -> dive x x.Range (traverseSynModuleDecl path)) |> pick range mors - and traverseSynExpr origPath (expr:SynExpr) = + synModuleDecls + |> List.map (fun x -> dive x x.Range (traverseSynModuleDecl path)) + |> pick range mors + + and traverseSynExpr origPath (expr: SynExpr) = let pick = pick expr.Range - let defaultTraverse e = + + let defaultTraverse e = let path = SyntaxNode.SynExpr e :: origPath let traverseSynExpr = traverseSynExpr path let traverseSynType = traverseSynType path let traversePat = traversePat path + match e with | SynExpr.Paren (synExpr, _, _, _parenRange) -> traverseSynExpr synExpr - | SynExpr.Quote (_synExpr, _, synExpr2, _, _range) -> - [//dive synExpr synExpr.Range traverseSynExpr // TODO, what is this? - dive synExpr2 synExpr2.Range traverseSynExpr] + | SynExpr.Quote (_synExpr, _, synExpr2, _, _range) -> + [ //dive synExpr synExpr.Range traverseSynExpr // TODO, what is this? + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr | SynExpr.Const (_synConst, _range) -> None - | SynExpr.InterpolatedString (parts, _, _) -> - [ for part in parts do - match part with - | SynInterpolatedStringPart.String _ -> () - | SynInterpolatedStringPart.FillExpr (fillExpr, _) -> - yield dive fillExpr fillExpr.Range traverseSynExpr ] + | SynExpr.InterpolatedString (parts, _, _) -> + [ + for part in parts do + match part with + | SynInterpolatedStringPart.String _ -> () + | SynInterpolatedStringPart.FillExpr (fillExpr, _) -> yield dive fillExpr fillExpr.Range traverseSynExpr + ] |> pick expr | SynExpr.Typed (synExpr, synType, _range) -> @@ -276,192 +349,225 @@ module SyntaxTraversal = | None -> traverseSynType synType | x -> x - | SynExpr.Tuple (_, synExprList, _, _range) + | SynExpr.Tuple (_, synExprList, _, _range) | SynExpr.ArrayOrList (_, synExprList, _range) -> synExprList |> List.map (fun x -> dive x x.Range traverseSynExpr) |> pick expr - - | SynExpr.AnonRecd (_isStruct, copyOpt, synExprList, _range) -> - [ match copyOpt with - | Some(expr, (withRange, _)) -> - yield dive expr expr.Range traverseSynExpr - yield dive () withRange (fun () -> - if posGeq pos withRange.End then - // special case: caret is after WITH - // { x with $ } - visitor.VisitRecordField (path, Some expr, None) - else - None - ) + + | SynExpr.AnonRecd (_isStruct, copyOpt, synExprList, _range) -> + [ + match copyOpt with + | Some (expr, (withRange, _)) -> + yield dive expr expr.Range traverseSynExpr + + yield + dive () withRange (fun () -> + if posGeq pos withRange.End then + // special case: caret is after WITH + // { x with $ } + visitor.VisitRecordField(path, Some expr, None) + else + None) | _ -> () - for _, _, x in synExprList do + for _, _, x in synExprList do yield dive x x.Range traverseSynExpr - ] |> pick expr + ] + |> pick expr - | SynExpr.Record (inheritOpt,copyOpt,fields, _range) -> - [ - let diveIntoSeparator offsideColumn scPosOpt copyOpt = + | SynExpr.Record (inheritOpt, copyOpt, fields, _range) -> + [ + let diveIntoSeparator offsideColumn scPosOpt copyOpt = match scPosOpt with - | Some scPos -> - if posGeq pos scPos then + | Some scPos -> + if posGeq pos scPos then visitor.VisitRecordField(path, copyOpt, None) // empty field after the inherits - else None - | None -> + else + None + | None -> //semicolon position is not available - use offside rule if pos.Column = offsideColumn then visitor.VisitRecordField(path, copyOpt, None) // empty field after the inherits - else None + else + None match inheritOpt with - | Some(_ty,expr, _range, sepOpt, inheritRange) -> + | Some (_ty, expr, _range, sepOpt, inheritRange) -> // dive into argument - yield dive expr expr.Range (fun expr -> - // special-case:caret is located in the offside position below inherit - // inherit A() - // $ - if not (rangeContainsPos expr.Range pos) && sepOpt.IsNone && pos.Column = inheritRange.StartColumn then - visitor.VisitRecordField(path, None, None) - else - traverseSynExpr expr - ) - match sepOpt with - | Some (sep, scPosOpt) -> - yield dive () sep (fun () -> - // special case: caret is below 'inherit' + one or more fields are already defined + yield + dive expr expr.Range (fun expr -> + // special-case:caret is located in the offside position below inherit // inherit A() // $ - // field1 = 5 - diveIntoSeparator inheritRange.StartColumn scPosOpt None - ) + if + not (rangeContainsPos expr.Range pos) + && sepOpt.IsNone + && pos.Column = inheritRange.StartColumn + then + visitor.VisitRecordField(path, None, None) + else + traverseSynExpr expr) + + match sepOpt with + | Some (sep, scPosOpt) -> + yield + dive () sep (fun () -> + // special case: caret is below 'inherit' + one or more fields are already defined + // inherit A() + // $ + // field1 = 5 + diveIntoSeparator inheritRange.StartColumn scPosOpt None) | None -> () | _ -> () + match copyOpt with - | Some(expr, (withRange, _)) -> - yield dive expr expr.Range traverseSynExpr - yield dive () withRange (fun () -> - if posGeq pos withRange.End then - // special case: caret is after WITH - // { x with $ } - visitor.VisitRecordField (path, Some expr, None) - else - None - ) + | Some (expr, (withRange, _)) -> + yield dive expr expr.Range traverseSynExpr + + yield + dive () withRange (fun () -> + if posGeq pos withRange.End then + // special case: caret is after WITH + // { x with $ } + visitor.VisitRecordField(path, Some expr, None) + else + None) | _ -> () + let copyOpt = Option.map fst copyOpt - for SynExprRecordField(fieldName=(field, _); expr=e; blockSeparator=sepOpt) in fields do - yield dive (path, copyOpt, Some field) field.Range (fun r -> - if rangeContainsPos field.Range pos then - visitor.VisitRecordField r - else - None - ) - let offsideColumn = + + for SynExprRecordField (fieldName = (field, _); expr = e; blockSeparator = sepOpt) in fields do + yield + dive (path, copyOpt, Some field) field.Range (fun r -> + if rangeContainsPos field.Range pos then + visitor.VisitRecordField r + else + None) + + let offsideColumn = match inheritOpt with - | Some(_,_, _, _, inheritRange) -> inheritRange.StartColumn + | Some (_, _, _, _, inheritRange) -> inheritRange.StartColumn | None -> field.Range.StartColumn match e with - | Some e -> yield dive e e.Range (fun expr -> - // special case: caret is below field binding - // field x = 5 - // $ - if not (rangeContainsPos e.Range pos) && sepOpt.IsNone && pos.Column = offsideColumn then - visitor.VisitRecordField(path, copyOpt, None) - else - traverseSynExpr expr - ) + | Some e -> + yield + dive e e.Range (fun expr -> + // special case: caret is below field binding + // field x = 5 + // $ + if + not (rangeContainsPos e.Range pos) + && sepOpt.IsNone + && pos.Column = offsideColumn + then + visitor.VisitRecordField(path, copyOpt, None) + else + traverseSynExpr expr) | None -> () match sepOpt with - | Some (sep, scPosOpt) -> - yield dive () sep (fun () -> - // special case: caret is between field bindings - // field1 = 5 - // $ - // field2 = 5 - diveIntoSeparator offsideColumn scPosOpt copyOpt - ) + | Some (sep, scPosOpt) -> + yield + dive () sep (fun () -> + // special case: caret is between field bindings + // field1 = 5 + // $ + // field2 = 5 + diveIntoSeparator offsideColumn scPosOpt copyOpt) | _ -> () - ] |> pick expr + ] + |> pick expr | SynExpr.New (_, _synType, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.ObjExpr (objType=ty; argOptions=baseCallOpt; bindings=binds; members=ms; extraImpls=ifaces) -> + | SynExpr.ObjExpr (objType = ty; argOptions = baseCallOpt; bindings = binds; members = ms; extraImpls = ifaces) -> let binds = unionBindingAndMembers binds ms - let result = - ifaces - |> Seq.map (fun (SynInterfaceImpl(interfaceTy=ty)) -> ty) + + let result = + ifaces + |> Seq.map (fun (SynInterfaceImpl (interfaceTy = ty)) -> ty) |> Seq.tryPick (fun ty -> visitor.VisitInterfaceSynMemberDefnType(path, ty)) - - if result.IsSome then + + if result.IsSome then result else - [ - match baseCallOpt with - | Some(expr,_) -> - // this is like a call to 'new', so mock up a 'new' so we can recurse and use that existing logic - let newCall = SynExpr.New (false, ty, expr, unionRanges ty.Range expr.Range) - yield dive newCall newCall.Range traverseSynExpr - | _ -> () - for b in binds do - yield dive b b.RangeOfBindingWithRhs (traverseSynBinding path) - for SynInterfaceImpl(bindings=binds) in ifaces do + [ + match baseCallOpt with + | Some (expr, _) -> + // this is like a call to 'new', so mock up a 'new' so we can recurse and use that existing logic + let newCall = SynExpr.New(false, ty, expr, unionRanges ty.Range expr.Range) + yield dive newCall newCall.Range traverseSynExpr + | _ -> () for b in binds do yield dive b b.RangeOfBindingWithRhs (traverseSynBinding path) - ] |> pick expr + for SynInterfaceImpl (bindings = binds) in ifaces do + for b in binds do + yield dive b b.RangeOfBindingWithRhs (traverseSynBinding path) + ] + |> pick expr - | SynExpr.While (_spWhile, synExpr, synExpr2, _range) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + | SynExpr.While (_spWhile, synExpr, synExpr2, _range) -> + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr - | SynExpr.For (identBody=synExpr; toBody=synExpr2; doBody=synExpr3) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr - dive synExpr3 synExpr3.Range traverseSynExpr] + | SynExpr.For (identBody = synExpr; toBody = synExpr2; doBody = synExpr3) -> + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + dive synExpr3 synExpr3.Range traverseSynExpr + ] |> pick expr | SynExpr.ForEach (_spFor, _spIn, _seqExprOnly, _isFromSource, synPat, synExpr, synExpr2, _range) -> - [dive synPat synPat.Range traversePat - dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + [ + dive synPat synPat.Range traversePat + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr | SynExpr.ArrayOrListComputed (_, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.ComputationExpr (_, synExpr, _range) -> + | SynExpr.ComputationExpr (_, synExpr, _range) -> // now parser treats this syntactic expression as computation expression // { identifier } // here we detect this situation and treat ComputationExpr { Identifier } as attempt to create record // note: sequence expressions use SynExpr.ComputationExpr too - they need to be filtered out - let isPartOfArrayOrList = + let isPartOfArrayOrList = match origPath with - | SyntaxNode.SynExpr(SynExpr.ArrayOrListComputed _) :: _ -> true + | SyntaxNode.SynExpr (SynExpr.ArrayOrListComputed _) :: _ -> true | _ -> false - let ok = + + let ok = match isPartOfArrayOrList, synExpr with - | false, SynExpr.Ident ident -> visitor.VisitRecordField(path, None, Some (SynLongIdent([ident], [], [None]))) + | false, SynExpr.Ident ident -> visitor.VisitRecordField(path, None, Some(SynLongIdent([ ident ], [], [ None ]))) | false, SynExpr.LongIdent (false, lidwd, _, _) -> visitor.VisitRecordField(path, None, Some lidwd) | _ -> None - if ok.IsSome then ok - else - traverseSynExpr synExpr - | SynExpr.Lambda (args=synSimplePats; body=synExpr) -> + if ok.IsSome then ok else traverseSynExpr synExpr + + | SynExpr.Lambda (args = synSimplePats; body = synExpr) -> match synSimplePats with - | SynSimplePats.SimplePats(pats,_) -> + | SynSimplePats.SimplePats (pats, _) -> match visitor.VisitSimplePats(path, pats) with | None -> traverseSynExpr synExpr | x -> x | _ -> traverseSynExpr synExpr - | SynExpr.MatchLambda (_isExnMatch,_argm,synMatchClauseList,_spBind,_wholem) -> - synMatchClauseList + | SynExpr.MatchLambda (_isExnMatch, _argm, synMatchClauseList, _spBind, _wholem) -> + synMatchClauseList |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path)) |> pick expr - | SynExpr.Match (expr=synExpr; clauses=synMatchClauseList) -> - [yield dive synExpr synExpr.Range traverseSynExpr - yield! synMatchClauseList |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path))] + | SynExpr.Match (expr = synExpr; clauses = synMatchClauseList) -> + [ + yield dive synExpr synExpr.Range traverseSynExpr + yield! + synMatchClauseList + |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path)) + ] |> pick expr | SynExpr.Do (synExpr, _range) -> traverseSynExpr synExpr @@ -473,52 +579,70 @@ module SyntaxTraversal = | SynExpr.DebugPoint (_, _, synExpr) -> traverseSynExpr synExpr | SynExpr.Dynamic _ -> None - + | SynExpr.App (_exprAtomicFlag, isInfix, synExpr, synExpr2, _range) -> if isInfix then - [dive synExpr2 synExpr2.Range traverseSynExpr - dive synExpr synExpr.Range traverseSynExpr] // reverse the args + [ + dive synExpr2 synExpr2.Range traverseSynExpr + dive synExpr synExpr.Range traverseSynExpr + ] // reverse the args |> pick expr else - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr | SynExpr.TypeApp (synExpr, _, _synTypeList, _commas, _, _, _range) -> traverseSynExpr synExpr - | SynExpr.LetOrUse (_, isRecursive, synBindingList, synExpr, range, _) -> + | SynExpr.LetOrUse (_, isRecursive, synBindingList, synExpr, range, _) -> match visitor.VisitLetOrUse(path, isRecursive, traverseSynBinding path, synBindingList, range) with | None -> - [yield! synBindingList |> List.map (fun x -> dive x x.RangeOfBindingWithRhs (traverseSynBinding path)) - yield dive synExpr synExpr.Range traverseSynExpr] + [ + yield! + synBindingList + |> List.map (fun x -> dive x x.RangeOfBindingWithRhs (traverseSynBinding path)) + yield dive synExpr synExpr.Range traverseSynExpr + ] |> pick expr | x -> x - | SynExpr.TryWith (tryExpr=synExpr; withCases=synMatchClauseList) -> - [yield dive synExpr synExpr.Range traverseSynExpr - yield! synMatchClauseList |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path))] + | SynExpr.TryWith (tryExpr = synExpr; withCases = synMatchClauseList) -> + [ + yield dive synExpr synExpr.Range traverseSynExpr + yield! + synMatchClauseList + |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path)) + ] |> pick expr - | SynExpr.TryFinally (tryExpr=synExpr; finallyExpr=synExpr2) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + | SynExpr.TryFinally (tryExpr = synExpr; finallyExpr = synExpr2) -> + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr | SynExpr.Lazy (synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.SequentialOrImplicitYield (_sequencePointInfoForSequential, synExpr, synExpr2, _, _range) + | SynExpr.SequentialOrImplicitYield (_sequencePointInfoForSequential, synExpr, synExpr2, _, _range) - | SynExpr.Sequential (_sequencePointInfoForSequential, _, synExpr, synExpr2, _range) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + | SynExpr.Sequential (_sequencePointInfoForSequential, _, synExpr, synExpr2, _range) -> + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr - | SynExpr.IfThenElse (ifExpr=synExpr; thenExpr=synExpr2; elseExpr=synExprOpt) -> - [yield dive synExpr synExpr.Range traverseSynExpr - yield dive synExpr2 synExpr2.Range traverseSynExpr - match synExprOpt with - | None -> () - | Some x -> yield dive x x.Range traverseSynExpr] + | SynExpr.IfThenElse (ifExpr = synExpr; thenExpr = synExpr2; elseExpr = synExprOpt) -> + [ + yield dive synExpr synExpr.Range traverseSynExpr + yield dive synExpr2 synExpr2.Range traverseSynExpr + match synExprOpt with + | None -> () + | Some x -> yield dive x x.Range traverseSynExpr + ] |> pick expr | SynExpr.Ident _ident -> None @@ -532,43 +656,60 @@ module SyntaxTraversal = | SynExpr.Set (synExpr, synExpr2, _) | SynExpr.DotSet (synExpr, _, synExpr2, _) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr - | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> - [ match expr1 with Some e -> dive e e.Range traverseSynExpr | None -> () - match expr2 with Some e -> dive e e.Range traverseSynExpr | None -> () ] + | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> + [ + match expr1 with + | Some e -> dive e e.Range traverseSynExpr + | None -> () + match expr2 with + | Some e -> dive e e.Range traverseSynExpr + | None -> () + ] |> pick expr - | SynExpr.IndexFromEnd (e, _) -> - traverseSynExpr e + | SynExpr.IndexFromEnd (e, _) -> traverseSynExpr e - | SynExpr.DotIndexedGet (synExpr, indexArgs, _range, _range2) -> - [yield dive synExpr synExpr.Range traverseSynExpr - yield dive indexArgs indexArgs.Range traverseSynExpr] + | SynExpr.DotIndexedGet (synExpr, indexArgs, _range, _range2) -> + [ + yield dive synExpr synExpr.Range traverseSynExpr + yield dive indexArgs indexArgs.Range traverseSynExpr + ] |> pick expr - | SynExpr.DotIndexedSet (synExpr, indexArgs, synExpr2, _, _range, _range2) -> - [yield dive synExpr synExpr.Range traverseSynExpr - yield dive indexArgs indexArgs.Range traverseSynExpr - yield dive synExpr2 synExpr2.Range traverseSynExpr] + | SynExpr.DotIndexedSet (synExpr, indexArgs, synExpr2, _, _range, _range2) -> + [ + yield dive synExpr synExpr.Range traverseSynExpr + yield dive indexArgs indexArgs.Range traverseSynExpr + yield dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr - | SynExpr.JoinIn (synExpr1, _range, synExpr2, _range2) -> - [dive synExpr1 synExpr1.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + | SynExpr.JoinIn (synExpr1, _range, synExpr2, _range2) -> + [ + dive synExpr1 synExpr1.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr | SynExpr.NamedIndexedPropertySet (_longIdent, synExpr, synExpr2, _range) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr] + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + ] |> pick expr - | SynExpr.DotNamedIndexedPropertySet (synExpr, _longIdent, synExpr2, synExpr3, _range) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synExpr2 synExpr2.Range traverseSynExpr - dive synExpr3 synExpr3.Range traverseSynExpr] + | SynExpr.DotNamedIndexedPropertySet (synExpr, _longIdent, synExpr2, synExpr3, _range) -> + [ + dive synExpr synExpr.Range traverseSynExpr + dive synExpr2 synExpr2.Range traverseSynExpr + dive synExpr3 synExpr3.Range traverseSynExpr + ] |> pick expr | SynExpr.TypeTest (synExpr, synType, _range) @@ -576,8 +717,10 @@ module SyntaxTraversal = | SynExpr.Upcast (synExpr, synType, _range) | SynExpr.Downcast (synExpr, synType, _range) -> - [dive synExpr synExpr.Range traverseSynExpr - dive synType synType.Range traverseSynType] + [ + dive synExpr synExpr.Range traverseSynExpr + dive synType synType.Range traverseSynType + ] |> pick expr | SynExpr.InferredUpcast (synExpr, _range) -> traverseSynExpr synExpr @@ -596,21 +739,27 @@ module SyntaxTraversal = | SynExpr.YieldOrReturnFrom (_, synExpr, _range) -> traverseSynExpr synExpr - | SynExpr.LetOrUseBang(pat=synPat; rhs=synExpr; andBangs=andBangSynExprs; body=synExpr2) -> + | SynExpr.LetOrUseBang (pat = synPat; rhs = synExpr; andBangs = andBangSynExprs; body = synExpr2) -> [ yield dive synPat synPat.Range traversePat yield dive synExpr synExpr.Range traverseSynExpr yield! - [ for SynExprAndBang(pat=andBangSynPat; body=andBangSynExpr) in andBangSynExprs do - yield (dive andBangSynPat andBangSynPat.Range traversePat) - yield (dive andBangSynExpr andBangSynExpr.Range traverseSynExpr)] + [ + for SynExprAndBang (pat = andBangSynPat; body = andBangSynExpr) in andBangSynExprs do + yield (dive andBangSynPat andBangSynPat.Range traversePat) + yield (dive andBangSynExpr andBangSynExpr.Range traverseSynExpr) + ] yield dive synExpr2 synExpr2.Range traverseSynExpr ] |> pick expr - | SynExpr.MatchBang (expr=synExpr; clauses=synMatchClauseList) -> - [yield dive synExpr synExpr.Range traverseSynExpr - yield! synMatchClauseList |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path))] + | SynExpr.MatchBang (expr = synExpr; clauses = synMatchClauseList) -> + [ + yield dive synExpr synExpr.Range traverseSynExpr + yield! + synMatchClauseList + |> List.map (fun x -> dive x x.Range (traverseSynMatchClause path)) + ] |> pick expr | SynExpr.DoBang (synExpr, _range) -> traverseSynExpr synExpr @@ -634,6 +783,7 @@ module SyntaxTraversal = and traversePat origPath (pat: SynPat) = let defaultTraverse p = let path = SyntaxNode.SynPat p :: origPath + match p with | SynPat.Paren (p, _) -> traversePat path p | SynPat.As (p1, p2, _) @@ -642,185 +792,190 @@ module SyntaxTraversal = | SynPat.Tuple (_, ps, _) | SynPat.ArrayOrList (_, ps, _) -> ps |> List.tryPick (traversePat path) | SynPat.Attrib (p, _, _) -> traversePat path p - | SynPat.LongIdent(argPats=args) -> + | SynPat.LongIdent (argPats = args) -> match args with | SynArgPats.Pats ps -> ps |> List.tryPick (traversePat path) - | SynArgPats.NamePatPairs (ps, _) -> - ps |> List.map (fun (_, _, pat) -> pat) |> List.tryPick (traversePat path) + | SynArgPats.NamePatPairs (ps, _) -> ps |> List.map (fun (_, _, pat) -> pat) |> List.tryPick (traversePat path) | SynPat.Typed (p, ty, _) -> match traversePat path p with | None -> traverseSynType path ty | x -> x | _ -> None - - visitor.VisitPat (origPath, defaultTraverse, pat) + + visitor.VisitPat(origPath, defaultTraverse, pat) and traverseSynType origPath (StripParenTypes ty) = let defaultTraverse ty = let path = SyntaxNode.SynType ty :: origPath + match ty with | SynType.App (typeName, _, typeArgs, _, _, _, _) | SynType.LongIdentApp (typeName, _, _, typeArgs, _, _, _) -> - [ yield typeName - yield! typeArgs ] - |> List.tryPick (traverseSynType path) - | SynType.Fun (ty1, ty2, _) -> [ty1; ty2] |> List.tryPick (traverseSynType path) - | SynType.MeasurePower (ty, _, _) + [ yield typeName; yield! typeArgs ] |> List.tryPick (traverseSynType path) + | SynType.Fun (argType = ty1; returnType = ty2) -> [ ty1; ty2 ] |> List.tryPick (traverseSynType path) + | SynType.MeasurePower (ty, _, _) | SynType.HashConstraint (ty, _) | SynType.WithGlobalConstraints (ty, _, _) | SynType.Array (_, ty, _) -> traverseSynType path ty | SynType.StaticConstantNamed (ty1, ty2, _) - | SynType.MeasureDivide (ty1, ty2, _) -> [ty1; ty2] |> List.tryPick (traverseSynType path) + | SynType.MeasureDivide (ty1, ty2, _) -> [ ty1; ty2 ] |> List.tryPick (traverseSynType path) | SynType.Tuple (_, tys, _) -> tys |> List.map snd |> List.tryPick (traverseSynType path) | SynType.StaticConstantExpr (expr, _) -> traverseSynExpr [] expr | SynType.Anon _ -> None | _ -> None - visitor.VisitType (origPath, defaultTraverse, ty) - - and normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path traverseInherit (synMemberDefns:SynMemberDefns) = - synMemberDefns - // property getters are setters are two members that can have the same range, so do some somersaults to deal with this - |> Seq.groupBy (fun x -> x.Range) - |> Seq.choose (fun (r, mems) -> - match mems |> Seq.toList with - | [mem] -> // the typical case, a single member has this range 'r' - Some (dive mem r (traverseSynMemberDefn path traverseInherit)) - | [SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(longDotId=lid1; extraId=Some(info1)))) as mem1 - SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(longDotId=lid2; extraId=Some(info2)))) as mem2] -> // can happen if one is a getter and one is a setter - // ensure same long id - assert( (lid1.LongIdent,lid2.LongIdent) ||> List.forall2 (fun x y -> x.idText = y.idText) ) - // ensure one is getter, other is setter - assert( (info1.idText="set" && info2.idText="get") || - (info2.idText="set" && info1.idText="get") ) - Some ( - r,(fun() -> - // both mem1 and mem2 have same range, would violate dive-and-pick assertions, so just try the first one, else try the second one: - match traverseSynMemberDefn path (fun _ -> None) mem1 with - | Some _ as x -> x - | _ -> traverseSynMemberDefn path (fun _ -> None) mem2 ) - ) - | [] -> -#if DEBUG - assert false - failwith "impossible, Seq.groupBy never returns empty results" -#else - // swallow AST error and recover silently - None -#endif - | _ -> -#if DEBUG - assert false // more than 2 members claim to have the same range, this indicates a bug in the AST - failwith "bug in AST" -#else - // swallow AST error and recover silently - None -#endif - ) - - and traverseSynTypeDefn origPath (SynTypeDefn(synComponentInfo, synTypeDefnRepr, synMemberDefns, _, tRange, _) as tydef) = + visitor.VisitType(origPath, defaultTraverse, ty) + + and normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path traverseInherit (synMemberDefns: SynMemberDefns) = + synMemberDefns + // property getters are setters are two members that can have the same range, so do some somersaults to deal with this + |> Seq.map (fun mb -> + match mb with + | SynMemberDefn.GetSetMember (Some binding, None, m, _) + | SynMemberDefn.GetSetMember (None, Some binding, m, _) -> + dive (SynMemberDefn.Member(binding, m)) m (traverseSynMemberDefn path traverseInherit) + | SynMemberDefn.GetSetMember (Some getBinding, Some setBinding, m, _) -> + let traverse () = + match traverseSynMemberDefn path (fun _ -> None) (SynMemberDefn.Member(getBinding, m)) with + | Some _ as x -> x + | None -> traverseSynMemberDefn path (fun _ -> None) (SynMemberDefn.Member(setBinding, m)) + + m, traverse + | mem -> dive mem mem.Range (traverseSynMemberDefn path traverseInherit)) + + and traverseSynTypeDefn origPath (SynTypeDefn (synComponentInfo, synTypeDefnRepr, synMemberDefns, _, tRange, _) as tydef) = let path = SyntaxNode.SynTypeDefn tydef :: origPath - - match visitor.VisitComponentInfo (origPath, synComponentInfo) with + + match visitor.VisitComponentInfo(origPath, synComponentInfo) with | Some x -> Some x | None -> - [ - match synTypeDefnRepr with - | SynTypeDefnRepr.Exception _ -> - // This node is generated in CheckExpressions.fs, not in the AST. - // But note exception declarations are missing from this tree walk. - () - | SynTypeDefnRepr.ObjectModel(synTypeDefnKind, synMemberDefns, _oRange) -> - // traverse inherit function is used to capture type specific data required for processing Inherit part - let traverseInherit (synType: SynType, range: range) = - visitor.VisitInheritSynMemberDefn(path, synComponentInfo, synTypeDefnKind, synType, synMemberDefns, range) - yield! synMemberDefns |> normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path traverseInherit - | SynTypeDefnRepr.Simple(synTypeDefnSimpleRepr, _range) -> - match synTypeDefnSimpleRepr with - | SynTypeDefnSimpleRepr.Record(_synAccessOption, fields, m) -> - yield dive () synTypeDefnRepr.Range (fun () -> visitor.VisitRecordDefn(path, fields, m)) - | SynTypeDefnSimpleRepr.Union(_synAccessOption, cases, m) -> - yield dive () synTypeDefnRepr.Range (fun () -> visitor.VisitUnionDefn(path, cases, m)) - | SynTypeDefnSimpleRepr.Enum(cases, m) -> - yield dive () synTypeDefnRepr.Range (fun () -> visitor.VisitEnumDefn(path, cases, m)) - | SynTypeDefnSimpleRepr.TypeAbbrev(_, synType, m) -> - yield dive synTypeDefnRepr synTypeDefnRepr.Range (fun _ -> visitor.VisitTypeAbbrev(path, synType, m)) - | _ -> + [ + match synTypeDefnRepr with + | SynTypeDefnRepr.Exception _ -> + // This node is generated in CheckExpressions.fs, not in the AST. + // But note exception declarations are missing from this tree walk. () - yield! synMemberDefns |> normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path (fun _ -> None) - ] |> pick tRange tydef + | SynTypeDefnRepr.ObjectModel (synTypeDefnKind, synMemberDefns, _oRange) -> + // traverse inherit function is used to capture type specific data required for processing Inherit part + let traverseInherit (synType: SynType, range: range) = + visitor.VisitInheritSynMemberDefn(path, synComponentInfo, synTypeDefnKind, synType, synMemberDefns, range) - and traverseSynMemberDefn path traverseInherit (m:SynMemberDefn) = - let pick (debugObj:obj) = pick m.Range debugObj + yield! + synMemberDefns + |> normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path traverseInherit + | SynTypeDefnRepr.Simple (synTypeDefnSimpleRepr, _range) -> + match synTypeDefnSimpleRepr with + | SynTypeDefnSimpleRepr.Record (_synAccessOption, fields, m) -> + yield dive () synTypeDefnRepr.Range (fun () -> visitor.VisitRecordDefn(path, fields, m)) + | SynTypeDefnSimpleRepr.Union (_synAccessOption, cases, m) -> + yield dive () synTypeDefnRepr.Range (fun () -> visitor.VisitUnionDefn(path, cases, m)) + | SynTypeDefnSimpleRepr.Enum (cases, m) -> + yield dive () synTypeDefnRepr.Range (fun () -> visitor.VisitEnumDefn(path, cases, m)) + | SynTypeDefnSimpleRepr.TypeAbbrev (_, synType, m) -> + yield dive synTypeDefnRepr synTypeDefnRepr.Range (fun _ -> visitor.VisitTypeAbbrev(path, synType, m)) + | _ -> () + yield! + synMemberDefns + |> normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path (fun _ -> None) + ] + |> pick tRange tydef + + and traverseSynMemberDefn path traverseInherit (m: SynMemberDefn) = + let pick (debugObj: obj) = pick m.Range debugObj let path = SyntaxNode.SynMemberDefn m :: path + match m with - | SynMemberDefn.Open(_longIdent, _range) -> None - | SynMemberDefn.Member(synBinding, _range) -> traverseSynBinding path synBinding - | SynMemberDefn.ImplicitCtor(_synAccessOption, _synAttributes, simplePats, _identOption, _doc, _range) -> + | SynMemberDefn.Open (_longIdent, _range) -> None + | SynMemberDefn.Member (synBinding, _range) -> traverseSynBinding path synBinding + | SynMemberDefn.GetSetMember (getBinding, setBinding, _, _) -> + match getBinding, setBinding with + | None, None -> None + | Some binding, None + | None, Some binding -> traverseSynBinding path binding + | Some getBinding, Some setBinding -> + traverseSynBinding path getBinding + |> Option.orElseWith (fun () -> traverseSynBinding path setBinding) + + | SynMemberDefn.ImplicitCtor (_synAccessOption, _synAttributes, simplePats, _identOption, _doc, _range) -> match simplePats with - | SynSimplePats.SimplePats(simplePats, _) -> visitor.VisitSimplePats(path, simplePats) + | SynSimplePats.SimplePats (simplePats, _) -> visitor.VisitSimplePats(path, simplePats) | _ -> None - | SynMemberDefn.ImplicitInherit(synType, synExpr, _identOption, range) -> + | SynMemberDefn.ImplicitInherit (synType, synExpr, _identOption, range) -> [ - dive () synType.Range (fun () -> + dive () synType.Range (fun () -> match traverseInherit (synType, range) with | None -> visitor.VisitImplicitInherit(path, traverseSynExpr path, synType, synExpr, range) | x -> x) - dive () synExpr.Range (fun() -> - visitor.VisitImplicitInherit(path, traverseSynExpr path, synType, synExpr, range) - ) - ] |> pick m - | SynMemberDefn.AutoProperty(synExpr=synExpr) -> traverseSynExpr path synExpr - | SynMemberDefn.LetBindings(synBindingList, isRecursive, _, range) -> + dive () synExpr.Range (fun () -> visitor.VisitImplicitInherit(path, traverseSynExpr path, synType, synExpr, range)) + ] + |> pick m + | SynMemberDefn.AutoProperty (synExpr = synExpr) -> traverseSynExpr path synExpr + | SynMemberDefn.LetBindings (synBindingList, isRecursive, _, range) -> match visitor.VisitLetOrUse(path, isRecursive, traverseSynBinding path, synBindingList, range) with | Some x -> Some x - | None -> synBindingList |> List.map (fun x -> dive x x.RangeOfBindingWithRhs (traverseSynBinding path)) |> pick m - | SynMemberDefn.AbstractSlot(_synValSig, _memberFlags, _range) -> None - | SynMemberDefn.Interface(interfaceType=synType; members=synMemberDefnsOption) -> + | None -> + synBindingList + |> List.map (fun x -> dive x x.RangeOfBindingWithRhs (traverseSynBinding path)) + |> pick m + | SynMemberDefn.AbstractSlot (_synValSig, _memberFlags, _range) -> None + | SynMemberDefn.Interface (interfaceType = synType; members = synMemberDefnsOption) -> match visitor.VisitInterfaceSynMemberDefnType(path, synType) with - | None -> - match synMemberDefnsOption with + | None -> + match synMemberDefnsOption with | None -> None - | Some(x) -> [ yield! x |> normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path (fun _ -> None) ] |> pick x + | Some (x) -> + [ + yield! + x + |> normalizeMembersToDealWithPeculiaritiesOfGettersAndSetters path (fun _ -> None) + ] + |> pick x | ok -> ok - | SynMemberDefn.Inherit(synType, _identOption, range) -> traverseInherit (synType, range) - | SynMemberDefn.ValField(_synField, _range) -> None - | SynMemberDefn.NestedType(synTypeDefn, _synAccessOption, _range) -> traverseSynTypeDefn path synTypeDefn + | SynMemberDefn.Inherit (synType, _identOption, range) -> traverseInherit (synType, range) + | SynMemberDefn.ValField (_synField, _range) -> None + | SynMemberDefn.NestedType (synTypeDefn, _synAccessOption, _range) -> traverseSynTypeDefn path synTypeDefn and traverseSynMatchClause origPath mc = let defaultTraverse mc = let path = SyntaxNode.SynMatchClause mc :: origPath + match mc with - | SynMatchClause(pat=synPat; whenExpr=synExprOption; resultExpr=synExpr) as all -> - [dive synPat synPat.Range (traversePat path) ] - @ - ([ + | SynMatchClause (pat = synPat; whenExpr = synExprOption; resultExpr = synExpr) as all -> + [ dive synPat synPat.Range (traversePat path) ] + @ ([ match synExprOption with | None -> () | Some guard -> yield guard yield synExpr - ] - |> List.map (fun x -> dive x x.Range (traverseSynExpr path)) - )|> pick all.Range all + ] + |> List.map (fun x -> dive x x.Range (traverseSynExpr path))) + |> pick all.Range all + visitor.VisitMatchClause(origPath, defaultTraverse, mc) and traverseSynBinding origPath b = let defaultTraverse b = let path = SyntaxNode.SynBinding b :: origPath + match b with - | SynBinding(headPat=synPat; expr=synExpr) -> + | SynBinding (headPat = synPat; expr = synExpr) -> match traversePat path synPat with | None -> traverseSynExpr path synExpr | x -> x - visitor.VisitBinding(origPath, defaultTraverse ,b) + + visitor.VisitBinding(origPath, defaultTraverse, b) match parseTree with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = l))-> + | ParsedInput.ImplFile (ParsedImplFileInput (modules = l)) -> let fileRange = #if DEBUG - match l with [] -> range0 | _ -> l |> List.map (fun x -> x.Range) |> List.reduce unionRanges + match l with + | [] -> range0 + | _ -> l |> List.map (fun x -> x.Range) |> List.reduce unionRanges #else - range0 // only used for asserting, does not matter in non-debug + range0 // only used for asserting, does not matter in non-debug #endif - l |> List.map (fun x -> dive x x.Range (traverseSynModuleOrNamespace [])) |> pick fileRange l + l + |> List.map (fun x -> dive x x.Range (traverseSynModuleOrNamespace [])) + |> pick fileRange l | ParsedInput.SigFile _sigFile -> None diff --git a/src/Compiler/Service/ServiceParsedInputOps.fs b/src/Compiler/Service/ServiceParsedInputOps.fs index 692539a1ca3..a7ffb760e5a 100644 --- a/src/Compiler/Service/ServiceParsedInputOps.fs +++ b/src/Compiler/Service/ServiceParsedInputOps.fs @@ -6,7 +6,7 @@ open System open System.IO open System.Collections.Generic open System.Text.RegularExpressions -open Internal.Utilities.Library +open Internal.Utilities.Library open FSharp.Compiler.Diagnostics open FSharp.Compiler.Syntax open FSharp.Compiler.Syntax.PrettyNaming @@ -21,20 +21,22 @@ module SourceFileImpl = 0 = String.Compare(".fsi", ext, StringComparison.OrdinalIgnoreCase) /// Additional #defines that should be in place when editing a file in a file editor such as VS. - let GetImplicitConditionalDefinesForEditing(isInteractive: bool) = - if isInteractive then ["INTERACTIVE";"EDITING"] // This is still used by the foreground parse - else ["COMPILED";"EDITING"] - + let GetImplicitConditionalDefinesForEditing (isInteractive: bool) = + if isInteractive then + [ "INTERACTIVE"; "EDITING" ] // This is still used by the foreground parse + else + [ "COMPILED"; "EDITING" ] + type CompletionPath = string list * string option // plid * residue [] -type FSharpInheritanceOrigin = +type FSharpInheritanceOrigin = | Class | Interface | Unknown [] -type InheritanceContext = +type InheritanceContext = | Class | Interface | Unknown @@ -48,7 +50,7 @@ type RecordContext = | Declaration of isInIdentifier: bool [] -type CompletionContext = +type CompletionContext = /// Completion context cannot be determined due to errors | Invalid @@ -84,7 +86,11 @@ type ShortIdents = ShortIdent[] type MaybeUnresolvedIdent = { Ident: ShortIdent; Resolved: bool } -type ModuleKind = { IsAutoOpen: bool; HasModuleSuffix: bool } +type ModuleKind = + { + IsAutoOpen: bool + HasModuleSuffix: bool + } [] type EntityKind = @@ -92,14 +98,18 @@ type EntityKind = | Type | FunctionOrValue of isActivePattern: bool | Module of ModuleKind + override x.ToString() = sprintf "%A" x type InsertionContextEntity = - { FullRelativeName: string - Qualifier: string - Namespace: string option - FullDisplayName: string - LastIdent: ShortIdent } + { + FullRelativeName: string + Qualifier: string + Namespace: string option + FullDisplayName: string + LastIdent: ShortIdent + } + override x.ToString() = sprintf "%A" x type ScopeKind = @@ -108,42 +118,54 @@ type ScopeKind = | NestedModule | OpenDeclaration | HashDirective + override x.ToString() = sprintf "%A" x -type InsertionContext = - { ScopeKind: ScopeKind - Pos: pos } +type InsertionContext = { ScopeKind: ScopeKind; Pos: pos } -type FSharpModule = - { Idents: ShortIdents - Range: range } +type FSharpModule = { Idents: ShortIdents; Range: range } type OpenStatementInsertionPoint = | TopLevel | Nearest -[] +[] module Entity = let getRelativeNamespace (targetNs: ShortIdents) (sourceNs: ShortIdents) = let rec loop index = - if index > targetNs.Length - 1 then sourceNs[index..] + if index > targetNs.Length - 1 then + sourceNs[index..] // target namespace is not a full parent of source namespace, keep the source ns as is - elif index > sourceNs.Length - 1 then sourceNs - elif targetNs[index] = sourceNs[index] then loop (index + 1) - else sourceNs[index..] - if sourceNs.Length = 0 || targetNs.Length = 0 then sourceNs - else loop 0 + elif index > sourceNs.Length - 1 then + sourceNs + elif targetNs[index] = sourceNs[index] then + loop (index + 1) + else + sourceNs[index..] + + if sourceNs.Length = 0 || targetNs.Length = 0 then + sourceNs + else + loop 0 let cutAutoOpenModules (autoOpenParent: ShortIdents option) (candidateNs: ShortIdents) = - let nsCount = + let nsCount = match autoOpenParent with - | Some parent when parent.Length > 0 -> - min (parent.Length - 1) candidateNs.Length + | Some parent when parent.Length > 0 -> min (parent.Length - 1) candidateNs.Length | _ -> candidateNs.Length - candidateNs[0..nsCount - 1] - let tryCreate (targetNamespace: ShortIdents option, targetScope: ShortIdents, partiallyQualifiedName: MaybeUnresolvedIdent[], - requiresQualifiedAccessParent: ShortIdents option, autoOpenParent: ShortIdents option, candidateNamespace: ShortIdents option, candidate: ShortIdents) = + candidateNs[0 .. nsCount - 1] + + let tryCreate + ( + targetNamespace: ShortIdents option, + targetScope: ShortIdents, + partiallyQualifiedName: MaybeUnresolvedIdent[], + requiresQualifiedAccessParent: ShortIdents option, + autoOpenParent: ShortIdents option, + candidateNamespace: ShortIdents option, + candidate: ShortIdents + ) = match candidate with | [||] -> [||] | _ -> @@ -154,189 +176,257 @@ module Entity = |> Array.filter (fun x -> x |> Array.exists (fun x -> not x.Resolved)) |> Array.choose (fun parts -> let parts = parts |> Array.map (fun x -> x.Ident) - if not (candidate |> Array.endsWith parts) then None - else - let identCount = parts.Length - let fullOpenableNs, restIdents = - let openableNsCount = - match requiresQualifiedAccessParent with - | Some parent -> min parent.Length candidate.Length - | None -> candidate.Length - candidate[0..openableNsCount - 2], candidate[openableNsCount - 1..] - - let openableNs = cutAutoOpenModules autoOpenParent fullOpenableNs - - let getRelativeNs ns = - match targetNamespace, candidateNamespace with - | Some targetNs, Some candidateNs when candidateNs = targetNs -> - getRelativeNamespace targetScope ns - | None, _ -> getRelativeNamespace targetScope ns - | _ -> ns - - let relativeNs = getRelativeNs openableNs - - match relativeNs, restIdents with - | [||], [||] -> None - | [||], [|_|] -> None - | _ -> - let fullRelativeName = Array.append (getRelativeNs fullOpenableNs) restIdents - let ns = - match relativeNs with - | [||] -> None - | _ when identCount > 1 && relativeNs.Length >= identCount -> - Some (relativeNs[0..relativeNs.Length - identCount] |> String.concat ".") - | _ -> Some (relativeNs |> String.concat ".") - let qualifier = - if fullRelativeName.Length > 1 && fullRelativeName.Length >= identCount then - fullRelativeName[0..fullRelativeName.Length - identCount] - else fullRelativeName - Some - { FullRelativeName = String.concat "." fullRelativeName //.[0..fullRelativeName.Length - identCount - 1] - Qualifier = String.concat "." qualifier - Namespace = ns - FullDisplayName = match restIdents with [|_|] -> "" | _ -> String.concat "." restIdents - LastIdent = Array.tryLast restIdents |> Option.defaultValue "" }) + + if not (candidate |> Array.endsWith parts) then + None + else + let identCount = parts.Length + + let fullOpenableNs, restIdents = + let openableNsCount = + match requiresQualifiedAccessParent with + | Some parent -> min parent.Length candidate.Length + | None -> candidate.Length + + candidate[0 .. openableNsCount - 2], candidate[openableNsCount - 1 ..] + + let openableNs = cutAutoOpenModules autoOpenParent fullOpenableNs + + let getRelativeNs ns = + match targetNamespace, candidateNamespace with + | Some targetNs, Some candidateNs when candidateNs = targetNs -> getRelativeNamespace targetScope ns + | None, _ -> getRelativeNamespace targetScope ns + | _ -> ns + + let relativeNs = getRelativeNs openableNs + + match relativeNs, restIdents with + | [||], [||] -> None + | [||], [| _ |] -> None + | _ -> + let fullRelativeName = Array.append (getRelativeNs fullOpenableNs) restIdents + + let ns = + match relativeNs with + | [||] -> None + | _ when identCount > 1 && relativeNs.Length >= identCount -> + Some(relativeNs[0 .. relativeNs.Length - identCount] |> String.concat ".") + | _ -> Some(relativeNs |> String.concat ".") + + let qualifier = + if fullRelativeName.Length > 1 && fullRelativeName.Length >= identCount then + fullRelativeName[0 .. fullRelativeName.Length - identCount] + else + fullRelativeName + + Some + { + FullRelativeName = String.concat "." fullRelativeName //.[0..fullRelativeName.Length - identCount - 1] + Qualifier = String.concat "." qualifier + Namespace = ns + FullDisplayName = + match restIdents with + | [| _ |] -> "" + | _ -> String.concat "." restIdents + LastIdent = Array.tryLast restIdents |> Option.defaultValue "" + }) module ParsedInput = - + let emptyStringSet = HashSet() - let GetRangeOfExprLeftOfDot(pos: pos, parsedInput) = - let CheckLongIdent(longIdent: LongIdent) = + let GetRangeOfExprLeftOfDot (pos: pos, parsedInput) = + let CheckLongIdent (longIdent: LongIdent) = // find the longest prefix before the "pos" dot - let mutable r = (List.head longIdent).idRange + let mutable r = (List.head longIdent).idRange let mutable couldBeBeforeFront = true + for i in longIdent do if posGeq pos i.idRange.End then r <- unionRanges r i.idRange couldBeBeforeFront <- false + couldBeBeforeFront, r - SyntaxTraversal.Traverse(pos, parsedInput, { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = - let expr = expr // fix debugger locals + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, traverseSynExpr, defaultTraverse, expr) = + let expr = expr // fix debugger locals + + match expr with + | SynExpr.LongIdent(longDotId = SynLongIdent ([ id ], [], [ Some _ ])) -> defaultTraverse (SynExpr.Ident(id)) + + | SynExpr.LongIdent (_, lid, _altNameRefCell, _) -> + let (SynLongIdent (longIdent, _, _)) = lid + let _, r = CheckLongIdent longIdent + Some r + + | SynExpr.LongIdentSet (lid, synExpr, _) -> + let (SynLongIdent (longIdent, _, _)) = lid + + if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then + traverseSynExpr synExpr + else + let _, r = CheckLongIdent longIdent + Some r + + | SynExpr.DotGet (synExpr, _dotm, lid, _) -> + let (SynLongIdent (longIdent, _, _)) = lid + + if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then + traverseSynExpr synExpr + else + let inFront, r = CheckLongIdent longIdent + + if inFront then + Some synExpr.Range + else + // see comment below for SynExpr.DotSet + Some(unionRanges synExpr.Range r) + + | SynExpr.Set (synExpr, synExpr2, range) -> + if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then + traverseSynExpr synExpr + elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then + traverseSynExpr synExpr2 + else + Some range + + | SynExpr.DotSet (synExpr, lid, synExpr2, _) -> + let (SynLongIdent (longIdent, _, _)) = lid + + if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then + traverseSynExpr synExpr + elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then + traverseSynExpr synExpr2 + else + let inFront, r = CheckLongIdent longIdent + + if inFront then + Some synExpr.Range + else + // f(0).X.Y.Z + // ^ + // - r has this value + // ---- synExpr.Range has this value + // ------ we want this value + Some(unionRanges synExpr.Range r) + + | SynExpr.DotNamedIndexedPropertySet (synExpr, lid, synExpr2, synExpr3, _) -> + let (SynLongIdent (longIdent, _, _)) = lid + + if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then + traverseSynExpr synExpr + elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then + traverseSynExpr synExpr2 + elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr3.Range pos then + traverseSynExpr synExpr3 + else + let inFront, r = CheckLongIdent longIdent + + if inFront then + Some synExpr.Range + else + Some(unionRanges synExpr.Range r) + + // get this for e.g. "bar()." + | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _) -> + if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then + traverseSynExpr synExpr + else + Some synExpr.Range + + | SynExpr.FromParseError (synExpr, range) -> + if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then + traverseSynExpr synExpr + else + Some range + + | SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ ident ])), rhs, _) when + ident.idText = "op_ArrayLookup" + && not (SyntaxTraversal.rangeContainsPosLeftEdgeInclusive rhs.Range pos) + -> + + match defaultTraverse expr with + | None -> + // (expr).(expr) is an ML-deprecated array lookup, but we want intellisense on the dot + // also want it for e.g. [|arr|].(0) + Some expr.Range + | x -> x // we found the answer deeper somewhere in the lhs + + | SynExpr.Const (SynConst.Double _, range) -> Some range + + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(pos, parsedInput, visitor) + + /// searches for the expression island suitable for the evaluation by the debugger + let TryFindExpressionIslandInPosition (pos: pos, parsedInput) = + let getLidParts (lid: LongIdent) = + lid + |> Seq.takeWhile (fun i -> posGeq pos i.idRange.Start) + |> Seq.map (fun i -> i.idText) + |> Seq.toList + + // tries to locate simple expression island + // foundCandidate = false means that we are looking for the candidate expression + // foundCandidate = true - we found candidate (DotGet) and now drill down to the left part + let rec TryGetExpression foundCandidate expr = match expr with - | SynExpr.LongIdent(longDotId = SynLongIdent([id], [], [Some _])) -> - defaultTraverse (SynExpr.Ident(id)) - | SynExpr.LongIdent (_, SynLongIdent(longIdent, _, _), _altNameRefCell, _range) -> - let _, r = CheckLongIdent longIdent - Some r - | SynExpr.LongIdentSet (SynLongIdent(longIdent, _, _), synExpr, _range) -> - if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - let _, r = CheckLongIdent longIdent - Some r - | SynExpr.DotGet (synExpr, _dotm, SynLongIdent(longIdent, _, _), _range) -> - if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - let inFront, r = CheckLongIdent longIdent - if inFront then - Some synExpr.Range - else - // see comment below for SynExpr.DotSet - Some (unionRanges synExpr.Range r) - | SynExpr.Set (synExpr, synExpr2, range) -> - if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then - traverseSynExpr synExpr2 - else - Some range - | SynExpr.DotSet (synExpr, SynLongIdent(longIdent, _, _), synExpr2, _range) -> - if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then - traverseSynExpr synExpr2 - else - let inFront, r = CheckLongIdent longIdent - if inFront then - Some synExpr.Range - else - // f(0).X.Y.Z - // ^ - // - r has this value - // ---- synExpr.Range has this value - // ------ we want this value - Some (unionRanges synExpr.Range r) - | SynExpr.DotNamedIndexedPropertySet (synExpr, SynLongIdent(longIdent, _, _), synExpr2, synExpr3, _range) -> - if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then - traverseSynExpr synExpr2 - elif SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr3.Range pos then - traverseSynExpr synExpr3 - else - let inFront, r = CheckLongIdent longIdent - if inFront then - Some synExpr.Range + | SynExpr.Paren (e, _, _, _) when foundCandidate -> TryGetExpression foundCandidate e + + | SynExpr.LongIdent (_isOptional, SynLongIdent (lid, _, _), _altNameRefCell, _m) -> getLidParts lid |> Some + + | SynExpr.DotGet (leftPart, _, SynLongIdent (lid, _, _), _) when (rangeContainsPos (rangeOfLid lid) pos) || foundCandidate -> + // requested position is at the lid part of the DotGet + // process left part and append result to the result of processing lid + let leftPartResult = TryGetExpression true leftPart + + match leftPartResult with + | Some leftPartResult -> [ yield! leftPartResult; yield! getLidParts lid ] |> Some + | None -> None + + | SynExpr.FromParseError (synExpr, _) -> TryGetExpression foundCandidate synExpr + + | _ -> None + + let rec visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(_, _traverseSynExpr, defaultTraverse, expr) = + if rangeContainsPos expr.Range pos then + match TryGetExpression false expr with + | Some parts -> parts |> String.concat "." |> Some + | _ -> defaultTraverse expr else - Some (unionRanges synExpr.Range r) - | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _range) -> // get this for e.g. "bar()." - if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - Some synExpr.Range - | SynExpr.FromParseError (synExpr, range) -> - if SyntaxTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - Some range - | SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ident])), rhs, _) - when ident.idText = "op_ArrayLookup" - && not(SyntaxTraversal.rangeContainsPosLeftEdgeInclusive rhs.Range pos) -> - match defaultTraverse expr with - | None -> - // (expr).(expr) is an ML-deprecated array lookup, but we want intellisense on the dot - // also want it for e.g. [|arr|].(0) - Some expr.Range - | x -> x // we found the answer deeper somewhere in the lhs - | SynExpr.Const (SynConst.Double _, range) -> Some range - | _ -> defaultTraverse expr - }) - - /// searches for the expression island suitable for the evaluation by the debugger - let TryFindExpressionIslandInPosition(pos: pos, parsedInput) = - let getLidParts (lid : LongIdent) = - lid - |> Seq.takeWhile (fun i -> posGeq pos i.idRange.Start) - |> Seq.map (fun i -> i.idText) - |> Seq.toList - - // tries to locate simple expression island - // foundCandidate = false means that we are looking for the candidate expression - // foundCandidate = true - we found candidate (DotGet) and now drill down to the left part - let rec TryGetExpression foundCandidate expr = - match expr with - | SynExpr.Paren (e, _, _, _) when foundCandidate -> - TryGetExpression foundCandidate e - | SynExpr.LongIdent (_isOptional, SynLongIdent(lid, _, _), _altNameRefCell, _m) -> - getLidParts lid |> Some - | SynExpr.DotGet (leftPart, _, SynLongIdent(lid, _, _), _) when (rangeContainsPos (rangeOfLid lid) pos) || foundCandidate -> - // requested position is at the lid part of the DotGet - // process left part and append result to the result of processing lid - let leftPartResult = TryGetExpression true leftPart - match leftPartResult with - | Some leftPartResult -> - [ - yield! leftPartResult - yield! getLidParts lid - ] |> Some - | None -> None - | SynExpr.FromParseError (synExpr, _range) -> TryGetExpression foundCandidate synExpr - | _ -> None + None + } - let rec walker = - { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = - if rangeContainsPos expr.Range pos then - match TryGetExpression false expr with - | Some parts -> parts |> String.concat "." |> Some - | _ -> defaultTraverse expr - else - None } - SyntaxTraversal.Traverse(pos, parsedInput, walker) + SyntaxTraversal.Traverse(pos, parsedInput, visitor) + + let traverseLidOrElse pos (optExprIfLeftOfLongId: SynExpr option) (SynLongIdent (lid, dots, _) as lidwd) = + let resultIfLeftOfLongId = + match optExprIfLeftOfLongId with + | None -> None + | Some e -> Some(e.Range.End, posGeq lidwd.Range.Start pos) + + let dotSearch = + dots + |> List.mapi (fun i x -> i, x) + |> List.rev + |> List.tryFind (fun (_, m) -> posGt pos m.Start) + + match dotSearch with + | None -> resultIfLeftOfLongId + | Some (n, _) -> + let flag = + // foo.$ + (lid.Length = n + 1) + || + // foo.$bar + posGeq lid[n + 1].idRange.Start pos + + Some(lid[n].idRange.End, flag) // Given a cursor position here: // f(x) . ident @@ -350,320 +440,431 @@ module ParsedInput = // ^ // would return None // TODO would be great to unify this with GetRangeOfExprLeftOfDot above, if possible, as they are similar - let TryFindExpressionASTLeftOfDotLeftOfCursor(pos, parsedInput) = + let TryFindExpressionASTLeftOfDotLeftOfCursor (pos, parsedInput) = let dive x = SyntaxTraversal.dive x let pick x = SyntaxTraversal.pick pos x - let walker = + + let visitor = { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = + member _.VisitExpr(_, traverseSynExpr, defaultTraverse, expr) = let pick = pick expr.Range - let traverseSynExpr, defaultTraverse, expr = traverseSynExpr, defaultTraverse, expr // for debugging: debugger does not get object expression params as local vars - if not(rangeContainsPos expr.Range pos) then + let traverseSynExpr, defaultTraverse, expr = traverseSynExpr, defaultTraverse, expr // for debugging: debugger does not get object expression params as local vars + + if not (rangeContainsPos expr.Range pos) then match expr with | SynExpr.DiscardAfterMissingQualificationAfterDot (e, _m) -> // This happens with e.g. "f(x) . $" when you bring up a completion list a few spaces after a dot. The cursor is not 'in the parse tree', // but the dive algorithm will dive down into this node, and this is the one case where we do want to give a result despite the cursor // not properly being in a node. match traverseSynExpr e with - | None -> Some (e.Range.End, false) + | None -> Some(e.Range.End, false) | r -> r - | _ -> - // This happens for e.g. "System.Console.[]$", where the ".[]" token is thrown away by the parser and we dive into the System.Console longId + | _ -> + // This happens for e.g. "System.Console.[]$", where the ".[]" token is thrown away by the parser and we dive into the System.Console longId // even though the cursor/dot is not in there. In those cases we want to return None, because there is not really a dot completion before // the cursor location. None else - let rec traverseLidOrElse (optExprIfLeftOfLongId : SynExpr option) (SynLongIdent(lid, dots, _) as lidwd) = - let resultIfLeftOfLongId = - match optExprIfLeftOfLongId with - | None -> None - | Some e -> Some (e.Range.End, posGeq lidwd.Range.Start pos) - match dots |> List.mapi (fun i x -> i, x) |> List.rev |> List.tryFind (fun (_, m) -> posGt pos m.Start) with - | None -> resultIfLeftOfLongId - | Some (n, _) -> Some ((List.item n lid).idRange.End, (List.length lid = n+1) // foo.$ - || (posGeq (List.item (n+1) lid).idRange.Start pos)) // foo.$bar match expr with - | SynExpr.LongIdent (longDotId = SynLongIdent([id], [], [Some _])) -> - defaultTraverse (SynExpr.Ident(id)) - | SynExpr.LongIdent (_isOptional, lidwd, _altNameRefCell, _m) -> - traverseLidOrElse None lidwd + | SynExpr.LongIdent(longDotId = SynLongIdent ([ id ], [], [ Some _ ])) -> defaultTraverse (SynExpr.Ident(id)) + | SynExpr.LongIdent (_isOptional, lidwd, _altNameRefCell, _m) -> traverseLidOrElse pos None lidwd + | SynExpr.LongIdentSet (lidwd, exprRhs, _m) -> - [ dive lidwd lidwd.Range (traverseLidOrElse None) - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr - | SynExpr.DotGet (exprLeft, dotm, lidwd, _m) -> - let afterDotBeforeLid = mkRange dotm.FileName dotm.End lidwd.Range.Start - [ dive exprLeft exprLeft.Range traverseSynExpr - dive exprLeft afterDotBeforeLid (fun e -> Some (e.Range.End, true)) - dive lidwd lidwd.Range (traverseLidOrElse (Some exprLeft)) - ] |> pick expr + [ + dive lidwd lidwd.Range (traverseLidOrElse pos None) + dive exprRhs exprRhs.Range traverseSynExpr + ] + |> pick expr + + | SynExpr.DotGet (exprLeft, mDot, lidwd, _m) -> + let afterDotBeforeLid = mkRange mDot.FileName mDot.End lidwd.Range.Start + + [ + dive exprLeft exprLeft.Range traverseSynExpr + dive exprLeft afterDotBeforeLid (fun e -> Some(e.Range.End, true)) + dive lidwd lidwd.Range (traverseLidOrElse pos (Some exprLeft)) + ] + |> pick expr + | SynExpr.DotSet (exprLeft, lidwd, exprRhs, _m) -> - [ dive exprLeft exprLeft.Range traverseSynExpr - dive lidwd lidwd.Range (traverseLidOrElse(Some exprLeft)) - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr + [ + dive exprLeft exprLeft.Range traverseSynExpr + dive lidwd lidwd.Range (traverseLidOrElse pos (Some exprLeft)) + dive exprRhs exprRhs.Range traverseSynExpr + ] + |> pick expr + | SynExpr.Set (exprLeft, exprRhs, _m) -> - [ dive exprLeft exprLeft.Range traverseSynExpr - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr + [ + dive exprLeft exprLeft.Range traverseSynExpr + dive exprRhs exprRhs.Range traverseSynExpr + ] + |> pick expr + | SynExpr.NamedIndexedPropertySet (lidwd, exprIndexer, exprRhs, _m) -> - [ dive lidwd lidwd.Range (traverseLidOrElse None) - dive exprIndexer exprIndexer.Range traverseSynExpr - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr + [ + dive lidwd lidwd.Range (traverseLidOrElse pos None) + dive exprIndexer exprIndexer.Range traverseSynExpr + dive exprRhs exprRhs.Range traverseSynExpr + ] + |> pick expr + | SynExpr.DotNamedIndexedPropertySet (exprLeft, lidwd, exprIndexer, exprRhs, _m) -> - [ dive exprLeft exprLeft.Range traverseSynExpr - dive lidwd lidwd.Range (traverseLidOrElse(Some exprLeft)) - dive exprIndexer exprIndexer.Range traverseSynExpr - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr + [ + dive exprLeft exprLeft.Range traverseSynExpr + dive lidwd lidwd.Range (traverseLidOrElse pos (Some exprLeft)) + dive exprIndexer exprIndexer.Range traverseSynExpr + dive exprRhs exprRhs.Range traverseSynExpr + ] + |> pick expr + | SynExpr.Const (SynConst.Double _, m) -> if posEq m.End pos then // the cursor is at the dot - Some (m.End, false) + Some(m.End, false) else // the cursor is left of the dot None + | SynExpr.DiscardAfterMissingQualificationAfterDot (e, m) -> match traverseSynExpr e with - | None -> + | None -> if posEq m.End pos then // the cursor is at the dot - Some (e.Range.End, false) + Some(e.Range.End, false) else // the cursor is left of the dot None | r -> r - | SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ident])), lhs, _m) - when ident.idText = "op_ArrayLookup" - && not(SyntaxTraversal.rangeContainsPosLeftEdgeInclusive lhs.Range pos) -> + + | SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ ident ])), lhs, _m) when + ident.idText = "op_ArrayLookup" + && not (SyntaxTraversal.rangeContainsPosLeftEdgeInclusive lhs.Range pos) + -> match defaultTraverse expr with | None -> // (expr).(expr) is an ML-deprecated array lookup, but we want intellisense on the dot // also want it for e.g. [|arr|].(0) - Some (lhs.Range.End, false) - | x -> x // we found the answer deeper somewhere in the lhs - | _ -> defaultTraverse expr } - SyntaxTraversal.Traverse(pos, parsedInput, walker) - + Some(lhs.Range.End, false) + | x -> x // we found the answer deeper somewhere in the lhs + | _ -> defaultTraverse expr + } + + SyntaxTraversal.Traverse(pos, parsedInput, visitor) + let GetEntityKind (pos: pos, parsedInput: ParsedInput) : EntityKind option = - let (|ConstructorPats|) = function + let (|ConstructorPats|) pats = + match pats with | SynArgPats.Pats ps -> ps - | SynArgPats.NamePatPairs(xs, _) -> List.map (fun (_, _, pat) -> pat) xs + | SynArgPats.NamePatPairs (xs, _) -> List.map (fun (_, _, pat) -> pat) xs - /// An recursive pattern that collect all sequential expressions to avoid StackOverflowException - let rec (|Sequentials|_|) = function - | SynExpr.Sequential (_, _, e, Sequentials es, _) -> Some (e :: es) - | SynExpr.Sequential (_, _, e1, e2, _) -> Some [e1; e2] + /// A recursive pattern that collect all sequential expressions to avoid StackOverflowException + let rec (|Sequentials|_|) expr = + match expr with + | SynExpr.Sequential (_, _, e, Sequentials es, _) -> Some(e :: es) + | SynExpr.Sequential (_, _, e1, e2, _) -> Some [ e1; e2 ] | _ -> None let inline isPosInRange range = rangeContainsPos range pos let inline ifPosInRange range f = - if isPosInRange range then f() - else None + if isPosInRange range then f () else None - let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.tryPick (walkSynModuleOrNamespace true) moduleOrNamespaceList - and walkSynModuleOrNamespace isTopLevel (SynModuleOrNamespace(decls = decls; attribs = Attributes attrs; range = r)) = + and walkSynModuleOrNamespace isTopLevel inp = + let (SynModuleOrNamespace (decls = decls; attribs = Attributes attrs; range = r)) = + inp + List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> ifPosInRange r (fun _ -> List.tryPick (walkSynModuleDecl isTopLevel) decls)) - and walkAttribute (attr: SynAttribute) = - if isPosInRange attr.Range then Some EntityKind.Attribute else None + and walkAttribute (attr: SynAttribute) = + if isPosInRange attr.Range then + Some EntityKind.Attribute + else + None |> Option.orElseWith (fun () -> walkExprWithKind (Some EntityKind.Type) attr.ArgExpr) - and walkTypar (SynTypar (ident, _, _)) = ifPosInRange ident.idRange (fun _ -> Some EntityKind.Type) + and walkTypar typar = + let (SynTypar (ident, _, _)) = typar + ifPosInRange ident.idRange (fun _ -> Some EntityKind.Type) + + and walkTyparDecl typarDecl = + let (SynTyparDecl (Attributes attrs, typar)) = typarDecl - and walkTyparDecl (SynTyparDecl.SynTyparDecl (Attributes attrs, typar)) = List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> walkTypar typar) - + and walkTypeConstraint cx = match cx with | SynTypeConstraint.WhereTyparDefaultsToType (t1, t2, _) -> walkTypar t1 |> Option.orElseWith (fun () -> walkType t2) - | SynTypeConstraint.WhereTyparIsValueType(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsReferenceType(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsUnmanaged(t, _) -> walkTypar t + | SynTypeConstraint.WhereTyparIsValueType (t, _) -> walkTypar t + | SynTypeConstraint.WhereTyparIsReferenceType (t, _) -> walkTypar t + | SynTypeConstraint.WhereTyparIsUnmanaged (t, _) -> walkTypar t | SynTypeConstraint.WhereTyparSupportsNull (t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsComparable(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsEquatable(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparSubtypeOfType(t, ty, _) -> walkTypar t |> Option.orElseWith (fun () -> walkType ty) - | SynTypeConstraint.WhereTyparSupportsMember(ts, sign, _) -> + | SynTypeConstraint.WhereTyparIsComparable (t, _) -> walkTypar t + | SynTypeConstraint.WhereTyparIsEquatable (t, _) -> walkTypar t + | SynTypeConstraint.WhereTyparSubtypeOfType (t, ty, _) -> walkTypar t |> Option.orElseWith (fun () -> walkType ty) + | SynTypeConstraint.WhereTyparSupportsMember (ts, sign, _) -> List.tryPick walkType ts |> Option.orElseWith (fun () -> walkMemberSig sign) - | SynTypeConstraint.WhereTyparIsEnum(t, ts, _) -> walkTypar t |> Option.orElseWith (fun () -> List.tryPick walkType ts) - | SynTypeConstraint.WhereTyparIsDelegate(t, ts, _) -> walkTypar t |> Option.orElseWith (fun () -> List.tryPick walkType ts) + | SynTypeConstraint.WhereTyparIsEnum (t, ts, _) -> walkTypar t |> Option.orElseWith (fun () -> List.tryPick walkType ts) + | SynTypeConstraint.WhereTyparIsDelegate (t, ts, _) -> walkTypar t |> Option.orElseWith (fun () -> List.tryPick walkType ts) and walkPatWithKind (kind: EntityKind option) pat = - match pat with + match pat with | SynPat.Ands (pats, _) -> List.tryPick walkPat pats - | SynPat.As (pat1, pat2, _) -> List.tryPick walkPat [pat1; pat2] - | SynPat.Typed(pat, t, _) -> walkPat pat |> Option.orElseWith (fun () -> walkType t) - | SynPat.Attrib(pat, Attributes attrs, _) -> walkPat pat |> Option.orElseWith (fun () -> List.tryPick walkAttribute attrs) - | SynPat.Or(pat1, pat2, _, _) -> List.tryPick walkPat [pat1; pat2] - | SynPat.LongIdent(typarDecls=typars; argPats=ConstructorPats pats; range=r) -> + | SynPat.As (pat1, pat2, _) -> List.tryPick walkPat [ pat1; pat2 ] + | SynPat.Typed (pat, t, _) -> walkPat pat |> Option.orElseWith (fun () -> walkType t) + | SynPat.Attrib (pat, Attributes attrs, _) -> walkPat pat |> Option.orElseWith (fun () -> List.tryPick walkAttribute attrs) + | SynPat.Or (pat1, pat2, _, _) -> List.tryPick walkPat [ pat1; pat2 ] + | SynPat.LongIdent (typarDecls = typars; argPats = ConstructorPats pats; range = r) -> ifPosInRange r (fun _ -> kind) - |> Option.orElseWith (fun () -> - typars - |> Option.bind (fun (ValTyparDecls (typars, constraints, _)) -> + |> Option.orElseWith (fun () -> + typars + |> Option.bind (fun (ValTyparDecls (typars, constraints, _)) -> List.tryPick walkTyparDecl typars |> Option.orElseWith (fun () -> List.tryPick walkTypeConstraint constraints))) |> Option.orElseWith (fun () -> List.tryPick walkPat pats) - | SynPat.Tuple(_, pats, _) -> List.tryPick walkPat pats - | SynPat.Paren(pat, _) -> walkPat pat - | SynPat.ArrayOrList(_, pats, _) -> List.tryPick walkPat pats - | SynPat.IsInst(t, _) -> walkType t - | SynPat.QuoteExpr(e, _) -> walkExpr e + | SynPat.Tuple (_, pats, _) -> List.tryPick walkPat pats + | SynPat.Paren (pat, _) -> walkPat pat + | SynPat.ArrayOrList (_, pats, _) -> List.tryPick walkPat pats + | SynPat.IsInst (t, _) -> walkType t + | SynPat.QuoteExpr (e, _) -> walkExpr e | _ -> None and walkPat = walkPatWithKind None and walkBinding bind = - let (SynBinding(attributes=Attributes attrs; headPat=pat; returnInfo=returnInfo; expr=e)) = bind + let (SynBinding (attributes = Attributes attrs; headPat = pat; returnInfo = returnInfo; expr = e)) = + bind + List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> walkPat pat) |> Option.orElseWith (fun () -> walkExpr e) - |> Option.orElseWith (fun () -> + |> Option.orElseWith (fun () -> match returnInfo with | Some (SynBindingReturnInfo (t, _, _)) -> walkType t | None -> None) - and walkInterfaceImpl (SynInterfaceImpl(bindings=bindings)) = - List.tryPick walkBinding bindings + and walkInterfaceImpl (SynInterfaceImpl (bindings = bindings)) = List.tryPick walkBinding bindings and walkType ty = match ty with - | SynType.LongIdent ident -> + | SynType.LongIdent ident -> // we protect it with try..with because System.Exception : rangeOfLidwd may raise // at FSharp.Compiler.Syntax.LongIdentWithDots.get_Range() in D:\j\workspace\release_ci_pa---3f142ccc\src\ast.fs: line 156 - try ifPosInRange ident.Range (fun _ -> Some EntityKind.Type) with _ -> None - | SynType.App(ty, _, types, _, _, _, _) -> - walkType ty |> Option.orElseWith (fun () -> List.tryPick walkType types) - | SynType.LongIdentApp(_, _, _, types, _, _, _) -> List.tryPick walkType types - | SynType.Tuple(_, ts, _) -> ts |> List.tryPick (fun (_, t) -> walkType t) - | SynType.Array(_, t, _) -> walkType t - | SynType.Fun(t1, t2, _) -> walkType t1 |> Option.orElseWith (fun () -> walkType t2) - | SynType.WithGlobalConstraints(t, _, _) -> walkType t - | SynType.HashConstraint(t, _) -> walkType t - | SynType.MeasureDivide(t1, t2, _) -> walkType t1 |> Option.orElseWith (fun () -> walkType t2) - | SynType.MeasurePower(t, _, _) -> walkType t - | SynType.Paren(t, _) -> walkType t + try + ifPosInRange ident.Range (fun _ -> Some EntityKind.Type) + with _ -> + None + | SynType.App (ty, _, types, _, _, _, _) -> walkType ty |> Option.orElseWith (fun () -> List.tryPick walkType types) + | SynType.LongIdentApp (_, _, _, types, _, _, _) -> List.tryPick walkType types + | SynType.Tuple (_, ts, _) -> ts |> List.tryPick (fun (_, t) -> walkType t) + | SynType.Array (_, t, _) -> walkType t + | SynType.Fun (argType = t1; returnType = t2) -> walkType t1 |> Option.orElseWith (fun () -> walkType t2) + | SynType.WithGlobalConstraints (t, _, _) -> walkType t + | SynType.HashConstraint (t, _) -> walkType t + | SynType.MeasureDivide (t1, t2, _) -> walkType t1 |> Option.orElseWith (fun () -> walkType t2) + | SynType.MeasurePower (t, _, _) -> walkType t + | SynType.Paren (t, _) -> walkType t | _ -> None - and walkClause (SynMatchClause(pat=pat; whenExpr=e1; resultExpr=e2)) = - walkPatWithKind (Some EntityKind.Type) pat + and walkClause clause = + let (SynMatchClause (pat = pat; whenExpr = e1; resultExpr = e2)) = clause + + walkPatWithKind (Some EntityKind.Type) pat |> Option.orElseWith (fun () -> walkExpr e2) |> Option.orElseWith (fun () -> Option.bind walkExpr e1) - and walkExprWithKind (parentKind: EntityKind option) expr = + and walkExprWithKind parentKind expr = match expr with - | SynExpr.LongIdent(_, SynLongIdent([ident], _, [ Some _]), _, _) -> - ifPosInRange ident.idRange (fun _ -> Some (EntityKind.FunctionOrValue false)) - | SynExpr.LongIdent (_, SynLongIdent(_, dotRanges, _), _, r) -> + | SynExpr.LongIdent (_, SynLongIdent ([ ident ], _, [ Some _ ]), _, _) -> + ifPosInRange ident.idRange (fun _ -> Some(EntityKind.FunctionOrValue false)) + + | SynExpr.LongIdent (_, SynLongIdent (_, dotRanges, _), _, r) -> match dotRanges with - | [] when isPosInRange r -> parentKind |> Option.orElseWith (fun () -> Some (EntityKind.FunctionOrValue false)) - | firstDotRange :: _ -> - let firstPartRange = + | [] when isPosInRange r -> + parentKind + |> Option.orElseWith (fun () -> Some(EntityKind.FunctionOrValue false)) + | firstDotRange :: _ -> + let firstPartRange = mkRange "" r.Start (mkPos firstDotRange.StartLine (firstDotRange.StartColumn - 1)) + if isPosInRange firstPartRange then - parentKind |> Option.orElseWith (fun () -> Some (EntityKind.FunctionOrValue false)) - else None + parentKind + |> Option.orElseWith (fun () -> Some(EntityKind.FunctionOrValue false)) + else + None | _ -> None + | SynExpr.Paren (e, _, _, _) -> walkExprWithKind parentKind e + | SynExpr.Quote (_, _, e, _, _) -> walkExprWithKind parentKind e + | SynExpr.Typed (e, _, _) -> walkExprWithKind parentKind e + | SynExpr.Tuple (_, es, _, _) -> List.tryPick (walkExprWithKind parentKind) es + | SynExpr.ArrayOrList (_, es, _) -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.Record (_, _, fields, r) -> + + | SynExpr.Record (_, _, fields, r) -> ifPosInRange r (fun _ -> - fields |> List.tryPick (fun (SynExprRecordField(expr=e)) -> e |> Option.bind (walkExprWithKind parentKind))) + fields + |> List.tryPick (fun (SynExprRecordField (expr = e)) -> e |> Option.bind (walkExprWithKind parentKind))) + | SynExpr.New (_, t, e, _) -> walkExprWithKind parentKind e |> Option.orElseWith (fun () -> walkType t) - | SynExpr.ObjExpr (objType=ty; bindings=bindings; members=ms; extraImpls=ifaces) -> + + | SynExpr.ObjExpr (objType = ty; bindings = bindings; members = ms; extraImpls = ifaces) -> let bindings = unionBindingAndMembers bindings ms + walkType ty |> Option.orElseWith (fun () -> List.tryPick walkBinding bindings) |> Option.orElseWith (fun () -> List.tryPick walkInterfaceImpl ifaces) - | SynExpr.While (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.For (identBody=e1; toBody=e2; doBody=e3) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] - | SynExpr.ForEach (_, _, _, _, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + + | SynExpr.While (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2 ] + + | SynExpr.For (identBody = e1; toBody = e2; doBody = e3) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2; e3 ] + + | SynExpr.ForEach (_, _, _, _, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2 ] + | SynExpr.ArrayOrListComputed (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.ComputationExpr (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.Lambda (body = e) -> walkExprWithKind parentKind e - | SynExpr.MatchLambda (_, _, synMatchClauseList, _, _) -> - List.tryPick walkClause synMatchClauseList - | SynExpr.Match (expr=e; clauses=synMatchClauseList) -> - walkExprWithKind parentKind e |> Option.orElseWith (fun () -> List.tryPick walkClause synMatchClauseList) + + | SynExpr.MatchLambda (_, _, synMatchClauseList, _, _) -> List.tryPick walkClause synMatchClauseList + + | SynExpr.Match (expr = e; clauses = synMatchClauseList) -> + walkExprWithKind parentKind e + |> Option.orElseWith (fun () -> List.tryPick walkClause synMatchClauseList) + | SynExpr.Do (e, _) -> walkExprWithKind parentKind e + | SynExpr.Assert (e, _) -> walkExprWithKind parentKind e - | SynExpr.App (_, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.TypeApp (e, _, tys, _, _, _, _) -> - walkExprWithKind (Some EntityKind.Type) e |> Option.orElseWith (fun () -> List.tryPick walkType tys) - | SynExpr.LetOrUse (bindings=bindings; body=e) -> List.tryPick walkBinding bindings |> Option.orElseWith (fun () -> walkExprWithKind parentKind e) - | SynExpr.TryWith (tryExpr=e; withCases=clauses) -> walkExprWithKind parentKind e |> Option.orElseWith (fun () -> List.tryPick walkClause clauses) - | SynExpr.TryFinally (tryExpr=e1; finallyExpr=e2) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + + | SynExpr.App (_, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2 ] + + | SynExpr.TypeApp (e, _, tys, _, _, _, _) -> + walkExprWithKind (Some EntityKind.Type) e + |> Option.orElseWith (fun () -> List.tryPick walkType tys) + + | SynExpr.LetOrUse (bindings = bindings; body = e) -> + List.tryPick walkBinding bindings + |> Option.orElseWith (fun () -> walkExprWithKind parentKind e) + + | SynExpr.TryWith (tryExpr = e; withCases = clauses) -> + walkExprWithKind parentKind e + |> Option.orElseWith (fun () -> List.tryPick walkClause clauses) + + | SynExpr.TryFinally (tryExpr = e1; finallyExpr = e2) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2 ] + | SynExpr.Lazy (e, _) -> walkExprWithKind parentKind e + | Sequentials es -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.IfThenElse (ifExpr=e1; thenExpr=e2; elseExpr=e3) -> - List.tryPick (walkExprWithKind parentKind) [e1; e2] |> Option.orElseWith (fun () -> match e3 with None -> None | Some e -> walkExprWithKind parentKind e) - | SynExpr.Ident ident -> ifPosInRange ident.idRange (fun _ -> Some (EntityKind.FunctionOrValue false)) + + | SynExpr.IfThenElse (ifExpr = e1; thenExpr = e2; elseExpr = e3) -> + List.tryPick (walkExprWithKind parentKind) [ e1; e2 ] + |> Option.orElseWith (fun () -> + match e3 with + | None -> None + | Some e -> walkExprWithKind parentKind e) + + | SynExpr.Ident ident -> ifPosInRange ident.idRange (fun _ -> Some(EntityKind.FunctionOrValue false)) + | SynExpr.LongIdentSet (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.DotGet (e, _, _, _) -> walkExprWithKind parentKind e + | SynExpr.DotSet (e, _, _, _) -> walkExprWithKind parentKind e + | SynExpr.Set (e, _, _) -> walkExprWithKind parentKind e - | SynExpr.DotIndexedGet (e, args, _, _) -> walkExprWithKind parentKind e |> Option.orElseWith (fun () -> walkExprWithKind parentKind args) - | SynExpr.DotIndexedSet (e, args, _, _, _, _) -> walkExprWithKind parentKind e |> Option.orElseWith (fun () -> walkExprWithKind parentKind args) - | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] + + | SynExpr.DotIndexedGet (e, args, _, _) -> + walkExprWithKind parentKind e + |> Option.orElseWith (fun () -> walkExprWithKind parentKind args) + + | SynExpr.DotIndexedSet (e, args, _, _, _, _) -> + walkExprWithKind parentKind e + |> Option.orElseWith (fun () -> walkExprWithKind parentKind args) + + | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2 ] + + | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2; e3 ] + | SynExpr.TypeTest (e, t, _) -> walkExprWithKind parentKind e |> Option.orElseWith (fun () -> walkType t) + | SynExpr.Upcast (e, t, _) -> walkExprWithKind parentKind e |> Option.orElseWith (fun () -> walkType t) + | SynExpr.Downcast (e, t, _) -> walkExprWithKind parentKind e |> Option.orElseWith (fun () -> walkType t) + | SynExpr.InferredUpcast (e, _) -> walkExprWithKind parentKind e + | SynExpr.InferredDowncast (e, _) -> walkExprWithKind parentKind e + | SynExpr.AddressOf (_, e, _, _) -> walkExprWithKind parentKind e - | SynExpr.JoinIn (e1, _, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] + + | SynExpr.JoinIn (e1, _, e2, _) -> List.tryPick (walkExprWithKind parentKind) [ e1; e2 ] + | SynExpr.YieldOrReturn (_, e, _) -> walkExprWithKind parentKind e + | SynExpr.YieldOrReturnFrom (_, e, _) -> walkExprWithKind parentKind e - | SynExpr.Match (expr=e; clauses=synMatchClauseList) - | SynExpr.MatchBang (expr=e; clauses=synMatchClauseList) -> - walkExprWithKind parentKind e |> Option.orElseWith (fun () -> List.tryPick walkClause synMatchClauseList) - | SynExpr.LetOrUseBang(rhs=e1; andBangs=es; body=e2) -> + + | SynExpr.Match (expr = e; clauses = synMatchClauseList) + + | SynExpr.MatchBang (expr = e; clauses = synMatchClauseList) -> + walkExprWithKind parentKind e + |> Option.orElseWith (fun () -> List.tryPick walkClause synMatchClauseList) + + | SynExpr.LetOrUseBang (rhs = e1; andBangs = es; body = e2) -> [ yield e1 - for SynExprAndBang(body=eAndBang) in es do + for SynExprAndBang (body = eAndBang) in es do yield eAndBang yield e2 ] - |> List.tryPick (walkExprWithKind parentKind) + |> List.tryPick (walkExprWithKind parentKind) + | SynExpr.DoBang (e, _) -> walkExprWithKind parentKind e + | SynExpr.TraitCall (ts, sign, e, _) -> - List.tryPick walkTypar ts + List.tryPick walkTypar ts |> Option.orElseWith (fun () -> walkMemberSig sign) |> Option.orElseWith (fun () -> walkExprWithKind parentKind e) + | _ -> None - and walkExpr = walkExprWithKind None + and walkExpr expr = walkExprWithKind None expr and walkSimplePat pat = match pat with | SynSimplePat.Attrib (pat, Attributes attrs, _) -> - walkSimplePat pat |> Option.orElseWith (fun () -> List.tryPick walkAttribute attrs) - | SynSimplePat.Typed(pat, t, _) -> walkSimplePat pat |> Option.orElseWith (fun () -> walkType t) + walkSimplePat pat + |> Option.orElseWith (fun () -> List.tryPick walkAttribute attrs) + | SynSimplePat.Typed (pat, t, _) -> walkSimplePat pat |> Option.orElseWith (fun () -> walkType t) | _ -> None - and walkField (SynField(Attributes attrs, _, _, t, _, _, _, _)) = + and walkField synField = + let (SynField (Attributes attrs, _, _, t, _, _, _, _)) = synField List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> walkType t) - and walkValSig (SynValSig(attributes=Attributes attrs; synType=t)) = + and walkValSig synValSig = + let (SynValSig (attributes = Attributes attrs; synType = t)) = synValSig List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> walkType t) and walkMemberSig membSig = match membSig with | SynMemberSig.Inherit (t, _) -> walkType t - | SynMemberSig.Member(vs, _, _) -> walkValSig vs - | SynMemberSig.Interface(t, _) -> walkType t - | SynMemberSig.ValField(f, _) -> walkField f - | SynMemberSig.NestedType(nestedType=SynTypeDefnSig.SynTypeDefnSig (typeInfo=info; typeRepr=repr; members=memberSigs)) -> + + | SynMemberSig.Member (vs, _, _) -> walkValSig vs + + | SynMemberSig.Interface (t, _) -> walkType t + + | SynMemberSig.ValField (f, _) -> walkField f + + | SynMemberSig.NestedType(nestedType = SynTypeDefnSig.SynTypeDefnSig (typeInfo = info; typeRepr = repr; members = memberSigs)) -> walkComponentInfo false info |> Option.orElseWith (fun () -> walkTypeDefnSigRepr repr) |> Option.orElseWith (fun () -> List.tryPick walkMemberSig memberSigs) @@ -671,57 +872,92 @@ module ParsedInput = and walkMember memb = match memb with | SynMemberDefn.AbstractSlot (valSig, _, _) -> walkValSig valSig - | SynMemberDefn.Member(binding, _) -> walkBinding binding - | SynMemberDefn.ImplicitCtor(_, Attributes attrs, SynSimplePats.SimplePats(simplePats, _), _, _, _) -> - List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> List.tryPick walkSimplePat simplePats) - | SynMemberDefn.ImplicitInherit(t, e, _, _) -> walkType t |> Option.orElseWith (fun () -> walkExpr e) - | SynMemberDefn.LetBindings(bindings, _, _, _) -> List.tryPick walkBinding bindings - | SynMemberDefn.Interface(interfaceType=t; members=members) -> - walkType t |> Option.orElseWith (fun () -> members |> Option.bind (List.tryPick walkMember)) - | SynMemberDefn.Inherit(t, _, _) -> walkType t - | SynMemberDefn.ValField(field, _) -> walkField field - | SynMemberDefn.NestedType(tdef, _, _) -> walkTypeDefn tdef - | SynMemberDefn.AutoProperty(attributes=Attributes attrs; typeOpt=t; synExpr=e) -> + + | SynMemberDefn.Member (binding, _) -> walkBinding binding + + | SynMemberDefn.GetSetMember (getBinding, setBinding, _, _) -> + match getBinding, setBinding with + | None, None -> None + | Some binding, None + | None, Some binding -> walkBinding binding + | Some getBinding, Some setBinding -> walkBinding getBinding |> Option.orElseWith (fun () -> walkBinding setBinding) + + | SynMemberDefn.ImplicitCtor (_, Attributes attrs, SynSimplePats.SimplePats (simplePats, _), _, _, _) -> + List.tryPick walkAttribute attrs + |> Option.orElseWith (fun () -> List.tryPick walkSimplePat simplePats) + + | SynMemberDefn.ImplicitInherit (t, e, _, _) -> walkType t |> Option.orElseWith (fun () -> walkExpr e) + + | SynMemberDefn.LetBindings (bindings, _, _, _) -> List.tryPick walkBinding bindings + + | SynMemberDefn.Interface (interfaceType = t; members = members) -> + walkType t + |> Option.orElseWith (fun () -> members |> Option.bind (List.tryPick walkMember)) + + | SynMemberDefn.Inherit (t, _, _) -> walkType t + + | SynMemberDefn.ValField (field, _) -> walkField field + + | SynMemberDefn.NestedType (tdef, _, _) -> walkTypeDefn tdef + + | SynMemberDefn.AutoProperty (attributes = Attributes attrs; typeOpt = t; synExpr = e) -> List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> Option.bind walkType t) |> Option.orElseWith (fun () -> walkExpr e) + | _ -> None and walkEnumCase (SynEnumCase(attributes = Attributes attrs)) = List.tryPick walkAttribute attrs - and walkUnionCaseType = function + and walkUnionCaseType inp = + match inp with | SynUnionCaseKind.Fields fields -> List.tryPick walkField fields - | SynUnionCaseKind.FullType(t, _) -> walkType t + | SynUnionCaseKind.FullType (t, _) -> walkType t - and walkUnionCase (SynUnionCase(attributes=Attributes attrs; caseType=t)) = - List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> walkUnionCaseType t) + and walkUnionCase synUnionCase = + let (SynUnionCase (attributes = Attributes attrs; caseType = t)) = synUnionCase - and walkTypeDefnSimple = function + List.tryPick walkAttribute attrs + |> Option.orElseWith (fun () -> walkUnionCaseType t) + + and walkTypeDefnSimple synTypeDefn = + match synTypeDefn with | SynTypeDefnSimpleRepr.Enum (cases, _) -> List.tryPick walkEnumCase cases - | SynTypeDefnSimpleRepr.Union(_, cases, _) -> List.tryPick walkUnionCase cases - | SynTypeDefnSimpleRepr.Record(_, fields, _) -> List.tryPick walkField fields - | SynTypeDefnSimpleRepr.TypeAbbrev(_, t, _) -> walkType t + | SynTypeDefnSimpleRepr.Union (_, cases, _) -> List.tryPick walkUnionCase cases + | SynTypeDefnSimpleRepr.Record (_, fields, _) -> List.tryPick walkField fields + | SynTypeDefnSimpleRepr.TypeAbbrev (_, t, _) -> walkType t | _ -> None - and walkComponentInfo isModule (SynComponentInfo(Attributes attrs, TyparsAndConstraints (typars, cs1), cs2, _, _, _, _, r)) = + and walkComponentInfo isModule compInfo = + let (SynComponentInfo (Attributes attrs, TyparsAndConstraints (typars, cs1), cs2, _, _, _, _, r)) = + compInfo + let constraints = cs1 @ cs2 - if isModule then None else ifPosInRange r (fun _ -> Some EntityKind.Type) - |> Option.orElseWith (fun () -> + + if isModule then + None + else + ifPosInRange r (fun _ -> Some EntityKind.Type) + |> Option.orElseWith (fun () -> List.tryPick walkAttribute attrs |> Option.orElseWith (fun () -> List.tryPick walkTyparDecl typars) |> Option.orElseWith (fun () -> List.tryPick walkTypeConstraint constraints)) - and walkTypeDefnRepr = function + and walkTypeDefnRepr inp = + match inp with | SynTypeDefnRepr.ObjectModel (_, defns, _) -> List.tryPick walkMember defns - | SynTypeDefnRepr.Simple(defn, _) -> walkTypeDefnSimple defn + | SynTypeDefnRepr.Simple (defn, _) -> walkTypeDefnSimple defn | SynTypeDefnRepr.Exception _ -> None - and walkTypeDefnSigRepr = function + and walkTypeDefnSigRepr inp = + match inp with | SynTypeDefnSigRepr.ObjectModel (_, defns, _) -> List.tryPick walkMemberSig defns - | SynTypeDefnSigRepr.Simple(defn, _) -> walkTypeDefnSimple defn + | SynTypeDefnSigRepr.Simple (defn, _) -> walkTypeDefnSimple defn | SynTypeDefnSigRepr.Exception _ -> None - and walkTypeDefn (SynTypeDefn (typeInfo=info; typeRepr=repr; members=members)) = + and walkTypeDefn typeDefn = + let (SynTypeDefn (typeInfo = info; typeRepr = repr; members = members)) = typeDefn + walkComponentInfo false info |> Option.orElseWith (fun () -> walkTypeDefnRepr repr) |> Option.orElseWith (fun () -> List.tryPick walkMember members) @@ -729,218 +965,300 @@ module ParsedInput = and walkSynModuleDecl isTopLevel (decl: SynModuleDecl) = match decl with | SynModuleDecl.NamespaceFragment fragment -> walkSynModuleOrNamespace isTopLevel fragment - | SynModuleDecl.NestedModule(moduleInfo=info; decls=modules; range=range) -> + + | SynModuleDecl.NestedModule (moduleInfo = info; decls = modules; range = range) -> walkComponentInfo true info |> Option.orElseWith (fun () -> ifPosInRange range (fun _ -> List.tryPick (walkSynModuleDecl false) modules)) + | SynModuleDecl.Open _ -> None + | SynModuleDecl.Let (_, bindings, _) -> List.tryPick walkBinding bindings + | SynModuleDecl.Expr (expr, _) -> walkExpr expr + | SynModuleDecl.Types (types, _) -> List.tryPick walkTypeDefn types + | _ -> None - match parsedInput with + match parsedInput with | ParsedInput.SigFile _ -> None | ParsedInput.ImplFile input -> walkImplFileInput input + //-------------------------------------------------------------------------------------------- + // TryGetCompletionContext + /// Matches the most nested [< and >] pair. - let insideAttributeApplicationRegex = Regex(@"(?<=\[\<)(?(.*?))(?=\>\])", RegexOptions.Compiled ||| RegexOptions.ExplicitCapture) + let insideAttributeApplicationRegex = + Regex(@"(?<=\[\<)(?(.*?))(?=\>\])", RegexOptions.Compiled ||| RegexOptions.ExplicitCapture) + + // Categorise via attributes + let (|Class|Interface|Struct|Unknown|Invalid|) synAttributes = + let (|SynAttr|_|) name (attr: SynAttribute) = + match attr with + | { + TypeName = SynLongIdent ([ x ], _, _) + } when x.idText = name -> Some() + | _ -> None - /// Try to determine completion context for the given pair (row, columns) - let TryGetCompletionContext (pos, parsedInput: ParsedInput, lineStr: string) : CompletionContext option = + let rec getKind isClass isInterface isStruct attrs = + match attrs with + | [] -> isClass, isInterface, isStruct + | SynAttr "Class" :: xs -> getKind true isInterface isStruct xs + | SynAttr "AbstractClass" :: xs -> getKind true isInterface isStruct xs + | SynAttr "Interface" :: xs -> getKind isClass true isStruct xs + | SynAttr "Struct" :: xs -> getKind isClass isInterface true xs + | _ :: xs -> getKind isClass isInterface isStruct xs + + match getKind false false false synAttributes with + | false, false, false -> Unknown + | true, false, false -> Class + | false, true, false -> Interface + | false, false, true -> Struct + | _ -> Invalid + + let GetCompletionContextForInheritSynMember (compInfo, typeDefnKind: SynTypeDefnKind, completionPath) = + + let (SynComponentInfo(attributes = Attributes synAttributes)) = compInfo + + let success k = + Some(CompletionContext.Inherit(k, completionPath)) + + // if kind is specified - take it + // if kind is non-specified + // - try to obtain it from attribute + // - if no attributes present - infer kind from members + match typeDefnKind with + | SynTypeDefnKind.Class -> + match synAttributes with + | Class + | Unknown -> success InheritanceContext.Class + | _ -> Some CompletionContext.Invalid // non-matching attributes + | SynTypeDefnKind.Interface -> + match synAttributes with + | Interface + | Unknown -> success InheritanceContext.Interface + | _ -> Some CompletionContext.Invalid // non-matching attributes + | SynTypeDefnKind.Struct -> + // display nothing for structs + Some CompletionContext.Invalid + | SynTypeDefnKind.Unspecified -> + match synAttributes with + | Class -> success InheritanceContext.Class + | Interface -> success InheritanceContext.Interface + | Unknown -> + // user do not specify kind explicitly or via attributes + success InheritanceContext.Unknown + | _ -> + // unable to uniquely detect kind from the attributes - return invalid context + Some CompletionContext.Invalid + | _ -> None - match GetEntityKind(pos, parsedInput) with - | Some EntityKind.Attribute -> Some CompletionContext.AttributeApplication - | _ -> - - let parseLid (SynLongIdent(lid, dots, _)) = - let rec collect plid (parts : Ident list) (dots : range list) = - match parts, dots with - | [], _ -> Some (plid, None) - | x :: xs, ds -> - if rangeContainsPos x.idRange pos then - // pos lies with the range of current identifier - let s = x.idText.Substring(0, pos.Column - x.idRange.Start.Column) - let residue = if s.Length <> 0 then Some s else None - Some (plid, residue) - elif posGt x.idRange.Start pos then - // can happen if caret is placed after dot but before the existing identifier A. $ B - // return accumulated plid with no residue - Some (plid, None) - else - match ds with - | [] -> - // pos lies after the id and no dots found - return accumulated plid and current id as residue - Some (plid, Some x.idText) - | d :: ds -> - if posGeq pos d.End then - // pos lies after the dot - proceed to the next identifier - collect (x.idText :: plid) xs ds - else - // pos after the id but before the dot - // A $.B - return nothing - None + let (|Operator|_|) name e = + match e with + | SynExpr.App (ExprAtomicFlag.NonAtomic, + false, + SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ ident ])), lhs, _), + rhs, + _) when ident.idText = name -> Some(lhs, rhs) + | _ -> None - match collect [] lid dots with - | Some (parts, residue) -> - Some ((List.rev parts), residue) - | None -> None - - let (|Class|Interface|Struct|Unknown|Invalid|) synAttributes = - let (|SynAttr|_|) name (attr : SynAttribute) = - match attr with - | {TypeName = SynLongIdent([x], _, _)} when x.idText = name -> Some () - | _ -> None - - let rec getKind isClass isInterface isStruct = - function - | [] -> isClass, isInterface, isStruct - | SynAttr "Class" :: xs -> getKind true isInterface isStruct xs - | SynAttr "AbstractClass" :: xs -> getKind true isInterface isStruct xs - | SynAttr "Interface" :: xs -> getKind isClass true isStruct xs - | SynAttr "Struct" :: xs -> getKind isClass isInterface true xs - | _ :: xs -> getKind isClass isInterface isStruct xs - - match getKind false false false synAttributes with - | false, false, false -> Unknown - | true, false, false -> Class - | false, true, false -> Interface - | false, false, true -> Struct - | _ -> Invalid - - let GetCompletionContextForInheritSynMember (SynComponentInfo(Attributes synAttributes, _, _, _, _, _, _, _), typeDefnKind : SynTypeDefnKind, completionPath) = - - let success k = Some (CompletionContext.Inherit (k, completionPath)) - - // if kind is specified - take it - // if kind is non-specified - // - try to obtain it from attribute - // - if no attributes present - infer kind from members - match typeDefnKind with - | SynTypeDefnKind.Class -> - match synAttributes with - | Class | Unknown -> success InheritanceContext.Class - | _ -> Some CompletionContext.Invalid // non-matching attributes - | SynTypeDefnKind.Interface -> - match synAttributes with - | Interface | Unknown -> success InheritanceContext.Interface - | _ -> Some CompletionContext.Invalid // non-matching attributes - | SynTypeDefnKind.Struct -> - // display nothing for structs - Some CompletionContext.Invalid - | SynTypeDefnKind.Unspecified -> - match synAttributes with - | Class -> success InheritanceContext.Class - | Interface -> success InheritanceContext.Interface - | Unknown -> - // user do not specify kind explicitly or via attributes - success InheritanceContext.Unknown - | _ -> - // unable to uniquely detect kind from the attributes - return invalid context - Some CompletionContext.Invalid - | _ -> None + // checks if we are in a range operator + let isAtRangeOp (p: SyntaxVisitorPath) = + match p with + | SyntaxNode.SynExpr (SynExpr.IndexRange _) :: _ -> true + | _ -> false - let (|Operator|_|) name e = - match e with - | SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ident])), lhs, _), rhs, _) - when ident.idText = name -> Some (lhs, rhs) - | _ -> None + let (|Setter|_|) e = + match e with + | Operator "op_Equality" (SynExpr.Ident id, _) -> Some id + | _ -> None - // checks if we are in a range operator - let isAtRangeOp (p : SyntaxVisitorPath) = - match p with - | SyntaxNode.SynExpr(SynExpr.IndexRange _) :: _ -> true - | _ -> false + let findSetters argList = + match argList with + | SynExpr.Paren (SynExpr.Tuple (false, parameters, _, _), _, _, _) -> + let setters = HashSet() - let (|Setter|_|) e = - match e with - | Operator "op_Equality" (SynExpr.Ident id , _) -> Some id - | _ -> None + for p in parameters do + match p with + | Setter id -> ignore (setters.Add id.idText) + | _ -> () - let findSetters argList = - match argList with - | SynExpr.Paren (SynExpr.Tuple (false, parameters, _, _), _, _, _) -> - let setters = HashSet() - for p in parameters do - match p with - | Setter id -> ignore(setters.Add id.idText) - | _ -> () - setters - | _ -> emptyStringSet - - let endOfLastIdent (lid: SynLongIdent) = - let last = List.last lid.LongIdent - last.idRange.End - - let endOfClosingTokenOrLastIdent (mClosing: range option) (lid : SynLongIdent) = - match mClosing with - | Some m -> m.End - | None -> endOfLastIdent lid - - let endOfClosingTokenOrIdent (mClosing: range option) (id : Ident) = - match mClosing with - | Some m -> m.End - | None -> id.idRange.End - - let (|NewObjectOrMethodCall|_|) e = - match e with - | SynExpr.New (_, SynType.LongIdent typeName, arg, _) -> - // new A() - Some (endOfLastIdent typeName, findSetters arg) - | SynExpr.New (_, SynType.App(StripParenTypes (SynType.LongIdent typeName), _, _, _, mGreaterThan, _, _), arg, _) -> - // new A<_>() - Some (endOfClosingTokenOrLastIdent mGreaterThan typeName, findSetters arg) - | SynExpr.App (_, false, SynExpr.Ident id, arg, _) -> - // A() - Some (id.idRange.End, findSetters arg) - | SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.Ident id, _, _, _, mGreaterThan, _, _), arg, _) -> - // A<_>() - Some (endOfClosingTokenOrIdent mGreaterThan id, findSetters arg) - | SynExpr.App (_, false, SynExpr.LongIdent (_, lid, _, _), arg, _) -> - // A.B() - Some (endOfLastIdent lid, findSetters arg) - | SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.LongIdent (_, lid, _, _), _, _, _, mGreaterThan, _, _), arg, _) -> - // A.B<_>() - Some (endOfClosingTokenOrLastIdent mGreaterThan lid, findSetters arg) - | _ -> None - - let isOnTheRightOfComma (elements: SynExpr list) (commas: range list) current = - let rec loop elements (commas: range list) = - match elements with - | x :: xs -> - match commas with - | c :: cs -> - if x === current then posLt c.End pos || posEq c.End pos - else loop xs cs - | _ -> false + setters + | _ -> emptyStringSet + + let endOfLastIdent (lid: SynLongIdent) = + let last = List.last lid.LongIdent + last.idRange.End + + let endOfClosingTokenOrLastIdent (mClosing: range option) (lid: SynLongIdent) = + match mClosing with + | Some m -> m.End + | None -> endOfLastIdent lid + + let endOfClosingTokenOrIdent (mClosing: range option) (id: Ident) = + match mClosing with + | Some m -> m.End + | None -> id.idRange.End + + let (|NewObjectOrMethodCall|_|) e = + match e with + | SynExpr.New (_, SynType.LongIdent typeName, arg, _) -> + // new A() + Some(endOfLastIdent typeName, findSetters arg) + + | SynExpr.New (_, SynType.App (StripParenTypes (SynType.LongIdent typeName), _, _, _, mGreaterThan, _, _), arg, _) -> + // new A<_>() + Some(endOfClosingTokenOrLastIdent mGreaterThan typeName, findSetters arg) + + | SynExpr.App (_, false, SynExpr.Ident id, arg, _) -> + // A() + Some(id.idRange.End, findSetters arg) + + | SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.Ident id, _, _, _, mGreaterThan, _, _), arg, _) -> + // A<_>() + Some(endOfClosingTokenOrIdent mGreaterThan id, findSetters arg) + + | SynExpr.App (_, false, SynExpr.LongIdent (_, lid, _, _), arg, _) -> + // A.B() + Some(endOfLastIdent lid, findSetters arg) + + | SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.LongIdent (_, lid, _, _), _, _, _, mGreaterThan, _, _), arg, _) -> + // A.B<_>() + Some(endOfClosingTokenOrLastIdent mGreaterThan lid, findSetters arg) + | _ -> None + + let isOnTheRightOfComma pos (elements: SynExpr list) (commas: range list) current = + let rec loop elements (commas: range list) = + match elements with + | x :: xs -> + match commas with + | c :: cs -> + if x === current then + posLt c.End pos || posEq c.End pos + else + loop xs cs | _ -> false - loop elements commas - - let (|PartOfParameterList|_|) precedingArgument path = - match path with - | SyntaxNode.SynExpr(SynExpr.Paren _) :: SyntaxNode.SynExpr(NewObjectOrMethodCall args) :: _ -> - if Option.isSome precedingArgument then None else Some args - | SyntaxNode.SynExpr(SynExpr.Tuple (false, elements, commas, _)) :: SyntaxNode.SynExpr(SynExpr.Paren _) :: SyntaxNode.SynExpr(NewObjectOrMethodCall args) :: _ -> - match precedingArgument with - | None -> Some args - | Some e -> - // if expression is passed then - // 1. find it in among elements of the tuple - // 2. find corresponding comma - // 3. check that current position is past the comma - // this is used for cases like (a = something-here.) if the cursor is after . - // in this case this is not object initializer completion context - if isOnTheRightOfComma elements commas e then Some args else None + | _ -> false + + loop elements commas + + let (|PartOfParameterList|_|) pos precedingArgument path = + match path with + | SyntaxNode.SynExpr (SynExpr.Paren _) :: SyntaxNode.SynExpr (NewObjectOrMethodCall args) :: _ -> + if Option.isSome precedingArgument then None else Some args + | SyntaxNode.SynExpr (SynExpr.Tuple (false, elements, commas, _)) :: SyntaxNode.SynExpr (SynExpr.Paren _) :: SyntaxNode.SynExpr (NewObjectOrMethodCall args) :: _ -> + match precedingArgument with + | None -> Some args + | Some e -> + // if expression is passed then + // 1. find it in among elements of the tuple + // 2. find corresponding comma + // 3. check that current position is past the comma + // this is used for cases like (a = something-here.) if the cursor is after . + // in this case this is not object initializer completion context + if isOnTheRightOfComma pos elements commas e then + Some args + else + None + | _ -> None + + let (|SkipFromParseErrorPat|) pat = + match pat with + | SynPat.FromParseError (pat, _) -> pat + | _ -> pat + + let rec parseLidAux pos plid (parts: Ident list) (dots: range list) = + match parts, dots with + | [], _ -> Some(plid, None) + | x :: xs, ds -> + if rangeContainsPos x.idRange pos then + // pos lies with the range of current identifier + let s = x.idText.Substring(0, pos.Column - x.idRange.Start.Column) + let residue = if s.Length <> 0 then Some s else None + Some(plid, residue) + elif posGt x.idRange.Start pos then + // can happen if caret is placed after dot but before the existing identifier A. $ B + // return accumulated plid with no residue + Some(plid, None) + else + match ds with + | [] -> + // pos lies after the id and no dots found - return accumulated plid and current id as residue + Some(plid, Some x.idText) + | d :: ds -> + if posGeq pos d.End then + // pos lies after the dot - proceed to the next identifier + parseLidAux pos (x.idText :: plid) xs ds + else + // pos after the id but before the dot + // A $.B - return nothing + None + + let parseLid pos (SynLongIdent (lid, dots, _)) = + match parseLidAux pos [] lid dots with + | Some (parts, residue) -> Some((List.rev parts), residue) + | None -> None + + /// Try to determine completion context at the given position within in an attribute using approximate analysis based on line text matching + let TryGetCompletionContextOfAttributes (pos: pos, lineStr: string) : CompletionContext option = + // Uncompleted attribute applications are not presented in the AST in any way. So, we have to parse source string. + let cutLeadingAttributes (str: string) = + // cut off leading attributes, i.e. we cut "[]" to " >]" + match str.LastIndexOf ';' with + | -1 -> str + | idx when idx < str.Length -> str[ idx + 1 .. ].TrimStart() + | _ -> "" + + let isLongIdent (lid: string) = + lid |> Seq.forall (fun c -> IsIdentifierPartCharacter c || c = '.' || c = ':') // ':' may occur in "[]" + + // match the most nested paired [< and >] first + let matches = + insideAttributeApplicationRegex.Matches lineStr + |> Seq.cast + |> Seq.filter (fun m -> m.Index <= pos.Column && m.Index + m.Length >= pos.Column) + |> Seq.toArray + + if matches.Length > 0 then + matches + |> Seq.tryPick (fun m -> + let g = m.Groups["attribute"] + let col = pos.Column - g.Index + + if col >= 0 && col < g.Length then + let str = g.Value.Substring(0, col).TrimStart() // cut other rhs attributes + let str = cutLeadingAttributes str + + if isLongIdent str then + Some CompletionContext.AttributeApplication + else + None + else + None) + else + // Paired [< and >] were not found, try to determine that we are after [< without closing >] + match lineStr.LastIndexOf("[<", StringComparison.Ordinal) with + | -1 -> None + | openParenIndex when pos.Column >= openParenIndex + 2 -> + let str = lineStr[ openParenIndex + 2 .. pos.Column - 1 ].TrimStart() + let str = cutLeadingAttributes str + + if isLongIdent str then + Some CompletionContext.AttributeApplication + else + None | _ -> None - let (|SkipFromParseErrorPat|) pat = - match pat with - | SynPat.FromParseError(pat, _) -> pat - | _ -> pat + /// Try to determine completion context for the given pair (row, columns) + let TryGetCompletionContext (pos, parsedInput: ParsedInput, lineStr: string) : CompletionContext option = + + match GetEntityKind(pos, parsedInput) with + | Some EntityKind.Attribute -> Some CompletionContext.AttributeApplication + | _ -> - let walker = - { - new SyntaxVisitorBase<_>() with - member _.VisitExpr(path, _, defaultTraverse, expr) = + let visitor = + { new SyntaxVisitorBase<_>() with + member _.VisitExpr(path, _, defaultTraverse, expr) = if isAtRangeOp path then match defaultTraverse expr with @@ -951,156 +1269,164 @@ module ParsedInput = // new A($) | SynExpr.Const (SynConst.Unit, m) when rangeContainsPos m pos -> match path with - | SyntaxNode.SynExpr(NewObjectOrMethodCall args) :: _ -> - Some (CompletionContext.ParameterList args) - | _ -> - defaultTraverse expr + | SyntaxNode.SynExpr (NewObjectOrMethodCall args) :: _ -> Some(CompletionContext.ParameterList args) + | _ -> defaultTraverse expr + // new (... A$) | SynExpr.Ident id - | SynExpr.LongIdent(longDotId = SynLongIdent([id], [], [ Some _ ])) when id.idRange.End = pos -> + | SynExpr.LongIdent(longDotId = SynLongIdent ([ id ], [], [ Some _ ])) when id.idRange.End = pos -> match path with - | PartOfParameterList None args -> - Some (CompletionContext.ParameterList args) - | _ -> - defaultTraverse expr + | PartOfParameterList pos None args -> Some(CompletionContext.ParameterList args) + | _ -> defaultTraverse expr + // new (A$ = 1) // new (A = 1, $) | Setter id when id.idRange.End = pos || rangeBeforePos expr.Range pos -> let precedingArgument = if id.idRange.End = pos then None else Some expr + match path with - | PartOfParameterList precedingArgument args-> - Some (CompletionContext.ParameterList args) - | _ -> - defaultTraverse expr - | SynExpr.Record(None, None, [], _) -> - Some(CompletionContext.RecordField RecordContext.Empty) + | PartOfParameterList pos precedingArgument args -> Some(CompletionContext.ParameterList args) + | _ -> defaultTraverse expr + + | SynExpr.Record (None, None, [], _) -> Some(CompletionContext.RecordField RecordContext.Empty) + // Unchecked.defaultof - | SynExpr.TypeApp (typeArgsRange = range) when rangeContainsPos range pos -> - Some CompletionContext.PatternType + | SynExpr.TypeApp (typeArgsRange = range) when rangeContainsPos range pos -> Some CompletionContext.PatternType | _ -> defaultTraverse expr - member _.VisitRecordField(path, copyOpt, field) = - let contextFromTreePath completionPath = + member _.VisitRecordField(path, copyOpt, field) = + let contextFromTreePath completionPath = // detect records usage in constructor match path with - | SyntaxNode.SynExpr _ :: SyntaxNode.SynBinding _ :: SyntaxNode.SynMemberDefn _ :: SyntaxNode.SynTypeDefn(SynTypeDefn(typeInfo=SynComponentInfo(longId=[id]))) :: _ -> + | SyntaxNode.SynExpr _ :: SyntaxNode.SynBinding _ :: SyntaxNode.SynMemberDefn _ :: SyntaxNode.SynTypeDefn (SynTypeDefn(typeInfo = SynComponentInfo(longId = [ id ]))) :: _ -> RecordContext.Constructor(id.idText) - | SyntaxNode.SynExpr(SynExpr.Record(None, _, fields, _)) :: _ -> - let isFirstField = + | SyntaxNode.SynExpr (SynExpr.Record (None, _, fields, _)) :: _ -> + let isFirstField = match field, fields with | Some contextLid, SynExprRecordField(fieldName = lid, _) :: _ -> contextLid.Range = lid.Range | _ -> false RecordContext.New(completionPath, isFirstField) - // Unfinished `{ xxx }` expression considered a record field by the tree walker. - | SyntaxNode.SynExpr(SynExpr.ComputationExpr _) :: _ -> - RecordContext.New(completionPath, true) + // Unfinished `{ xxx }` expression considered a record field by the tree visitor. + | SyntaxNode.SynExpr (SynExpr.ComputationExpr _) :: _ -> RecordContext.New(completionPath, true) - | _ -> - RecordContext.New(completionPath, false) + | _ -> RecordContext.New(completionPath, false) match field with - | Some field -> - match parseLid field with + | Some field -> + match parseLid pos field with | Some completionPath -> - let recordContext = + let recordContext = match copyOpt with - | Some (s : SynExpr) -> RecordContext.CopyOnUpdate(s.Range, completionPath) + | Some (s: SynExpr) -> RecordContext.CopyOnUpdate(s.Range, completionPath) | None -> contextFromTreePath completionPath - Some (CompletionContext.RecordField recordContext) + + Some(CompletionContext.RecordField recordContext) | None -> None | None -> - let recordContext = + let recordContext = match copyOpt with | Some s -> RecordContext.CopyOnUpdate(s.Range, ([], None)) | None -> contextFromTreePath ([], None) - Some (CompletionContext.RecordField recordContext) - - member _.VisitInheritSynMemberDefn(_path, componentInfo, typeDefnKind, synType, _members, _range) = + + Some(CompletionContext.RecordField recordContext) + + member _.VisitInheritSynMemberDefn(_, componentInfo, typeDefnKind, synType, _, _) = match synType with - | SynType.LongIdent lidwd -> - match parseLid lidwd with - | Some completionPath -> GetCompletionContextForInheritSynMember (componentInfo, typeDefnKind, completionPath) + | SynType.LongIdent lidwd -> + match parseLid pos lidwd with + | Some completionPath -> GetCompletionContextForInheritSynMember(componentInfo, typeDefnKind, completionPath) | None -> Some CompletionContext.Invalid // A $ .B -> no completion list - | _ -> None - - member _.VisitBinding(_path, defaultTraverse, (SynBinding(headPat = headPat) as synBinding)) = - + | _ -> None + + member _.VisitBinding(_, defaultTraverse, (SynBinding (headPat = headPat) as synBinding)) = + let visitParam (SkipFromParseErrorPat pat) = match pat with | SynPat.Named (range = range) - | SynPat.As (_, SynPat.Named (range = range), _) when rangeContainsPos range pos -> + | SynPat.As (_, SynPat.Named (range = range), _) when rangeContainsPos range pos -> // parameter without type hint, no completion - Some CompletionContext.Invalid - | SynPat.Typed(SynPat.Named(_, _, _, range), _, _) when rangeContainsPos range pos -> + Some CompletionContext.Invalid + | SynPat.Typed (SynPat.Named (_, _, _, range), _, _) when rangeContainsPos range pos -> // parameter with type hint, but we are on its name, no completion Some CompletionContext.Invalid | _ -> defaultTraverse synBinding match headPat with - | SynPat.LongIdent(longDotId = lidwd) when rangeContainsPos lidwd.Range pos -> + | SynPat.LongIdent (longDotId = lidwd) when rangeContainsPos lidwd.Range pos -> // let fo|o x = () Some CompletionContext.Invalid - | SynPat.LongIdent(argPats=ctorArgs) -> + | SynPat.LongIdent (argPats = ctorArgs) -> match ctorArgs with | SynArgPats.Pats pats -> - pats |> List.tryPick (fun (SkipFromParseErrorPat pat) -> + pats + |> List.tryPick (fun (SkipFromParseErrorPat pat) -> match pat with - | SynPat.Paren(pat, _) -> + | SynPat.Paren (pat, _) -> match pat with - | SynPat.Tuple(_, pats, _) -> - pats |> List.tryPick visitParam + | SynPat.Tuple (_, pats, _) -> pats |> List.tryPick visitParam | _ -> visitParam pat - | SynPat.Wild range | SynPat.FromParseError (SynPat.Named _, range) when rangeContainsPos range pos -> + | SynPat.Wild range + | SynPat.FromParseError (SynPat.Named _, range) when rangeContainsPos range pos -> // let foo (x| Some CompletionContext.Invalid - | _ -> visitParam pat - ) + | _ -> visitParam pat) | _ -> defaultTraverse synBinding - | SynPat.Named(range = range) + | SynPat.Named (range = range) | SynPat.As (_, SynPat.Named (range = range), _) when rangeContainsPos range pos -> // let fo|o = 1 Some CompletionContext.Invalid - | _ -> defaultTraverse synBinding - - member _.VisitHashDirective (_path, _directive, range) = + | _ -> defaultTraverse synBinding + + member _.VisitHashDirective(_, _directive, range) = // No completions in a directive - if rangeContainsPos range pos then Some CompletionContext.Invalid - else None - - member _.VisitModuleOrNamespace(_path, SynModuleOrNamespace(longId = idents)) = + if rangeContainsPos range pos then + Some CompletionContext.Invalid + else + None + + member _.VisitModuleOrNamespace(_, SynModuleOrNamespace (longId = idents)) = match List.tryLast idents with - | Some lastIdent when pos.Line = lastIdent.idRange.EndLine && lastIdent.idRange.EndColumn >= 0 && pos.Column <= lineStr.Length -> - let stringBetweenModuleNameAndPos = lineStr[lastIdent.idRange.EndColumn..pos.Column - 1] + | Some lastIdent when + pos.Line = lastIdent.idRange.EndLine + && lastIdent.idRange.EndColumn >= 0 + && pos.Column <= lineStr.Length + -> + let stringBetweenModuleNameAndPos = + lineStr[lastIdent.idRange.EndColumn .. pos.Column - 1] + if stringBetweenModuleNameAndPos |> Seq.forall (fun x -> x = ' ' || x = '.') then // No completions in a top level a module or namespace identifier Some CompletionContext.Invalid - else None - | _ -> None + else + None + | _ -> None - member _.VisitComponentInfo(_path, SynComponentInfo(range = range)) = + member _.VisitComponentInfo(_, SynComponentInfo (range = range)) = // No completions in component info (unless it's within an attribute) // /// XmlDo| // type R = class end - if rangeContainsPos range pos then Some CompletionContext.Invalid - else None + if rangeContainsPos range pos then + Some CompletionContext.Invalid + else + None - member _.VisitLetOrUse(_path, _, _, bindings, range) = + member _.VisitLetOrUse(_, _, _, bindings, range) = match bindings with | [] when range.StartLine = pos.Line -> Some CompletionContext.Invalid | _ -> None - member _.VisitSimplePats (_path, pats) = - pats |> List.tryPick (fun pat -> + member _.VisitSimplePats(_, pats) = + pats + |> List.tryPick (fun pat -> // No completions in an identifier in a pattern match pat with // fun x| -> - | SynSimplePat.Id(range = range) when rangeContainsPos range pos -> - Some CompletionContext.Invalid - | SynSimplePat.Typed(SynSimplePat.Id(range = idRange), synType, _) -> + | SynSimplePat.Id (range = range) when rangeContainsPos range pos -> Some CompletionContext.Invalid + | SynSimplePat.Typed (SynSimplePat.Id (range = idRange), synType, _) -> // fun (x|: int) -> if rangeContainsPos idRange pos then Some CompletionContext.Invalid @@ -1111,178 +1437,167 @@ module ParsedInput = None | _ -> None) - member _.VisitPat (_, defaultTraverse, pat) = + member _.VisitPat(_, defaultTraverse, pat) = match pat with - | SynPat.IsInst (_, range) when rangeContainsPos range pos -> - Some CompletionContext.PatternType + | SynPat.IsInst (_, range) when rangeContainsPos range pos -> Some CompletionContext.PatternType | _ -> defaultTraverse pat - member _.VisitModuleDecl(_path, defaultTraverse, decl) = + member _.VisitModuleDecl(_, defaultTraverse, decl) = match decl with - | SynModuleDecl.Open(target, m) -> + | SynModuleDecl.Open (target, m) -> // in theory, this means we're "in an open" - // in practice, because the parse tree/walkers do not handle attributes well yet, need extra check below to ensure not e.g. $here$ + // in practice, because the parse tree/visitors do not handle attributes well yet, need extra check below to ensure not e.g. $here$ // open System // [ true | SynOpenDeclTarget.ModuleOrNamespace _ -> false - Some (CompletionContext.OpenDeclaration isOpenType) + + Some(CompletionContext.OpenDeclaration isOpenType) else None | _ -> defaultTraverse decl - member _.VisitType(_path, defaultTraverse, ty) = + member _.VisitType(_, defaultTraverse, ty) = match ty with - | SynType.LongIdent _ when rangeContainsPos ty.Range pos -> - Some CompletionContext.PatternType + | SynType.LongIdent _ when rangeContainsPos ty.Range pos -> Some CompletionContext.PatternType | _ -> defaultTraverse ty - member _.VisitRecordDefn(_path, fields, range) = + member _.VisitRecordDefn(_, fields, range) = fields |> List.tryPick (fun (SynField (idOpt = idOpt; range = fieldRange)) -> match idOpt with - | Some id when rangeContainsPos id.idRange pos -> Some(CompletionContext.RecordField(RecordContext.Declaration true)) + | Some id when rangeContainsPos id.idRange pos -> + Some(CompletionContext.RecordField(RecordContext.Declaration true)) | _ when rangeContainsPos fieldRange pos -> Some(CompletionContext.RecordField(RecordContext.Declaration false)) | _ -> None) // No completions in a record outside of all fields - |> Option.orElseWith (fun () -> if rangeContainsPos range pos then Some CompletionContext.Invalid else None) + |> Option.orElseWith (fun () -> + if rangeContainsPos range pos then + Some CompletionContext.Invalid + else + None) - member _.VisitUnionDefn(_path, cases, _range) = - cases |> List.tryPick (fun (SynUnionCase (ident = SynIdent(id,_); caseType = caseType)) -> + member _.VisitUnionDefn(_, cases, _) = + cases + |> List.tryPick (fun (SynUnionCase (ident = SynIdent (id, _); caseType = caseType)) -> if rangeContainsPos id.idRange pos then // No completions in a union case identifier Some CompletionContext.Invalid else match caseType with | SynUnionCaseKind.Fields fieldCases -> - fieldCases |> List.tryPick (fun (SynField (idOpt = fieldIdOpt; range = fieldRange)) -> + fieldCases + |> List.tryPick (fun (SynField (idOpt = fieldIdOpt; range = fieldRange)) -> match fieldIdOpt with // No completions in a union case field identifier | Some id when rangeContainsPos id.idRange pos -> Some CompletionContext.Invalid - | _ -> if rangeContainsPos fieldRange pos then Some CompletionContext.UnionCaseFieldsDeclaration else None) + | _ -> + if rangeContainsPos fieldRange pos then + Some CompletionContext.UnionCaseFieldsDeclaration + else + None) | _ -> None) - member _.VisitEnumDefn(_path, _, range) = + member _.VisitEnumDefn(_, _, range) = // No completions anywhere in an enum - if rangeContainsPos range pos then Some CompletionContext.Invalid else None + if rangeContainsPos range pos then + Some CompletionContext.Invalid + else + None - member _.VisitTypeAbbrev(_path, _, range) = - if rangeContainsPos range pos then Some CompletionContext.TypeAbbreviationOrSingleCaseUnion else None - } + member _.VisitTypeAbbrev(_, _, range) = + if rangeContainsPos range pos then + Some CompletionContext.TypeAbbreviationOrSingleCaseUnion + else + None + } - SyntaxTraversal.Traverse(pos, parsedInput, walker) - // Uncompleted attribute applications are not presented in the AST in any way. So, we have to parse source string. - |> Option.orElseWith (fun _ -> - let cutLeadingAttributes (str: string) = - // cut off leading attributes, i.e. we cut "[]" to " >]" - match str.LastIndexOf ';' with - | -1 -> str - | idx when idx < str.Length -> str[idx + 1..].TrimStart() - | _ -> "" - - let isLongIdent = Seq.forall (fun c -> IsIdentifierPartCharacter c || c = '.' || c = ':') // ':' may occur in "[]" - - // match the most nested paired [< and >] first - let matches = - insideAttributeApplicationRegex.Matches lineStr - |> Seq.cast - |> Seq.filter (fun m -> m.Index <= pos.Column && m.Index + m.Length >= pos.Column) - |> Seq.toArray - - if not (Array.isEmpty matches) then - matches - |> Seq.tryPick (fun m -> - let g = m.Groups["attribute"] - let col = pos.Column - g.Index - if col >= 0 && col < g.Length then - let str = g.Value.Substring(0, col).TrimStart() // cut other rhs attributes - let str = cutLeadingAttributes str - if isLongIdent str then - Some CompletionContext.AttributeApplication - else None - else None) - else - // Paired [< and >] were not found, try to determine that we are after [< without closing >] - match lineStr.LastIndexOf("[<", StringComparison.Ordinal) with - | -1 -> None - | openParenIndex when pos.Column >= openParenIndex + 2 -> - let str = lineStr[openParenIndex + 2..pos.Column - 1].TrimStart() - let str = cutLeadingAttributes str - if isLongIdent str then - Some CompletionContext.AttributeApplication - else None - | _ -> None) + let ctxt = SyntaxTraversal.Traverse(pos, parsedInput, visitor) + + match ctxt with + | Some _ -> ctxt + | _ -> TryGetCompletionContextOfAttributes(pos, lineStr) + + //-------------------------------------------------------------------------------------------- + // TryGetInsertionContext /// Check if we are at an "open" declaration - let GetFullNameOfSmallestModuleOrNamespaceAtPoint (pos: pos, parsedInput: ParsedInput) = + let GetFullNameOfSmallestModuleOrNamespaceAtPoint (pos: pos, parsedInput: ParsedInput) = let mutable path = [] - let visitor = + + let visitor = { new SyntaxVisitorBase() with - override this.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = + override this.VisitExpr(_, _traverseSynExpr, defaultTraverse, expr) = // don't need to keep going, namespaces and modules never appear inside Exprs - None - override this.VisitModuleOrNamespace(_path, SynModuleOrNamespace(longId = longId; range = range)) = - if rangeContainsPos range pos then + None + + override this.VisitModuleOrNamespace(_, SynModuleOrNamespace (longId = longId; range = range)) = + if rangeContainsPos range pos then path <- path @ longId - None // we should traverse the rest of the AST to find the smallest module + + None // we should traverse the rest of the AST to find the smallest module } + SyntaxTraversal.Traverse(pos, parsedInput, visitor) |> ignore path |> List.map (fun x -> x.idText) |> List.toArray /// An recursive pattern that collect all sequential expressions to avoid StackOverflowException - let rec (|Sequentials|_|) = function - | SynExpr.Sequential (_, _, e, Sequentials es, _) -> - Some(e :: es) - | SynExpr.Sequential (_, _, e1, e2, _) -> - Some [e1; e2] + let rec (|Sequentials|_|) expr = + match expr with + | SynExpr.Sequential (_, _, e, Sequentials es, _) -> Some(e :: es) + | SynExpr.Sequential (_, _, e1, e2, _) -> Some [ e1; e2 ] | _ -> None - let (|ConstructorPats|) = function + let (|ConstructorPats|) pats = + match pats with | SynArgPats.Pats ps -> ps - | SynArgPats.NamePatPairs(xs, _) -> List.map (fun (_, _, pat) -> pat) xs + | SynArgPats.NamePatPairs (xs, _) -> List.map (fun (_, _, pat) -> pat) xs /// Returns all `Ident`s and `LongIdent`s found in an untyped AST. let getLongIdents (parsedInput: ParsedInput) : IDictionary = let identsByEndPos = Dictionary() - + let addLongIdent (longIdent: LongIdent) = for ident in longIdent do identsByEndPos[ident.idRange.End] <- longIdent - + let addLongIdentWithDots (SynLongIdent (longIdent, lids, _) as value) = match longIdent with | [] -> () - | [_] as idents -> identsByEndPos[value.Range.End] <- idents + | [ _ ] as idents -> identsByEndPos[value.Range.End] <- idents | idents -> for dotRange in lids do identsByEndPos[mkPos dotRange.EndLine (dotRange.EndColumn - 1)] <- idents + identsByEndPos[value.Range.End] <- idents - + let addIdent (ident: Ident) = - identsByEndPos[ident.idRange.End] <- [ident] - + identsByEndPos[ident.idRange.End] <- [ ident ] + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.iter walkSynModuleOrNamespace moduleOrNamespaceList - - and walkSynModuleOrNamespace (SynModuleOrNamespace(decls = decls; attribs = Attributes attrs)) = + + and walkSynModuleOrNamespace (SynModuleOrNamespace (decls = decls; attribs = Attributes attrs)) = List.iter walkAttribute attrs List.iter walkSynModuleDecl decls - + and walkAttribute (attr: SynAttribute) = addLongIdentWithDots attr.TypeName walkExpr attr.ArgExpr - + and walkTyparDecl (SynTyparDecl.SynTyparDecl (Attributes attrs, typar)) = List.iter walkAttribute attrs walkTypar typar - - and walkTypeConstraint = function + + and walkTypeConstraint cx = + match cx with | SynTypeConstraint.WhereTyparIsValueType (t, _) | SynTypeConstraint.WhereTyparIsReferenceType (t, _) | SynTypeConstraint.WhereTyparIsUnmanaged (t, _) @@ -1290,16 +1605,23 @@ module ParsedInput = | SynTypeConstraint.WhereTyparIsComparable (t, _) | SynTypeConstraint.WhereTyparIsEquatable (t, _) -> walkTypar t | SynTypeConstraint.WhereTyparDefaultsToType (t, ty, _) - | SynTypeConstraint.WhereTyparSubtypeOfType (t, ty, _) -> walkTypar t; walkType ty + | SynTypeConstraint.WhereTyparSubtypeOfType (t, ty, _) -> + walkTypar t + walkType ty | SynTypeConstraint.WhereTyparIsEnum (t, ts, _) - | SynTypeConstraint.WhereTyparIsDelegate (t, ts, _) -> walkTypar t; List.iter walkType ts - | SynTypeConstraint.WhereTyparSupportsMember (ts, sign, _) -> List.iter walkType ts; walkMemberSig sign - - and walkPat = function - | SynPat.Tuple (_,pats, _) + | SynTypeConstraint.WhereTyparIsDelegate (t, ts, _) -> + walkTypar t + List.iter walkType ts + | SynTypeConstraint.WhereTyparSupportsMember (ts, sign, _) -> + List.iter walkType ts + walkMemberSig sign + + and walkPat pat = + match pat with + | SynPat.Tuple (_, pats, _) | SynPat.ArrayOrList (_, pats, _) | SynPat.Ands (pats, _) -> List.iter walkPat pats - | SynPat.Named (SynIdent(ident,_), _, _, _) -> addIdent ident + | SynPat.Named (SynIdent (ident, _), _, _, _) -> addIdent ident | SynPat.Typed (pat, t, _) -> walkPat pat walkType t @@ -1307,56 +1629,66 @@ module ParsedInput = walkPat pat List.iter walkAttribute attrs | SynPat.As (pat1, pat2, _) - | SynPat.Or (pat1, pat2, _, _) -> List.iter walkPat [pat1; pat2] - | SynPat.LongIdent (longDotId=ident; typarDecls=typars; argPats=ConstructorPats pats) -> + | SynPat.Or (pat1, pat2, _, _) -> List.iter walkPat [ pat1; pat2 ] + | SynPat.LongIdent (longDotId = ident; typarDecls = typars; argPats = ConstructorPats pats) -> addLongIdentWithDots ident + typars |> Option.iter (fun (ValTyparDecls (typars, constraints, _)) -> - List.iter walkTyparDecl typars - List.iter walkTypeConstraint constraints) + List.iter walkTyparDecl typars + List.iter walkTypeConstraint constraints) + List.iter walkPat pats | SynPat.Paren (pat, _) -> walkPat pat | SynPat.IsInst (t, _) -> walkType t - | SynPat.QuoteExpr(e, _) -> walkExpr e + | SynPat.QuoteExpr (e, _) -> walkExpr e | _ -> () - + and walkTypar (SynTypar _) = () - - and walkBinding (SynBinding(attributes=Attributes attrs; headPat=pat; returnInfo=returnInfo; expr=e)) = + + and walkBinding (SynBinding (attributes = Attributes attrs; headPat = pat; returnInfo = returnInfo; expr = e)) = List.iter walkAttribute attrs walkPat pat walkExpr e returnInfo |> Option.iter (fun (SynBindingReturnInfo (t, _, _)) -> walkType t) - - and walkInterfaceImpl (SynInterfaceImpl(bindings=bindings)) = List.iter walkBinding bindings - - and walkType = function + + and walkInterfaceImpl (SynInterfaceImpl (bindings = bindings)) = List.iter walkBinding bindings + + and walkType synType = + match synType with | SynType.Array (_, t, _) | SynType.HashConstraint (t, _) | SynType.MeasurePower (t, _, _) | SynType.Paren (t, _) -> walkType t - | SynType.Fun (t1, t2, _) - | SynType.MeasureDivide (t1, t2, _) -> walkType t1; walkType t2 + | SynType.Fun (argType = t1; returnType = t2) + | SynType.MeasureDivide (t1, t2, _) -> + walkType t1 + walkType t2 | SynType.LongIdent ident -> addLongIdentWithDots ident - | SynType.App (ty, _, types, _, _, _, _) -> walkType ty; List.iter walkType types + | SynType.App (ty, _, types, _, _, _, _) -> + walkType ty + List.iter walkType types | SynType.LongIdentApp (_, _, _, types, _, _, _) -> List.iter walkType types | SynType.Tuple (_, ts, _) -> ts |> List.iter (fun (_, t) -> walkType t) | SynType.WithGlobalConstraints (t, typeConstraints, _) -> - walkType t; List.iter walkTypeConstraint typeConstraints + walkType t + List.iter walkTypeConstraint typeConstraints | _ -> () - - and walkClause (SynMatchClause (pat=pat; whenExpr=e1; resultExpr=e2)) = + + and walkClause (SynMatchClause (pat = pat; whenExpr = e1; resultExpr = e2)) = walkPat pat walkExpr e2 e1 |> Option.iter walkExpr - - and walkSimplePats = function + + and walkSimplePats spats = + match spats with | SynSimplePats.SimplePats (pats, _) -> List.iter walkSimplePat pats - | SynSimplePats.Typed (pats, ty, _) -> + | SynSimplePats.Typed (pats, ty, _) -> walkSimplePats pats walkType ty - - and walkExpr = function + + and walkExpr expr = + match expr with | SynExpr.Paren (e, _, _, _) | SynExpr.Quote (_, _, e, _, _) | SynExpr.Typed (e, _, _) @@ -1371,52 +1703,60 @@ module ParsedInput = | SynExpr.Assert (e, _) | SynExpr.Lazy (e, _) | SynExpr.YieldOrReturnFrom (_, e, _) -> walkExpr e - | SynExpr.Lambda (args=pats; body=e) -> + | SynExpr.Lambda (args = pats; body = e) -> walkSimplePats pats walkExpr e | SynExpr.New (_, t, e, _) | SynExpr.TypeTest (e, t, _) | SynExpr.Upcast (e, t, _) - | SynExpr.Downcast (e, t, _) -> walkExpr e; walkType t + | SynExpr.Downcast (e, t, _) -> + walkExpr e + walkType t | SynExpr.Tuple (_, es, _, _) | Sequentials es | SynExpr.ArrayOrList (_, es, _) -> List.iter walkExpr es | SynExpr.App (_, _, e1, e2, _) - | SynExpr.TryFinally (tryExpr=e1; finallyExpr=e2) - | SynExpr.While (_, e1, e2, _) -> List.iter walkExpr [e1; e2] + | SynExpr.TryFinally (tryExpr = e1; finallyExpr = e2) + | SynExpr.While (_, e1, e2, _) -> List.iter walkExpr [ e1; e2 ] | SynExpr.Record (_, _, fields, _) -> - fields |> List.iter (fun (SynExprRecordField(fieldName=(ident, _); expr=e)) -> - addLongIdentWithDots ident - e |> Option.iter walkExpr) + fields + |> List.iter (fun (SynExprRecordField (fieldName = (ident, _); expr = e)) -> + addLongIdentWithDots ident + e |> Option.iter walkExpr) | SynExpr.Ident ident -> addIdent ident - | SynExpr.ObjExpr (objType=ty; argOptions=argOpt; bindings=bindings; members=ms; extraImpls=ifaces) -> + | SynExpr.ObjExpr (objType = ty; argOptions = argOpt; bindings = bindings; members = ms; extraImpls = ifaces) -> let bindings = unionBindingAndMembers bindings ms - argOpt |> Option.iter (fun (e, ident) -> + + argOpt + |> Option.iter (fun (e, ident) -> walkExpr e ident |> Option.iter addIdent) + walkType ty List.iter walkBinding bindings List.iter walkInterfaceImpl ifaces | SynExpr.LongIdent (_, ident, _, _) -> addLongIdentWithDots ident - | SynExpr.For (ident=ident; identBody=e1; toBody=e2; doBody=e3) -> + | SynExpr.For (ident = ident; identBody = e1; toBody = e2; doBody = e3) -> addIdent ident - List.iter walkExpr [e1; e2; e3] + List.iter walkExpr [ e1; e2; e3 ] | SynExpr.ForEach (_, _, _, _, pat, e1, e2, _) -> walkPat pat - List.iter walkExpr [e1; e2] - | SynExpr.MatchLambda (_, _, synMatchClauseList, _, _) -> - List.iter walkClause synMatchClauseList - | SynExpr.Match (expr=e; clauses=synMatchClauseList) -> + List.iter walkExpr [ e1; e2 ] + | SynExpr.MatchLambda (_, _, synMatchClauseList, _, _) -> List.iter walkClause synMatchClauseList + | SynExpr.Match (expr = e; clauses = synMatchClauseList) -> walkExpr e List.iter walkClause synMatchClauseList | SynExpr.TypeApp (e, _, tys, _, _, _, _) -> - List.iter walkType tys; walkExpr e - | SynExpr.LetOrUse (bindings=bindings; body=e) -> - List.iter walkBinding bindings; walkExpr e - | SynExpr.TryWith (tryExpr=e; withCases=clauses) -> - List.iter walkClause clauses; walkExpr e - | SynExpr.IfThenElse (ifExpr=e1; thenExpr=e2; elseExpr=e3) -> - List.iter walkExpr [e1; e2] + List.iter walkType tys + walkExpr e + | SynExpr.LetOrUse (bindings = bindings; body = e) -> + List.iter walkBinding bindings + walkExpr e + | SynExpr.TryWith (tryExpr = e; withCases = clauses) -> + List.iter walkClause clauses + walkExpr e + | SynExpr.IfThenElse (ifExpr = e1; thenExpr = e2; elseExpr = e3) -> + List.iter walkExpr [ e1; e2 ] e3 |> Option.iter walkExpr | SynExpr.LongIdentSet (ident, e, _) | SynExpr.DotGet (e, _, ident, _) -> @@ -1429,11 +1769,15 @@ module ParsedInput = | SynExpr.Set (e1, e2, _) -> walkExpr e1 walkExpr e2 - | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> - match expr1 with Some e -> walkExpr e | None -> () - match expr2 with Some e -> walkExpr e | None -> () - | SynExpr.IndexFromEnd (e, _) -> - walkExpr e + | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> + match expr1 with + | Some e -> walkExpr e + | None -> () + + match expr2 with + | Some e -> walkExpr e + | None -> () + | SynExpr.IndexFromEnd (e, _) -> walkExpr e | SynExpr.DotIndexedGet (e, args, _, _) -> walkExpr e walkExpr args @@ -1443,144 +1787,173 @@ module ParsedInput = walkExpr e2 | SynExpr.NamedIndexedPropertySet (ident, e1, e2, _) -> addLongIdentWithDots ident - List.iter walkExpr [e1; e2] + List.iter walkExpr [ e1; e2 ] | SynExpr.DotNamedIndexedPropertySet (e1, ident, e2, e3, _) -> addLongIdentWithDots ident - List.iter walkExpr [e1; e2; e3] - | SynExpr.JoinIn (e1, _, e2, _) -> List.iter walkExpr [e1; e2] - | SynExpr.LetOrUseBang (pat=pat; rhs=e1; andBangs=es; body=e2) -> + List.iter walkExpr [ e1; e2; e3 ] + | SynExpr.JoinIn (e1, _, e2, _) -> List.iter walkExpr [ e1; e2 ] + | SynExpr.LetOrUseBang (pat = pat; rhs = e1; andBangs = es; body = e2) -> walkPat pat walkExpr e1 - for SynExprAndBang(pat = patAndBang; body = eAndBang) in es do + + for SynExprAndBang (pat = patAndBang; body = eAndBang) in es do walkPat patAndBang walkExpr eAndBang + walkExpr e2 | SynExpr.TraitCall (ts, sign, e, _) -> List.iter walkTypar ts walkMemberSig sign walkExpr e - | SynExpr.Const (SynConst.Measure(_, _, m), _) -> walkMeasure m + | SynExpr.Const (SynConst.Measure (_, _, m), _) -> walkMeasure m | _ -> () - - and walkMeasure = function + + and walkMeasure measure = + match measure with | SynMeasure.Product (m1, m2, _) - | SynMeasure.Divide (m1, m2, _) -> walkMeasure m1; walkMeasure m2 + | SynMeasure.Divide (m1, m2, _) -> + walkMeasure m1 + walkMeasure m2 | SynMeasure.Named (longIdent, _) -> addLongIdent longIdent | SynMeasure.Seq (ms, _) -> List.iter walkMeasure ms - | SynMeasure.Paren(m, _) + | SynMeasure.Paren (m, _) | SynMeasure.Power (m, _, _) -> walkMeasure m | SynMeasure.Var (ty, _) -> walkTypar ty | SynMeasure.One | SynMeasure.Anon _ -> () - - and walkSimplePat = function + + and walkSimplePat spat = + match spat with | SynSimplePat.Attrib (pat, Attributes attrs, _) -> walkSimplePat pat List.iter walkAttribute attrs - | SynSimplePat.Typed(pat, t, _) -> + | SynSimplePat.Typed (pat, t, _) -> walkSimplePat pat walkType t | _ -> () - - and walkField (SynField(Attributes attrs, _, _, t, _, _, _, _)) = + + and walkField (SynField (Attributes attrs, _, _, t, _, _, _, _)) = List.iter walkAttribute attrs walkType t - - and walkValSig (SynValSig(attributes=Attributes attrs; synType=t; arity=SynValInfo(argInfos, argInfo))) = + + and walkValSig (SynValSig (attributes = Attributes attrs; synType = t; arity = SynValInfo (argInfos, argInfo))) = List.iter walkAttribute attrs walkType t + argInfo :: (argInfos |> List.concat) - |> List.collect (fun (SynArgInfo(Attributes attrs, _, _)) -> attrs) + |> List.collect (fun (SynArgInfo (Attributes attrs, _, _)) -> attrs) |> List.iter walkAttribute - - and walkMemberSig = function + + and walkMemberSig membSig = + match membSig with | SynMemberSig.Inherit (t, _) - | SynMemberSig.Interface(t, _) -> walkType t - | SynMemberSig.Member(vs, _, _) -> walkValSig vs - | SynMemberSig.ValField(f, _) -> walkField f - | SynMemberSig.NestedType(nestedType=SynTypeDefnSig.SynTypeDefnSig (typeInfo=info; typeRepr=repr; members=memberSigs)) -> + | SynMemberSig.Interface (t, _) -> walkType t + | SynMemberSig.Member (vs, _, _) -> walkValSig vs + | SynMemberSig.ValField (f, _) -> walkField f + | SynMemberSig.NestedType (nestedType = typeDefn) -> + let (SynTypeDefnSig (typeInfo = info; typeRepr = repr; members = memberSigs)) = + typeDefn + let isTypeExtensionOrAlias = match repr with - | SynTypeDefnSigRepr.Simple(SynTypeDefnSimpleRepr.TypeAbbrev _, _) - | SynTypeDefnSigRepr.ObjectModel(SynTypeDefnKind.Abbrev, _, _) - | SynTypeDefnSigRepr.ObjectModel(kind=SynTypeDefnKind.Augmentation _) -> true + | SynTypeDefnSigRepr.Simple (SynTypeDefnSimpleRepr.TypeAbbrev _, _) + | SynTypeDefnSigRepr.ObjectModel (SynTypeDefnKind.Abbrev, _, _) + | SynTypeDefnSigRepr.ObjectModel(kind = SynTypeDefnKind.Augmentation _) -> true | _ -> false + walkComponentInfo isTypeExtensionOrAlias info walkTypeDefnSigRepr repr List.iter walkMemberSig memberSigs - + and walkMember memb = match memb with | SynMemberDefn.AbstractSlot (valSig, _, _) -> walkValSig valSig | SynMemberDefn.Member (binding, _) -> walkBinding binding - | SynMemberDefn.ImplicitCtor (_, Attributes attrs, SynSimplePats.SimplePats(simplePats, _), _, _, _) -> + | SynMemberDefn.GetSetMember (getBinding, setBinding, _, _) -> + Option.iter walkBinding getBinding + Option.iter walkBinding setBinding + | SynMemberDefn.ImplicitCtor (_, Attributes attrs, SynSimplePats.SimplePats (simplePats, _), _, _, _) -> List.iter walkAttribute attrs List.iter walkSimplePat simplePats - | SynMemberDefn.ImplicitInherit (t, e, _, _) -> walkType t; walkExpr e + | SynMemberDefn.ImplicitInherit (t, e, _, _) -> + walkType t + walkExpr e | SynMemberDefn.LetBindings (bindings, _, _, _) -> List.iter walkBinding bindings - | SynMemberDefn.Interface (interfaceType=t; members=members) -> + | SynMemberDefn.Interface (interfaceType = t; members = members) -> walkType t members |> Option.iter (List.iter walkMember) | SynMemberDefn.Inherit (t, _, _) -> walkType t | SynMemberDefn.ValField (field, _) -> walkField field | SynMemberDefn.NestedType (tdef, _, _) -> walkTypeDefn tdef - | SynMemberDefn.AutoProperty (attributes=Attributes attrs; typeOpt=t; synExpr=e) -> + | SynMemberDefn.AutoProperty (attributes = Attributes attrs; typeOpt = t; synExpr = e) -> List.iter walkAttribute attrs Option.iter walkType t walkExpr e | _ -> () - - and walkEnumCase (SynEnumCase(attributes=Attributes attrs)) = List.iter walkAttribute attrs - - and walkUnionCaseType = function + + and walkEnumCase (SynEnumCase(attributes = Attributes attrs)) = List.iter walkAttribute attrs + + and walkUnionCaseType kind = + match kind with | SynUnionCaseKind.Fields fields -> List.iter walkField fields | SynUnionCaseKind.FullType (t, _) -> walkType t - - and walkUnionCase (SynUnionCase(attributes=Attributes attrs; caseType=t)) = + + and walkUnionCase (SynUnionCase (attributes = Attributes attrs; caseType = t)) = List.iter walkAttribute attrs walkUnionCaseType t - - and walkTypeDefnSimple = function + + and walkTypeDefnSimple typeDefn = + match typeDefn with | SynTypeDefnSimpleRepr.Enum (cases, _) -> List.iter walkEnumCase cases | SynTypeDefnSimpleRepr.Union (_, cases, _) -> List.iter walkUnionCase cases | SynTypeDefnSimpleRepr.Record (_, fields, _) -> List.iter walkField fields | SynTypeDefnSimpleRepr.TypeAbbrev (_, t, _) -> walkType t | _ -> () - - and walkComponentInfo isTypeExtensionOrAlias (SynComponentInfo(Attributes attrs, TyparsAndConstraints (typars, cs1), cs2, longIdent, _, _, _, _)) = + + and walkComponentInfo isTypeExtensionOrAlias compInfo = + let (SynComponentInfo (Attributes attrs, TyparsAndConstraints (typars, cs1), cs2, longIdent, _, _, _, _)) = + compInfo + let constraints = cs1 @ cs2 List.iter walkAttribute attrs List.iter walkTyparDecl typars List.iter walkTypeConstraint constraints + if isTypeExtensionOrAlias then addLongIdent longIdent - - and walkTypeDefnRepr = function + + and walkTypeDefnRepr inp = + match inp with | SynTypeDefnRepr.ObjectModel (_, defns, _) -> List.iter walkMember defns - | SynTypeDefnRepr.Simple(defn, _) -> walkTypeDefnSimple defn + | SynTypeDefnRepr.Simple (defn, _) -> walkTypeDefnSimple defn | SynTypeDefnRepr.Exception _ -> () - - and walkTypeDefnSigRepr = function + + and walkTypeDefnSigRepr inp = + match inp with | SynTypeDefnSigRepr.ObjectModel (_, defns, _) -> List.iter walkMemberSig defns - | SynTypeDefnSigRepr.Simple(defn, _) -> walkTypeDefnSimple defn + | SynTypeDefnSigRepr.Simple (defn, _) -> walkTypeDefnSimple defn | SynTypeDefnSigRepr.Exception _ -> () - - and walkTypeDefn (SynTypeDefn (typeInfo=info; typeRepr=repr; members=members; implicitConstructor=implicitCtor)) = + + and walkTypeDefn typeDefn = + let (SynTypeDefn (typeInfo = info; typeRepr = repr; members = members; implicitConstructor = implicitCtor)) = + typeDefn + let isTypeExtensionOrAlias = match repr with - | SynTypeDefnRepr.ObjectModel (kind=SynTypeDefnKind.Augmentation _) + | SynTypeDefnRepr.ObjectModel(kind = SynTypeDefnKind.Augmentation _) | SynTypeDefnRepr.ObjectModel (SynTypeDefnKind.Abbrev, _, _) | SynTypeDefnRepr.Simple (SynTypeDefnSimpleRepr.TypeAbbrev _, _) -> true | _ -> false + walkComponentInfo isTypeExtensionOrAlias info walkTypeDefnRepr repr List.iter walkMember members Option.iter walkMember implicitCtor - + and walkSynModuleDecl (decl: SynModuleDecl) = match decl with | SynModuleDecl.NamespaceFragment fragment -> walkSynModuleOrNamespace fragment - | SynModuleDecl.NestedModule (moduleInfo=info; decls=modules) -> + | SynModuleDecl.NestedModule (moduleInfo = info; decls = modules) -> walkComponentInfo false info List.iter walkSynModuleDecl modules | SynModuleDecl.Let (_, bindings, _) -> List.iter walkBinding bindings @@ -1588,98 +1961,118 @@ module ParsedInput = | SynModuleDecl.Types (types, _) -> List.iter walkTypeDefn types | SynModuleDecl.Attributes (Attributes attrs, _) -> List.iter walkAttribute attrs | _ -> () - + match parsedInput with - | ParsedInput.ImplFile input -> - walkImplFileInput input + | ParsedInput.ImplFile input -> walkImplFileInput input | _ -> () //debug "%A" idents upcast identsByEndPos - + let GetLongIdentAt parsedInput pos = let idents = getLongIdents parsedInput + match idents.TryGetValue pos with | true, idents -> Some idents | _ -> None type Scope = - { ShortIdents: ShortIdents - Kind: ScopeKind } + { + ShortIdents: ShortIdents + Kind: ScopeKind + } - let tryFindNearestPointAndModules (currentLine: int) (ast: ParsedInput) (insertionPoint: OpenStatementInsertionPoint) = + let tryFindNearestPointAndModules currentLine (ast: ParsedInput) (insertionPoint: OpenStatementInsertionPoint) = // We ignore all diagnostics during this operation // // Based on an initial review, no diagnostics should be generated. However the code should be checked more closely. - use _ignoreAllDiagnostics = new DiagnosticsScope() + use _ignoreAllDiagnostics = new DiagnosticsScope() let mutable result = None let mutable ns = None - let modules = ResizeArray() + let modules = ResizeArray() let inline longIdentToIdents ident = ident |> Seq.map string |> Seq.toArray - + let addModule (longIdent: LongIdent, range: range) = - modules.Add - { Idents = longIdentToIdents longIdent - Range = range } + modules.Add + { + Idents = longIdentToIdents longIdent + Range = range + } let doRange kind (scope: LongIdent) line col = if line <= currentLine then match result, insertionPoint with - | None, _ -> - result <- Some ({ ShortIdents = longIdentToIdents scope; Kind = kind }, mkPos line col, false) + | None, _ -> + result <- + Some( + { + ShortIdents = longIdentToIdents scope + Kind = kind + }, + mkPos line col, + false + ) | Some (_, _, true), _ -> () | Some (oldScope, oldPos, false), OpenStatementInsertionPoint.TopLevel when kind <> OpenDeclaration -> - result <- Some (oldScope, oldPos, true) + result <- Some(oldScope, oldPos, true) | Some (oldScope, oldPos, _), _ -> match kind, oldScope.Kind with - | (Namespace | NestedModule | TopModule), OpenDeclaration + | (Namespace + | NestedModule + | TopModule), + OpenDeclaration | _ when oldPos.Line <= line -> result <- - Some ({ ShortIdents = - match scope with - | [] -> oldScope.ShortIdents + Some( + { + ShortIdents = + match scope with + | [] -> oldScope.ShortIdents | _ -> longIdentToIdents scope - Kind = kind }, - mkPos line col, - false) + Kind = kind + }, + mkPos line col, + false + ) | _ -> () let getMinColumn decls = match decls with | [] -> None - | firstDecl :: _ -> + | firstDecl :: _ -> match firstDecl with - | SynModuleDecl.NestedModule (range=r) - | SynModuleDecl.Let (range=r) - | SynModuleDecl.Expr (range=r) - | SynModuleDecl.Types (range=r) - | SynModuleDecl.Exception (range=r) - | SynModuleDecl.Open (range=r) - | SynModuleDecl.HashDirective (range=r) -> Some r + | SynModuleDecl.NestedModule (range = r) + | SynModuleDecl.Let (range = r) + | SynModuleDecl.Expr (range = r) + | SynModuleDecl.Types (range = r) + | SynModuleDecl.Exception (range = r) + | SynModuleDecl.Open (range = r) + | SynModuleDecl.HashDirective (range = r) -> Some r | _ -> None |> Option.map (fun r -> r.StartColumn) - - let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = + let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = List.iter (walkSynModuleOrNamespace []) moduleOrNamespaceList - and walkSynModuleOrNamespace (parent: LongIdent) (SynModuleOrNamespace(longId = ident; kind = kind; decls = decls; range = range)) = + and walkSynModuleOrNamespace (parent: LongIdent) modul = + let (SynModuleOrNamespace (longId = ident; kind = kind; decls = decls; range = range)) = + modul + if range.EndLine >= currentLine then let isModule = kind.IsModule + match isModule, parent, ident with - | false, _, _ -> ns <- Some (longIdentToIdents ident) + | false, _, _ -> ns <- Some(longIdentToIdents ident) // top level module with "inlined" namespace like Ns1.Ns2.TopModule - | true, [], _f :: _s :: _ -> + | true, [], _f :: _s :: _ -> let ident = longIdentToIdents ident - ns <- Some ident[0..ident.Length - 2] + ns <- Some ident[0 .. ident.Length - 2] | _ -> () - + let fullIdent = parent @ ident - let startLine = - if isModule then range.StartLine - else range.StartLine - 1 + let startLine = if isModule then range.StartLine else range.StartLine - 1 let scopeKind = match isModule, parent with @@ -1694,18 +2087,21 @@ module ParsedInput = and walkSynModuleDecl (parent: LongIdent) (decl: SynModuleDecl) = match decl with | SynModuleDecl.NamespaceFragment fragment -> walkSynModuleOrNamespace parent fragment - | SynModuleDecl.NestedModule(moduleInfo=SynComponentInfo(longId=ident); decls=decls; range=range) -> + | SynModuleDecl.NestedModule (moduleInfo = SynComponentInfo (longId = ident); decls = decls; range = range) -> let fullIdent = parent @ ident addModule (fullIdent, range) + if range.EndLine >= currentLine then - let moduleBodyIndentation = getMinColumn decls |> Option.defaultValue (range.StartColumn + 4) + let moduleBodyIndentation = + getMinColumn decls |> Option.defaultValue (range.StartColumn + 4) + doRange NestedModule fullIdent range.StartLine moduleBodyIndentation List.iter (walkSynModuleDecl fullIdent) decls | SynModuleDecl.Open (_, range) -> doRange OpenDeclaration [] range.EndLine (range.StartColumn - 5) | SynModuleDecl.HashDirective (_, range) -> doRange HashDirective [] range.EndLine range.StartColumn | _ -> () - match ast with + match ast with | ParsedInput.SigFile _ -> () | ParsedInput.ImplFile input -> walkImplFileInput input @@ -1714,9 +2110,9 @@ module ParsedInput = |> Option.map (fun (scope, pos, _) -> let ns = ns |> Option.map longIdentToIdents scope, ns, mkPos (pos.Line + 1) pos.Column) - - let modules = - modules + + let modules = + modules |> Seq.filter (fun x -> x.Range.EndLine < currentLine) |> Seq.sortBy (fun x -> -x.Idents.Length) |> Seq.toList @@ -1732,65 +2128,104 @@ module ParsedInput = match scope.Kind with | TopModule -> NestedModule | x -> x - { ScopeKind = scopeKind - Pos = mkPos (Line.fromZ m.Range.EndLine) m.Range.StartColumn } - let TryFindInsertionContext (currentLine: int) (parsedInput: ParsedInput) (partiallyQualifiedName: MaybeUnresolvedIdent[]) (insertionPoint: OpenStatementInsertionPoint) = - let res, modules = tryFindNearestPointAndModules currentLine parsedInput insertionPoint - fun (requiresQualifiedAccessParent: ShortIdents option, autoOpenParent: ShortIdents option, entityNamespace: ShortIdents option, entity: ShortIdents) -> + { + ScopeKind = scopeKind + Pos = mkPos (Line.fromZ m.Range.EndLine) m.Range.StartColumn + } + + let TryFindInsertionContext + (currentLine: int) + (parsedInput: ParsedInput) + (partiallyQualifiedName: MaybeUnresolvedIdent[]) + (insertionPoint: OpenStatementInsertionPoint) + = + let res, modules = + tryFindNearestPointAndModules currentLine parsedInput insertionPoint + + fun (requiresQualifiedAccessParent: ShortIdents option, + autoOpenParent: ShortIdents option, + entityNamespace: ShortIdents option, + entity: ShortIdents) -> // We ignore all diagnostics during this operation // // Based on an initial review, no diagnostics should be generated. However the code should be checked more closely. - use _ignoreAllDiagnostics = new DiagnosticsScope() + use _ignoreAllDiagnostics = new DiagnosticsScope() + match res with | None -> [||] - | Some (scope, ns, pos) -> - Entity.tryCreate(ns, scope.ShortIdents, partiallyQualifiedName, requiresQualifiedAccessParent, autoOpenParent, entityNamespace, entity) + | Some (scope, ns, pos) -> + let entities = + Entity.tryCreate ( + ns, + scope.ShortIdents, + partiallyQualifiedName, + requiresQualifiedAccessParent, + autoOpenParent, + entityNamespace, + entity + ) + + entities |> Array.map (fun e -> e, findBestPositionToInsertOpenDeclaration modules scope pos entity) /// Corrects insertion line number based on kind of scope and text surrounding the insertion point. - let AdjustInsertionPoint (getLineStr: int -> string) ctx = + let AdjustInsertionPoint (getLineStr: int -> string) ctx = let line = match ctx.ScopeKind with | ScopeKind.TopModule -> if ctx.Pos.Line > 1 then - // it's an implicit module without any open declarations + // it's an implicit module without any open declarations let line = getLineStr (ctx.Pos.Line - 2) + let isImplicitTopLevelModule = not (line.StartsWithOrdinal("module") && not (line.EndsWithOrdinal("="))) + if isImplicitTopLevelModule then 1 else ctx.Pos.Line - else 1 + else + 1 + | ScopeKind.Namespace -> // For namespaces the start line is start line of the first nested entity - // If we are not on the first line, try to find opening namespace, and return line after it (in F# format) + // If we are not on the first line, try to find opening namespace, and return line after it (in F# format) if ctx.Pos.Line > 1 then - [0..ctx.Pos.Line - 1] + [ 0 .. ctx.Pos.Line - 1 ] |> List.mapi (fun i line -> i, getLineStr line) - |> List.tryPick (fun (i, lineStr) -> - if lineStr.StartsWithOrdinal("namespace") then Some i - else None) + |> List.tryPick (fun (i, lineStr) -> + if lineStr.StartsWithOrdinal("namespace") then + Some i + else + None) |> function // move to the next line below "namespace" and convert it to F# 1-based line number - | Some line -> line + 2 + | Some line -> line + 2 | None -> ctx.Pos.Line // If we are on 1st line in the namespace ctx, this line _should_ be the namespace declaration, check it and return next line. // Otherwise, return first line (which theoretically should not happen). else let lineStr = getLineStr (ctx.Pos.Line - 1) + if lineStr.StartsWithOrdinal("namespace") then ctx.Pos.Line + 1 else ctx.Pos.Line + | _ -> ctx.Pos.Line mkPos line ctx.Pos.Column - - let FindNearestPointToInsertOpenDeclaration (currentLine: int) (parsedInput: ParsedInput) (entity: ShortIdents) (insertionPoint: OpenStatementInsertionPoint) = + + let FindNearestPointToInsertOpenDeclaration + (currentLine: int) + (parsedInput: ParsedInput) + (entity: ShortIdents) + (insertionPoint: OpenStatementInsertionPoint) + = match tryFindNearestPointAndModules currentLine parsedInput insertionPoint with - | Some (scope, _, point), modules -> - findBestPositionToInsertOpenDeclaration modules scope point entity + | Some (scope, _, point), modules -> findBestPositionToInsertOpenDeclaration modules scope point entity | _ -> - // we failed to find insertion point because ast is empty for some reason, return top left point in this case - { ScopeKind = ScopeKind.TopModule - Pos = mkPos 1 0 } + // we failed to find insertion point because ast is empty for some reason, return top left point in this case + { + ScopeKind = ScopeKind.TopModule + Pos = mkPos 1 0 + } diff --git a/src/Compiler/Service/ServiceStructure.fs b/src/Compiler/Service/ServiceStructure.fs index bc9f5255c3e..cbc625f709b 100644 --- a/src/Compiler/Service/ServiceStructure.fs +++ b/src/Compiler/Service/ServiceStructure.fs @@ -17,42 +17,46 @@ module Structure = module Range = /// Create a range starting at the end of r1 and finishing at the end of r2 - let endToEnd (r1: range) (r2: range) = mkFileIndexRange r1.FileIndex r1.End r2.End + let endToEnd (r1: range) (r2: range) = + mkFileIndexRange r1.FileIndex r1.End r2.End /// Create a range starting at the end of r1 and finishing at the start of r2 - let endToStart (r1: range) (r2: range) = mkFileIndexRange r1.FileIndex r1.End r2.Start + let endToStart (r1: range) (r2: range) = + mkFileIndexRange r1.FileIndex r1.End r2.Start /// Create a range beginning at the start of r1 and finishing at the end of r2 - let startToEnd (r1: range) (r2: range) = mkFileIndexRange r1.FileIndex r1.Start r2.End + let startToEnd (r1: range) (r2: range) = + mkFileIndexRange r1.FileIndex r1.Start r2.End /// Create a range beginning at the start of r1 and finishing at the start of r2 - let startToStart (r1: range) (r2: range) = mkFileIndexRange r1.FileIndex r1.Start r2.Start + let startToStart (r1: range) (r2: range) = + mkFileIndexRange r1.FileIndex r1.Start r2.Start /// Create a new range from r by shifting the starting column by m - let modStart (m:int) (r: range) = - let modstart = mkPos r.StartLine (r.StartColumn+m) + let modStart (m: int) (r: range) = + let modstart = mkPos r.StartLine (r.StartColumn + m) mkFileIndexRange r.FileIndex modstart r.End /// Create a new range from r by shifting the ending column by m - let modEnd (m:int) (r: range) = - let modend = mkPos r.EndLine (r.EndColumn+m) + let modEnd (m: int) (r: range) = + let modend = mkPos r.EndLine (r.EndColumn + m) mkFileIndexRange r.FileIndex r.Start modend /// Produce a new range by adding modStart to the StartColumn of `r` /// and subtracting modEnd from the EndColumn of `r` - let modBoth modStart modEnd (r:range) = - let rStart = mkPos r.StartLine (r.StartColumn+modStart) - let rEnd = mkPos r.EndLine (r.EndColumn - modEnd) + let modBoth modStart modEnd (r: range) = + let rStart = mkPos r.StartLine (r.StartColumn + modStart) + let rEnd = mkPos r.EndLine (r.EndColumn - modEnd) mkFileIndexRange r.FileIndex rStart rEnd - let longIdentRange (longId:LongIdent) = - match longId with + let longIdentRange (longId: LongIdent) = + match longId with | [] -> range0 | head :: _ -> Range.startToEnd head.idRange (List.last longId).idRange - /// Calculate the range of the provided type arguments (<'a, ..., 'z>) + /// Calculate the range of the provided type arguments (<'a, ..., 'z>) /// or return the range `other` when `typeArgs` = [] - let rangeOfTypeArgsElse other (typeArgs:SynTyparDecl list) = + let rangeOfTypeArgsElse other (typeArgs: SynTyparDecl list) = match typeArgs with | [] -> other | ls -> @@ -60,16 +64,16 @@ module Structure = |> List.map (fun (SynTyparDecl (_, typarg)) -> typarg.Range) |> List.reduce unionRanges - let rangeOfSynPatsElse other (synPats:SynSimplePat list) = + let rangeOfSynPatsElse other (synPats: SynSimplePat list) = match synPats with | [] -> other | ls -> - ls + ls |> List.map (fun x -> - match x with - | SynSimplePat.Attrib(range = r) - | SynSimplePat.Id(range = r) - | SynSimplePat.Typed(range = r) -> r) + match x with + | SynSimplePat.Attrib (range = r) + | SynSimplePat.Id (range = r) + | SynSimplePat.Typed (range = r) -> r) |> List.reduce unionRanges /// Collapse indicates the way a range/snapshot should be collapsed. `Same` is for a scope inside @@ -130,92 +134,105 @@ module Structure = | Comment | XmlDocComment - override self.ToString() = + override self.ToString() = match self with - | Open -> "Open" - | Namespace -> "Namespace" - | Module -> "Module" - | Type -> "Type" - | Member -> "Member" - | LetOrUse -> "LetOrUse" - | Val -> "Val" - | ComputationExpr -> "ComputationExpr" - | IfThenElse -> "IfThenElse" - | ThenInIfThenElse -> "ThenInIfThenElse" - | ElseInIfThenElse -> "ElseInIfThenElse" - | TryWith -> "TryWith" - | TryInTryWith -> "TryInTryWith" - | WithInTryWith -> "WithInTryWith" - | TryFinally -> "TryFinally" - | TryInTryFinally -> "TryInTryFinally" + | Open -> "Open" + | Namespace -> "Namespace" + | Module -> "Module" + | Type -> "Type" + | Member -> "Member" + | LetOrUse -> "LetOrUse" + | Val -> "Val" + | ComputationExpr -> "ComputationExpr" + | IfThenElse -> "IfThenElse" + | ThenInIfThenElse -> "ThenInIfThenElse" + | ElseInIfThenElse -> "ElseInIfThenElse" + | TryWith -> "TryWith" + | TryInTryWith -> "TryInTryWith" + | WithInTryWith -> "WithInTryWith" + | TryFinally -> "TryFinally" + | TryInTryFinally -> "TryInTryFinally" | FinallyInTryFinally -> "FinallyInTryFinally" - | ArrayOrList -> "ArrayOrList" - | ObjExpr -> "ObjExpr" - | For -> "For" - | While -> "While" - | Match -> "Match" - | MatchBang -> "MatchBang" - | MatchLambda -> "MatchLambda" - | MatchClause -> "MatchClause" - | Lambda -> "Lambda" - | Quote -> "Quote" - | Record -> "Record" - | SpecialFunc -> "SpecialFunc" - | Do -> "Do" - | New -> "New" - | Attribute -> "Attribute" - | Interface -> "Interface" - | HashDirective -> "HashDirective" - | LetOrUseBang -> "LetOrUseBang" - | TypeExtension -> "TypeExtension" - | YieldOrReturn -> "YieldOrReturn" - | YieldOrReturnBang -> "YieldOrReturnBang" - | Tuple -> "Tuple" - | UnionCase -> "UnionCase" - | EnumCase -> "EnumCase" - | RecordField -> "RecordField" - | RecordDefn -> "RecordDefn" - | UnionDefn -> "UnionDefn" - | Comment -> "Comment" - | XmlDocComment -> "XmlDocComment" + | ArrayOrList -> "ArrayOrList" + | ObjExpr -> "ObjExpr" + | For -> "For" + | While -> "While" + | Match -> "Match" + | MatchBang -> "MatchBang" + | MatchLambda -> "MatchLambda" + | MatchClause -> "MatchClause" + | Lambda -> "Lambda" + | Quote -> "Quote" + | Record -> "Record" + | SpecialFunc -> "SpecialFunc" + | Do -> "Do" + | New -> "New" + | Attribute -> "Attribute" + | Interface -> "Interface" + | HashDirective -> "HashDirective" + | LetOrUseBang -> "LetOrUseBang" + | TypeExtension -> "TypeExtension" + | YieldOrReturn -> "YieldOrReturn" + | YieldOrReturnBang -> "YieldOrReturnBang" + | Tuple -> "Tuple" + | UnionCase -> "UnionCase" + | EnumCase -> "EnumCase" + | RecordField -> "RecordField" + | RecordDefn -> "RecordDefn" + | UnionDefn -> "UnionDefn" + | Comment -> "Comment" + | XmlDocComment -> "XmlDocComment" /// Stores the range for a construct, the sub-range that should be collapsed for outlining, /// a tag for the construct type, and a tag for the collapse style [] - type ScopeRange = - { Scope: Scope - Collapse: Collapse - /// HintSpan in BlockSpan - Range: range - /// TextSpan in BlockSpan - CollapseRange: range } + type ScopeRange = + { + Scope: Scope + Collapse: Collapse + /// HintSpan in BlockSpan + Range: range + /// TextSpan in BlockSpan + CollapseRange: range + } type LineNumber = int type LineStr = string - type CommentType = SingleLine | XmlDoc + + type CommentType = + | SingleLine + | XmlDoc [] type CommentList = - { Lines: ResizeArray - Type: CommentType } + { + Lines: ResizeArray + Type: CommentType + } + static member New ty lineStr = - { Type = ty - Lines = ResizeArray [lineStr] } + { + Type = ty + Lines = ResizeArray [ lineStr ] + } - /// Returns outlining ranges for given parsed input. + /// Returns outlining ranges for given parsed input. let getOutliningRanges (sourceLines: string[]) (parsedInput: ParsedInput) = let acc = ResizeArray() /// Validation function to ensure that ranges yielded for outlining span 2 or more lines - let inline rcheck scope collapse (fullRange: range) (collapseRange: range) = - if fullRange.StartLine <> fullRange.EndLine then - acc.Add { Scope = scope - Collapse = collapse - Range = fullRange - CollapseRange = collapseRange } - - //============================================// - // Implementation File AST Traversal // + let inline rcheck scope collapse (fullRange: range) (collapseRange: range) = + if fullRange.StartLine <> fullRange.EndLine then + acc.Add + { + Scope = scope + Collapse = collapse + Range = fullRange + CollapseRange = collapseRange + } + + //============================================// + // Implementation File AST Traversal // //============================================// let rec parseExpr expr = @@ -228,32 +245,39 @@ module Structure = | SynExpr.DotGet (e, _, _, _) | SynExpr.Do (e, _) | SynExpr.Typed (e, _, _) - | SynExpr.DotIndexedGet (e, _, _, _) -> - parseExpr e + | SynExpr.DotIndexedGet (e, _, _, _) -> parseExpr e + | SynExpr.Set (e1, e2, _) | SynExpr.DotSet (e1, _, e2, _) - | SynExpr.DotIndexedSet (e1, _, e2, _, _, _) -> + | SynExpr.DotIndexedSet (e1, _, e2, _, _, _) -> parseExpr e1 parseExpr e2 - | SynExpr.New (_, _, expr, r) -> - rcheck Scope.New Collapse.Below r expr.Range - parseExpr expr + + | SynExpr.New (_, _, e, r) -> + rcheck Scope.New Collapse.Below r e.Range + parseExpr e + | SynExpr.YieldOrReturn (_, e, r) -> rcheck Scope.YieldOrReturn Collapse.Below r r parseExpr e + | SynExpr.YieldOrReturnFrom (_, e, r) -> rcheck Scope.YieldOrReturnBang Collapse.Below r r parseExpr e + | SynExpr.DoBang (e, r) -> rcheck Scope.Do Collapse.Below r <| Range.modStart 3 r parseExpr e - | SynExpr.LetOrUseBang (pat=pat; rhs=eLet; andBangs=es; body=eBody) -> - [ - yield eLet - for SynExprAndBang(body = eAndBang) in es do - yield eAndBang - ] - |> List.iter (fun e -> + + | SynExpr.LetOrUseBang (pat = pat; rhs = eLet; andBangs = es; body = eBody) -> + let exprs = + [ + eLet + for SynExprAndBang (body = eAndBang) in es do + eAndBang + ] + + for e in exprs do // for `let!`, `use!` or `and!` the pattern begins at the end of the // keyword so that this scope can be used without adjustment if there is no `=` // on the same line. If there is an `=` the range will be adjusted during the @@ -261,111 +285,155 @@ module Structure = let r = Range.endToEnd pat.Range e.Range rcheck Scope.LetOrUseBang Collapse.Below r r parseExpr e - ) + parseExpr eBody - | SynExpr.For (doBody=e; range=r) + + | SynExpr.For (doBody = e; range = r) | SynExpr.ForEach (_, _, _, _, _, _, e, r) -> rcheck Scope.For Collapse.Below r r parseExpr e - | SynExpr.LetOrUse (bindings=bindings; body=body) -> + + | SynExpr.LetOrUse (bindings = bindings; body = body) -> parseBindings bindings parseExpr body - | SynExpr.Match (matchDebugPoint=seqPointAtBinding; clauses=clauses; range=r) - | SynExpr.MatchBang (matchDebugPoint=seqPointAtBinding; clauses=clauses; range=r) -> + + | SynExpr.Match (matchDebugPoint = seqPointAtBinding; clauses = clauses; range = r) + | SynExpr.MatchBang (matchDebugPoint = seqPointAtBinding; clauses = clauses; range = r) -> match seqPointAtBinding with | DebugPointAtBinding.Yes sr -> let collapse = Range.endToEnd sr r rcheck Scope.Match Collapse.Same r collapse | _ -> () + List.iter parseMatchClause clauses + | SynExpr.MatchLambda (_, caseRange, clauses, matchSeqPoint, r) -> let caseRange = match matchSeqPoint with | DebugPointAtBinding.Yes r -> r | _ -> caseRange + let collapse = Range.endToEnd caseRange r rcheck Scope.MatchLambda Collapse.Same r collapse List.iter parseMatchClause clauses + | SynExpr.App (atomicFlag, isInfix, funcExpr, argExpr, r) -> // seq exprs, custom operators, etc - if ExprAtomicFlag.NonAtomic=atomicFlag && (not isInfix) - && (function SynExpr.Ident _ -> true | _ -> false) funcExpr - && (function SynExpr.ComputationExpr _ -> false | _ -> true ) argExpr then - // if the argExpr is a computation expression another match will handle the outlining - // these cases must be removed to prevent creating unnecessary tags for the same scope + if + ExprAtomicFlag.NonAtomic = atomicFlag + && not isInfix + && (match funcExpr with + | SynExpr.Ident _ -> true + | _ -> false) + && (match argExpr with + | SynExpr.ComputationExpr _ -> false + | _ -> true) + then + // if the argExpr is a computation expression another match will handle the outlining + // these cases must be removed to prevent creating unnecessary tags for the same scope let collapse = Range.endToEnd funcExpr.Range r rcheck Scope.SpecialFunc Collapse.Below r collapse - elif ExprAtomicFlag.NonAtomic=atomicFlag && (not isInfix) - && (function SynExpr.ComputationExpr _ -> true | _ -> false) argExpr then - let collapse = Range.startToEnd argExpr.Range r - rcheck Scope.ComputationExpr Collapse.Same r <| Range.modBoth 1 1 collapse + + elif + ExprAtomicFlag.NonAtomic = atomicFlag + && (not isInfix) + && (match argExpr with + | SynExpr.ComputationExpr _ -> true + | _ -> false) + then + let collapse = Range.startToEnd argExpr.Range r + let collapse = Range.modBoth 1 1 collapse + rcheck Scope.ComputationExpr Collapse.Same r collapse + parseExpr argExpr parseExpr funcExpr + | SynExpr.Sequential (_, _, e1, e2, _) -> parseExpr e1 parseExpr e2 + | SynExpr.ArrayOrListComputed (isArray, e, r) -> - rcheck Scope.ArrayOrList Collapse.Same r <| Range.modBoth (if isArray then 2 else 1) (if isArray then 2 else 1) r + let collapse = Range.modBoth (if isArray then 2 else 1) (if isArray then 2 else 1) r + rcheck Scope.ArrayOrList Collapse.Same r collapse parseExpr e - | SynExpr.ComputationExpr (_, e, _r) as _c -> - parseExpr e - | SynExpr.ObjExpr (argOptions=argOpt; bindings=bindings; members=ms; extraImpls=extraImpls; newExprRange=newRange; range=wholeRange) as _objExpr -> + + | SynExpr.ComputationExpr (_, e, _r) as _c -> parseExpr e + + | SynExpr.ObjExpr (argOptions = argOpt + bindings = bindings + members = ms + extraImpls = extraImpls + newExprRange = newRange + range = mWhole) -> let bindings = unionBindingAndMembers bindings ms + match argOpt with | Some (args, _) -> - let collapse = Range.endToEnd args.Range wholeRange - rcheck Scope.ObjExpr Collapse.Below wholeRange collapse + let collapse = Range.endToEnd args.Range mWhole + rcheck Scope.ObjExpr Collapse.Below mWhole collapse | None -> - let collapse = Range.endToEnd newRange wholeRange - rcheck Scope.ObjExpr Collapse.Below wholeRange collapse + let collapse = Range.endToEnd newRange mWhole + rcheck Scope.ObjExpr Collapse.Below mWhole collapse + parseBindings bindings parseExprInterfaces extraImpls - | SynExpr.TryWith (e, matchClauses, wholeRange, tryPoint, withPoint, _trivia) -> + + | SynExpr.TryWith (e, matchClauses, mWhole, tryPoint, withPoint, _trivia) -> match tryPoint, withPoint with - | DebugPointAtTry.Yes tryRange, DebugPointAtWith.Yes withRange -> - let fullrange = Range.startToEnd tryRange wholeRange - let collapse = Range.endToEnd tryRange wholeRange + | DebugPointAtTry.Yes tryRange, DebugPointAtWith.Yes withRange -> + let mFull = Range.startToEnd tryRange mWhole + let collapse = Range.endToEnd tryRange mWhole let collapseTry = Range.endToStart tryRange withRange let fullrangeTry = Range.startToStart tryRange withRange - let collapseWith = Range.endToEnd withRange wholeRange - let fullrangeWith = Range.startToEnd withRange wholeRange - rcheck Scope.TryWith Collapse.Below fullrange collapse + let collapseWith = Range.endToEnd withRange mWhole + let fullrangeWith = Range.startToEnd withRange mWhole + rcheck Scope.TryWith Collapse.Below mFull collapse rcheck Scope.TryInTryWith Collapse.Below fullrangeTry collapseTry rcheck Scope.WithInTryWith Collapse.Below fullrangeWith collapseWith | _ -> () + parseExpr e List.iter parseMatchClause matchClauses + | SynExpr.TryFinally (tryExpr, finallyExpr, r, tryPoint, finallyPoint, _trivia) -> match tryPoint, finallyPoint with | DebugPointAtTry.Yes tryRange, DebugPointAtFinally.Yes finallyRange -> let collapse = Range.endToEnd tryRange finallyExpr.Range - let fullrange = Range.startToEnd tryRange finallyExpr.Range + let mFull = Range.startToEnd tryRange finallyExpr.Range let collapseFinally = Range.endToEnd finallyRange r let fullrangeFinally = Range.startToEnd finallyRange r - rcheck Scope.TryFinally Collapse.Below fullrange collapse - rcheck Scope.FinallyInTryFinally Collapse.Below fullrangeFinally collapseFinally + rcheck Scope.TryFinally Collapse.Below mFull collapse + rcheck Scope.FinallyInTryFinally Collapse.Below fullrangeFinally collapseFinally | _ -> () + parseExpr tryExpr parseExpr finallyExpr - | SynExpr.IfThenElse (ifExpr=ifExpr; thenExpr=thenExpr; elseExpr=elseExprOpt; spIfToThen=spIfToThen; range=r; trivia=trivia) -> + + | SynExpr.IfThenElse (ifExpr = ifExpr + thenExpr = thenExpr + elseExpr = elseExprOpt + spIfToThen = spIfToThen + range = r + trivia = trivia) -> match spIfToThen with | DebugPointAtBinding.Yes rt -> // Outline the entire IfThenElse - let fullrange = Range.startToEnd rt r - let collapse = Range.endToEnd ifExpr.Range r - rcheck Scope.IfThenElse Collapse.Below fullrange collapse + let mFull = Range.startToEnd rt r + let collapse = Range.endToEnd ifExpr.Range r + rcheck Scope.IfThenElse Collapse.Below mFull collapse // Outline the `then` scope - let thenRange = Range.endToEnd (Range.modEnd -4 trivia.IfToThenRange) thenExpr.Range + let thenRange = Range.endToEnd (Range.modEnd -4 trivia.IfToThenRange) thenExpr.Range let thenCollapse = Range.endToEnd trivia.IfToThenRange thenExpr.Range rcheck Scope.ThenInIfThenElse Collapse.Below thenRange thenCollapse | _ -> () + parseExpr ifExpr parseExpr thenExpr + match elseExprOpt with | Some elseExpr -> match elseExpr with // prevent double collapsing on elifs - | SynExpr.IfThenElse _ -> - parseExpr elseExpr + | SynExpr.IfThenElse _ -> parseExpr elseExpr | _ -> // This is not the best way to establish the position of `else` // the AST doesn't provide an easy way to find the position of the keyword @@ -373,135 +441,180 @@ module Structure = // a suitable approach is determined parseExpr elseExpr | None -> () + | SynExpr.While (_, _, e, r) -> rcheck Scope.While Collapse.Below r r parseExpr e - | SynExpr.Lambda (args=pats; body=e; range=r) -> + + | SynExpr.Lambda (args = pats; body = e; range = r) -> match pats with | SynSimplePats.SimplePats (_, pr) - | SynSimplePats.Typed (_, _, pr) -> - rcheck Scope.Lambda Collapse.Below r (Range.endToEnd pr r) + | SynSimplePats.Typed (_, _, pr) -> rcheck Scope.Lambda Collapse.Below r (Range.endToEnd pr r) + parseExpr e + | SynExpr.Lazy (e, r) -> rcheck Scope.SpecialFunc Collapse.Below r r parseExpr e + | SynExpr.Quote (_, isRaw, e, _, r) -> // subtract columns so the @@> or @> is not collapsed - rcheck Scope.Quote Collapse.Same r (Range.modBoth (if isRaw then 3 else 2) (if isRaw then 3 else 2) r) + let collapse = Range.modBoth (if isRaw then 3 else 2) (if isRaw then 3 else 2) r + rcheck Scope.Quote Collapse.Same r collapse parseExpr e + | SynExpr.Tuple (_, es, _, r) -> rcheck Scope.Tuple Collapse.Same r r List.iter parseExpr es - | SynExpr.Paren (e, _, _, _) -> - parseExpr e + + | SynExpr.Paren (e, _, _, _) -> parseExpr e + | SynExpr.Record (recCtor, recCopy, recordFields, r) -> match recCtor with | Some (_, ctorArgs, _, _, _) -> parseExpr ctorArgs | _ -> () + match recCopy with | Some (e, _) -> parseExpr e | _ -> () - recordFields |> List.choose (fun (SynExprRecordField(expr=e)) -> e) |> List.iter parseExpr + + recordFields + |> List.choose (fun (SynExprRecordField (expr = e)) -> e) + |> List.iter parseExpr // exclude the opening `{` and closing `}` of the record from collapsing - rcheck Scope.Record Collapse.Same r <| Range.modBoth 1 1 r + let m = Range.modBoth 1 1 r + rcheck Scope.Record Collapse.Same r m | _ -> () - and parseMatchClause (SynMatchClause(pat=synPat; resultExpr=e) as clause) = - let rec getLastPat = function - | SynPat.Or(rhsPat=pat) -> getLastPat pat + and parseMatchClause (SynMatchClause (pat = synPat; resultExpr = e) as clause) = + let rec getLastPat = + function + | SynPat.Or (rhsPat = pat) -> getLastPat pat | x -> x let synPat = getLastPat synPat - let collapse = Range.endToEnd synPat.Range clause.Range // Collapse the scope starting with `->` + // Collapse the scope starting with `->` + let collapse = Range.endToEnd synPat.Range clause.Range rcheck Scope.MatchClause Collapse.Same e.Range collapse parseExpr e and parseAttributes (Attributes attrs) = - let attrListRange() = + let attrListRange () = if not (List.isEmpty attrs) then - let range = Range.startToEnd attrs[0].Range attrs[attrs.Length-1].ArgExpr.Range + let range = Range.startToEnd attrs[0].Range attrs[attrs.Length - 1].ArgExpr.Range rcheck Scope.Attribute Collapse.Same range range - match attrs with + match attrs with | [] -> () - | [_] -> attrListRange() + | [ _ ] -> attrListRange () | head :: tail -> - attrListRange() + attrListRange () parseExpr head.ArgExpr - // If there are more than 2 attributes only add tags to the 2nd and beyond, to avoid double collapsing on the first attribute + // If there are more than 2 attributes only add tags to the 2nd and beyond, to avoid + // double collapsing on the first attribute for attr in tail do let range = Range.startToEnd attr.Range attr.ArgExpr.Range rcheck Scope.Attribute Collapse.Same range range - + // visit the expressions inside each attribute for attr in attrs do parseExpr attr.ArgExpr - and parseBinding (SynBinding(kind=kind; attributes=attrs; valData=SynValData(memberFlags=memberFlags); expr=expr; range=br) as binding) = + and parseBinding binding = + let (SynBinding (kind = kind; attributes = attrs; valData = valData; expr = expr; range = br)) = binding + let (SynValData (memberFlags = memberFlags)) = valData + match kind with | SynBindingKind.Normal -> let collapse = Range.endToEnd binding.RangeOfBindingWithoutRhs binding.RangeOfBindingWithRhs + match memberFlags with - | Some {MemberKind=SynMemberKind.Constructor} -> - rcheck Scope.New Collapse.Below binding.RangeOfBindingWithRhs collapse - | Some _ -> - rcheck Scope.Member Collapse.Below binding.RangeOfBindingWithRhs collapse - | None -> - rcheck Scope.LetOrUse Collapse.Below binding.RangeOfBindingWithRhs collapse + | Some { + MemberKind = SynMemberKind.Constructor + } -> rcheck Scope.New Collapse.Below binding.RangeOfBindingWithRhs collapse + | Some _ -> rcheck Scope.Member Collapse.Below binding.RangeOfBindingWithRhs collapse + | None -> rcheck Scope.LetOrUse Collapse.Below binding.RangeOfBindingWithRhs collapse | SynBindingKind.Do -> let r = Range.modStart 2 br rcheck Scope.Do Collapse.Below br r | _ -> () + parseAttributes attrs parseExpr expr - and parseBindings sqs = for bind in sqs do parseBinding bind + and parseBindings sqs = + for bind in sqs do + parseBinding bind - and parseExprInterface (SynInterfaceImpl(interfaceTy=synType; bindings=bindings; range=range)) = + and parseExprInterface intf = + let (SynInterfaceImpl (interfaceTy = synType; bindings = bindings; range = range)) = intf let collapse = Range.endToEnd synType.Range range |> Range.modEnd -1 rcheck Scope.Interface Collapse.Below range collapse parseBindings bindings - and parseExprInterfaces (intfs: SynInterfaceImpl list) = List.iter parseExprInterface intfs + and parseExprInterfaces intfs = + for intf in intfs do + parseExprInterface intf and parseSynMemberDefn (objectModelRange: range) d = match d with - | SynMemberDefn.Member(SynBinding.SynBinding (attributes=attrs; valData=valData; headPat=synPat; range=bindingRange) as binding, _) -> - match valData with - | SynValData (Some { MemberKind=SynMemberKind.Constructor }, _, _) -> - let collapse = Range.endToEnd synPat.Range d.Range - rcheck Scope.New Collapse.Below d.Range collapse - | SynValData (Some { MemberKind=SynMemberKind.PropertyGet | SynMemberKind.PropertySet }, _, _) -> - let range = - mkRange - d.Range.FileName - (mkPos d.Range.StartLine objectModelRange.StartColumn) - d.Range.End - - let collapse = - match synPat with - | SynPat.LongIdent(longDotId=longIdent) -> - Range.endToEnd longIdent.Range d.Range - | _ -> Range.endToEnd bindingRange d.Range - - rcheck Scope.Member Collapse.Below range collapse - | _ -> - let collapse = Range.endToEnd bindingRange d.Range - rcheck Scope.Member Collapse.Below d.Range collapse - parseAttributes attrs - parseBinding binding - | SynMemberDefn.LetBindings (bindings, _, _, _) -> - parseBindings bindings - | SynMemberDefn.Interface (interfaceType=tp; members=iMembers; range=r) -> + | SynMemberDefn.Member (binding, _) -> + let (SynBinding (attributes = attrs; valData = valData; headPat = synPat; range = bindingRange)) = + binding + + match valData with + | SynValData (Some { + MemberKind = SynMemberKind.Constructor + }, + _, + _) -> + let collapse = Range.endToEnd synPat.Range d.Range + rcheck Scope.New Collapse.Below d.Range collapse + + | SynValData (Some { + MemberKind = SynMemberKind.PropertyGet | SynMemberKind.PropertySet + }, + _, + _) -> + let range = mkRange d.Range.FileName (mkPos d.Range.StartLine objectModelRange.StartColumn) d.Range.End + + let collapse = + match synPat with + | SynPat.LongIdent (longDotId = longIdent) -> Range.endToEnd longIdent.Range d.Range + | _ -> Range.endToEnd bindingRange d.Range + + rcheck Scope.Member Collapse.Below range collapse + | _ -> + let collapse = Range.endToEnd bindingRange d.Range + rcheck Scope.Member Collapse.Below d.Range collapse + + parseAttributes attrs + parseBinding binding + + | SynMemberDefn.GetSetMember (getBinding, setBinding, m, _) -> + getBinding + |> Option.map (fun b -> SynMemberDefn.Member(b, m)) + |> Option.iter (parseSynMemberDefn objectModelRange) + + setBinding + |> Option.map (fun b -> SynMemberDefn.Member(b, m)) + |> Option.iter (parseSynMemberDefn objectModelRange) + + | SynMemberDefn.LetBindings (bindings, _, _, _) -> parseBindings bindings + + | SynMemberDefn.Interface (interfaceType = tp; members = iMembers; range = r) -> rcheck Scope.Interface Collapse.Below d.Range (Range.endToEnd tp.Range d.Range) + match iMembers with | Some members -> List.iter (parseSynMemberDefn r) members | None -> () - | SynMemberDefn.NestedType (td, _, _) -> - parseTypeDefn td - | SynMemberDefn.AbstractSlot (SynValSig(synType=synt), _, r) -> + + | SynMemberDefn.NestedType (td, _, _) -> parseTypeDefn td + + | SynMemberDefn.AbstractSlot (SynValSig (synType = synt), _, r) -> rcheck Scope.Member Collapse.Below d.Range (Range.startToEnd synt.Range r) - | SynMemberDefn.AutoProperty (synExpr=e; range=r) -> + + | SynMemberDefn.AutoProperty (synExpr = e; range = r) -> rcheck Scope.Member Collapse.Below d.Range r parseExpr e | _ -> () @@ -519,81 +632,114 @@ module Structure = and parseSimpleRepr simple = match simple with | SynTypeDefnSimpleRepr.Enum (cases, _er) -> - for SynEnumCase (attributes=attrs; range=cr) in cases do + for SynEnumCase (attributes = attrs; range = cr) in cases do rcheck Scope.EnumCase Collapse.Below cr cr parseAttributes attrs + | SynTypeDefnSimpleRepr.Record (_, fields, rr) -> - rcheck Scope.RecordDefn Collapse.Same rr rr + rcheck Scope.RecordDefn Collapse.Same rr rr + for SynField (attrs, _, _, _, _, _, _, fr) in fields do rcheck Scope.RecordField Collapse.Below fr fr parseAttributes attrs + | SynTypeDefnSimpleRepr.Union (_, cases, ur) -> rcheck Scope.UnionDefn Collapse.Same ur ur - for SynUnionCase (attributes=attrs; range=cr) in cases do + + for SynUnionCase (attributes = attrs; range = cr) in cases do rcheck Scope.UnionCase Collapse.Below cr cr parseAttributes attrs + | _ -> () - and parseTypeDefn (SynTypeDefn(typeInfo=SynComponentInfo(typeParams=TyparDecls typeArgs; range=r); typeRepr=objectModel; members=members; range=fullrange)) = - let typeArgsRange = rangeOfTypeArgsElse r typeArgs - let collapse = Range.endToEnd (Range.modEnd 1 typeArgsRange) fullrange - match objectModel with - | SynTypeDefnRepr.ObjectModel (defnKind, objMembers, r) -> - match defnKind with - | SynTypeDefnKind.Augmentation _ -> - rcheck Scope.TypeExtension Collapse.Below fullrange collapse - | _ -> - rcheck Scope.Type Collapse.Below fullrange collapse - List.iter (parseSynMemberDefn r) objMembers - // visit the members of a type extension - List.iter (parseSynMemberDefn r) members - | SynTypeDefnRepr.Simple (simpleRepr, r) -> - rcheck Scope.Type Collapse.Below fullrange collapse - parseSimpleRepr simpleRepr - List.iter (parseSynMemberDefn r) members - | SynTypeDefnRepr.Exception _ -> () - - let getConsecutiveModuleDecls (predicate: SynModuleDecl -> range option) (scope: Scope) (decls: SynModuleDecl list) = + and parseTypeDefn typeDefn = + let (SynTypeDefn (typeInfo = typeInfo; typeRepr = objectModel; members = members; range = mFull)) = + typeDefn + + let (SynComponentInfo (typeParams = TyparDecls typeArgs; range = r)) = typeInfo + let typeArgsRange = rangeOfTypeArgsElse r typeArgs + let collapse = Range.endToEnd (Range.modEnd 1 typeArgsRange) mFull + + match objectModel with + | SynTypeDefnRepr.ObjectModel (defnKind, objMembers, r) -> + match defnKind with + | SynTypeDefnKind.Augmentation _ -> rcheck Scope.TypeExtension Collapse.Below mFull collapse + | _ -> rcheck Scope.Type Collapse.Below mFull collapse + + List.iter (parseSynMemberDefn r) objMembers + // visit the members of a type extension + List.iter (parseSynMemberDefn r) members + | SynTypeDefnRepr.Simple (simpleRepr, r) -> + rcheck Scope.Type Collapse.Below mFull collapse + parseSimpleRepr simpleRepr + List.iter (parseSynMemberDefn r) members + | SynTypeDefnRepr.Exception _ -> () + + let getConsecutiveModuleDecls (scope: Scope) (predicate: SynModuleDecl -> range option) decls = let groupConsecutiveDecls input = let rec loop (input: range list) (res: range list list) currentBulk = match input, currentBulk with | [], [] -> List.rev res | [], _ -> List.rev (currentBulk :: res) - | r :: rest, [] -> loop rest res [r] - | r :: rest, last :: _ - when r.StartLine = last.EndLine + 1 || - sourceLines[last.EndLine..r.StartLine - 2] |> Array.forall System.String.IsNullOrWhiteSpace -> + | r :: rest, [] -> loop rest res [ r ] + | r :: rest, last :: _ when + r.StartLine = last.EndLine + 1 + || sourceLines[last.EndLine .. r.StartLine - 2] + |> Array.forall System.String.IsNullOrWhiteSpace + -> loop rest res (r :: currentBulk) - | r :: rest, _ -> loop rest (currentBulk :: res) [r] + | r :: rest, _ -> loop rest (currentBulk :: res) [ r ] + loop input [] [] let selectRanges (ranges: range list) = match ranges with | [] -> None - | [r] when r.StartLine = r.EndLine -> None - | [r] -> + | [ r ] when r.StartLine = r.EndLine -> None + | [ r ] -> let range = mkRange "" r.Start r.End - Some { Scope = scope; Collapse = Collapse.Same; Range = range ; CollapseRange = range } + + let res = + { + Scope = scope + Collapse = Collapse.Same + Range = range + CollapseRange = range + } + + Some res | lastRange :: rest -> let firstRange = Seq.last rest let range = mkRange "" firstRange.Start lastRange.End - Some { Scope = scope; Collapse = Collapse.Same; Range = range; CollapseRange = range } - decls - |> List.choose predicate - |> groupConsecutiveDecls + let res = + { + Scope = scope + Collapse = Collapse.Same + Range = range + CollapseRange = range + } + + Some res + + decls + |> List.choose predicate + |> groupConsecutiveDecls |> List.choose selectRanges |> acc.AddRange - let collectOpens = getConsecutiveModuleDecls (function SynModuleDecl.Open (_, r) -> Some r | _ -> None) Scope.Open + let collectOpens = + getConsecutiveModuleDecls Scope.Open (function + | SynModuleDecl.Open (_, r) -> Some r + | _ -> None) let collectHashDirectives = - getConsecutiveModuleDecls( - function + getConsecutiveModuleDecls Scope.HashDirective (fun decl -> + match decl with | SynModuleDecl.HashDirective (ParsedHashDirective (directive, _, _), r) -> let prefixLength = "#".Length + directive.Length + " ".Length - Some (mkRange "" (mkPos r.StartLine prefixLength) r.End) - | _ -> None) Scope.HashDirective + Some(mkRange "" (mkPos r.StartLine prefixLength) r.End) + | _ -> None) let rec parseDeclaration (decl: SynModuleDecl) = match decl with @@ -601,6 +747,7 @@ module Structure = for binding in bindings do let collapse = Range.endToEnd binding.RangeOfBindingWithoutRhs r rcheck Scope.LetOrUse Collapse.Below r collapse + parseBindings bindings | SynModuleDecl.Types (types, _r) -> @@ -608,7 +755,8 @@ module Structure = parseTypeDefn t // Fold the attributes above a module - | SynModuleDecl.NestedModule (moduleInfo=SynComponentInfo (attributes=attrs; range=cmpRange); decls=decls) -> + | SynModuleDecl.NestedModule (moduleInfo = moduleInfo; decls = decls) -> + let (SynComponentInfo (attributes = attrs; range = cmpRange)) = moduleInfo // Outline the full scope of the module let r = Range.endToEnd cmpRange decl.Range rcheck Scope.Module Collapse.Below decl.Range r @@ -617,23 +765,21 @@ module Structure = collectOpens decls List.iter parseDeclaration decls - | SynModuleDecl.Expr (e, _) -> - parseExpr e + | SynModuleDecl.Expr (e, _) -> parseExpr e - | SynModuleDecl.Attributes (attrs, _) -> - parseAttributes attrs + | SynModuleDecl.Attributes (attrs, _) -> parseAttributes attrs | _ -> () let parseModuleOrNamespace (SynModuleOrNamespace (longId, _, kind, decls, _, attribs, _, r, _)) = parseAttributes attribs let idRange = longIdentRange longId - let fullrange = Range.startToEnd idRange r - let collapse = Range.endToEnd idRange r - + let mFull = Range.startToEnd idRange r + let collapse = Range.endToEnd idRange r + // do not return range for top level implicit module in scripts if kind = SynModuleOrNamespaceKind.NamedModule then - rcheck Scope.Module Collapse.Below fullrange collapse + rcheck Scope.Module Collapse.Below mFull collapse collectHashDirectives decls collectOpens decls @@ -646,31 +792,34 @@ module Structure = else None let getCommentRanges (lines: string[]) = - let rec loop (lastLineNum, currentComment: CommentList option, result as state) (lines: string list) lineNum = + let rec loop (lastLineNum, currentComment, result as state) (lines: string list) lineNum = match lines with | [] -> state | lineStr :: rest -> match lineStr.TrimStart(), currentComment with | Comment commentType, Some comment -> - loop( - if comment.Type = commentType && lineNum = lastLineNum + 1 then - comment.Lines.Add (lineNum, lineStr) - lineNum, currentComment, result - else lineNum, Some (CommentList.New commentType (lineNum, lineStr)), comment :: result) rest (lineNum + 1) + loop + (if comment.Type = commentType && lineNum = lastLineNum + 1 then + comment.Lines.Add(lineNum, lineStr) + lineNum, currentComment, result + else + let comments = CommentList.New commentType (lineNum, lineStr) + lineNum, Some comments, comment :: result) + rest + (lineNum + 1) | Comment commentType, None -> - loop(lineNum, Some (CommentList.New commentType (lineNum, lineStr)), result) rest (lineNum + 1) - | _, Some comment -> - loop(lineNum, None, comment :: result) rest (lineNum + 1) - | _ -> loop(lineNum, None, result) rest (lineNum + 1) - - let comments: CommentList list = - loop (-1, None, []) (List.ofArray lines) 0 - |> fun (_, lastComment, comments) -> - match lastComment with - | Some comment -> - comment :: comments - | _ -> comments - |> List.rev + let comments = CommentList.New commentType (lineNum, lineStr) + loop (lineNum, Some comments, result) rest (lineNum + 1) + | _, Some comment -> loop (lineNum, None, comment :: result) rest (lineNum + 1) + | _ -> loop (lineNum, None, result) rest (lineNum + 1) + + let comments = + let (_, lastComment, comments) = loop (-1, None, []) (List.ofArray lines) 0 + + match lastComment with + | Some comment -> comment :: comments + | _ -> comments + |> List.rev comments |> List.filter (fun comment -> comment.Lines.Count > 1) @@ -688,19 +837,20 @@ module Structure = let range = mkRange "" (mkPos (startLine + 1) startCol) (mkPos (endLine + 1) endCol) - { Scope = scopeType - Collapse = Collapse.Same - Range = range - CollapseRange = range }) + { + Scope = scopeType + Collapse = Collapse.Same + Range = range + CollapseRange = range + }) |> acc.AddRange - - //=======================================// - // Signature File AST Traversal // + //=======================================// + // Signature File AST Traversal // //=======================================// (* - The following helper functions are necessary due to a bug in the Parsed UAST within a + The following helper functions are necessary due to a bug in the Parsed UAST within a signature file that causes the scopes to extend past the end of the construct and overlap with the following construct. This necessitates inspecting the children of the construct and finding the end of the last child's range to use instead. @@ -713,150 +863,182 @@ module Structure = | [] -> r | ls -> match List.last ls with - | SynMemberSig.Inherit (range=r) - | SynMemberSig.Interface (range=r) - | SynMemberSig.Member (range=r) - | SynMemberSig.NestedType (range=r) - | SynMemberSig.ValField (range=r) -> r + | SynMemberSig.Inherit (range = r) + | SynMemberSig.Interface (range = r) + | SynMemberSig.Member (range = r) + | SynMemberSig.NestedType (range = r) + | SynMemberSig.ValField (range = r) -> r - let lastTypeDefnSigRangeElse range (typeSigs:SynTypeDefnSig list) = + let lastTypeDefnSigRangeElse range (typeSigs: SynTypeDefnSig list) = match typeSigs with | [] -> range | ls -> - let (SynTypeDefnSig(members=memberSigs; range=r)) = List.last ls + let (SynTypeDefnSig (members = memberSigs; range = r)) = List.last ls lastMemberSigRangeElse r memberSigs - let lastModuleSigDeclRangeElse range (sigDecls:SynModuleSigDecl list) = + let lastModuleSigDeclRangeElse range (sigDecls: SynModuleSigDecl list) = match sigDecls with | [] -> range - | ls -> + | ls -> match List.last ls with | SynModuleSigDecl.Types (typeSigs, r) -> lastTypeDefnSigRangeElse r typeSigs - | SynModuleSigDecl.Val (SynValSig(range=r), _) -> r - | SynModuleSigDecl.Exception(_, r) -> r - | SynModuleSigDecl.Open(_, r) -> r - | SynModuleSigDecl.ModuleAbbrev(_, _, r) -> r + | SynModuleSigDecl.Val (SynValSig (range = r), _) -> r + | SynModuleSigDecl.Exception (_, r) -> r + | SynModuleSigDecl.Open (_, r) -> r + | SynModuleSigDecl.ModuleAbbrev (_, _, r) -> r | _ -> range - let rec parseSynMemberDefnSig = function - | SynMemberSig.Member(valSigs, _, r) -> + let rec parseSynMemberDefnSig inp = + match inp with + | SynMemberSig.Member (valSigs, _, r) -> let collapse = Range.endToEnd valSigs.RangeOfId r rcheck Scope.Member Collapse.Below r collapse - | SynMemberSig.ValField(SynField(attrs, _, _, _, _, _, _, fr), fullrange) -> - let collapse = Range.endToEnd fr fullrange - rcheck Scope.Val Collapse.Below fullrange collapse + | SynMemberSig.ValField (SynField (attrs, _, _, _, _, _, _, fr), mFull) -> + let collapse = Range.endToEnd fr mFull + rcheck Scope.Val Collapse.Below mFull collapse parseAttributes attrs - | SynMemberSig.Interface(tp, r) -> - rcheck Scope.Interface Collapse.Below r (Range.endToEnd tp.Range r) - | SynMemberSig.NestedType (typeDefSig, _r) -> - parseTypeDefnSig typeDefSig + | SynMemberSig.Interface (tp, r) -> rcheck Scope.Interface Collapse.Below r (Range.endToEnd tp.Range r) + | SynMemberSig.NestedType (typeDefSig, _r) -> parseTypeDefnSig typeDefSig | _ -> () - and parseTypeDefnSig (SynTypeDefnSig (typeInfo=SynComponentInfo(attributes=attribs; typeParams=TyparDecls typeArgs; longId=longId; range=r); typeRepr=objectModel; members=memberSigs)) = + and parseTypeDefnSig typeDefn = + let (SynTypeDefnSig (typeInfo = typeInfo; typeRepr = objectModel; members = memberSigs)) = typeDefn + + let (SynComponentInfo (attributes = attribs; typeParams = TyparDecls typeArgs; longId = longId; range = r)) = + typeInfo + parseAttributes attribs let makeRanges memberSigs = let typeArgsRange = rangeOfTypeArgsElse r typeArgs let rangeEnd = lastMemberSigRangeElse r memberSigs let collapse = Range.endToEnd (Range.modEnd 1 typeArgsRange) rangeEnd - let fullrange = Range.startToEnd (longIdentRange longId) rangeEnd - fullrange, collapse + let mFull = Range.startToEnd (longIdentRange longId) rangeEnd + mFull, collapse List.iter parseSynMemberDefnSig memberSigs match objectModel with // matches against a type declaration with <'T, ...> and (args, ...) - | SynTypeDefnSigRepr.ObjectModel - (SynTypeDefnKind.Unspecified, objMembers, _) -> - List.iter parseSynMemberDefnSig objMembers - let fullrange, collapse = makeRanges objMembers - rcheck Scope.Type Collapse.Below fullrange collapse - | SynTypeDefnSigRepr.ObjectModel (kind=SynTypeDefnKind.Augmentation _; memberSigs=objMembers) -> - let fullrange, collapse = makeRanges objMembers - rcheck Scope.TypeExtension Collapse.Below fullrange collapse - List.iter parseSynMemberDefnSig objMembers + | SynTypeDefnSigRepr.ObjectModel (SynTypeDefnKind.Unspecified, objMembers, _) -> + List.iter parseSynMemberDefnSig objMembers + let mFull, collapse = makeRanges objMembers + rcheck Scope.Type Collapse.Below mFull collapse + + | SynTypeDefnSigRepr.ObjectModel (kind = SynTypeDefnKind.Augmentation _; memberSigs = objMembers) -> + let mFull, collapse = makeRanges objMembers + rcheck Scope.TypeExtension Collapse.Below mFull collapse + List.iter parseSynMemberDefnSig objMembers + | SynTypeDefnSigRepr.ObjectModel (_, objMembers, _) -> - let fullrange, collapse = makeRanges objMembers - rcheck Scope.Type Collapse.Below fullrange collapse - List.iter parseSynMemberDefnSig objMembers - // visit the members of a type extension + let mFull, collapse = makeRanges objMembers + rcheck Scope.Type Collapse.Below mFull collapse + List.iter parseSynMemberDefnSig objMembers + // visit the members of a type extension + | SynTypeDefnSigRepr.Simple (simpleRepr, _) -> - let fullrange, collapse = makeRanges memberSigs - rcheck Scope.Type Collapse.Below fullrange collapse + let mFull, collapse = makeRanges memberSigs + rcheck Scope.Type Collapse.Below mFull collapse parseSimpleRepr simpleRepr + | SynTypeDefnSigRepr.Exception _ -> () - let getConsecutiveSigModuleDecls (predicate: SynModuleSigDecl -> range option) (scope:Scope) (decls: SynModuleSigDecl list) = + let getConsecutiveSigModuleDecls (scope: Scope) (predicate: SynModuleSigDecl -> range option) decls = let groupConsecutiveSigDecls input = let rec loop (input: range list) (res: range list list) currentBulk = match input, currentBulk with | [], [] -> List.rev res | [], _ -> List.rev (currentBulk :: res) - | r :: rest, [] -> loop rest res [r] - | r :: rest, last :: _ when r.StartLine = last.EndLine + 1 -> - loop rest res (r :: currentBulk) - | r :: rest, _ -> loop rest (currentBulk :: res) [r] + | r :: rest, [] -> loop rest res [ r ] + | r :: rest, last :: _ when r.StartLine = last.EndLine + 1 -> loop rest res (r :: currentBulk) + | r :: rest, _ -> loop rest (currentBulk :: res) [ r ] + loop input [] [] let selectSigRanges (ranges: range list) = match ranges with | [] -> None - | [r] when r.StartLine = r.EndLine -> None - | [r] -> + | [ r ] when r.StartLine = r.EndLine -> None + | [ r ] -> let range = mkRange "" r.Start r.End - Some { Scope = scope; Collapse = Collapse.Same; Range = range ; CollapseRange = range } + + let res = + { + Scope = scope + Collapse = Collapse.Same + Range = range + CollapseRange = range + } + + Some res | lastRange :: rest -> let firstRange = Seq.last rest let range = mkRange "" firstRange.Start lastRange.End - Some { Scope = scope; Collapse = Collapse.Same; Range = range; CollapseRange = range } - decls - |> List.choose predicate - |> groupConsecutiveSigDecls + let res = + { + Scope = scope + Collapse = Collapse.Same + Range = range + CollapseRange = range + } + + Some res + + decls + |> List.choose predicate + |> groupConsecutiveSigDecls |> List.choose selectSigRanges |> acc.AddRange let collectSigHashDirectives (decls: SynModuleSigDecl list) = decls - |> getConsecutiveSigModuleDecls( - function + |> getConsecutiveSigModuleDecls Scope.HashDirective (fun decl -> + match decl with | SynModuleSigDecl.HashDirective (ParsedHashDirective (directive, _, _), r) -> let prefixLength = "#".Length + directive.Length + " ".Length - Some (mkRange "" (mkPos r.StartLine prefixLength) r.End) - | _ -> None) Scope.HashDirective + Some(mkRange "" (mkPos r.StartLine prefixLength) r.End) + | _ -> None) - let collectSigOpens = getConsecutiveSigModuleDecls (function SynModuleSigDecl.Open (_, r) -> Some r | _ -> None) Scope.Open + let collectSigOpens = + getConsecutiveSigModuleDecls Scope.Open (function + | SynModuleSigDecl.Open (_, r) -> Some r + | _ -> None) let rec parseModuleSigDeclaration (decl: SynModuleSigDecl) = match decl with - | SynModuleSigDecl.Val (SynValSig(attributes=attrs; ident=SynIdent(ident,_); range=valrange), r) -> + | SynModuleSigDecl.Val (valSig, r) -> + let (SynValSig (attributes = attrs; ident = SynIdent (ident, _); range = valrange)) = valSig let collapse = Range.endToEnd ident.idRange valrange rcheck Scope.Val Collapse.Below r collapse parseAttributes attrs - | SynModuleSigDecl.Types (typeSigs, _) -> - List.iter parseTypeDefnSig typeSigs + + | SynModuleSigDecl.Types (typeSigs, _) -> List.iter parseTypeDefnSig typeSigs + // Fold the attributes above a module - | SynModuleSigDecl.NestedModule (moduleInfo=SynComponentInfo (attributes=attrs; range=cmpRange); moduleDecls=decls; range=moduleRange) -> + | SynModuleSigDecl.NestedModule (moduleInfo = moduleInfo; moduleDecls = decls; range = moduleRange) -> + let (SynComponentInfo (attributes = attrs; range = cmpRange)) = moduleInfo let rangeEnd = lastModuleSigDeclRangeElse moduleRange decls // Outline the full scope of the module let collapse = Range.endToEnd cmpRange rangeEnd - let fullrange = Range.startToEnd moduleRange rangeEnd - rcheck Scope.Module Collapse.Below fullrange collapse + let mFull = Range.startToEnd moduleRange rangeEnd + rcheck Scope.Module Collapse.Below mFull collapse // A module's component info stores the ranges of its attributes parseAttributes attrs collectSigOpens decls List.iter parseModuleSigDeclaration decls | _ -> () - let parseModuleOrNamespaceSigs (SynModuleOrNamespaceSig(longId, _, kind, decls, _, attribs, _, r, _)) = + let parseModuleOrNamespaceSigs moduleSig = + let (SynModuleOrNamespaceSig (longId, _, kind, decls, _, attribs, _, r, _)) = moduleSig parseAttributes attribs let rangeEnd = lastModuleSigDeclRangeElse r decls let idrange = longIdentRange longId - let fullrange = Range.startToEnd idrange rangeEnd + let mFull = Range.startToEnd idrange rangeEnd let collapse = Range.endToEnd idrange rangeEnd - + if kind.IsModule then - rcheck Scope.Module Collapse.Below fullrange collapse + rcheck Scope.Module Collapse.Below mFull collapse collectSigHashDirectives decls collectSigOpens decls @@ -869,5 +1051,5 @@ module Structure = | ParsedInput.SigFile (ParsedSigFileInput (modules = moduleSigs)) -> List.iter parseModuleOrNamespaceSigs moduleSigs getCommentRanges sourceLines - + acc :> seq<_> diff --git a/src/Compiler/Service/ServiceUntypedParse.fs b/src/Compiler/Service/ServiceUntypedParse.fs deleted file mode 100755 index 74dc6eb245f..00000000000 --- a/src/Compiler/Service/ServiceUntypedParse.fs +++ /dev/null @@ -1,1471 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -//---------------------------------------------------------------------------- -// Open up the compiler as an incremental service for parsing, -// type checking and intellisense-like environment-reporting. -//-------------------------------------------------------------------------- - -namespace FSharp.Compiler.SourceCodeServices - -open System -open System.IO -open System.Collections.Generic -open System.Diagnostics -open System.Text.RegularExpressions - -open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.CompilerConfig -open FSharp.Compiler.Lib -open FSharp.Compiler.PrettyNaming -open FSharp.Compiler.Range -open FSharp.Compiler.SyntaxTree -open FSharp.Compiler.SyntaxTreeOps - -/// Methods for dealing with F# sources files. -module SourceFile = - - /// Source file extensions - let private compilableExtensions = FSharpSigFileSuffixes @ FSharpImplFileSuffixes @ FSharpScriptFileSuffixes - - /// Single file projects extensions - let private singleFileProjectExtensions = FSharpScriptFileSuffixes - - /// Whether or not this file is compilable - let IsCompilable file = - let ext = Path.GetExtension file - compilableExtensions |> List.exists(fun e->0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) - - /// Whether or not this file should be a single-file project - let MustBeSingleFileProject file = - let ext = Path.GetExtension file - singleFileProjectExtensions |> List.exists(fun e-> 0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) - -module SourceFileImpl = - let IsInterfaceFile file = - let ext = Path.GetExtension file - 0 = String.Compare(".fsi", ext, StringComparison.OrdinalIgnoreCase) - - /// Additional #defines that should be in place when editing a file in a file editor such as VS. - let AdditionalDefinesForUseInEditor(isInteractive: bool) = - if isInteractive then ["INTERACTIVE";"EDITING"] // This is still used by the foreground parse - else ["COMPILED";"EDITING"] - -type CompletionPath = string list * string option // plid * residue - -[] -type InheritanceOrigin = - | Class - | Interface - | Unknown - -[] -type InheritanceContext = - | Class - | Interface - | Unknown - -[] -type RecordContext = - | CopyOnUpdate of range * CompletionPath // range of copy-expr + current field - | Constructor of string // typename - | New of CompletionPath - -[] -type CompletionContext = - // completion context cannot be determined due to errors - | Invalid - // completing something after the inherit keyword - | Inherit of InheritanceContext * CompletionPath - // completing records field - | RecordField of RecordContext - | RangeOperator - // completing named parameters\setters in parameter list of constructor\method calls - // end of name ast node * list of properties\parameters that were already set - | ParameterList of pos * HashSet - | AttributeApplication - | OpenDeclaration of isOpenType: bool - /// completing pattern type (e.g. foo (x: |)) - | PatternType - -//---------------------------------------------------------------------------- -// FSharpParseFileResults -//---------------------------------------------------------------------------- - -[] -type FSharpParseFileResults(errors: FSharpErrorInfo[], input: ParsedInput option, parseHadErrors: bool, dependencyFiles: string[]) = - - member scope.Errors = errors - - member scope.ParseHadErrors = parseHadErrors - - member scope.ParseTree = input - - member scope.FindNoteworthyParamInfoLocations pos = - match input with - | Some input -> FSharpNoteworthyParamInfoLocations.Find(pos, input) - | _ -> None - - member scope.GetAllArgumentsForFunctionApplicationAtPostion pos = - match input with - | Some input -> SynExprAppLocationsImpl.getAllCurriedArgsAtPosition pos input - | None -> None - - member scope.IsTypeAnnotationGivenAtPosition pos = - match input with - | Some parseTree -> - let res = - AstTraversal.Traverse(pos, parseTree, { new AstTraversal.AstVisitorBase<_>() with - member _.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = - match expr with - | SynExpr.Typed (_expr, _typeExpr, range) when posEq range.Start pos -> - Some range - | _ -> defaultTraverse expr - - override _.VisitSimplePats(pats) = - match pats with - | [] -> None - | _ -> - let exprFunc pat = - match pat with - | SynSimplePat.Typed (_pat, _targetExpr, range) when posEq range.Start pos -> - Some range - | _ -> - None - - pats |> List.tryPick exprFunc - - override _.VisitPat(defaultTraverse, pat) = - match pat with - | SynPat.Typed (_pat, _targetType, range) when posEq range.Start pos -> - Some range - | _ -> defaultTraverse pat }) - res.IsSome - | None -> false - - member scope.IsBindingALambdaAtPosition pos = - match input with - | Some parseTree -> - let res = - AstTraversal.Traverse(pos, parseTree, { new AstTraversal.AstVisitorBase<_>() with - member _.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = - defaultTraverse expr - - override _.VisitBinding(defaultTraverse, binding) = - match binding with - | SynBinding.Binding(_, _, _, _, _, _, _, _, _, expr, range, _) when posEq range.Start pos -> - match expr with - | SynExpr.Lambda _ -> Some range - | _ -> None - | _ -> defaultTraverse binding }) - res.IsSome - | None -> false - - /// Get declared items and the selected item at the specified location - member private scope.GetNavigationItemsImpl() = - ErrorScope.Protect range0 - (fun () -> - match input with - | Some (ParsedInput.ImplFile _ as p) -> - FSharpNavigation.getNavigation p - | Some (ParsedInput.SigFile _) -> - FSharpNavigation.empty - | _ -> - FSharpNavigation.empty) - (fun err -> - Trace.TraceInformation(sprintf "FCS: recovering from error in GetNavigationItemsImpl: '%s'" err) - FSharpNavigation.empty) - - member private scope.ValidateBreakpointLocationImpl pos = - let isMatchRange m = rangeContainsPos m pos || m.StartLine = pos.Line - - // Process let-binding - let findBreakPoints () = - let checkRange m = [ if isMatchRange m then yield m ] - let walkBindSeqPt sp = [ match sp with DebugPointAtBinding m -> yield! checkRange m | _ -> () ] - let walkForSeqPt sp = [ match sp with DebugPointAtFor.Yes m -> yield! checkRange m | _ -> () ] - let walkWhileSeqPt sp = [ match sp with DebugPointAtWhile.Yes m -> yield! checkRange m | _ -> () ] - let walkTrySeqPt sp = [ match sp with DebugPointAtTry.Yes m -> yield! checkRange m | _ -> () ] - let walkWithSeqPt sp = [ match sp with DebugPointAtWith.Yes m -> yield! checkRange m | _ -> () ] - let walkFinallySeqPt sp = [ match sp with DebugPointAtFinally.Yes m -> yield! checkRange m | _ -> () ] - - let rec walkBind (Binding(_, _, _, _, _, _, SynValData(memFlagsOpt, _, _), synPat, _, synExpr, _, spInfo)) = - [ // Don't yield the binding sequence point if there are any arguments, i.e. we're defining a function or a method - let isFunction = - Option.isSome memFlagsOpt || - match synPat with - | SynPat.LongIdent (_, _, _, SynArgPats.Pats args, _, _) when not (List.isEmpty args) -> true - | _ -> false - if not isFunction then - yield! walkBindSeqPt spInfo - - yield! walkExpr (isFunction || (match spInfo with DebugPointAtBinding _ -> false | _-> true)) synExpr ] - - and walkExprs es = List.collect (walkExpr false) es - and walkBinds es = List.collect walkBind es - and walkMatchClauses cl = - [ for (Clause(_, whenExpr, e, _, _)) in cl do - match whenExpr with - | Some e -> yield! walkExpr false e - | _ -> () - yield! walkExpr true e ] - - and walkExprOpt (spAlways: bool) eOpt = [ match eOpt with Some e -> yield! walkExpr spAlways e | _ -> () ] - - and IsBreakableExpression e = - match e with - | SynExpr.Match _ - | SynExpr.IfThenElse _ - | SynExpr.For _ - | SynExpr.ForEach _ - | SynExpr.While _ -> true - | _ -> not (IsControlFlowExpression e) - - // Determine the breakpoint locations for an expression. spAlways indicates we always - // emit a breakpoint location for the expression unless it is a syntactic control flow construct - and walkExpr (spAlways: bool) e = - let m = e.Range - if not (isMatchRange m) then [] else - [ if spAlways && IsBreakableExpression e then - yield! checkRange m - - match e with - | SynExpr.ArbitraryAfterError _ - | SynExpr.LongIdent _ - | SynExpr.LibraryOnlyILAssembly _ - | SynExpr.LibraryOnlyStaticOptimization _ - | SynExpr.Null _ - | SynExpr.Ident _ - | SynExpr.ImplicitZero _ - | SynExpr.Const _ -> - () - - | SynExpr.Quote (_, _, e, _, _) - | SynExpr.TypeTest (e, _, _) - | SynExpr.Upcast (e, _, _) - | SynExpr.AddressOf (_, e, _, _) - | SynExpr.CompExpr (_, _, e, _) - | SynExpr.ArrayOrListOfSeqExpr (_, e, _) - | SynExpr.Typed (e, _, _) - | SynExpr.FromParseError (e, _) - | SynExpr.DiscardAfterMissingQualificationAfterDot (e, _) - | SynExpr.Do (e, _) - | SynExpr.Assert (e, _) - | SynExpr.Fixed (e, _) - | SynExpr.DotGet (e, _, _, _) - | SynExpr.LongIdentSet (_, e, _) - | SynExpr.New (_, _, e, _) - | SynExpr.TypeApp (e, _, _, _, _, _, _) - | SynExpr.LibraryOnlyUnionCaseFieldGet (e, _, _, _) - | SynExpr.Downcast (e, _, _) - | SynExpr.InferredUpcast (e, _) - | SynExpr.InferredDowncast (e, _) - | SynExpr.Lazy (e, _) - | SynExpr.TraitCall (_, _, e, _) - | SynExpr.Paren (e, _, _, _) -> - yield! walkExpr false e - - | SynExpr.InterpolatedString (parts, _) -> - yield! walkExprs [ for part in parts do - match part with - | SynInterpolatedStringPart.String _ -> () - | SynInterpolatedStringPart.FillExpr (fillExpr, _) -> yield fillExpr ] - - | SynExpr.YieldOrReturn (_, e, _) - | SynExpr.YieldOrReturnFrom (_, e, _) - | SynExpr.DoBang (e, _) -> - yield! checkRange e.Range - yield! walkExpr false e - - | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) - | SynExpr.DotSet (e1, _, e2, _) - | SynExpr.Set (e1, e2, _) - | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, _, _, e2, _) - | SynExpr.App (_, _, e1, e2, _) -> - yield! walkExpr false e1 - yield! walkExpr false e2 - - | SynExpr.ArrayOrList (_, es, _) - | SynExpr.Tuple (_, es, _, _) -> - yield! walkExprs es - - | SynExpr.Record (_, copyExprOpt, fs, _) -> - match copyExprOpt with - | Some (e, _) -> yield! walkExpr true e - | None -> () - yield! walkExprs (fs |> List.choose p23) - - | SynExpr.AnonRecd (_isStruct, copyExprOpt, fs, _) -> - match copyExprOpt with - | Some (e, _) -> yield! walkExpr true e - | None -> () - yield! walkExprs (fs |> List.map snd) - - | SynExpr.ObjExpr (_, args, bs, is, _, _) -> - match args with - | None -> () - | Some (arg, _) -> yield! walkExpr false arg - yield! walkBinds bs - for (InterfaceImpl(_, bs, _)) in is do yield! walkBinds bs - - | SynExpr.While (spWhile, e1, e2, _) -> - yield! walkWhileSeqPt spWhile - yield! walkExpr false e1 - yield! walkExpr true e2 - - | SynExpr.JoinIn (e1, _range, e2, _range2) -> - yield! walkExpr false e1 - yield! walkExpr false e2 - - | SynExpr.For (spFor, _, e1, _, e2, e3, _) -> - yield! walkForSeqPt spFor - yield! walkExpr false e1 - yield! walkExpr true e2 - yield! walkExpr true e3 - - | SynExpr.ForEach (spFor, _, _, _, e1, e2, _) -> - yield! walkForSeqPt spFor - yield! walkExpr false e1 - yield! walkExpr true e2 - - | SynExpr.MatchLambda (_isExnMatch, _argm, cl, spBind, _wholem) -> - yield! walkBindSeqPt spBind - for (Clause(_, whenExpr, e, _, _)) in cl do - yield! walkExprOpt false whenExpr - yield! walkExpr true e - - | SynExpr.Lambda (_, _, _, e, _, _) -> - yield! walkExpr true e - - | SynExpr.Match (spBind, e, cl, _) -> - yield! walkBindSeqPt spBind - yield! walkExpr false e - for (Clause(_, whenExpr, e, _, _)) in cl do - yield! walkExprOpt false whenExpr - yield! walkExpr true e - - | SynExpr.LetOrUse (_, _, bs, e, _) -> - yield! walkBinds bs - yield! walkExpr true e - - | SynExpr.TryWith (e, _, cl, _, _, spTry, spWith) -> - yield! walkTrySeqPt spTry - yield! walkWithSeqPt spWith - yield! walkExpr true e - yield! walkMatchClauses cl - - | SynExpr.TryFinally (e1, e2, _, spTry, spFinally) -> - yield! walkExpr true e1 - yield! walkExpr true e2 - yield! walkTrySeqPt spTry - yield! walkFinallySeqPt spFinally - - | SynExpr.SequentialOrImplicitYield (spSeq, e1, e2, _, _) - | SynExpr.Sequential (spSeq, _, e1, e2, _) -> - yield! walkExpr (match spSeq with DebugPointAtSequential.ExprOnly -> false | _ -> true) e1 - yield! walkExpr (match spSeq with DebugPointAtSequential.StmtOnly -> false | _ -> true) e2 - - | SynExpr.IfThenElse (e1, e2, e3opt, spBind, _, _, _) -> - yield! walkBindSeqPt spBind - yield! walkExpr false e1 - yield! walkExpr true e2 - yield! walkExprOpt true e3opt - - | SynExpr.DotIndexedGet (e1, es, _, _) -> - yield! walkExpr false e1 - yield! walkExprs [ for e in es do yield! e.Exprs ] - - | SynExpr.DotIndexedSet (e1, es, e2, _, _, _) -> - yield! walkExpr false e1 - yield! walkExprs [ for e in es do yield! e.Exprs ] - yield! walkExpr false e2 - - | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> - yield! walkExpr false e1 - yield! walkExpr false e2 - yield! walkExpr false e3 - - | SynExpr.LetOrUseBang (spBind, _, _, _, e1, es, e2, _) -> - yield! walkBindSeqPt spBind - yield! walkExpr true e1 - for (andBangSpBind,_,_,_,eAndBang,_) in es do - yield! walkBindSeqPt andBangSpBind - yield! walkExpr true eAndBang - yield! walkExpr true e2 - - | SynExpr.MatchBang (spBind, e, cl, _) -> - yield! walkBindSeqPt spBind - yield! walkExpr false e - for (Clause(_, whenExpr, e, _, _)) in cl do - yield! walkExprOpt false whenExpr - yield! walkExpr true e ] - - // Process a class declaration or F# type declaration - let rec walkTycon (TypeDefn(ComponentInfo(_, _, _, _, _, _, _, _), repr, membDefns, m)) = - if not (isMatchRange m) then [] else - [ for memb in membDefns do yield! walkMember memb - match repr with - | SynTypeDefnRepr.ObjectModel(_, membDefns, _) -> - for memb in membDefns do yield! walkMember memb - | _ -> () ] - - // Returns class-members for the right dropdown - and walkMember memb = - if not (rangeContainsPos memb.Range pos) then [] else - [ match memb with - | SynMemberDefn.LetBindings(binds, _, _, _) -> yield! walkBinds binds - | SynMemberDefn.AutoProperty(_attribs, _isStatic, _id, _tyOpt, _propKind, _, _xmlDoc, _access, synExpr, _, _) -> yield! walkExpr true synExpr - | SynMemberDefn.ImplicitCtor(_, _, _, _, _, m) -> yield! checkRange m - | SynMemberDefn.Member(bind, _) -> yield! walkBind bind - | SynMemberDefn.Interface(_, Some membs, _) -> for m in membs do yield! walkMember m - | SynMemberDefn.Inherit(_, _, m) -> - // can break on the "inherit" clause - yield! checkRange m - | SynMemberDefn.ImplicitInherit(_, arg, _, m) -> - // can break on the "inherit" clause - yield! checkRange m - yield! walkExpr true arg - | _ -> () ] - - // Process declarations nested in a module that should be displayed in the left dropdown - // (such as type declarations, nested modules etc.) - let rec walkDecl decl = - [ match decl with - | SynModuleDecl.Let(_, binds, m) when isMatchRange m -> - yield! walkBinds binds - | SynModuleDecl.DoExpr(spExpr, expr, m) when isMatchRange m -> - yield! walkBindSeqPt spExpr - yield! walkExpr false expr - | SynModuleDecl.ModuleAbbrev _ -> () - | SynModuleDecl.NestedModule(_, _isRec, decls, _, m) when isMatchRange m -> - for d in decls do yield! walkDecl d - | SynModuleDecl.Types(tydefs, m) when isMatchRange m -> - for d in tydefs do yield! walkTycon d - | SynModuleDecl.Exception(SynExceptionDefn(SynExceptionDefnRepr(_, _, _, _, _, _), membDefns, _), m) - when isMatchRange m -> - for m in membDefns do yield! walkMember m - | _ -> () ] - - // Collect all the items in a module - let walkModule (SynModuleOrNamespace(_, _, _, decls, _, _, _, m)) = - if isMatchRange m then - List.collect walkDecl decls - else - [] - - /// Get information for implementation file - let walkImplFile (modules: SynModuleOrNamespace list) = List.collect walkModule modules - - match input with - | Some (ParsedInput.ImplFile (ParsedImplFileInput (modules = modules))) -> walkImplFile modules - | _ -> [] - - ErrorScope.Protect range0 - (fun () -> - let locations = findBreakPoints() - - if pos.Column = 0 then - // we have a breakpoint that was set with mouse at line start - match locations |> List.filter (fun m -> m.StartLine = m.EndLine && pos.Line = m.StartLine) with - | [] -> - match locations |> List.filter (fun m -> rangeContainsPos m pos) with - | [] -> - match locations |> List.filter (fun m -> rangeBeforePos m pos |> not) with - | [] -> Seq.tryHead locations - | locationsAfterPos -> Seq.tryHead locationsAfterPos - | coveringLocations -> Seq.tryLast coveringLocations - | locationsOnSameLine -> Seq.tryHead locationsOnSameLine - else - match locations |> List.filter (fun m -> rangeContainsPos m pos) with - | [] -> - match locations |> List.filter (fun m -> rangeBeforePos m pos |> not) with - | [] -> Seq.tryHead locations - | locationsAfterPos -> Seq.tryHead locationsAfterPos - | coveringLocations -> Seq.tryLast coveringLocations) - (fun msg -> - Trace.TraceInformation(sprintf "FCS: recovering from error in ValidateBreakpointLocationImpl: '%s'" msg) - None) - - /// When these files appear or disappear the configuration for the current project is invalidated. - member scope.DependencyFiles = dependencyFiles - - member scope.FileName = - match input with - | Some (ParsedInput.ImplFile (ParsedImplFileInput (fileName = modname))) - | Some (ParsedInput.SigFile (ParsedSigFileInput (fileName = modname))) -> modname - | _ -> "" - - // Get items for the navigation drop down bar - member scope.GetNavigationItems() = - // This does not need to be run on the background thread - scope.GetNavigationItemsImpl() - - member scope.ValidateBreakpointLocation pos = - // This does not need to be run on the background thread - scope.ValidateBreakpointLocationImpl pos - -type ModuleKind = { IsAutoOpen: bool; HasModuleSuffix: bool } - -[] -type EntityKind = - | Attribute - | Type - | FunctionOrValue of isActivePattern: bool - | Module of ModuleKind - override x.ToString() = sprintf "%A" x - -module UntypedParseImpl = - - let emptyStringSet = HashSet() - - let GetRangeOfExprLeftOfDot(pos: pos, parseTreeOpt) = - match parseTreeOpt with - | None -> None - | Some parseTree -> - let CheckLongIdent(longIdent: LongIdent) = - // find the longest prefix before the "pos" dot - let mutable r = (List.head longIdent).idRange - let mutable couldBeBeforeFront = true - for i in longIdent do - if posGeq pos i.idRange.End then - r <- unionRanges r i.idRange - couldBeBeforeFront <- false - couldBeBeforeFront, r - - AstTraversal.Traverse(pos, parseTree, { new AstTraversal.AstVisitorBase<_>() with - member this.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = - let expr = expr // fix debugger locals - match expr with - | SynExpr.LongIdent (_, LongIdentWithDots(longIdent, _), _altNameRefCell, _range) -> - let _, r = CheckLongIdent longIdent - Some r - | SynExpr.LongIdentSet (LongIdentWithDots(longIdent, _), synExpr, _range) -> - if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - let _, r = CheckLongIdent longIdent - Some r - | SynExpr.DotGet (synExpr, _dotm, LongIdentWithDots(longIdent, _), _range) -> - if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - let inFront, r = CheckLongIdent longIdent - if inFront then - Some (synExpr.Range) - else - // see comment below for SynExpr.DotSet - Some ((unionRanges synExpr.Range r)) - | SynExpr.Set (synExpr, synExpr2, range) -> - if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then - traverseSynExpr synExpr2 - else - Some range - | SynExpr.DotSet (synExpr, LongIdentWithDots(longIdent, _), synExpr2, _range) -> - if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then - traverseSynExpr synExpr2 - else - let inFront, r = CheckLongIdent longIdent - if inFront then - Some (synExpr.Range) - else - // f(0).X.Y.Z - // ^ - // - r has this value - // ---- synExpr.Range has this value - // ------ we want this value - Some ((unionRanges synExpr.Range r)) - | SynExpr.DotNamedIndexedPropertySet (synExpr, LongIdentWithDots(longIdent, _), synExpr2, synExpr3, _range) -> - if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr2.Range pos then - traverseSynExpr synExpr2 - elif AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr3.Range pos then - traverseSynExpr synExpr3 - else - let inFront, r = CheckLongIdent longIdent - if inFront then - Some (synExpr.Range) - else - Some ((unionRanges synExpr.Range r)) - | SynExpr.DiscardAfterMissingQualificationAfterDot (synExpr, _range) -> // get this for e.g. "bar()." - if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - Some (synExpr.Range) - | SynExpr.FromParseError (synExpr, range) -> - if AstTraversal.rangeContainsPosLeftEdgeInclusive synExpr.Range pos then - traverseSynExpr synExpr - else - Some range - | SynExpr.App (ExprAtomicFlag.NonAtomic, true, (SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, _))), rhs, _) - when ident.idText = "op_ArrayLookup" - && not(AstTraversal.rangeContainsPosLeftEdgeInclusive rhs.Range pos) -> - match defaultTraverse expr with - | None -> - // (expr).(expr) is an ML-deprecated array lookup, but we want intellisense on the dot - // also want it for e.g. [|arr|].(0) - Some (expr.Range) - | x -> x // we found the answer deeper somewhere in the lhs - | SynExpr.Const (SynConst.Double(_), range) -> Some range - | _ -> defaultTraverse expr - }) - - /// searches for the expression island suitable for the evaluation by the debugger - let TryFindExpressionIslandInPosition(pos: pos, parseTreeOpt) = - match parseTreeOpt with - | None -> None - | Some parseTree -> - let getLidParts (lid : LongIdent) = - lid - |> Seq.takeWhile (fun i -> posGeq pos i.idRange.Start) - |> Seq.map (fun i -> i.idText) - |> Seq.toList - - // tries to locate simple expression island - // foundCandidate = false means that we are looking for the candidate expression - // foundCandidate = true - we found candidate (DotGet) and now drill down to the left part - let rec TryGetExpression foundCandidate expr = - match expr with - | SynExpr.Paren (e, _, _, _) when foundCandidate -> - TryGetExpression foundCandidate e - | SynExpr.LongIdent (_isOptional, LongIdentWithDots(lid, _), _altNameRefCell, _m) -> - getLidParts lid |> Some - | SynExpr.DotGet (leftPart, _, LongIdentWithDots(lid, _), _) when (rangeContainsPos (rangeOfLid lid) pos) || foundCandidate -> - // requested position is at the lid part of the DotGet - // process left part and append result to the result of processing lid - let leftPartResult = TryGetExpression true leftPart - match leftPartResult with - | Some leftPartResult -> - [ - yield! leftPartResult - yield! getLidParts lid - ] |> Some - | None -> None - | SynExpr.FromParseError (synExpr, _range) -> TryGetExpression foundCandidate synExpr - | _ -> None - - let rec walker = - { new AstTraversal.AstVisitorBase<_>() with - member this.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = - if rangeContainsPos expr.Range pos then - match TryGetExpression false expr with - | (Some parts) -> parts |> String.concat "." |> Some - | _ -> defaultTraverse expr - else - None } - AstTraversal.Traverse(pos, parseTree, walker) - - // Given a cursor position here: - // f(x) . ident - // ^ - // walk the AST to find the position here: - // f(x) . ident - // ^ - // On success, return Some (thatPos, boolTrueIfCursorIsAfterTheDotButBeforeTheIdentifier) - // If there's no dot, return None, so for example - // foo - // ^ - // would return None - // TODO would be great to unify this with GetRangeOfExprLeftOfDot above, if possible, as they are similar - let TryFindExpressionASTLeftOfDotLeftOfCursor(pos, parseTreeOpt) = - match parseTreeOpt with - | None -> None - | Some parseTree -> - let dive x = AstTraversal.dive x - let pick x = AstTraversal.pick pos x - let walker = - { new AstTraversal.AstVisitorBase<_>() with - member this.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = - let pick = pick expr.Range - let traverseSynExpr, defaultTraverse, expr = traverseSynExpr, defaultTraverse, expr // for debugging: debugger does not get object expression params as local vars - if not(rangeContainsPos expr.Range pos) then - match expr with - | SynExpr.DiscardAfterMissingQualificationAfterDot (e, _m) -> - // This happens with e.g. "f(x) . $" when you bring up a completion list a few spaces after a dot. The cursor is not 'in the parse tree', - // but the dive algorithm will dive down into this node, and this is the one case where we do want to give a result despite the cursor - // not properly being in a node. - match traverseSynExpr e with - | None -> Some (e.Range.End, false) - | r -> r - | _ -> - // This happens for e.g. "System.Console.[]$", where the ".[]" token is thrown away by the parser and we dive into the System.Console longId - // even though the cursor/dot is not in there. In those cases we want to return None, because there is not really a dot completion before - // the cursor location. - None - else - let rec traverseLidOrElse (optExprIfLeftOfLongId : SynExpr option) (LongIdentWithDots(lid, dots) as lidwd) = - let resultIfLeftOfLongId = - match optExprIfLeftOfLongId with - | None -> None - | Some e -> Some (e.Range.End, posGeq lidwd.Range.Start pos) - match dots |> List.mapi (fun i x -> i, x) |> List.rev |> List.tryFind (fun (_, m) -> posGt pos m.Start) with - | None -> resultIfLeftOfLongId - | Some (n, _) -> Some ((List.item n lid).idRange.End, (List.length lid = n+1) // foo.$ - || (posGeq (List.item (n+1) lid).idRange.Start pos)) // foo.$bar - match expr with - | SynExpr.LongIdent (_isOptional, lidwd, _altNameRefCell, _m) -> - traverseLidOrElse None lidwd - | SynExpr.LongIdentSet (lidwd, exprRhs, _m) -> - [ dive lidwd lidwd.Range (traverseLidOrElse None) - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr - | SynExpr.DotGet (exprLeft, dotm, lidwd, _m) -> - let afterDotBeforeLid = mkRange dotm.FileName dotm.End lidwd.Range.Start - [ dive exprLeft exprLeft.Range traverseSynExpr - dive exprLeft afterDotBeforeLid (fun e -> Some (e.Range.End, true)) - dive lidwd lidwd.Range (traverseLidOrElse (Some exprLeft)) - ] |> pick expr - | SynExpr.DotSet (exprLeft, lidwd, exprRhs, _m) -> - [ dive exprLeft exprLeft.Range traverseSynExpr - dive lidwd lidwd.Range (traverseLidOrElse(Some exprLeft)) - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr - | SynExpr.Set (exprLeft, exprRhs, _m) -> - [ dive exprLeft exprLeft.Range traverseSynExpr - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr - | SynExpr.NamedIndexedPropertySet (lidwd, exprIndexer, exprRhs, _m) -> - [ dive lidwd lidwd.Range (traverseLidOrElse None) - dive exprIndexer exprIndexer.Range traverseSynExpr - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr - | SynExpr.DotNamedIndexedPropertySet (exprLeft, lidwd, exprIndexer, exprRhs, _m) -> - [ dive exprLeft exprLeft.Range traverseSynExpr - dive lidwd lidwd.Range (traverseLidOrElse(Some exprLeft)) - dive exprIndexer exprIndexer.Range traverseSynExpr - dive exprRhs exprRhs.Range traverseSynExpr - ] |> pick expr - | SynExpr.Const (SynConst.Double(_), m) -> - if posEq m.End pos then - // the cursor is at the dot - Some (m.End, false) - else - // the cursor is left of the dot - None - | SynExpr.DiscardAfterMissingQualificationAfterDot (e, m) -> - match traverseSynExpr e with - | None -> - if posEq m.End pos then - // the cursor is at the dot - Some (e.Range.End, false) - else - // the cursor is left of the dot - None - | r -> r - | SynExpr.App (ExprAtomicFlag.NonAtomic, true, (SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, _))), lhs, _m) - when ident.idText = "op_ArrayLookup" - && not(AstTraversal.rangeContainsPosLeftEdgeInclusive lhs.Range pos) -> - match defaultTraverse expr with - | None -> - // (expr).(expr) is an ML-deprecated array lookup, but we want intellisense on the dot - // also want it for e.g. [|arr|].(0) - Some (lhs.Range.End, false) - | x -> x // we found the answer deeper somewhere in the lhs - | _ -> defaultTraverse expr } - AstTraversal.Traverse(pos, parseTree, walker) - - let GetEntityKind (pos: pos, input: ParsedInput) : EntityKind option = - let (|ConstructorPats|) = function - | Pats ps -> ps - | NamePatPairs(xs, _) -> List.map snd xs - - /// An recursive pattern that collect all sequential expressions to avoid StackOverflowException - let rec (|Sequentials|_|) = function - | SynExpr.Sequential (_, _, e, Sequentials es, _) -> Some (e :: es) - | SynExpr.Sequential (_, _, e1, e2, _) -> Some [e1; e2] - | _ -> None - - let inline isPosInRange range = rangeContainsPos range pos - - let inline ifPosInRange range f = - if isPosInRange range then f() - else None - - let rec walkImplFileInput (ParsedImplFileInput (modules = moduleOrNamespaceList)) = - List.tryPick (walkSynModuleOrNamespace true) moduleOrNamespaceList - - and walkSynModuleOrNamespace isTopLevel (SynModuleOrNamespace(_, _, _, decls, _, Attributes attrs, _, r)) = - List.tryPick walkAttribute attrs - |> Option.orElse (ifPosInRange r (fun _ -> List.tryPick (walkSynModuleDecl isTopLevel) decls)) - - and walkAttribute (attr: SynAttribute) = - if isPosInRange attr.Range then Some EntityKind.Attribute else None - |> Option.orElse (walkExprWithKind (Some EntityKind.Type) attr.ArgExpr) - - and walkTypar (Typar (ident, _, _)) = ifPosInRange ident.idRange (fun _ -> Some EntityKind.Type) - - and walkTyparDecl (SynTyparDecl.TyparDecl (Attributes attrs, typar)) = - List.tryPick walkAttribute attrs - |> Option.orElse (walkTypar typar) - - and walkTypeConstraint = function - | SynTypeConstraint.WhereTyparDefaultsToType (t1, t2, _) -> walkTypar t1 |> Option.orElse (walkType t2) - | SynTypeConstraint.WhereTyparIsValueType(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsReferenceType(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsUnmanaged(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparSupportsNull (t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsComparable(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparIsEquatable(t, _) -> walkTypar t - | SynTypeConstraint.WhereTyparSubtypeOfType(t, ty, _) -> walkTypar t |> Option.orElse (walkType ty) - | SynTypeConstraint.WhereTyparSupportsMember(ts, sign, _) -> - List.tryPick walkType ts |> Option.orElse (walkMemberSig sign) - | SynTypeConstraint.WhereTyparIsEnum(t, ts, _) -> walkTypar t |> Option.orElse (List.tryPick walkType ts) - | SynTypeConstraint.WhereTyparIsDelegate(t, ts, _) -> walkTypar t |> Option.orElse (List.tryPick walkType ts) - - and walkPatWithKind (kind: EntityKind option) = function - | SynPat.Ands (pats, _) -> List.tryPick walkPat pats - | SynPat.Named(SynPat.Wild nameRange as pat, _, _, _, _) -> - if isPosInRange nameRange then None - else walkPat pat - | SynPat.Typed(pat, t, _) -> walkPat pat |> Option.orElse (walkType t) - | SynPat.Attrib(pat, Attributes attrs, _) -> walkPat pat |> Option.orElse (List.tryPick walkAttribute attrs) - | SynPat.Or(pat1, pat2, _) -> List.tryPick walkPat [pat1; pat2] - | SynPat.LongIdent(_, _, typars, ConstructorPats pats, _, r) -> - ifPosInRange r (fun _ -> kind) - |> Option.orElse ( - typars - |> Option.bind (fun (SynValTyparDecls (typars, _, constraints)) -> - List.tryPick walkTyparDecl typars - |> Option.orElse (List.tryPick walkTypeConstraint constraints))) - |> Option.orElse (List.tryPick walkPat pats) - | SynPat.Tuple(_, pats, _) -> List.tryPick walkPat pats - | SynPat.Paren(pat, _) -> walkPat pat - | SynPat.ArrayOrList(_, pats, _) -> List.tryPick walkPat pats - | SynPat.IsInst(t, _) -> walkType t - | SynPat.QuoteExpr(e, _) -> walkExpr e - | _ -> None - - and walkPat = walkPatWithKind None - - and walkBinding (SynBinding.Binding(_, _, _, _, Attributes attrs, _, _, pat, returnInfo, e, _, _)) = - List.tryPick walkAttribute attrs - |> Option.orElse (walkPat pat) - |> Option.orElse (walkExpr e) - |> Option.orElse ( - match returnInfo with - | Some (SynBindingReturnInfo (t, _, _)) -> walkType t - | None -> None) - - and walkInterfaceImpl (InterfaceImpl(_, bindings, _)) = - List.tryPick walkBinding bindings - - and walkIndexerArg = function - | SynIndexerArg.One (e, _, _) -> walkExpr e - | SynIndexerArg.Two(e1, _, e2, _, _, _) -> List.tryPick walkExpr [e1; e2] - - and walkType = function - | SynType.LongIdent ident -> - // we protect it with try..with because System.Exception : rangeOfLidwd may raise - // at FSharp.Compiler.SyntaxTree.LongIdentWithDots.get_Range() in D:\j\workspace\release_ci_pa---3f142ccc\src\ast.fs: line 156 - try ifPosInRange ident.Range (fun _ -> Some EntityKind.Type) with _ -> None - | SynType.App(ty, _, types, _, _, _, _) -> - walkType ty |> Option.orElse (List.tryPick walkType types) - | SynType.LongIdentApp(_, _, _, types, _, _, _) -> List.tryPick walkType types - | SynType.Tuple(_, ts, _) -> ts |> List.tryPick (fun (_, t) -> walkType t) - | SynType.Array(_, t, _) -> walkType t - | SynType.Fun(t1, t2, _) -> walkType t1 |> Option.orElse (walkType t2) - | SynType.WithGlobalConstraints(t, _, _) -> walkType t - | SynType.HashConstraint(t, _) -> walkType t - | SynType.MeasureDivide(t1, t2, _) -> walkType t1 |> Option.orElse (walkType t2) - | SynType.MeasurePower(t, _, _) -> walkType t - | SynType.Paren(t, _) -> walkType t - | _ -> None - - and walkClause (Clause(pat, e1, e2, _, _)) = - walkPatWithKind (Some EntityKind.Type) pat - |> Option.orElse (walkExpr e2) - |> Option.orElse (Option.bind walkExpr e1) - - and walkExprWithKind (parentKind: EntityKind option) = function - | SynExpr.LongIdent (_, LongIdentWithDots(_, dotRanges), _, r) -> - match dotRanges with - | [] when isPosInRange r -> parentKind |> Option.orElse (Some (EntityKind.FunctionOrValue false)) - | firstDotRange :: _ -> - let firstPartRange = - mkRange "" r.Start (mkPos firstDotRange.StartLine (firstDotRange.StartColumn - 1)) - if isPosInRange firstPartRange then - parentKind |> Option.orElse (Some (EntityKind.FunctionOrValue false)) - else None - | _ -> None - | SynExpr.Paren (e, _, _, _) -> walkExprWithKind parentKind e - | SynExpr.Quote (_, _, e, _, _) -> walkExprWithKind parentKind e - | SynExpr.Typed (e, _, _) -> walkExprWithKind parentKind e - | SynExpr.Tuple (_, es, _, _) -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.ArrayOrList (_, es, _) -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.Record (_, _, fields, r) -> - ifPosInRange r (fun _ -> - fields |> List.tryPick (fun (_, e, _) -> e |> Option.bind (walkExprWithKind parentKind))) - | SynExpr.New (_, t, e, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.ObjExpr (ty, _, bindings, ifaces, _, _) -> - walkType ty - |> Option.orElse (List.tryPick walkBinding bindings) - |> Option.orElse (List.tryPick walkInterfaceImpl ifaces) - | SynExpr.While (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.For (_, _, e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] - | SynExpr.ForEach (_, _, _, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.ArrayOrListOfSeqExpr (_, e, _) -> walkExprWithKind parentKind e - | SynExpr.CompExpr (_, _, e, _) -> walkExprWithKind parentKind e - | SynExpr.Lambda (_, _, _, e, _, _) -> walkExprWithKind parentKind e - | SynExpr.MatchLambda (_, _, synMatchClauseList, _, _) -> - List.tryPick walkClause synMatchClauseList - | SynExpr.Match (_, e, synMatchClauseList, _) -> - walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkClause synMatchClauseList) - | SynExpr.Do (e, _) -> walkExprWithKind parentKind e - | SynExpr.Assert (e, _) -> walkExprWithKind parentKind e - | SynExpr.App (_, _, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.TypeApp (e, _, tys, _, _, _, _) -> - walkExprWithKind (Some EntityKind.Type) e |> Option.orElse (List.tryPick walkType tys) - | SynExpr.LetOrUse (_, _, bindings, e, _) -> List.tryPick walkBinding bindings |> Option.orElse (walkExprWithKind parentKind e) - | SynExpr.TryWith (e, _, clauses, _, _, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkClause clauses) - | SynExpr.TryFinally (e1, e2, _, _, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.Lazy (e, _) -> walkExprWithKind parentKind e - | Sequentials es -> List.tryPick (walkExprWithKind parentKind) es - | SynExpr.IfThenElse (e1, e2, e3, _, _, _, _) -> - List.tryPick (walkExprWithKind parentKind) [e1; e2] |> Option.orElse (match e3 with None -> None | Some e -> walkExprWithKind parentKind e) - | SynExpr.Ident ident -> ifPosInRange ident.idRange (fun _ -> Some (EntityKind.FunctionOrValue false)) - | SynExpr.LongIdentSet (_, e, _) -> walkExprWithKind parentKind e - | SynExpr.DotGet (e, _, _, _) -> walkExprWithKind parentKind e - | SynExpr.DotSet (e, _, _, _) -> walkExprWithKind parentKind e - | SynExpr.Set (e, _, _) -> walkExprWithKind parentKind e - | SynExpr.DotIndexedGet (e, args, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkIndexerArg args) - | SynExpr.DotIndexedSet (e, args, _, _, _, _) -> walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkIndexerArg args) - | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2; e3] - | SynExpr.TypeTest (e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.Upcast (e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.Downcast (e, t, _) -> walkExprWithKind parentKind e |> Option.orElse (walkType t) - | SynExpr.InferredUpcast (e, _) -> walkExprWithKind parentKind e - | SynExpr.InferredDowncast (e, _) -> walkExprWithKind parentKind e - | SynExpr.AddressOf (_, e, _, _) -> walkExprWithKind parentKind e - | SynExpr.JoinIn (e1, _, e2, _) -> List.tryPick (walkExprWithKind parentKind) [e1; e2] - | SynExpr.YieldOrReturn (_, e, _) -> walkExprWithKind parentKind e - | SynExpr.YieldOrReturnFrom (_, e, _) -> walkExprWithKind parentKind e - | SynExpr.Match (_, e, synMatchClauseList, _) - | SynExpr.MatchBang (_, e, synMatchClauseList, _) -> - walkExprWithKind parentKind e |> Option.orElse (List.tryPick walkClause synMatchClauseList) - | SynExpr.LetOrUseBang(_, _, _, _, e1, es, e2, _) -> - [ - yield e1 - for (_,_,_,_,eAndBang,_) in es do - yield eAndBang - yield e2 - ] - |> List.tryPick (walkExprWithKind parentKind) - | SynExpr.DoBang (e, _) -> walkExprWithKind parentKind e - | SynExpr.TraitCall (ts, sign, e, _) -> - List.tryPick walkTypar ts - |> Option.orElse (walkMemberSig sign) - |> Option.orElse (walkExprWithKind parentKind e) - | _ -> None - - and walkExpr = walkExprWithKind None - - and walkSimplePat = function - | SynSimplePat.Attrib (pat, Attributes attrs, _) -> - walkSimplePat pat |> Option.orElse (List.tryPick walkAttribute attrs) - | SynSimplePat.Typed(pat, t, _) -> walkSimplePat pat |> Option.orElse (walkType t) - | _ -> None - - and walkField (SynField.Field(Attributes attrs, _, _, t, _, _, _, _)) = - List.tryPick walkAttribute attrs |> Option.orElse (walkType t) - - and walkValSig (SynValSig.ValSpfn(Attributes attrs, _, _, t, _, _, _, _, _, _, _)) = - List.tryPick walkAttribute attrs |> Option.orElse (walkType t) - - and walkMemberSig = function - | SynMemberSig.Inherit (t, _) -> walkType t - | SynMemberSig.Member(vs, _, _) -> walkValSig vs - | SynMemberSig.Interface(t, _) -> walkType t - | SynMemberSig.ValField(f, _) -> walkField f - | SynMemberSig.NestedType(SynTypeDefnSig.TypeDefnSig (info, repr, memberSigs, _), _) -> - walkComponentInfo false info - |> Option.orElse (walkTypeDefnSigRepr repr) - |> Option.orElse (List.tryPick walkMemberSig memberSigs) - - and walkMember = function - | SynMemberDefn.AbstractSlot (valSig, _, _) -> walkValSig valSig - | SynMemberDefn.Member(binding, _) -> walkBinding binding - | SynMemberDefn.ImplicitCtor(_, Attributes attrs, SynSimplePats.SimplePats(simplePats, _), _, _, _) -> - List.tryPick walkAttribute attrs |> Option.orElse (List.tryPick walkSimplePat simplePats) - | SynMemberDefn.ImplicitInherit(t, e, _, _) -> walkType t |> Option.orElse (walkExpr e) - | SynMemberDefn.LetBindings(bindings, _, _, _) -> List.tryPick walkBinding bindings - | SynMemberDefn.Interface(t, members, _) -> - walkType t |> Option.orElse (members |> Option.bind (List.tryPick walkMember)) - | SynMemberDefn.Inherit(t, _, _) -> walkType t - | SynMemberDefn.ValField(field, _) -> walkField field - | SynMemberDefn.NestedType(tdef, _, _) -> walkTypeDefn tdef - | SynMemberDefn.AutoProperty(Attributes attrs, _, _, t, _, _, _, _, e, _, _) -> - List.tryPick walkAttribute attrs - |> Option.orElse (Option.bind walkType t) - |> Option.orElse (walkExpr e) - | _ -> None - - and walkEnumCase (EnumCase(Attributes attrs, _, _, _, _)) = List.tryPick walkAttribute attrs - - and walkUnionCaseType = function - | SynUnionCaseType.UnionCaseFields fields -> List.tryPick walkField fields - | SynUnionCaseType.UnionCaseFullType(t, _) -> walkType t - - and walkUnionCase (UnionCase(Attributes attrs, _, t, _, _, _)) = - List.tryPick walkAttribute attrs |> Option.orElse (walkUnionCaseType t) - - and walkTypeDefnSimple = function - | SynTypeDefnSimpleRepr.Enum (cases, _) -> List.tryPick walkEnumCase cases - | SynTypeDefnSimpleRepr.Union(_, cases, _) -> List.tryPick walkUnionCase cases - | SynTypeDefnSimpleRepr.Record(_, fields, _) -> List.tryPick walkField fields - | SynTypeDefnSimpleRepr.TypeAbbrev(_, t, _) -> walkType t - | _ -> None - - and walkComponentInfo isModule (ComponentInfo(Attributes attrs, typars, constraints, _, _, _, _, r)) = - if isModule then None else ifPosInRange r (fun _ -> Some EntityKind.Type) - |> Option.orElse ( - List.tryPick walkAttribute attrs - |> Option.orElse (List.tryPick walkTyparDecl typars) - |> Option.orElse (List.tryPick walkTypeConstraint constraints)) - - and walkTypeDefnRepr = function - | SynTypeDefnRepr.ObjectModel (_, defns, _) -> List.tryPick walkMember defns - | SynTypeDefnRepr.Simple(defn, _) -> walkTypeDefnSimple defn - | SynTypeDefnRepr.Exception(_) -> None - - and walkTypeDefnSigRepr = function - | SynTypeDefnSigRepr.ObjectModel (_, defns, _) -> List.tryPick walkMemberSig defns - | SynTypeDefnSigRepr.Simple(defn, _) -> walkTypeDefnSimple defn - | SynTypeDefnSigRepr.Exception(_) -> None - - and walkTypeDefn (TypeDefn (info, repr, members, _)) = - walkComponentInfo false info - |> Option.orElse (walkTypeDefnRepr repr) - |> Option.orElse (List.tryPick walkMember members) - - and walkSynModuleDecl isTopLevel (decl: SynModuleDecl) = - match decl with - | SynModuleDecl.NamespaceFragment fragment -> walkSynModuleOrNamespace isTopLevel fragment - | SynModuleDecl.NestedModule(info, _, modules, _, range) -> - walkComponentInfo true info - |> Option.orElse (ifPosInRange range (fun _ -> List.tryPick (walkSynModuleDecl false) modules)) - | SynModuleDecl.Open _ -> None - | SynModuleDecl.Let (_, bindings, _) -> List.tryPick walkBinding bindings - | SynModuleDecl.DoExpr (_, expr, _) -> walkExpr expr - | SynModuleDecl.Types (types, _) -> List.tryPick walkTypeDefn types - | _ -> None - - match input with - | ParsedInput.SigFile _ -> None - | ParsedInput.ImplFile input -> walkImplFileInput input - - type internal TS = AstTraversal.TraverseStep - /// Matches the most nested [< and >] pair. - let insideAttributeApplicationRegex = Regex(@"(?<=\[\<)(?(.*?))(?=\>\])", RegexOptions.Compiled ||| RegexOptions.ExplicitCapture) - - /// Try to determine completion context for the given pair (row, columns) - let TryGetCompletionContext (pos, parsedInput: ParsedInput, lineStr: string) : CompletionContext option = - - match GetEntityKind(pos, parsedInput) with - | Some EntityKind.Attribute -> Some CompletionContext.AttributeApplication - | _ -> - - let parseLid (LongIdentWithDots(lid, dots)) = - let rec collect plid (parts : Ident list) (dots : range list) = - match parts, dots with - | [], _ -> Some (plid, None) - | x :: xs, ds -> - if rangeContainsPos x.idRange pos then - // pos lies with the range of current identifier - let s = x.idText.Substring(0, pos.Column - x.idRange.Start.Column) - let residue = if s.Length <> 0 then Some s else None - Some (plid, residue) - elif posGt x.idRange.Start pos then - // can happen if caret is placed after dot but before the existing identifier A. $ B - // return accumulated plid with no residue - Some (plid, None) - else - match ds with - | [] -> - // pos lies after the id and no dots found - return accumulated plid and current id as residue - Some (plid, Some (x.idText)) - | d :: ds -> - if posGeq pos d.End then - // pos lies after the dot - proceed to the next identifier - collect ((x.idText) :: plid) xs ds - else - // pos after the id but before the dot - // A $.B - return nothing - None - - match collect [] lid dots with - | Some (parts, residue) -> - Some ((List.rev parts), residue) - | None -> None - - let (|Class|Interface|Struct|Unknown|Invalid|) synAttributes = - let (|SynAttr|_|) name (attr : SynAttribute) = - match attr with - | {TypeName = LongIdentWithDots([x], _)} when x.idText = name -> Some () - | _ -> None - - let rec getKind isClass isInterface isStruct = - function - | [] -> isClass, isInterface, isStruct - | (SynAttr "Class") :: xs -> getKind true isInterface isStruct xs - | (SynAttr "AbstractClass") :: xs -> getKind true isInterface isStruct xs - | (SynAttr "Interface") :: xs -> getKind isClass true isStruct xs - | (SynAttr "Struct") :: xs -> getKind isClass isInterface true xs - | _ :: xs -> getKind isClass isInterface isStruct xs - - match getKind false false false synAttributes with - | false, false, false -> Unknown - | true, false, false -> Class - | false, true, false -> Interface - | false, false, true -> Struct - | _ -> Invalid - - let GetCompletionContextForInheritSynMember ((ComponentInfo(Attributes synAttributes, _, _, _, _, _, _, _)), typeDefnKind : SynTypeDefnKind, completionPath) = - - let success k = Some (CompletionContext.Inherit (k, completionPath)) - - // if kind is specified - take it - // if kind is non-specified - // - try to obtain it from attribute - // - if no attributes present - infer kind from members - match typeDefnKind with - | TyconClass -> - match synAttributes with - | Class | Unknown -> success InheritanceContext.Class - | _ -> Some CompletionContext.Invalid // non-matching attributes - | TyconInterface -> - match synAttributes with - | Interface | Unknown -> success InheritanceContext.Interface - | _ -> Some CompletionContext.Invalid // non-matching attributes - | TyconStruct -> - // display nothing for structs - Some CompletionContext.Invalid - | TyconUnspecified -> - match synAttributes with - | Class -> success InheritanceContext.Class - | Interface -> success InheritanceContext.Interface - | Unknown -> - // user do not specify kind explicitly or via attributes - success InheritanceContext.Unknown - | _ -> - // unable to uniquely detect kind from the attributes - return invalid context - Some CompletionContext.Invalid - | _ -> None - - let (|Operator|_|) name e = - match e with - | SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.Ident ident, lhs, _), rhs, _) - when ident.idText = name -> Some (lhs, rhs) - | _ -> None - - // checks if we are in rhs of the range operator - let isInRhsOfRangeOp (p : AstTraversal.TraversePath) = - match p with - | TS.Expr(Operator "op_Range" _) :: _ -> true - | _ -> false - - let (|Setter|_|) e = - match e with - | Operator "op_Equality" (SynExpr.Ident id, _) -> Some id - | _ -> None - - let findSetters argList = - match argList with - | SynExpr.Paren (SynExpr.Tuple (false, parameters, _, _), _, _, _) -> - let setters = HashSet() - for p in parameters do - match p with - | Setter id -> ignore(setters.Add id.idText) - | _ -> () - setters - | _ -> emptyStringSet - - let endOfLastIdent (lid: LongIdentWithDots) = - let last = List.last lid.Lid - last.idRange.End - - let endOfClosingTokenOrLastIdent (mClosing: range option) (lid : LongIdentWithDots) = - match mClosing with - | Some m -> m.End - | None -> endOfLastIdent lid - - let endOfClosingTokenOrIdent (mClosing: range option) (id : Ident) = - match mClosing with - | Some m -> m.End - | None -> id.idRange.End - - let (|NewObjectOrMethodCall|_|) e = - match e with - | (SynExpr.New (_, SynType.LongIdent typeName, arg, _)) -> - // new A() - Some (endOfLastIdent typeName, findSetters arg) - | (SynExpr.New (_, SynType.App(StripParenTypes (SynType.LongIdent typeName), _, _, _, mGreaterThan, _, _), arg, _)) -> - // new A<_>() - Some (endOfClosingTokenOrLastIdent mGreaterThan typeName, findSetters arg) - | (SynExpr.App (_, false, SynExpr.Ident id, arg, _)) -> - // A() - Some (id.idRange.End, findSetters arg) - | (SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.Ident id, _, _, _, mGreaterThan, _, _), arg, _)) -> - // A<_>() - Some (endOfClosingTokenOrIdent mGreaterThan id, findSetters arg) - | (SynExpr.App (_, false, SynExpr.LongIdent (_, lid, _, _), arg, _)) -> - // A.B() - Some (endOfLastIdent lid, findSetters arg) - | (SynExpr.App (_, false, SynExpr.TypeApp (SynExpr.LongIdent (_, lid, _, _), _, _, _, mGreaterThan, _, _), arg, _)) -> - // A.B<_>() - Some (endOfClosingTokenOrLastIdent mGreaterThan lid, findSetters arg) - | _ -> None - - let isOnTheRightOfComma (elements: SynExpr list) (commas: range list) current = - let rec loop elements (commas: range list) = - match elements with - | x :: xs -> - match commas with - | c :: cs -> - if x === current then posLt c.End pos || posEq c.End pos - else loop xs cs - | _ -> false - | _ -> false - loop elements commas - - let (|PartOfParameterList|_|) precedingArgument path = - match path with - | TS.Expr(SynExpr.Paren _) :: TS.Expr(NewObjectOrMethodCall args) :: _ -> - if Option.isSome precedingArgument then None else Some args - | TS.Expr(SynExpr.Tuple (false, elements, commas, _)) :: TS.Expr(SynExpr.Paren _) :: TS.Expr(NewObjectOrMethodCall args) :: _ -> - match precedingArgument with - | None -> Some args - | Some e -> - // if expression is passed then - // 1. find it in among elements of the tuple - // 2. find corresponding comma - // 3. check that current position is past the comma - // this is used for cases like (a = something-here.) if the cursor is after . - // in this case this is not object initializer completion context - if isOnTheRightOfComma elements commas e then Some args else None - | _ -> None - - let walker = - { - new AstTraversal.AstVisitorBase<_>() with - member __.VisitExpr(path, _, defaultTraverse, expr) = - - if isInRhsOfRangeOp path then - match defaultTraverse expr with - | None -> Some CompletionContext.RangeOperator // nothing was found - report that we were in the context of range operator - | x -> x // ok, we found something - return it - else - match expr with - // new A($) - | SynExpr.Const (SynConst.Unit, m) when rangeContainsPos m pos -> - match path with - | TS.Expr(NewObjectOrMethodCall args) :: _ -> - Some (CompletionContext.ParameterList args) - | _ -> - defaultTraverse expr - // new (... A$) - | SynExpr.Ident id when id.idRange.End = pos -> - match path with - | PartOfParameterList None args -> - Some (CompletionContext.ParameterList args) - | _ -> - defaultTraverse expr - // new (A$ = 1) - // new (A = 1, $) - | Setter id when id.idRange.End = pos || rangeBeforePos expr.Range pos -> - let precedingArgument = if id.idRange.End = pos then None else Some expr - match path with - | PartOfParameterList precedingArgument args-> - Some (CompletionContext.ParameterList args) - | _ -> - defaultTraverse expr - - | _ -> defaultTraverse expr - - member __.VisitRecordField(path, copyOpt, field) = - let contextFromTreePath completionPath = - // detect records usage in constructor - match path with - | TS.Expr(_) :: TS.Binding(_) :: TS.MemberDefn(_) :: TS.TypeDefn(SynTypeDefn.TypeDefn(ComponentInfo(_, _, _, [id], _, _, _, _), _, _, _)) :: _ -> - RecordContext.Constructor(id.idText) - | _ -> RecordContext.New completionPath - match field with - | Some field -> - match parseLid field with - | Some completionPath -> - let recordContext = - match copyOpt with - | Some (s : SynExpr) -> RecordContext.CopyOnUpdate(s.Range, completionPath) - | None -> contextFromTreePath completionPath - Some (CompletionContext.RecordField recordContext) - | None -> None - | None -> - let recordContext = - match copyOpt with - | Some s -> RecordContext.CopyOnUpdate(s.Range, ([], None)) - | None -> contextFromTreePath ([], None) - Some (CompletionContext.RecordField recordContext) - - member __.VisitInheritSynMemberDefn(componentInfo, typeDefnKind, synType, _members, _range) = - match synType with - | SynType.LongIdent lidwd -> - match parseLid lidwd with - | Some completionPath -> GetCompletionContextForInheritSynMember (componentInfo, typeDefnKind, completionPath) - | None -> Some (CompletionContext.Invalid) // A $ .B -> no completion list - - | _ -> None - - member __.VisitBinding(defaultTraverse, (Binding(headPat = headPat) as synBinding)) = - - let visitParam = function - | SynPat.Named (range = range) when rangeContainsPos range pos -> - // parameter without type hint, no completion - Some CompletionContext.Invalid - | SynPat.Typed(SynPat.Named(SynPat.Wild range, _, _, _, _), _, _) when rangeContainsPos range pos -> - // parameter with type hint, but we are on its name, no completion - Some CompletionContext.Invalid - | _ -> defaultTraverse synBinding - - match headPat with - | SynPat.LongIdent(longDotId = lidwd) when rangeContainsPos lidwd.Range pos -> - // let fo|o x = () - Some CompletionContext.Invalid - | SynPat.LongIdent(_, _, _, ctorArgs, _, _) -> - match ctorArgs with - | SynArgPats.Pats pats -> - pats |> List.tryPick (fun pat -> - match pat with - | SynPat.Paren(pat, _) -> - match pat with - | SynPat.Tuple(_, pats, _) -> - pats |> List.tryPick visitParam - | _ -> visitParam pat - | SynPat.Wild range when rangeContainsPos range pos -> - // let foo (x| - Some CompletionContext.Invalid - | _ -> visitParam pat - ) - | _ -> defaultTraverse synBinding - | SynPat.Named(range = range) when rangeContainsPos range pos -> - // let fo|o = 1 - Some CompletionContext.Invalid - | _ -> defaultTraverse synBinding - - member __.VisitHashDirective range = - if rangeContainsPos range pos then Some CompletionContext.Invalid - else None - - member __.VisitModuleOrNamespace(SynModuleOrNamespace(longId = idents)) = - match List.tryLast idents with - | Some lastIdent when pos.Line = lastIdent.idRange.EndLine && lastIdent.idRange.EndColumn >= 0 && pos.Column <= lineStr.Length -> - let stringBetweenModuleNameAndPos = lineStr.[lastIdent.idRange.EndColumn..pos.Column - 1] - if stringBetweenModuleNameAndPos |> Seq.forall (fun x -> x = ' ' || x = '.') then - Some CompletionContext.Invalid - else None - | _ -> None - - member __.VisitComponentInfo(ComponentInfo(range = range)) = - if rangeContainsPos range pos then Some CompletionContext.Invalid - else None - - member __.VisitLetOrUse(_, _, bindings, range) = - match bindings with - | [] when range.StartLine = pos.Line -> Some CompletionContext.Invalid - | _ -> None - - member __.VisitSimplePats pats = - pats |> List.tryPick (fun pat -> - match pat with - | SynSimplePat.Id(range = range) - | SynSimplePat.Typed(SynSimplePat.Id(range = range), _, _) when rangeContainsPos range pos -> - Some CompletionContext.Invalid - | _ -> None) - - member __.VisitModuleDecl(defaultTraverse, decl) = - match decl with - | SynModuleDecl.Open(target, m) -> - // in theory, this means we're "in an open" - // in practice, because the parse tree/walkers do not handle attributes well yet, need extra check below to ensure not e.g. $here$ - // open System - // [ true - | SynOpenDeclTarget.ModuleOrNamespace _ -> false - Some (CompletionContext.OpenDeclaration isOpenType) - else - None - | _ -> defaultTraverse decl - - member __.VisitType(defaultTraverse, ty) = - match ty with - | SynType.LongIdent _ when rangeContainsPos ty.Range pos -> - Some CompletionContext.PatternType - | _ -> defaultTraverse ty - } - - AstTraversal.Traverse(pos, parsedInput, walker) - // Uncompleted attribute applications are not presented in the AST in any way. So, we have to parse source string. - |> Option.orElseWith (fun _ -> - let cutLeadingAttributes (str: string) = - // cut off leading attributes, i.e. we cut "[]" to " >]" - match str.LastIndexOf ';' with - | -1 -> str - | idx when idx < str.Length -> str.[idx + 1..].TrimStart() - | _ -> "" - - let isLongIdent = Seq.forall (fun c -> IsIdentifierPartCharacter c || c = '.' || c = ':') // ':' may occur in "[]" - - // match the most nested paired [< and >] first - let matches = - insideAttributeApplicationRegex.Matches lineStr - |> Seq.cast - |> Seq.filter (fun m -> m.Index <= pos.Column && m.Index + m.Length >= pos.Column) - |> Seq.toArray - - if not (Array.isEmpty matches) then - matches - |> Seq.tryPick (fun m -> - let g = m.Groups.["attribute"] - let col = pos.Column - g.Index - if col >= 0 && col < g.Length then - let str = g.Value.Substring(0, col).TrimStart() // cut other rhs attributes - let str = cutLeadingAttributes str - if isLongIdent str then - Some CompletionContext.AttributeApplication - else None - else None) - else - // Paired [< and >] were not found, try to determine that we are after [< without closing >] - match lineStr.LastIndexOf("[<", StringComparison.Ordinal) with - | -1 -> None - | openParenIndex when pos.Column >= openParenIndex + 2 -> - let str = lineStr.[openParenIndex + 2..pos.Column - 1].TrimStart() - let str = cutLeadingAttributes str - if isLongIdent str then - Some CompletionContext.AttributeApplication - else None - | _ -> None) - - /// Check if we are at an "open" declaration - let GetFullNameOfSmallestModuleOrNamespaceAtPoint (parsedInput: ParsedInput, pos: pos) = - let mutable path = [] - let visitor = - { new AstTraversal.AstVisitorBase() with - override this.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = - // don't need to keep going, namespaces and modules never appear inside Exprs - None - override this.VisitModuleOrNamespace(SynModuleOrNamespace(longId = longId; range = range)) = - if rangeContainsPos range pos then - path <- path @ longId - None // we should traverse the rest of the AST to find the smallest module - } - AstTraversal.Traverse(pos, parsedInput, visitor) |> ignore - path |> List.map (fun x -> x.idText) |> List.toArray diff --git a/src/Compiler/Service/ServiceXmlDocParser.fs b/src/Compiler/Service/ServiceXmlDocParser.fs index f76fcb16011..f0b137b4bb8 100644 --- a/src/Compiler/Service/ServiceXmlDocParser.fs +++ b/src/Compiler/Service/ServiceXmlDocParser.fs @@ -9,31 +9,30 @@ open FSharp.Compiler.Text.Range open FSharp.Compiler.Xml /// Represent an Xml documentation block in source code -type XmlDocable = - | XmlDocable of line:int * indent:int * paramNames:string list +type XmlDocable = XmlDocable of line: int * indent: int * paramNames: string list module XmlDocParsing = - - let (|ConstructorPats|) = function + + let (|ConstructorPats|) = + function | SynArgPats.Pats ps -> ps - | SynArgPats.NamePatPairs(pats=xs) -> List.map (fun (_, _, pat) -> pat) xs + | SynArgPats.NamePatPairs (pats = xs) -> List.map (fun (_, _, pat) -> pat) xs let rec digNamesFrom pat = match pat with - | SynPat.As (_, SynPat.Named(SynIdent(id,_),_isTheThisVar,_access,_range), _) - | SynPat.Named (SynIdent(id,_),_isTheThisVar,_access,_range) -> [id.idText] - | SynPat.Typed(pat,_type,_range) -> digNamesFrom pat - | SynPat.Attrib(pat,_attrs,_range) -> digNamesFrom pat - | SynPat.LongIdent(argPats=ConstructorPats pats) -> - pats |> List.collect digNamesFrom - | SynPat.Tuple(_,pats,_range) -> pats |> List.collect digNamesFrom - | SynPat.Paren(pat,_range) -> digNamesFrom pat - | SynPat.OptionalVal (id, _) -> [id.idText] - | SynPat.As _ // no one uses as in fun decls - | SynPat.Or _ // no one uses ors in fun decls - | SynPat.Ands _ // no one uses ands in fun decls - | SynPat.ArrayOrList _ // no one uses this in fun decls - | SynPat.Record _ // no one uses this in fun decls + | SynPat.As (_, SynPat.Named (SynIdent (id, _), _isTheThisVar, _access, _range), _) + | SynPat.Named (SynIdent (id, _), _isTheThisVar, _access, _range) -> [ id.idText ] + | SynPat.Typed (pat, _type, _range) -> digNamesFrom pat + | SynPat.Attrib (pat, _attrs, _range) -> digNamesFrom pat + | SynPat.LongIdent(argPats = ConstructorPats pats) -> pats |> List.collect digNamesFrom + | SynPat.Tuple (_, pats, _range) -> pats |> List.collect digNamesFrom + | SynPat.Paren (pat, _range) -> digNamesFrom pat + | SynPat.OptionalVal (id, _) -> [ id.idText ] + | SynPat.As _ // no one uses as in fun decls + | SynPat.Or _ // no one uses ors in fun decls + | SynPat.Ands _ // no one uses ands in fun decls + | SynPat.ArrayOrList _ // no one uses this in fun decls + | SynPat.Record _ // no one uses this in fun decls | SynPat.Null _ | SynPat.Const _ | SynPat.Wild _ @@ -43,113 +42,175 @@ module XmlDocParsing = | SynPat.InstanceMember _ | SynPat.FromParseError _ -> [] - let getXmlDocablesImpl(sourceText: ISourceText, input: ParsedInput) = + let getParamNames binding = + let (SynBinding (valData = synValData; headPat = synPat)) = binding + + match synValData with + | SynValData (_, SynValInfo (curriedArgs, _), _) when not curriedArgs.IsEmpty -> + let parameters = + [ + for args in curriedArgs do + for (SynArgInfo (_, _, ident)) in args do + match ident with + | Some ident -> ident.idText + | None -> () + ] + + match parameters with + | [] -> + let paramNames = digNamesFrom synPat + paramNames + | _ :: _ -> parameters + | _ -> [] + + let getXmlDocablesImpl (sourceText: ISourceText, input: ParsedInput) = let indentOf (lineNum: int) = let mutable i = 0 - let line = sourceText.GetLineString(lineNum-1) // -1 because lineNum reported by xmldocs are 1-based, but array is 0-based + // -1 because lineNum reported by xmldocs are 1-based, but array is 0-based + let line = sourceText.GetLineString(lineNum - 1) + while i < line.Length && line.Chars(i) = ' ' do i <- i + 1 + i - let isEmptyXmlDoc (preXmlDoc: PreXmlDoc) = - preXmlDoc.ToXmlDoc(false, None).IsEmpty + let isEmptyXmlDoc (preXmlDoc: PreXmlDoc) = preXmlDoc.ToXmlDoc(false, None).IsEmpty let rec getXmlDocablesSynModuleDecl decl = - match decl with - | SynModuleDecl.NestedModule(decls=synModuleDecls) -> - (synModuleDecls |> List.collect getXmlDocablesSynModuleDecl) - | SynModuleDecl.Let(_, synBindingList, range) -> - let anyXmlDoc = - synBindingList |> List.exists (fun (SynBinding(xmlDoc=preXmlDoc)) -> - not <| isEmptyXmlDoc preXmlDoc) - if anyXmlDoc then [] else - let synAttributes = - synBindingList |> List.collect (fun (SynBinding(attributes=a)) -> a) - let fullRange = synAttributes |> List.fold (fun r a -> unionRanges r a.Range) range - let line = fullRange.StartLine - let indent = indentOf line - [ for SynBinding(valData=synValData; headPat=synPat) in synBindingList do - match synValData with - | SynValData(_memberFlagsOpt, SynValInfo(args, _), _) when not (List.isEmpty args) -> - let parameters = - args - |> List.collect ( - List.collect (fun (SynArgInfo(_, _, ident)) -> - match ident with - | Some ident -> [ident.idText] - | None -> [])) - match parameters with - | [] -> - let paramNames = digNamesFrom synPat - yield! paramNames - | _ :: _ -> - yield! parameters - | _ -> () ] - |> fun paramNames -> [ XmlDocable(line,indent,paramNames) ] - | SynModuleDecl.Types(synTypeDefnList, _) -> (synTypeDefnList |> List.collect getXmlDocablesSynTypeDefn) - | SynModuleDecl.NamespaceFragment(synModuleOrNamespace) -> getXmlDocablesSynModuleOrNamespace synModuleOrNamespace - | SynModuleDecl.ModuleAbbrev _ - | SynModuleDecl.Expr _ - | SynModuleDecl.Exception _ - | SynModuleDecl.Open _ - | SynModuleDecl.Attributes _ - | SynModuleDecl.HashDirective _ -> [] - - and getXmlDocablesSynModuleOrNamespace (SynModuleOrNamespace(decls = synModuleDecls)) = - (synModuleDecls |> List.collect getXmlDocablesSynModuleDecl) - - and getXmlDocablesSynTypeDefn (SynTypeDefn(typeInfo=SynComponentInfo(attributes=synAttributes; xmlDoc=preXmlDoc; range=compRange); typeRepr=synTypeDefnRepr; members=synMemberDefns; range=tRange)) = - let stuff = + [ + match decl with + | SynModuleDecl.NestedModule (decls = decls) -> + for decl in decls do + yield! getXmlDocablesSynModuleDecl decl + | SynModuleDecl.Let (_, synBindingList, range) -> + let anyXmlDoc = + synBindingList + |> List.exists (fun (SynBinding (xmlDoc = preXmlDoc)) -> not (isEmptyXmlDoc preXmlDoc)) + + if not anyXmlDoc then + let synAttributes = + synBindingList |> List.collect (fun (SynBinding (attributes = a)) -> a) + + let fullRange = synAttributes |> List.fold (fun r a -> unionRanges r a.Range) range + let line = fullRange.StartLine + let indent = indentOf line + + let paramNames = + [ + for binding in synBindingList do + yield! getParamNames binding + ] + + yield XmlDocable(line, indent, paramNames) + | SynModuleDecl.Types (typeDefns, _) -> + for typeDefn in typeDefns do + yield! getXmlDocablesSynTypeDefn typeDefn + | SynModuleDecl.NamespaceFragment (synModuleOrNamespace) -> yield! getXmlDocablesSynModuleOrNamespace synModuleOrNamespace + | SynModuleDecl.ModuleAbbrev _ + | SynModuleDecl.Expr _ + | SynModuleDecl.Exception _ + | SynModuleDecl.Open _ + | SynModuleDecl.Attributes _ + | SynModuleDecl.HashDirective _ -> () + ] + + and getXmlDocablesSynModuleOrNamespace inp = + let (SynModuleOrNamespace (decls = decls)) = inp + decls |> List.collect getXmlDocablesSynModuleDecl + + and getXmlDocablesSynTypeDefn typeDefn = + let (SynTypeDefn (typeInfo = typeInfo; typeRepr = synTypeDefnRepr; members = synMemberDefns; range = tRange)) = + typeDefn + + let (SynComponentInfo (attributes = synAttributes; xmlDoc = preXmlDoc; range = compRange)) = + typeInfo + + [ match synTypeDefnRepr with - | SynTypeDefnRepr.ObjectModel(_, synMemberDefns, _) -> (synMemberDefns |> List.collect getXmlDocablesSynMemberDefn) - | SynTypeDefnRepr.Simple(_synTypeDefnSimpleRepr, _range) -> [] - | SynTypeDefnRepr.Exception _ -> [] - let docForTypeDefn = - if isEmptyXmlDoc preXmlDoc then - let fullRange = synAttributes |> List.fold (fun r a -> unionRanges r a.Range) (unionRanges compRange tRange) - let line = fullRange.StartLine - let indent = indentOf line - [XmlDocable(line,indent,[])] - else [] - docForTypeDefn @ stuff @ (synMemberDefns |> List.collect getXmlDocablesSynMemberDefn) + | SynTypeDefnRepr.ObjectModel (_, extraMemberDefns, _) -> + for extraMemberDefn in extraMemberDefns do + yield! getXmlDocablesSynMemberDefn extraMemberDefn + | SynTypeDefnRepr.Simple _ -> () + | SynTypeDefnRepr.Exception _ -> () - and getXmlDocablesSynMemberDefn = function - | SynMemberDefn.Member(SynBinding(attributes=synAttributes; xmlDoc=preXmlDoc; headPat=synPat), memRange) -> if isEmptyXmlDoc preXmlDoc then - let fullRange = synAttributes |> List.fold (fun r a -> unionRanges r a.Range) memRange - let line = fullRange.StartLine + let fullRange = + synAttributes + |> List.fold (fun r a -> unionRanges r a.Range) (unionRanges compRange tRange) + + let line = fullRange.StartLine let indent = indentOf line - let paramNames = digNamesFrom synPat - [XmlDocable(line,indent,paramNames)] - else [] - | SynMemberDefn.AbstractSlot(SynValSig(attributes=synAttributes; arity=synValInfo; xmlDoc=preXmlDoc), _, range) -> - if isEmptyXmlDoc preXmlDoc then + XmlDocable(line, indent, []) + for memberDefn in synMemberDefns do + yield! getXmlDocablesSynMemberDefn memberDefn + ] + + and getXmlDocablesSynMemberDefn inp = + [ + match inp with + | SynMemberDefn.Member (memberBinding, memRange) -> + let (SynBinding (attributes = synAttributes; xmlDoc = preXmlDoc; headPat = synPat)) = + memberBinding + + if isEmptyXmlDoc preXmlDoc then + let fullRange = + synAttributes |> List.fold (fun r a -> unionRanges r a.Range) memRange + + let line = fullRange.StartLine + let indent = indentOf line + let paramNames = digNamesFrom synPat + XmlDocable(line, indent, paramNames) + + | SynMemberDefn.GetSetMember (getBinding, setBinding, m, _) -> + yield! + getBinding + |> Option.map (fun b -> SynMemberDefn.Member(b, m)) + |> Option.toList + |> List.collect getXmlDocablesSynMemberDefn + + yield! + setBinding + |> Option.map (fun b -> SynMemberDefn.Member(b, m)) + |> Option.toList + |> List.collect getXmlDocablesSynMemberDefn + + | SynMemberDefn.AbstractSlot (valSig, _, range) -> + let (SynValSig (attributes = synAttributes; arity = synValInfo; xmlDoc = preXmlDoc)) = + valSig + + if isEmptyXmlDoc preXmlDoc then + let fullRange = synAttributes |> List.fold (fun r a -> unionRanges r a.Range) range + let line = fullRange.StartLine + let indent = indentOf line + let paramNames = synValInfo.ArgNames + XmlDocable(line, indent, paramNames) + + | SynMemberDefn.Interface (members = synMemberDefnsOption) -> + match synMemberDefnsOption with + | None -> () + | Some (xs) -> + for x in xs do + yield! getXmlDocablesSynMemberDefn x + + | SynMemberDefn.NestedType (synTypeDefn, _, _) -> yield! getXmlDocablesSynTypeDefn synTypeDefn + + | SynMemberDefn.AutoProperty (attributes = synAttributes; range = range) -> let fullRange = synAttributes |> List.fold (fun r a -> unionRanges r a.Range) range - let line = fullRange.StartLine + let line = fullRange.StartLine let indent = indentOf line - let paramNames = synValInfo.ArgNames - [XmlDocable(line,indent,paramNames)] - else [] - | SynMemberDefn.Interface(members=synMemberDefnsOption) -> - match synMemberDefnsOption with - | None -> [] - | Some(x) -> x |> List.collect getXmlDocablesSynMemberDefn - | SynMemberDefn.NestedType(synTypeDefn, _, _) -> getXmlDocablesSynTypeDefn synTypeDefn - | SynMemberDefn.AutoProperty(attributes=synAttributes; range=range) -> - let fullRange = synAttributes |> List.fold (fun r a -> unionRanges r a.Range) range - let line = fullRange.StartLine - let indent = indentOf line - [XmlDocable(line, indent, [])] - | SynMemberDefn.Open _ - | SynMemberDefn.ImplicitCtor _ - | SynMemberDefn.ImplicitInherit _ - | SynMemberDefn.Inherit _ - | SynMemberDefn.ValField _ - | SynMemberDefn.LetBindings _ -> [] + XmlDocable(line, indent, []) + + | SynMemberDefn.Open _ + | SynMemberDefn.ImplicitCtor _ + | SynMemberDefn.ImplicitInherit _ + | SynMemberDefn.Inherit _ + | SynMemberDefn.ValField _ + | SynMemberDefn.LetBindings _ -> () + ] and getXmlDocablesInput input = match input with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = symModules))-> + | ParsedInput.ImplFile (ParsedImplFileInput (modules = symModules)) -> symModules |> List.collect getXmlDocablesSynModuleOrNamespace | ParsedInput.SigFile _ -> [] @@ -157,24 +218,24 @@ module XmlDocParsing = getXmlDocablesInput input module XmlDocComment = - let ws (s: string, pos) = + let ws (s: string, pos) = let res = s.TrimStart() - Some (res, pos + (s.Length - res.Length)) + Some(res, pos + (s.Length - res.Length)) let str (prefix: string) (s: string, pos) = match s.StartsWithOrdinal(prefix) with - | true -> + | true -> let res = s.Substring prefix.Length - Some (res, pos + (s.Length - res.Length)) + Some(res, pos + (s.Length - res.Length)) | _ -> None - let eol (s: string, pos) = + let eol (s: string, pos) = match s with - | "" -> Some ("", pos) + | "" -> Some("", pos) | _ -> None let (>=>) f g = f >> Option.bind g - + // if it's a blank XML comment with trailing "<", returns Some (index of the "<"), otherwise returns None let IsBlank (s: string) = let parser = ws >=> str "///" >=> ws >=> str "<" >=> eol @@ -185,4 +246,4 @@ module XmlDocParser = /// Get the list of Xml documentation from current source code let GetXmlDocables (sourceText: ISourceText, input) = - XmlDocParsing.getXmlDocablesImpl (sourceText, input) \ No newline at end of file + XmlDocParsing.getXmlDocablesImpl (sourceText, input) diff --git a/src/Compiler/Service/service.fs b/src/Compiler/Service/service.fs index 47fb5591178..20fd5956c43 100644 --- a/src/Compiler/Service/service.fs +++ b/src/Compiler/Service/service.fs @@ -6,14 +6,16 @@ open System open System.Diagnostics open System.IO open System.Reflection +open System.Reflection.Emit open System.Threading open Internal.Utilities.Collections open Internal.Utilities.Library open Internal.Utilities.Library.Extras -open FSharp.Compiler +open FSharp.Compiler open FSharp.Compiler.AbstractIL open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader +open FSharp.Compiler.AbstractIL.ILDynamicAssemblyWriter open FSharp.Compiler.CodeAnalysis open FSharp.Compiler.CompilerConfig open FSharp.Compiler.CompilerDiagnostics @@ -31,7 +33,7 @@ open FSharp.Compiler.Syntax open FSharp.Compiler.Tokenization open FSharp.Compiler.Text open FSharp.Compiler.Text.Range -open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TcGlobals open FSharp.Compiler.BuildGraph [] @@ -40,241 +42,324 @@ module EnvMisc = let parseFileCacheSize = GetEnvInteger "FCS_ParseFileCacheSize" 2 let checkFileInProjectCacheSize = GetEnvInteger "FCS_CheckFileInProjectCacheSize" 10 - let projectCacheSizeDefault = GetEnvInteger "FCS_ProjectCacheSizeDefault" 3 + let projectCacheSizeDefault = GetEnvInteger "FCS_ProjectCacheSizeDefault" 3 let frameworkTcImportsCacheStrongSize = GetEnvInteger "FCS_frameworkTcImportsCacheStrongSizeDefault" 8 //---------------------------------------------------------------------------- // BackgroundCompiler // -/// Callback that indicates whether a requested result has become obsolete. -[] -type IsResultObsolete = - | IsResultObsolete of (unit->bool) - +/// Callback that indicates whether a requested result has become obsolete. +[] +type IsResultObsolete = IsResultObsolete of (unit -> bool) [] -module Helpers = +module Helpers = /// Determine whether two (fileName,options) keys are identical w.r.t. affect on checking - let AreSameForChecking2((fileName1: string, options1: FSharpProjectOptions), (fileName2, options2)) = - (fileName1 = fileName2) - && FSharpProjectOptions.AreSameForChecking(options1,options2) - - /// Determine whether two (fileName,options) keys should be identical w.r.t. resource usage - let AreSubsumable2((fileName1:string,o1:FSharpProjectOptions),(fileName2:string,o2:FSharpProjectOptions)) = + let AreSameForChecking2 ((fileName1: string, options1: FSharpProjectOptions), (fileName2, options2)) = (fileName1 = fileName2) - && FSharpProjectOptions.UseSameProject(o1,o2) + && FSharpProjectOptions.AreSameForChecking(options1, options2) + + /// Determine whether two (fileName,options) keys should be identical w.r.t. resource usage + let AreSubsumable2 ((fileName1: string, o1: FSharpProjectOptions), (fileName2: string, o2: FSharpProjectOptions)) = + (fileName1 = fileName2) && FSharpProjectOptions.UseSameProject(o1, o2) /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. parsing - let AreSameForParsing((fileName1: string, source1Hash: int64, options1), (fileName2, source2Hash, options2)) = + let AreSameForParsing ((fileName1: string, source1Hash: int64, options1), (fileName2, source2Hash, options2)) = fileName1 = fileName2 && options1 = options2 && source1Hash = source2Hash - let AreSimilarForParsing((fileName1, _, _), (fileName2, _, _)) = - fileName1 = fileName2 - + let AreSimilarForParsing ((fileName1, _, _), (fileName2, _, _)) = fileName1 = fileName2 + /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. checking - let AreSameForChecking3((fileName1: string, source1Hash: int64, options1: FSharpProjectOptions), (fileName2, source2Hash, options2)) = - (fileName1 = fileName2) - && FSharpProjectOptions.AreSameForChecking(options1,options2) + let AreSameForChecking3 ((fileName1: string, source1Hash: int64, options1: FSharpProjectOptions), (fileName2, source2Hash, options2)) = + (fileName1 = fileName2) + && FSharpProjectOptions.AreSameForChecking(options1, options2) && source1Hash = source2Hash /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. resource usage - let AreSubsumable3((fileName1:string,_,o1:FSharpProjectOptions),(fileName2:string,_,o2:FSharpProjectOptions)) = - (fileName1 = fileName2) - && FSharpProjectOptions.UseSameProject(o1,o2) + let AreSubsumable3 ((fileName1: string, _, o1: FSharpProjectOptions), (fileName2: string, _, o2: FSharpProjectOptions)) = + (fileName1 = fileName2) && FSharpProjectOptions.UseSameProject(o1, o2) module CompileHelpers = - let mkCompilationDiagnosticsHandlers() = + let mkCompilationDiagnosticsHandlers () = let diagnostics = ResizeArray<_>() - let diagnosticSink isError exn = + let diagnosticSink isError exn = let main, related = SplitRelatedDiagnostics exn - let oneDiagnostic e = diagnostics.Add(FSharpDiagnostic.CreateFromException (e, isError, range0, true)) // Suggest names for errors + + let oneDiagnostic e = + diagnostics.Add(FSharpDiagnostic.CreateFromException(e, isError, range0, true)) // Suggest names for errors + oneDiagnostic main List.iter oneDiagnostic related - let diagnosticsLogger = - { new DiagnosticsLogger("CompileAPI") with - + let diagnosticsLogger = + { new DiagnosticsLogger("CompileAPI") with + member _.DiagnosticSink(exn, isError) = diagnosticSink isError exn member _.ErrorCount = diagnostics |> Seq.filter (fun diagnostic -> diagnostic.Severity = FSharpDiagnosticSeverity.Error) - |> Seq.length } + |> Seq.length + } + + let loggerProvider = + { new DiagnosticsLoggerProvider() with + member _.CreateDiagnosticsLoggerUpToMaxErrors(_tcConfigBuilder, _exiter) = diagnosticsLogger + } - let loggerProvider = - { new DiagnosticsLoggerProvider() with - member _.CreateDiagnosticsLoggerUpToMaxErrors(_tcConfigBuilder, _exiter) = diagnosticsLogger } diagnostics, diagnosticsLogger, loggerProvider - let tryCompile diagnosticsLogger f = - use unwindParsePhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse - use unwindEL_2 = PushDiagnosticsLoggerPhaseUntilUnwind (fun _ -> diagnosticsLogger) - let exiter = { new Exiter with member x.Exit n = raise StopProcessing } - try + let tryCompile diagnosticsLogger f = + use unwindParsePhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse + use unwindEL_2 = PushDiagnosticsLoggerPhaseUntilUnwind(fun _ -> diagnosticsLogger) + + let exiter = + { new Exiter with + member x.Exit n = raise StopProcessing + } + + try f exiter 0 - with e -> + with e -> stopProcessingRecovery e range0 1 - /// Compile using the given flags. Source files names are resolved via the FileSystem API. The output file must be given by a -o flag. - let compileFromArgs (ctok, argv: string[], legacyReferenceResolver, tcImportsCapture, dynamicAssemblyCreator) = - - let diagnostics, diagnosticsLogger, loggerProvider = mkCompilationDiagnosticsHandlers() - let result = - tryCompile diagnosticsLogger (fun exiter -> - CompileFromCommandLineArguments (ctok, argv, legacyReferenceResolver, (*bannerAlreadyPrinted*)true, ReduceMemoryFlag.Yes, CopyFSharpCoreFlag.No, exiter, loggerProvider, tcImportsCapture, dynamicAssemblyCreator) ) - + /// Compile using the given flags. Source files names are resolved via the FileSystem API. The output file must be given by a -o flag. + let compileFromArgs (ctok, argv: string[], legacyReferenceResolver, tcImportsCapture, dynamicAssemblyCreator) = + + let diagnostics, diagnosticsLogger, loggerProvider = mkCompilationDiagnosticsHandlers () + + let result = + tryCompile diagnosticsLogger (fun exiter -> + CompileFromCommandLineArguments( + ctok, + argv, + legacyReferenceResolver, + true, + ReduceMemoryFlag.Yes, + CopyFSharpCoreFlag.No, + exiter, + loggerProvider, + tcImportsCapture, + dynamicAssemblyCreator + )) + diagnostics.ToArray(), result - let compileFromAsts (ctok, legacyReferenceResolver, asts, assemblyName, outFile, dependencies, noframework, pdbFile, executable, tcImportsCapture, dynamicAssemblyCreator) = + let compileFromAsts + ( + ctok, + legacyReferenceResolver, + asts, + assemblyName, + outFile, + dependencies, + noframework, + pdbFile, + executable, + tcImportsCapture, + dynamicAssemblyCreator + ) = + + let diagnostics, diagnosticsLogger, loggerProvider = mkCompilationDiagnosticsHandlers () - let diagnostics, diagnosticsLogger, loggerProvider = mkCompilationDiagnosticsHandlers() - let executable = defaultArg executable true - let target = if executable then CompilerTarget.ConsoleExe else CompilerTarget.Dll - - let result = - tryCompile diagnosticsLogger (fun exiter -> - CompileFromSyntaxTrees (ctok, legacyReferenceResolver, ReduceMemoryFlag.Yes, assemblyName, target, outFile, pdbFile, dependencies, noframework, exiter, loggerProvider, asts, tcImportsCapture, dynamicAssemblyCreator)) + + let target = + if executable then + CompilerTarget.ConsoleExe + else + CompilerTarget.Dll + + let result = + tryCompile diagnosticsLogger (fun exiter -> + CompileFromSyntaxTrees( + ctok, + legacyReferenceResolver, + ReduceMemoryFlag.Yes, + assemblyName, + target, + outFile, + pdbFile, + dependencies, + noframework, + exiter, + loggerProvider, + asts, + tcImportsCapture, + dynamicAssemblyCreator + )) diagnostics.ToArray(), result - let createDynamicAssembly (debugInfo: bool, tcImportsRef: TcImports option ref, execute: bool, assemblyBuilderRef: _ option ref) (tcConfig: TcConfig, tcGlobals:TcGlobals, outfile, ilxMainModule) = + let createDynamicAssembly + (debugInfo: bool, tcImportsRef: TcImports option ref, execute: bool, assemblyBuilderRef: _ option ref) + (tcConfig: TcConfig, tcGlobals: TcGlobals, outfile, ilxMainModule) + = // Create an assembly builder let assemblyName = AssemblyName(Path.GetFileNameWithoutExtension outfile) - let flags = System.Reflection.Emit.AssemblyBuilderAccess.Run + let flags = AssemblyBuilderAccess.Run #if FX_NO_APP_DOMAINS let assemblyBuilder = System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(assemblyName, flags) let moduleBuilder = assemblyBuilder.DefineDynamicModule("IncrementalModule") #else let assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, flags) let moduleBuilder = assemblyBuilder.DefineDynamicModule("IncrementalModule", debugInfo) -#endif - // Omit resources in dynamic assemblies, because the module builder is constructed without a file name the module +#endif + // Omit resources in dynamic assemblies, because the module builder is constructed without a file name the module // is tagged as transient and as such DefineManifestResource will throw an invalid operation if resources are present. - // + // // Also, the dynamic assembly creator can't currently handle types called "" from statically linked assemblies. - let ilxMainModule = - { ilxMainModule with - TypeDefs = ilxMainModule.TypeDefs.AsList() |> List.filter (fun td -> not (isTypeNameForGlobalFunctions td.Name)) |> mkILTypeDefs - Resources=mkILResources [] } + let ilxMainModule = + { ilxMainModule with + TypeDefs = + ilxMainModule.TypeDefs.AsList() + |> List.filter (fun td -> not (isTypeNameForGlobalFunctions td.Name)) + |> mkILTypeDefs + Resources = mkILResources [] + } // The function used to resolve types while emitting the code - let assemblyResolver s = - match tcImportsRef.Value.Value.TryFindExistingFullyQualifiedPathByExactAssemblyRef s with - | Some res -> Some (Choice1Of2 res) + let assemblyResolver s = + match tcImportsRef.Value.Value.TryFindExistingFullyQualifiedPathByExactAssemblyRef s with + | Some res -> Some(Choice1Of2 res) | None -> None // Emit the code - let _emEnv,execs = ILDynamicAssemblyWriter.EmitDynamicAssemblyFragment(tcGlobals.ilg, tcConfig.emitTailcalls, ILDynamicAssemblyWriter.emEnv0, assemblyBuilder, moduleBuilder, ilxMainModule, debugInfo, assemblyResolver, tcGlobals.TryFindSysILTypeRef) + let _emEnv, execs = + EmitDynamicAssemblyFragment( + tcGlobals.ilg, + tcConfig.emitTailcalls, + emEnv0, + assemblyBuilder, + moduleBuilder, + ilxMainModule, + debugInfo, + assemblyResolver, + tcGlobals.TryFindSysILTypeRef + ) // Execute the top-level initialization, if requested - if execute then - for exec in execs do - match exec() with + if execute then + for exec in execs do + match exec () with | None -> () - | Some exn -> + | Some exn -> PreserveStackTrace exn raise exn // Register the reflected definitions for the dynamically generated assembly - for resource in ilxMainModule.Resources.AsList() do - if IsReflectedDefinitionsResource resource then - Quotations.Expr.RegisterReflectedDefinitions (assemblyBuilder, moduleBuilder.Name, resource.GetBytes().ToArray()) + for resource in ilxMainModule.Resources.AsList() do + if IsReflectedDefinitionsResource resource then + Quotations.Expr.RegisterReflectedDefinitions(assemblyBuilder, moduleBuilder.Name, resource.GetBytes().ToArray()) // Save the result assemblyBuilderRef.Value <- Some assemblyBuilder - - let setOutputStreams execute = + + let setOutputStreams execute = // Set the output streams, if requested match execute with - | Some (writer,error) -> + | Some (writer, error) -> Console.SetOut writer Console.SetError error | None -> () type SourceTextHash = int64 type CacheStamp = int64 -type FileName = string +type FileName = string type FilePath = string type ProjectPath = string type FileVersion = int -type ParseCacheLockToken() = interface LockToken -type ScriptClosureCacheToken() = interface LockToken +type ParseCacheLockToken() = + interface LockToken + +type ScriptClosureCacheToken() = + interface LockToken type CheckFileCacheKey = FileName * SourceTextHash * FSharpProjectOptions type CheckFileCacheValue = FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash * DateTime // There is only one instance of this type, held in FSharpChecker -type BackgroundCompiler( - legacyReferenceResolver, - projectCacheSize, - keepAssemblyContents, - keepAllBackgroundResolutions, - tryGetMetadataSnapshot, - suggestNamesForErrors, - keepAllBackgroundSymbolUses, - enableBackgroundItemKeyStoreAndSemanticClassification, - enablePartialTypeChecking) as self = +type BackgroundCompiler + ( + legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking + ) as self = let beforeFileChecked = Event() let fileParsed = Event() let fileChecked = Event() let projectChecked = Event() - // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.scriptClosureCache + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.scriptClosureCache /// Information about the derived script closure. - let scriptClosureCache = - MruCache(projectCacheSize, - areSame=FSharpProjectOptions.AreSameForChecking, - areSimilar=FSharpProjectOptions.UseSameProject) + let scriptClosureCache = + MruCache( + projectCacheSize, + areSame = FSharpProjectOptions.AreSameForChecking, + areSimilar = FSharpProjectOptions.UseSameProject + ) let frameworkTcImportsCache = FrameworkImportsCache(frameworkTcImportsCacheStrongSize) // We currently share one global dependency provider for all scripts for the FSharpChecker. // For projects, one is used per project. - // + // // Sharing one for all scripts is necessary for good performance from GetProjectOptionsFromScript, // which requires a dependency provider to process through the project options prior to working out // if the cached incremental builder can be used for the project. let dependencyProviderForScripts = new DependencyProvider() - /// CreateOneIncrementalBuilder (for background type checking). Note that fsc.fs also - /// creates an incremental builder used by the command line compiler. - let CreateOneIncrementalBuilder (options:FSharpProjectOptions, userOpName) = - node { - Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "CreateOneIncrementalBuilder", options.ProjectFileName) - let projectReferences = - [ for r in options.ReferencedProjects do - - match r with - | FSharpReferencedProject.FSharpReference(nm,opts) -> - // Don't use cross-project references for FSharp.Core, since various bits of code require a concrete FSharp.Core to exist on-disk. - // The only solutions that have these cross-project references to FSharp.Core are VisualFSharp.sln and FSharp.sln. The only ramification - // of this is that you need to build FSharp.Core to get intellisense in those projects. - - if (try Path.GetFileNameWithoutExtension(nm) with _ -> "") <> GetFSharpCoreLibraryName() then - { new IProjectReference with - member x.EvaluateRawContents() = - node { - Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "GetAssemblyData", nm) - return! self.GetAssemblyData(opts, userOpName + ".CheckReferencedProject("+nm+")") - } - member x.TryGetLogicalTimeStamp(cache) = + let getProjectReferences (options: FSharpProjectOptions) userOpName = + [ + for r in options.ReferencedProjects do + + match r with + | FSharpReferencedProject.FSharpReference (nm, opts) -> + // Don't use cross-project references for FSharp.Core, since various bits of code + // require a concrete FSharp.Core to exist on-disk. The only solutions that have + // these cross-project references to FSharp.Core are VisualFSharp.sln and FSharp.sln. The ramification + // of this is that you need to build FSharp.Core to get intellisense in those projects. + + if + (try + Path.GetFileNameWithoutExtension(nm) + with _ -> + "") + <> GetFSharpCoreLibraryName() + then + { new IProjectReference with + member x.EvaluateRawContents() = + node { + Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "GetAssemblyData", nm) + return! self.GetAssemblyData(opts, userOpName + ".CheckReferencedProject(" + nm + ")") + } + + member x.TryGetLogicalTimeStamp(cache) = self.TryGetLogicalTimeStampForProject(cache, opts) - member x.FileName = nm } - - | FSharpReferencedProject.PEReference(nm,getStamp,delayedReader) -> - { new IProjectReference with - member x.EvaluateRawContents() = - node { + + member x.FileName = nm + } + + | FSharpReferencedProject.PEReference (nm, getStamp, delayedReader) -> + { new IProjectReference with + member x.EvaluateRawContents() = + node { let! ilReaderOpt = delayedReader.TryGetILModuleReader() |> NodeCode.FromCancellable + match ilReaderOpt with | Some ilReader -> let ilModuleDef, ilAsmRefs = ilReader.ILModuleDef, ilReader.ILAssemblyRefs @@ -284,72 +369,91 @@ type BackgroundCompiler( // Note 'false' - if a PEReference doesn't find an ILModuleReader then we don't // continue to try to use an on-disk DLL return ProjectAssemblyDataResult.Unavailable false - } - member x.TryGetLogicalTimeStamp _ = getStamp() |> Some - member x.FileName = nm } - - | FSharpReferencedProject.ILModuleReference(nm,getStamp,getReader) -> - { new IProjectReference with - member x.EvaluateRawContents() = - node { - let ilReader = getReader() + } + + member x.TryGetLogicalTimeStamp _ = getStamp () |> Some + member x.FileName = nm + } + + | FSharpReferencedProject.ILModuleReference (nm, getStamp, getReader) -> + { new IProjectReference with + member x.EvaluateRawContents() = + node { + let ilReader = getReader () let ilModuleDef, ilAsmRefs = ilReader.ILModuleDef, ilReader.ILAssemblyRefs let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData return ProjectAssemblyDataResult.Available data - } - member x.TryGetLogicalTimeStamp _ = getStamp() |> Some - member x.FileName = nm } - ] + } - let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options) + member x.TryGetLogicalTimeStamp _ = getStamp () |> Some + member x.FileName = nm + } + ] - let! builderOpt, diagnostics = - IncrementalBuilder.TryCreateIncrementalBuilderForProjectOptions ( - legacyReferenceResolver, - FSharpCheckerResultsSettings.defaultFSharpBinariesDir, - frameworkTcImportsCache, - loadClosure, - Array.toList options.SourceFiles, - Array.toList options.OtherOptions, - projectReferences, - options.ProjectDirectory, - options.UseScriptResolutionRules, - keepAssemblyContents, - keepAllBackgroundResolutions, - tryGetMetadataSnapshot, - suggestNamesForErrors, - keepAllBackgroundSymbolUses, - enableBackgroundItemKeyStoreAndSemanticClassification, - enablePartialTypeChecking, - (if options.UseScriptResolutionRules then Some dependencyProviderForScripts else None)) - - match builderOpt with - | None -> () - | Some builder -> + /// CreateOneIncrementalBuilder (for background type checking). Note that fsc.fs also + /// creates an incremental builder used by the command line compiler. + let CreateOneIncrementalBuilder (options: FSharpProjectOptions, userOpName) = + node { + Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "CreateOneIncrementalBuilder", options.ProjectFileName) + let projectReferences = getProjectReferences options userOpName + + let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options) + + let dependencyProvider = + if options.UseScriptResolutionRules then + Some dependencyProviderForScripts + else + None + + let! builderOpt, diagnostics = + IncrementalBuilder.TryCreateIncrementalBuilderForProjectOptions( + legacyReferenceResolver, + FSharpCheckerResultsSettings.defaultFSharpBinariesDir, + frameworkTcImportsCache, + loadClosure, + Array.toList options.SourceFiles, + Array.toList options.OtherOptions, + projectReferences, + options.ProjectDirectory, + options.UseScriptResolutionRules, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking, + dependencyProvider + ) + + match builderOpt with + | None -> () + | Some builder -> #if !NO_TYPEPROVIDERS - // Register the behaviour that responds to CCUs being invalidated because of type - // provider Invalidate events. This invalidates the configuration in the build. - builder.ImportsInvalidatedByTypeProvider.Add(fun () -> self.InvalidateConfiguration(options, userOpName)) + // Register the behaviour that responds to CCUs being invalidated because of type + // provider Invalidate events. This invalidates the configuration in the build. + builder.ImportsInvalidatedByTypeProvider.Add(fun () -> self.InvalidateConfiguration(options, userOpName)) #endif - // Register the callback called just before a file is typechecked by the background builder (without recording - // errors or intellisense information). - // - // This indicates to the UI that the file type check state is dirty. If the file is open and visible then - // the UI will sooner or later request a typecheck of the file, recording errors and intellisense information. - builder.BeforeFileChecked.Add (fun file -> beforeFileChecked.Trigger(file, options)) - builder.FileParsed.Add (fun file -> fileParsed.Trigger(file, options)) - builder.FileChecked.Add (fun file -> fileChecked.Trigger(file, options)) - builder.ProjectChecked.Add (fun () -> projectChecked.Trigger options) - - return (builderOpt, diagnostics) - } + // Register the callback called just before a file is typechecked by the background builder (without recording + // errors or intellisense information). + // + // This indicates to the UI that the file type check state is dirty. If the file is open and visible then + // the UI will sooner or later request a typecheck of the file, recording errors and intellisense information. + builder.BeforeFileChecked.Add(fun file -> beforeFileChecked.Trigger(file, options)) + builder.FileParsed.Add(fun file -> fileParsed.Trigger(file, options)) + builder.FileChecked.Add(fun file -> fileChecked.Trigger(file, options)) + builder.ProjectChecked.Add(fun () -> projectChecked.Trigger options) + + return (builderOpt, diagnostics) + } let parseCacheLock = Lock() - + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.parseFileInProjectCache. Most recently used cache for parsing files. - let parseFileCache = MruCache(parseFileCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing) + let parseFileCache = + MruCache(parseFileCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing) // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.checkFileInProjectCache // @@ -360,36 +464,39 @@ type BackgroundCompiler( // Also keyed on source. This can only be out of date if the antecedent is out of date let checkFileInProjectCache = - MruCache> - (keepStrongly=checkFileInProjectCacheSize, - areSame=AreSameForChecking3, - areSimilar=AreSubsumable3) + MruCache>( + keepStrongly = checkFileInProjectCacheSize, + areSame = AreSameForChecking3, + areSimilar = AreSubsumable3 + ) - // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.incrementalBuildersCache. This root typically holds more + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.incrementalBuildersCache. This root typically holds more // live information than anything else in the F# Language Service, since it holds up to 3 (projectCacheStrongSize) background project builds // strongly. - // - /// Cache of builds keyed by options. - let gate = obj() - let incrementalBuildersCache = - MruCache> - (keepStrongly=projectCacheSize, keepMax=projectCacheSize, - areSame = FSharpProjectOptions.AreSameForChecking, - areSimilar = FSharpProjectOptions.UseSameProject) + // + /// Cache of builds keyed by options. + let gate = obj () + + let incrementalBuildersCache = + MruCache>( + keepStrongly = projectCacheSize, + keepMax = projectCacheSize, + areSame = FSharpProjectOptions.AreSameForChecking, + areSimilar = FSharpProjectOptions.UseSameProject + ) let tryGetBuilderNode options = - incrementalBuildersCache.TryGet (AnyCallerThread, options) + incrementalBuildersCache.TryGet(AnyCallerThread, options) let tryGetBuilder options : NodeCode option = - tryGetBuilderNode options - |> Option.map (fun x -> x.GetOrComputeValue()) + tryGetBuilderNode options |> Option.map (fun x -> x.GetOrComputeValue()) let tryGetSimilarBuilder options : NodeCode option = - incrementalBuildersCache.TryGetSimilar (AnyCallerThread, options) + incrementalBuildersCache.TryGetSimilar(AnyCallerThread, options) |> Option.map (fun x -> x.GetOrComputeValue()) let tryGetAnyBuilder options : NodeCode option = - incrementalBuildersCache.TryGetAny (AnyCallerThread, options) + incrementalBuildersCache.TryGetAny(AnyCallerThread, options) |> Option.map (fun x -> x.GetOrComputeValue()) let createBuilderNode (options, userOpName, ct: CancellationToken) = @@ -397,11 +504,9 @@ type BackgroundCompiler( if ct.IsCancellationRequested then GraphNode(node.Return(None, [||])) else - let getBuilderNode = - GraphNode(CreateOneIncrementalBuilder(options, userOpName)) - incrementalBuildersCache.Set (AnyCallerThread, options, getBuilderNode) - getBuilderNode - ) + let getBuilderNode = GraphNode(CreateOneIncrementalBuilder(options, userOpName)) + incrementalBuildersCache.Set(AnyCallerThread, options, getBuilderNode) + getBuilderNode) let createAndGetBuilder (options, userOpName) = node { @@ -412,28 +517,26 @@ type BackgroundCompiler( let getOrCreateBuilder (options, userOpName) : NodeCode = match tryGetBuilder options with - | Some getBuilder -> + | Some getBuilder -> node { match! getBuilder with - | builderOpt, creationDiags when builderOpt.IsNone || not builderOpt.Value.IsReferencesInvalidated -> + | builderOpt, creationDiags when builderOpt.IsNone || not builderOpt.Value.IsReferencesInvalidated -> Logger.Log LogCompilerFunctionId.Service_IncrementalBuildersCache_GettingCache - return builderOpt,creationDiags + return builderOpt, creationDiags | _ -> // The builder could be re-created, // clear the check file caches that are associated with it. // We must do this in order to not return stale results when references // in the project get changed/added/removed. - parseCacheLock.AcquireLock(fun ltok -> + parseCacheLock.AcquireLock(fun ltok -> options.SourceFiles |> Array.iter (fun sourceFile -> let key = (sourceFile, 0L, options) - checkFileInProjectCache.RemoveAnySimilar(ltok, key) - ) - ) + checkFileInProjectCache.RemoveAnySimilar(ltok, key))) + return! createAndGetBuilder (options, userOpName) } - | _ -> - createAndGetBuilder (options, userOpName) + | _ -> createAndGetBuilder (options, userOpName) let getSimilarOrCreateBuilder (options, userOpName) = match tryGetSimilarBuilder options with @@ -449,81 +552,86 @@ type BackgroundCompiler( let getAnyBuilder (options, userOpName) = match tryGetAnyBuilder options with - | Some getBuilder -> + | Some getBuilder -> Logger.Log LogCompilerFunctionId.Service_IncrementalBuildersCache_GettingCache getBuilder - | _ -> - getOrCreateBuilder (options, userOpName) + | _ -> getOrCreateBuilder (options, userOpName) + + static let mutable actualParseFileCount = 0 + + static let mutable actualCheckFileCount = 0 /// Should be a fast operation. Ensures that we have only one async lazy object per file and its hash. - let getCheckFileNode (parseResults, - sourceText, - fileName, - options, - _fileVersion, - builder, - tcPrior, - tcInfo, - creationDiags) onComplete = + let getCheckFileNode (parseResults, sourceText, fileName, options, _fileVersion, builder, tcPrior, tcInfo, creationDiags) = // Here we lock for the creation of the node, not its execution - parseCacheLock.AcquireLock (fun ltok -> + parseCacheLock.AcquireLock(fun ltok -> let key = (fileName, sourceText.GetHashCode() |> int64, options) + match checkFileInProjectCache.TryGet(ltok, key) with | Some res -> res | _ -> let res = - GraphNode(node { - let! res = - self.CheckOneFileImplAux( - parseResults, - sourceText, - fileName, - options, - builder, - tcPrior, - tcInfo, - creationDiags) - onComplete() - return res - }) - checkFileInProjectCache.Set(ltok, key, res) - res - ) - - static let mutable actualParseFileCount = 0 + GraphNode( + node { + let! res = self.CheckOneFileImplAux(parseResults, sourceText, fileName, options, builder, tcPrior, tcInfo, creationDiags) + Interlocked.Increment(&actualCheckFileCount) |> ignore + return res + } + ) - static let mutable actualCheckFileCount = 0 + checkFileInProjectCache.Set(ltok, key, res) + res) member _.ParseFile(fileName: string, sourceText: ISourceText, options: FSharpParsingOptions, cache: bool, userOpName: string) = async { - if cache then - let hash = sourceText.GetHashCode() |> int64 - match parseCacheLock.AcquireLock(fun ltok -> parseFileCache.TryGet(ltok, (fileName, hash, options))) with - | Some res -> return res - | None -> - Interlocked.Increment(&actualParseFileCount) |> ignore - let parseDiags, parseTree, anyErrors = ParseAndCheckFile.parseFile(sourceText, fileName, options, userOpName, suggestNamesForErrors) - let res = FSharpParseFileResults(parseDiags, parseTree, anyErrors, options.SourceFiles) - parseCacheLock.AcquireLock(fun ltok -> parseFileCache.Set(ltok, (fileName, hash, options), res)) - return res - else - let parseDiags, parseTree, anyErrors = ParseAndCheckFile.parseFile(sourceText, fileName, options, userOpName, false) - return FSharpParseFileResults(parseDiags, parseTree, anyErrors, options.SourceFiles) + if cache then + let hash = sourceText.GetHashCode() |> int64 + + match parseCacheLock.AcquireLock(fun ltok -> parseFileCache.TryGet(ltok, (fileName, hash, options))) with + | Some res -> return res + | None -> + Interlocked.Increment(&actualParseFileCount) |> ignore + + let parseDiagnostics, parseTree, anyErrors = + ParseAndCheckFile.parseFile (sourceText, fileName, options, userOpName, suggestNamesForErrors) + + let res = FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, options.SourceFiles) + parseCacheLock.AcquireLock(fun ltok -> parseFileCache.Set(ltok, (fileName, hash, options), res)) + return res + else + let parseDiagnostics, parseTree, anyErrors = + ParseAndCheckFile.parseFile (sourceText, fileName, options, userOpName, false) + + return FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, options.SourceFiles) } /// Fetch the parse information from the background compiler (which checks w.r.t. the FileSystem API) member _.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName) = node { let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + match builderOpt with | None -> let parseTree = EmptyParsedInput(fileName, (false, false)) - return FSharpParseFileResults(creationDiags, parseTree, true, [| |]) - | Some builder -> - let parseTree,_,_,parseDiags = builder.GetParseResultsForFile fileName - let diagnostics = [| yield! creationDiags; yield! DiagnosticHelpers.CreateDiagnostics (builder.TcConfig.diagnosticsOptions, false, fileName, parseDiags, suggestNamesForErrors) |] - return FSharpParseFileResults(diagnostics = diagnostics, input = parseTree, parseHadErrors = false, dependencyFiles = builder.AllDependenciesDeprecated) + return FSharpParseFileResults(creationDiags, parseTree, true, [||]) + | Some builder -> + let parseTree, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName + + let parseDiagnostics = + DiagnosticHelpers.CreateDiagnostics(builder.TcConfig.diagnosticsOptions, false, fileName, parseDiagnostics, suggestNamesForErrors) + + let diagnostics = [| yield! creationDiags; yield! parseDiagnostics |] + + let parseResults = + FSharpParseFileResults( + diagnostics = diagnostics, + input = parseTree, + parseHadErrors = false, + dependencyFiles = builder.AllDependenciesDeprecated + ) + + return parseResults } member _.GetCachedCheckFileResult(builder: IncrementalBuilder, fileName, sourceText: ISourceText, options) = @@ -535,30 +643,31 @@ type BackgroundCompiler( match cachedResultsOpt with | Some cachedResults -> match! cachedResults.GetOrComputeValue() with - | parseResults, checkResults,_,priorTimeStamp - when - (match builder.GetCheckResultsBeforeFileInProjectEvenIfStale fileName with - | None -> false - | Some(tcPrior) -> - tcPrior.ProjectTimeStamp = priorTimeStamp && - builder.AreCheckResultsBeforeFileInProjectReady(fileName)) -> - return Some (parseResults,checkResults) + | parseResults, checkResults, _, priorTimeStamp when + (match builder.GetCheckResultsBeforeFileInProjectEvenIfStale fileName with + | None -> false + | Some (tcPrior) -> + tcPrior.ProjectTimeStamp = priorTimeStamp + && builder.AreCheckResultsBeforeFileInProjectReady(fileName)) + -> + return Some(parseResults, checkResults) | _ -> parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.RemoveAnySimilar(ltok, key)) return None - | _ -> - return None + | _ -> return None } member private _.CheckOneFileImplAux - (parseResults: FSharpParseFileResults, - sourceText: ISourceText, - fileName: string, - options: FSharpProjectOptions, - builder: IncrementalBuilder, - tcPrior: PartialCheckResults, - tcInfo: TcInfo, - creationDiags: FSharpDiagnostic[]) : NodeCode = + ( + parseResults: FSharpParseFileResults, + sourceText: ISourceText, + fileName: string, + options: FSharpProjectOptions, + builder: IncrementalBuilder, + tcPrior: PartialCheckResults, + tcInfo: TcInfo, + creationDiags: FSharpDiagnostic[] + ) : NodeCode = node { // Get additional script #load closure information if applicable. @@ -566,97 +675,107 @@ type BackgroundCompiler( let tcConfig = tcPrior.TcConfig let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options) - let! checkAnswer = - FSharpCheckFileResults.CheckOneFile ( + let! checkAnswer = + FSharpCheckFileResults.CheckOneFile( parseResults, sourceText, fileName, - options.ProjectFileName, + options.ProjectFileName, tcConfig, tcPrior.TcGlobals, - tcPrior.TcImports, + tcPrior.TcImports, tcInfo.tcState, tcInfo.moduleNamesDict, loadClosure, tcInfo.TcDiagnostics, - options.IsIncompleteTypeCheckEnvironment, - options, - builder, - Array.ofList tcInfo.tcDependencyFiles, - creationDiags, - parseResults.Diagnostics, + options.IsIncompleteTypeCheckEnvironment, + options, + builder, + Array.ofList tcInfo.tcDependencyFiles, + creationDiags, + parseResults.Diagnostics, keepAssemblyContents, - suggestNamesForErrors) + suggestNamesForErrors + ) |> NodeCode.FromCancellable + GraphNode.SetPreferredUILang tcConfig.preferredUiLang return (parseResults, checkAnswer, sourceText.GetHashCode() |> int64, tcPrior.ProjectTimeStamp) } - member private bc.CheckOneFileImpl - (parseResults: FSharpParseFileResults, - sourceText: ISourceText, - fileName: string, - options: FSharpProjectOptions, - fileVersion: int, - builder: IncrementalBuilder, - tcPrior: PartialCheckResults, - tcInfo: TcInfo, - creationDiags: FSharpDiagnostic[]) = - - node { + ( + parseResults: FSharpParseFileResults, + sourceText: ISourceText, + fileName: string, + options: FSharpProjectOptions, + fileVersion: int, + builder: IncrementalBuilder, + tcPrior: PartialCheckResults, + tcInfo: TcInfo, + creationDiags: FSharpDiagnostic[] + ) = + + node { match! bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) with | Some (_, results) -> return FSharpCheckFileAnswer.Succeeded results | _ -> let lazyCheckFile = - getCheckFileNode - (parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) - (fun () -> - Interlocked.Increment(&actualCheckFileCount) |> ignore - ) + getCheckFileNode (parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) let! _, results, _, _ = lazyCheckFile.GetOrComputeValue() return FSharpCheckFileAnswer.Succeeded results - } + } - /// 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) = + /// 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 + ) = node { - let! cachedResults = + let! cachedResults = node { - let! builderOpt, creationDiags = getAnyBuilder (options, userOpName) + let! builderOpt, creationDiags = getAnyBuilder (options, userOpName) match builderOpt with | Some builder -> match! bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) with - | Some (_, checkResults) -> return Some (builder, creationDiags, Some (FSharpCheckFileAnswer.Succeeded checkResults)) - | _ -> return Some (builder, creationDiags, None) + | Some (_, checkResults) -> return Some(builder, creationDiags, Some(FSharpCheckFileAnswer.Succeeded checkResults)) + | _ -> return Some(builder, creationDiags, None) | _ -> return None // the builder wasn't ready } - + match cachedResults with | None -> return None | Some (_, _, Some x) -> return Some x | Some (builder, creationDiags, None) -> Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "CheckFileInProjectAllowingStaleCachedResults.CacheMiss", fileName) + match builder.GetCheckResultsBeforeFileInProjectEvenIfStale fileName with - | Some tcPrior -> + | Some tcPrior -> match tcPrior.TryPeekTcInfo() with - | Some tcInfo -> - let! checkResults = bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) + | Some tcInfo -> + let! checkResults = + bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) + return Some checkResults - | None -> - return None - | None -> return None // the incremental builder was not up to date + | None -> return None + | None -> return None // the incremental builder was not up to date } /// 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) = node { - let! builderOpt,creationDiags = getOrCreateBuilder (options, userOpName) + let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + match builderOpt with - | None -> return FSharpCheckFileAnswer.Succeeded (FSharpCheckFileResults.MakeEmpty(fileName, creationDiags, keepAssemblyContents)) - | Some builder -> + | None -> return FSharpCheckFileAnswer.Succeeded(FSharpCheckFileResults.MakeEmpty(fileName, creationDiags, keepAssemblyContents)) + | Some builder -> // Check the cache. We can only use cached results when there is no work to do to bring the background builder up-to-date let! cachedResults = bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) @@ -669,25 +788,26 @@ type 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) = + member bc.ParseAndCheckFileInProject(fileName: string, fileVersion, sourceText: ISourceText, options: FSharpProjectOptions, userOpName) = node { let strGuid = "_ProjectId=" + (options.ProjectId |> Option.defaultValue "null") Logger.LogBlockMessageStart (fileName + strGuid) LogCompilerFunctionId.Service_ParseAndCheckFileInProject - let! builderOpt,creationDiags = getOrCreateBuilder (options, userOpName) + let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + match builderOpt with - | None -> + | None -> Logger.LogBlockMessageStop (fileName + strGuid + "-Failed_Aborted") LogCompilerFunctionId.Service_ParseAndCheckFileInProject let parseTree = EmptyParsedInput(fileName, (false, false)) - let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [| |]) + let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||]) return (parseResults, FSharpCheckFileAnswer.Aborted) - | Some builder -> + | Some builder -> let! cachedResults = bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) - match cachedResults with - | Some (parseResults, checkResults) -> + match cachedResults with + | Some (parseResults, checkResults) -> Logger.LogBlockMessageStop (fileName + strGuid + "-Successful_Cached") LogCompilerFunctionId.Service_ParseAndCheckFileInProject return (parseResults, FSharpCheckFileAnswer.Succeeded checkResults) @@ -695,11 +815,19 @@ type BackgroundCompiler( let! tcPrior = builder.GetCheckResultsBeforeFileInProject fileName let! tcInfo = tcPrior.GetOrComputeTcInfo() // Do the parsing. - let parsingOptions = FSharpParsingOptions.FromTcConfig(builder.TcConfig, Array.ofList builder.SourceFiles, options.UseScriptResolutionRules) + let parsingOptions = + FSharpParsingOptions.FromTcConfig(builder.TcConfig, Array.ofList builder.SourceFiles, options.UseScriptResolutionRules) + GraphNode.SetPreferredUILang tcPrior.TcConfig.preferredUiLang - let parseDiags, parseTree, anyErrors = ParseAndCheckFile.parseFile (sourceText, fileName, parsingOptions, userOpName, suggestNamesForErrors) - let parseResults = FSharpParseFileResults(parseDiags, parseTree, anyErrors, builder.AllDependenciesDeprecated) - let! checkResults = bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) + + let parseDiagnostics, parseTree, anyErrors = + ParseAndCheckFile.parseFile (sourceText, fileName, parsingOptions, userOpName, suggestNamesForErrors) + + let parseResults = + FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, builder.AllDependenciesDeprecated) + + let! checkResults = + bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) Logger.LogBlockMessageStop (fileName + strGuid + "-Successful") LogCompilerFunctionId.Service_ParseAndCheckFileInProject @@ -710,14 +838,15 @@ type BackgroundCompiler( member _.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName) = node { let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + match builderOpt with | None -> let parseTree = EmptyParsedInput(fileName, (false, false)) - let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [| |]) + let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||]) let typedResults = FSharpCheckFileResults.MakeEmpty(fileName, creationDiags, true) return (parseResults, typedResults) - | Some builder -> - let parseTree, _, _, parseDiags = builder.GetParseResultsForFile fileName + | Some builder -> + let parseTree, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName let! tcProj = builder.GetFullCheckResultsAfterFileInProject fileName let! tcInfo, tcInfoExtras = tcProj.GetOrComputeTcInfoWithExtras() @@ -732,46 +861,74 @@ type BackgroundCompiler( let tcDependencyFiles = tcInfo.tcDependencyFiles let tcDiagnostics = tcInfo.TcDiagnostics let diagnosticsOptions = builder.TcConfig.diagnosticsOptions - let parseDiags = [| yield! creationDiags; yield! DiagnosticHelpers.CreateDiagnostics (diagnosticsOptions, false, fileName, parseDiags, suggestNamesForErrors) |] - let tcDiagnostics = [| yield! creationDiags; yield! DiagnosticHelpers.CreateDiagnostics (diagnosticsOptions, false, fileName, tcDiagnostics, suggestNamesForErrors) |] - let parseResults = FSharpParseFileResults(diagnostics=parseDiags, input=parseTree, parseHadErrors=false, dependencyFiles=builder.AllDependenciesDeprecated) + + let parseDiagnostics = + DiagnosticHelpers.CreateDiagnostics(diagnosticsOptions, false, fileName, parseDiagnostics, suggestNamesForErrors) + + let parseDiagnostics = [| yield! creationDiags; yield! parseDiagnostics |] + + let tcDiagnostics = + DiagnosticHelpers.CreateDiagnostics(diagnosticsOptions, false, fileName, tcDiagnostics, suggestNamesForErrors) + + let tcDiagnostics = [| yield! creationDiags; yield! tcDiagnostics |] + + let parseResults = + FSharpParseFileResults( + diagnostics = parseDiagnostics, + input = parseTree, + parseHadErrors = false, + dependencyFiles = builder.AllDependenciesDeprecated + ) + let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options) - let typedResults = - FSharpCheckFileResults.Make - (fileName, - options.ProjectFileName, - tcProj.TcConfig, - tcProj.TcGlobals, - options.IsIncompleteTypeCheckEnvironment, - builder, - options, - Array.ofList tcDependencyFiles, - creationDiags, - parseResults.Diagnostics, - tcDiagnostics, - keepAssemblyContents, - Option.get latestCcuSigForFile, - tcState.Ccu, - tcProj.TcImports, - tcEnvAtEnd.AccessRights, - tcResolutions, - tcSymbolUses, - tcEnvAtEnd.NameEnv, - loadClosure, - latestImplementationFile, - tcOpenDeclarations) + + let typedResults = + FSharpCheckFileResults.Make( + fileName, + options.ProjectFileName, + tcProj.TcConfig, + tcProj.TcGlobals, + options.IsIncompleteTypeCheckEnvironment, + builder, + options, + Array.ofList tcDependencyFiles, + creationDiags, + parseResults.Diagnostics, + tcDiagnostics, + keepAssemblyContents, + Option.get latestCcuSigForFile, + tcState.Ccu, + tcProj.TcImports, + tcEnvAtEnd.AccessRights, + tcResolutions, + tcSymbolUses, + tcEnvAtEnd.NameEnv, + loadClosure, + latestImplementationFile, + tcOpenDeclarations + ) + return (parseResults, typedResults) - } + } - member _.FindReferencesInFile(fileName: string, options: FSharpProjectOptions, symbol: FSharpSymbol, canInvalidateProject: bool, userOpName: string) = + member _.FindReferencesInFile + ( + fileName: string, + options: FSharpProjectOptions, + symbol: FSharpSymbol, + canInvalidateProject: bool, + userOpName: string + ) = node { let! builderOpt, _ = getOrCreateBuilderWithInvalidationFlag (options, canInvalidateProject, userOpName) + match builderOpt with | None -> return Seq.empty - | Some builder -> + | Some builder -> if builder.ContainsFile fileName then let! checkResults = builder.GetFullCheckResultsAfterFileInProject fileName let! keyStoreOpt = checkResults.GetOrComputeItemKeyStoreIfEnabled() + match keyStoreOpt with | None -> return Seq.empty | Some reader -> return reader.FindAll symbol.Item @@ -779,92 +936,100 @@ type BackgroundCompiler( return Seq.empty } - member _.GetSemanticClassificationForFile(fileName: string, options: FSharpProjectOptions, userOpName: string) = node { let! builderOpt, _ = getOrCreateBuilder (options, userOpName) + match builderOpt with | None -> return None - | Some builder -> + | Some builder -> let! checkResults = builder.GetFullCheckResultsAfterFileInProject fileName let! scopt = checkResults.GetOrComputeSemanticClassificationIfEnabled() + match scopt with | None -> return None - | Some sc -> return Some (sc.GetView ()) + | Some sc -> return Some(sc.GetView()) } - /// Try to get recent approximate type check results for a file. - member _.TryGetRecentCheckResultsForFile(fileName: string, options:FSharpProjectOptions, sourceText: ISourceText option, _userOpName: string) = - match sourceText with - | Some sourceText -> + /// Try to get recent approximate type check results for a file. + member _.TryGetRecentCheckResultsForFile(fileName: string, options: FSharpProjectOptions, sourceText: ISourceText option, _userOpName: string) = + match sourceText with + | Some sourceText -> let hash = sourceText.GetHashCode() |> int64 - let resOpt = parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.TryGet(ltok,(fileName,hash,options))) + + let resOpt = + parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.TryGet(ltok, (fileName, hash, options))) + match resOpt with | Some res -> match res.TryPeekValue() with - | ValueSome(a,b,c,_) -> - Some(a,b,c) - | ValueNone -> - None - | None -> - None - | None -> - None + | ValueSome (a, b, c, _) -> Some(a, b, c) + | ValueNone -> None + | None -> None + | None -> None /// Parse and typecheck the whole project (the implementation, called recursively as project graph is evaluated) member private _.ParseAndCheckProjectImpl(options, userOpName) = - node { - let! builderOpt,creationDiags = getOrCreateBuilder (options, userOpName) - match builderOpt with - | None -> - return FSharpCheckProjectResults (options.ProjectFileName, None, keepAssemblyContents, creationDiags, None) - | Some builder -> - let! tcProj, ilAssemRef, tcAssemblyDataOpt, tcAssemblyExprOpt = builder.GetFullCheckResultsAndImplementationsForProject() - let diagnosticsOptions = tcProj.TcConfig.diagnosticsOptions - let fileName = DummyFileNameForRangesWithoutASpecificLocation - - // Although we do not use 'tcInfoExtras', computing it will make sure we get an extra info. - let! tcInfo, _tcInfoExtras = tcProj.GetOrComputeTcInfoWithExtras() - - let topAttribs = tcInfo.topAttribs - let tcState = tcInfo.tcState - let tcEnvAtEnd = tcInfo.tcEnvAtEndOfFile - let tcDiagnostics = tcInfo.TcDiagnostics - let tcDependencyFiles = tcInfo.tcDependencyFiles - let diagnostics = - [| yield! creationDiags - yield! DiagnosticHelpers.CreateDiagnostics (diagnosticsOptions, true, fileName, tcDiagnostics, suggestNamesForErrors) |] - - let getAssemblyData() = - match tcAssemblyDataOpt with - | ProjectAssemblyDataResult.Available data -> Some data - | _ -> None - - let details = - (tcProj.TcGlobals, tcProj.TcImports, tcState.Ccu, tcState.CcuSig, - Choice1Of2 builder, topAttribs, getAssemblyData, ilAssemRef, - tcEnvAtEnd.AccessRights, tcAssemblyExprOpt, - Array.ofList tcDependencyFiles, - options) - - let results = - FSharpCheckProjectResults( - options.ProjectFileName, - Some tcProj.TcConfig, - keepAssemblyContents, - diagnostics, - Some details - ) - return results - } + node { + let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | None -> + let emptyResults = + FSharpCheckProjectResults(options.ProjectFileName, None, keepAssemblyContents, creationDiags, None) + + return emptyResults + | Some builder -> + let! tcProj, ilAssemRef, tcAssemblyDataOpt, tcAssemblyExprOpt = builder.GetFullCheckResultsAndImplementationsForProject() + let diagnosticsOptions = tcProj.TcConfig.diagnosticsOptions + let fileName = DummyFileNameForRangesWithoutASpecificLocation + + // Although we do not use 'tcInfoExtras', computing it will make sure we get an extra info. + let! tcInfo, _tcInfoExtras = tcProj.GetOrComputeTcInfoWithExtras() + + let topAttribs = tcInfo.topAttribs + let tcState = tcInfo.tcState + let tcEnvAtEnd = tcInfo.tcEnvAtEndOfFile + let tcDiagnostics = tcInfo.TcDiagnostics + let tcDependencyFiles = tcInfo.tcDependencyFiles + + let tcDiagnostics = + DiagnosticHelpers.CreateDiagnostics(diagnosticsOptions, true, fileName, tcDiagnostics, suggestNamesForErrors) + + let diagnostics = [| yield! creationDiags; yield! tcDiagnostics |] + + let getAssemblyData () = + match tcAssemblyDataOpt with + | ProjectAssemblyDataResult.Available data -> Some data + | _ -> None + + let details = + (tcProj.TcGlobals, + tcProj.TcImports, + tcState.Ccu, + tcState.CcuSig, + Choice1Of2 builder, + topAttribs, + getAssemblyData, + ilAssemRef, + tcEnvAtEnd.AccessRights, + tcAssemblyExprOpt, + Array.ofList tcDependencyFiles, + options) + + let results = + FSharpCheckProjectResults(options.ProjectFileName, Some tcProj.TcConfig, keepAssemblyContents, diagnostics, Some details) + + return results + } member _.GetAssemblyData(options, userOpName) = node { - let! builderOpt,_ = getOrCreateBuilder (options, userOpName) - match builderOpt with - | None -> - return ProjectAssemblyDataResult.Unavailable true - | Some builder -> + let! builderOpt, _ = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | None -> return ProjectAssemblyDataResult.Unavailable true + | Some builder -> let! _, _, tcAssemblyDataOpt, _ = builder.GetCheckResultsAndImplementationsForProject() return tcAssemblyDataOpt } @@ -872,104 +1037,138 @@ type BackgroundCompiler( /// Get the timestamp that would be on the output if fully built immediately member private _.TryGetLogicalTimeStampForProject(cache, options) = match tryGetBuilderNode options with - | Some lazyWork -> + | Some lazyWork -> match lazyWork.TryPeekValue() with - | ValueSome (Some builder, _) -> - Some(builder.GetLogicalTimeStampForProject(cache)) - | _ -> - None - | _ -> - None + | ValueSome (Some builder, _) -> Some(builder.GetLogicalTimeStampForProject(cache)) + | _ -> None + | _ -> None /// Parse and typecheck the whole project. member bc.ParseAndCheckProject(options, userOpName) = bc.ParseAndCheckProjectImpl(options, userOpName) - member _.GetProjectOptionsFromScript(fileName, sourceText, previewEnabled, loadedTimeStamp, otherFlags, useFsiAuxLib: bool option, useSdkRefs: bool option, sdkDirOverride: string option, assumeDotNetFramework: bool option, optionsStamp: int64 option, _userOpName) = - cancellable { + member _.GetProjectOptionsFromScript + ( + fileName, + sourceText, + previewEnabled, + loadedTimeStamp, + otherFlags, + useFsiAuxLib: bool option, + useSdkRefs: bool option, + sdkDirOverride: string option, + assumeDotNetFramework: bool option, + optionsStamp: int64 option, + _userOpName + ) = + cancellable { use diagnostics = new DiagnosticsScope() // Do we add a reference to FSharp.Compiler.Interactive.Settings by default? let useFsiAuxLib = defaultArg useFsiAuxLib true - let useSdkRefs = defaultArg useSdkRefs true + let useSdkRefs = defaultArg useSdkRefs true let reduceMemoryUsage = ReduceMemoryFlag.Yes let previewEnabled = defaultArg previewEnabled false // Do we assume .NET Framework references for scripts? let assumeDotNetFramework = defaultArg assumeDotNetFramework true + let extraFlags = if previewEnabled then [| "--langversion:preview" |] else [||] + let otherFlags = defaultArg otherFlags extraFlags - let useSimpleResolution = + + let useSimpleResolution = #if ENABLE_MONO_SUPPORT runningOnMono || otherFlags |> Array.exists (fun x -> x = "--simpleresolution") #else true #endif let loadedTimeStamp = defaultArg loadedTimeStamp DateTime.MaxValue // Not 'now', we don't want to force reloading - let applyCompilerOptions tcConfigB = - let fsiCompilerOptions = GetCoreFsiCompilerOptions tcConfigB - ParseCompilerOptions (ignore, fsiCompilerOptions, Array.toList otherFlags) + + let applyCompilerOptions tcConfigB = + let fsiCompilerOptions = GetCoreFsiCompilerOptions tcConfigB + ParseCompilerOptions(ignore, fsiCompilerOptions, Array.toList otherFlags) let loadClosure = - LoadClosure.ComputeClosureOfScriptText(legacyReferenceResolver, - FSharpCheckerResultsSettings.defaultFSharpBinariesDir, fileName, sourceText, - CodeContext.Editing, useSimpleResolution, useFsiAuxLib, useSdkRefs, sdkDirOverride, Lexhelp.LexResourceManager(), - applyCompilerOptions, assumeDotNetFramework, - tryGetMetadataSnapshot, reduceMemoryUsage, dependencyProviderForScripts) - - let otherFlags = - [| yield "--noframework"; yield "--warn:3"; - yield! otherFlags - for r in loadClosure.References do yield "-r:" + fst r - for code,_ in loadClosure.NoWarns do yield "--nowarn:" + code + LoadClosure.ComputeClosureOfScriptText( + legacyReferenceResolver, + FSharpCheckerResultsSettings.defaultFSharpBinariesDir, + fileName, + sourceText, + CodeContext.Editing, + useSimpleResolution, + useFsiAuxLib, + useSdkRefs, + sdkDirOverride, + Lexhelp.LexResourceManager(), + applyCompilerOptions, + assumeDotNetFramework, + tryGetMetadataSnapshot, + reduceMemoryUsage, + dependencyProviderForScripts + ) + + let otherFlags = + [| + yield "--noframework" + yield "--warn:3" + yield! otherFlags + for r in loadClosure.References do + yield "-r:" + fst r + for code, _ in loadClosure.NoWarns do + yield "--nowarn:" + code |] - let options = + let options = { ProjectFileName = fileName + ".fsproj" // Make a name that is unique in this directory. ProjectId = None SourceFiles = loadClosure.SourceFiles |> List.map fst |> List.toArray - OtherOptions = otherFlags - ReferencedProjects= [| |] + OtherOptions = otherFlags + ReferencedProjects = [||] IsIncompleteTypeCheckEnvironment = false - UseScriptResolutionRules = true + UseScriptResolutionRules = true LoadTime = loadedTimeStamp - UnresolvedReferences = Some (FSharpUnresolvedReferencesSet(loadClosure.UnresolvedReferences)) + UnresolvedReferences = Some(FSharpUnresolvedReferencesSet(loadClosure.UnresolvedReferences)) OriginalLoadReferences = loadClosure.OriginalLoadReferences Stamp = optionsStamp } + scriptClosureCache.Set(AnyCallerThread, options, loadClosure) // Save the full load closure for later correlation. - let diags = loadClosure.LoadClosureRootFileDiagnostics |> List.map (fun (exn, isError) -> FSharpDiagnostic.CreateFromException(exn, isError, range.Zero, false)) + + let diags = + loadClosure.LoadClosureRootFileDiagnostics + |> List.map (fun (exn, isError) -> FSharpDiagnostic.CreateFromException(exn, isError, range.Zero, false)) + return options, (diags @ diagnostics.Diagnostics) - } - |> Cancellable.toAsync - + } + |> Cancellable.toAsync + member bc.InvalidateConfiguration(options: FSharpProjectOptions, userOpName) = - if incrementalBuildersCache.ContainsSimilarKey (AnyCallerThread, options) then - parseCacheLock.AcquireLock(fun ltok -> + if incrementalBuildersCache.ContainsSimilarKey(AnyCallerThread, options) then + parseCacheLock.AcquireLock(fun ltok -> for sourceFile in options.SourceFiles do - checkFileInProjectCache.RemoveAnySimilar(ltok, (sourceFile, 0L, options)) - ) + checkFileInProjectCache.RemoveAnySimilar(ltok, (sourceFile, 0L, options))) + let _ = createBuilderNode (options, userOpName, CancellationToken.None) () member bc.ClearCache(options: seq, _userOpName) = lock gate (fun () -> options - |> Seq.iter (fun options -> incrementalBuildersCache.RemoveAnySimilar(AnyCallerThread, options)) - ) + |> Seq.iter (fun options -> incrementalBuildersCache.RemoveAnySimilar(AnyCallerThread, options))) - member _.NotifyProjectCleaned (options: FSharpProjectOptions, userOpName) = + member _.NotifyProjectCleaned(options: FSharpProjectOptions, userOpName) = async { let! ct = Async.CancellationToken - // If there was a similar entry (as there normally will have been) then re-establish an empty builder . This - // is a somewhat arbitrary choice - it will have the effect of releasing memory associated with the previous + // If there was a similar entry (as there normally will have been) then re-establish an empty builder . This + // is a somewhat arbitrary choice - it will have the effect of releasing memory associated with the previous // builder, but costs some time. - if incrementalBuildersCache.ContainsSimilarKey (AnyCallerThread, options) then + if incrementalBuildersCache.ContainsSimilarKey(AnyCallerThread, options) then let _ = createBuilderNode (options, userOpName, ct) () } @@ -984,42 +1183,44 @@ type BackgroundCompiler( member _.ClearCaches() = lock gate (fun () -> - parseCacheLock.AcquireLock (fun ltok -> + parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.Clear(ltok) parseFileCache.Clear(ltok)) + incrementalBuildersCache.Clear(AnyCallerThread) frameworkTcImportsCache.Clear() - scriptClosureCache.Clear AnyCallerThread - ) + scriptClosureCache.Clear AnyCallerThread) member _.DownsizeCaches() = lock gate (fun () -> - parseCacheLock.AcquireLock (fun ltok -> - checkFileInProjectCache.Resize(ltok, newKeepStrongly=1) - parseFileCache.Resize(ltok, newKeepStrongly=1)) - incrementalBuildersCache.Resize(AnyCallerThread, newKeepStrongly=1, newKeepMax=1) + parseCacheLock.AcquireLock(fun ltok -> + checkFileInProjectCache.Resize(ltok, newKeepStrongly = 1) + parseFileCache.Resize(ltok, newKeepStrongly = 1)) + + incrementalBuildersCache.Resize(AnyCallerThread, newKeepStrongly = 1, newKeepMax = 1) frameworkTcImportsCache.Downsize() - scriptClosureCache.Resize(AnyCallerThread,newKeepStrongly=1, newKeepMax=1) - ) - + scriptClosureCache.Resize(AnyCallerThread, newKeepStrongly = 1, newKeepMax = 1)) + member _.FrameworkImportsCache = frameworkTcImportsCache static member ActualParseFileCount = actualParseFileCount static member ActualCheckFileCount = actualCheckFileCount - [] // There is typically only one instance of this type in an IDE process. -type FSharpChecker(legacyReferenceResolver, - projectCacheSize, - keepAssemblyContents, - keepAllBackgroundResolutions, - tryGetMetadataSnapshot, - suggestNamesForErrors, - keepAllBackgroundSymbolUses, - enableBackgroundItemKeyStoreAndSemanticClassification, - enablePartialTypeChecking) = +type FSharpChecker + ( + legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking + ) = let backgroundCompiler = BackgroundCompiler( @@ -1031,32 +1232,36 @@ type FSharpChecker(legacyReferenceResolver, suggestNamesForErrors, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification, - enablePartialTypeChecking) + enablePartialTypeChecking + ) static let globalInstance = lazy FSharpChecker.Create() - + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.braceMatchCache. Most recently used cache for brace matching. Accessed on the // background UI thread, not on the compiler thread. // // This cache is safe for concurrent access. - let braceMatchCache = MruCache(braceMatchCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing) - - /// Instantiate an interactive checker. - static member Create( - ?projectCacheSize, - ?keepAssemblyContents, - ?keepAllBackgroundResolutions, - ?legacyReferenceResolver, - ?tryGetMetadataSnapshot, - ?suggestNamesForErrors, - ?keepAllBackgroundSymbolUses, - ?enableBackgroundItemKeyStoreAndSemanticClassification, - ?enablePartialTypeChecking) = - - let legacyReferenceResolver = + let braceMatchCache = + MruCache(braceMatchCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing) + + /// Instantiate an interactive checker. + static member Create + ( + ?projectCacheSize, + ?keepAssemblyContents, + ?keepAllBackgroundResolutions, + ?legacyReferenceResolver, + ?tryGetMetadataSnapshot, + ?suggestNamesForErrors, + ?keepAllBackgroundSymbolUses, + ?enableBackgroundItemKeyStoreAndSemanticClassification, + ?enablePartialTypeChecking + ) = + + let legacyReferenceResolver = match legacyReferenceResolver with | Some rr -> rr - | None -> SimulatedMSBuildReferenceResolver.getResolver() + | None -> SimulatedMSBuildReferenceResolver.getResolver () let keepAssemblyContents = defaultArg keepAssemblyContents false let keepAllBackgroundResolutions = defaultArg keepAllBackgroundResolutions true @@ -1064,13 +1269,17 @@ type FSharpChecker(legacyReferenceResolver, let tryGetMetadataSnapshot = defaultArg tryGetMetadataSnapshot (fun _ -> None) let suggestNamesForErrors = defaultArg suggestNamesForErrors false let keepAllBackgroundSymbolUses = defaultArg keepAllBackgroundSymbolUses true - let enableBackgroundItemKeyStoreAndSemanticClassification = defaultArg enableBackgroundItemKeyStoreAndSemanticClassification false + + let enableBackgroundItemKeyStoreAndSemanticClassification = + defaultArg enableBackgroundItemKeyStoreAndSemanticClassification false + let enablePartialTypeChecking = defaultArg enablePartialTypeChecking false if keepAssemblyContents && enablePartialTypeChecking then invalidArg "enablePartialTypeChecking" "'keepAssemblyContents' and 'enablePartialTypeChecking' cannot be both enabled." - FSharpChecker(legacyReferenceResolver, + FSharpChecker( + legacyReferenceResolver, projectCacheSizeReal, keepAssemblyContents, keepAllBackgroundResolutions, @@ -1078,18 +1287,22 @@ type FSharpChecker(legacyReferenceResolver, suggestNamesForErrors, keepAllBackgroundSymbolUses, enableBackgroundItemKeyStoreAndSemanticClassification, - enablePartialTypeChecking) + enablePartialTypeChecking + ) member _.ReferenceResolver = legacyReferenceResolver member _.MatchBraces(fileName, sourceText: ISourceText, options: FSharpParsingOptions, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" let hash = sourceText.GetHashCode() |> int64 + async { match braceMatchCache.TryGet(AnyCallerThread, (fileName, hash, options)) with | Some res -> return res | None -> - let res = ParseAndCheckFile.matchBraces(sourceText, fileName, options, userOpName, suggestNamesForErrors) + let res = + ParseAndCheckFile.matchBraces (sourceText, fileName, options, userOpName, suggestNamesForErrors) + braceMatchCache.Set(AnyCallerThread, (fileName, hash, options), res) return res } @@ -1099,7 +1312,7 @@ type FSharpChecker(legacyReferenceResolver, let parsingOptions, _ = ic.GetParsingOptionsFromProjectOptions(options) ic.MatchBraces(fileName, SourceText.ofString source, parsingOptions, userOpName) - member ic.GetParsingOptionsFromProjectOptions(options): FSharpParsingOptions * _ = + member ic.GetParsingOptionsFromProjectOptions(options) : FSharpParsingOptions * _ = let sourceFiles = List.ofArray options.SourceFiles let argv = List.ofArray options.OtherOptions ic.GetParsingOptionsFromCommandLineArgs(sourceFiles, argv, options.UseScriptResolutionRules) @@ -1111,103 +1324,163 @@ type FSharpChecker(legacyReferenceResolver, member ic.ParseFileInProject(fileName, source: string, options, ?cache: bool, ?userOpName: string) = let parsingOptions, _ = ic.GetParsingOptionsFromProjectOptions(options) - ic.ParseFile(fileName, SourceText.ofString source, parsingOptions, ?cache=cache, ?userOpName=userOpName) + ic.ParseFile(fileName, SourceText.ofString source, parsingOptions, ?cache = cache, ?userOpName = userOpName) - member _.GetBackgroundParseResultsForFileInProject (fileName,options, ?userOpName: string) = + member _.GetBackgroundParseResultsForFileInProject(fileName, options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" + backgroundCompiler.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName) |> Async.AwaitNodeCode - - member _.GetBackgroundCheckResultsForFileInProject (fileName,options, ?userOpName: string) = + + member _.GetBackgroundCheckResultsForFileInProject(fileName, options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.GetBackgroundCheckResultsForFileInProject(fileName,options, userOpName) + + backgroundCompiler.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName) |> Async.AwaitNodeCode - - /// Try to get recent approximate type check results for a file. - member _.TryGetRecentCheckResultsForFile(fileName: string, options:FSharpProjectOptions, ?sourceText, ?userOpName: string) = + + /// Try to get recent approximate type check results for a file. + member _.TryGetRecentCheckResultsForFile(fileName: string, options: FSharpProjectOptions, ?sourceText, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.TryGetRecentCheckResultsForFile(fileName,options,sourceText,userOpName) + backgroundCompiler.TryGetRecentCheckResultsForFile(fileName, options, sourceText, userOpName) member _.Compile(argv: string[], ?userOpName: string) = let _userOpName = defaultArg userOpName "Unknown" + async { let ctok = CompilationThreadToken() return CompileHelpers.compileFromArgs (ctok, argv, legacyReferenceResolver, None, None) } - member _.Compile (ast:ParsedInput list, assemblyName:string, outFile:string, dependencies:string list, ?pdbFile:string, ?executable:bool, ?noframework:bool, ?userOpName: string) = - let _userOpName = defaultArg userOpName "Unknown" - async { - let ctok = CompilationThreadToken() - let noframework = defaultArg noframework false - return CompileHelpers.compileFromAsts (ctok, legacyReferenceResolver, ast, assemblyName, outFile, dependencies, noframework, pdbFile, executable, None, None) - } - - member _.CompileToDynamicAssembly (otherFlags: string[], execute: (TextWriter * TextWriter) option, ?userOpName: string) = - let _userOpName = defaultArg userOpName "Unknown" - async { - let ctok = CompilationThreadToken() - CompileHelpers.setOutputStreams execute - - // References used to capture the results of compilation - let tcImportsRef = ref None - let assemblyBuilderRef = ref None - let tcImportsCapture = Some (fun tcImports -> tcImportsRef.Value <- Some tcImports) - - // Function to generate and store the results of compilation - let debugInfo = otherFlags |> Array.exists (fun arg -> arg = "-g" || arg = "--debug:+" || arg = "/debug:+") - let dynamicAssemblyCreator = Some (CompileHelpers.createDynamicAssembly (debugInfo, tcImportsRef, execute.IsSome, assemblyBuilderRef)) - - // Perform the compilation, given the above capturing function. - let diagnostics, result = CompileHelpers.compileFromArgs (ctok, otherFlags, legacyReferenceResolver, tcImportsCapture, dynamicAssemblyCreator) - - // Retrieve and return the results - let assemblyOpt = - match assemblyBuilderRef.Value with - | None -> None - | Some a -> Some (a :> Assembly) + member _.Compile + ( + ast: ParsedInput list, + assemblyName: string, + outFile: string, + dependencies: string list, + ?pdbFile: string, + ?executable: bool, + ?noframework: bool, + ?userOpName: string + ) = + let _userOpName = defaultArg userOpName "Unknown" - return diagnostics, result, assemblyOpt - } + async { + let ctok = CompilationThreadToken() + let noframework = defaultArg noframework false + + return + CompileHelpers.compileFromAsts ( + ctok, + legacyReferenceResolver, + ast, + assemblyName, + outFile, + dependencies, + noframework, + pdbFile, + executable, + None, + None + ) + } + + member _.CompileToDynamicAssembly(otherFlags: string[], execute: (TextWriter * TextWriter) option, ?userOpName: string) = + let _userOpName = defaultArg userOpName "Unknown" - member _.CompileToDynamicAssembly (ast:ParsedInput list, assemblyName:string, dependencies:string list, execute: (TextWriter * TextWriter) option, ?debug:bool, ?noframework:bool, ?userOpName: string) = - let _userOpName = defaultArg userOpName "Unknown" - async { - let ctok = CompilationThreadToken() - CompileHelpers.setOutputStreams execute + async { + let ctok = CompilationThreadToken() + CompileHelpers.setOutputStreams execute - // References used to capture the results of compilation - let tcImportsRef = ref (None: TcImports option) - let assemblyBuilderRef = ref None - let tcImportsCapture = Some (fun tcImports -> tcImportsRef.Value <- Some tcImports) + // References used to capture the results of compilation + let tcImportsRef = ref None + let assemblyBuilderRef = ref None + let tcImportsCapture = Some(fun tcImports -> tcImportsRef.Value <- Some tcImports) - let debugInfo = defaultArg debug false - let noframework = defaultArg noframework false - let location = Path.Combine(FileSystem.GetTempPathShim(),"test"+string(hash assemblyName)) - try Directory.CreateDirectory(location) |> ignore with _ -> () + // Function to generate and store the results of compilation + let debugInfo = + otherFlags + |> Array.exists (fun arg -> arg = "-g" || arg = "--debug:+" || arg = "/debug:+") - let outFile = Path.Combine(location, assemblyName + ".dll") + let dynamicAssemblyCreator = + Some(CompileHelpers.createDynamicAssembly (debugInfo, tcImportsRef, execute.IsSome, assemblyBuilderRef)) - // Function to generate and store the results of compilation - let dynamicAssemblyCreator = Some (CompileHelpers.createDynamicAssembly (debugInfo, tcImportsRef, execute.IsSome, assemblyBuilderRef)) + // Perform the compilation, given the above capturing function. + let diagnostics, result = + CompileHelpers.compileFromArgs (ctok, otherFlags, legacyReferenceResolver, tcImportsCapture, dynamicAssemblyCreator) - // Perform the compilation, given the above capturing function. - let diagnostics, result = - CompileHelpers.compileFromAsts (ctok, legacyReferenceResolver, ast, assemblyName, outFile, dependencies, noframework, None, Some execute.IsSome, tcImportsCapture, dynamicAssemblyCreator) + // Retrieve and return the results + let assemblyOpt = + match assemblyBuilderRef.Value with + | None -> None + | Some a -> Some(a :> Assembly) - // Retrieve and return the results - let assemblyOpt = - match assemblyBuilderRef.Value with - | None -> None - | Some a -> Some (a :> Assembly) + return diagnostics, result, assemblyOpt + } - return diagnostics, result, assemblyOpt - } + member _.CompileToDynamicAssembly + ( + ast: ParsedInput list, + assemblyName: string, + dependencies: string list, + execute: (TextWriter * TextWriter) option, + ?debug: bool, + ?noframework: bool, + ?userOpName: string + ) = + let _userOpName = defaultArg userOpName "Unknown" + + async { + let ctok = CompilationThreadToken() + CompileHelpers.setOutputStreams execute + + // References used to capture the results of compilation + let tcImportsRef = ref (None: TcImports option) + let assemblyBuilderRef = ref None + let tcImportsCapture = Some(fun tcImports -> tcImportsRef.Value <- Some tcImports) + + let debugInfo = defaultArg debug false + let noframework = defaultArg noframework false + let location = Path.Combine(FileSystem.GetTempPathShim(), "test" + string (hash assemblyName)) + + try + Directory.CreateDirectory(location) |> ignore + with _ -> + () + + let outFile = Path.Combine(location, assemblyName + ".dll") + + // Function to generate and store the results of compilation + let dynamicAssemblyCreator = + Some(CompileHelpers.createDynamicAssembly (debugInfo, tcImportsRef, execute.IsSome, assemblyBuilderRef)) + + // Perform the compilation, given the above capturing function. + let diagnostics, result = + CompileHelpers.compileFromAsts ( + ctok, + legacyReferenceResolver, + ast, + assemblyName, + outFile, + dependencies, + noframework, + None, + Some execute.IsSome, + tcImportsCapture, + dynamicAssemblyCreator + ) + + // Retrieve and return the results + let assemblyOpt = + match assemblyBuilderRef.Value with + | None -> None + | Some a -> Some(a :> Assembly) + + return diagnostics, result, assemblyOpt + } /// This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation. /// For example, the type provider approvals file may have changed. - member ic.InvalidateAll() = - ic.ClearCaches() + member ic.InvalidateAll() = ic.ClearCaches() member ic.ClearCaches() = let utok = AnyCallerThread @@ -1219,9 +1492,9 @@ type FSharpChecker(legacyReferenceResolver, member ic.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() = ic.ClearCaches() GC.Collect() - GC.WaitForPendingFinalizers() + GC.WaitForPendingFinalizers() FxResolver.ClearStaticCaches() - + /// This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions. /// For example, dependent references may have been deleted or created. member _.InvalidateConfiguration(options: FSharpProjectOptions, ?userOpName: string) = @@ -1236,136 +1509,232 @@ type FSharpChecker(legacyReferenceResolver, /// This function is called when a project has been cleaned, and thus type providers should be refreshed. member _.NotifyProjectCleaned(options: FSharpProjectOptions, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.NotifyProjectCleaned (options, userOpName) - - /// Typecheck a source code file, returning a handle to the results of the + backgroundCompiler.NotifyProjectCleaned(options, userOpName) + + /// 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) = + member _.CheckFileInProjectAllowingStaleCachedResults + ( + parseResults: FSharpParseFileResults, + fileName: string, + fileVersion: int, + source: string, + options: FSharpProjectOptions, + ?userOpName: string + ) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.CheckFileInProjectAllowingStaleCachedResults(parseResults,fileName,fileVersion,SourceText.ofString source,options,userOpName) + + backgroundCompiler.CheckFileInProjectAllowingStaleCachedResults( + parseResults, + fileName, + fileVersion, + SourceText.ofString source, + options, + userOpName + ) |> Async.AwaitNodeCode - /// Typecheck a source code file, returning a handle to the results of the + /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. - member _.CheckFileInProject(parseResults:FSharpParseFileResults, fileName:string, fileVersion:int, sourceText:ISourceText, options:FSharpProjectOptions, ?userOpName: string) = + member _.CheckFileInProject + ( + parseResults: FSharpParseFileResults, + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + ?userOpName: string + ) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.CheckFileInProject(parseResults,fileName,fileVersion,sourceText,options,userOpName) + + backgroundCompiler.CheckFileInProject(parseResults, fileName, fileVersion, sourceText, options, userOpName) |> Async.AwaitNodeCode - /// Typecheck a source code file, returning a handle to the results of the + /// 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) = + member _.ParseAndCheckFileInProject + ( + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + ?userOpName: string + ) = let userOpName = defaultArg userOpName "Unknown" + backgroundCompiler.ParseAndCheckFileInProject(fileName, fileVersion, sourceText, options, userOpName) |> Async.AwaitNodeCode - + member _.ParseAndCheckProject(options, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" + backgroundCompiler.ParseAndCheckProject(options, userOpName) |> Async.AwaitNodeCode - member _.FindBackgroundReferencesInFile(fileName:string, options: FSharpProjectOptions, symbol: FSharpSymbol, ?canInvalidateProject: bool, ?userOpName: string) = + member _.FindBackgroundReferencesInFile + ( + fileName: string, + options: FSharpProjectOptions, + symbol: FSharpSymbol, + ?canInvalidateProject: bool, + ?userOpName: string + ) = let canInvalidateProject = defaultArg canInvalidateProject true let userOpName = defaultArg userOpName "Unknown" + backgroundCompiler.FindReferencesInFile(fileName, options, symbol, canInvalidateProject, userOpName) |> Async.AwaitNodeCode - member _.GetBackgroundSemanticClassificationForFile(fileName:string, options: FSharpProjectOptions, ?userOpName) = + member _.GetBackgroundSemanticClassificationForFile(fileName: string, options: FSharpProjectOptions, ?userOpName) = let userOpName = defaultArg userOpName "Unknown" + backgroundCompiler.GetSemanticClassificationForFile(fileName, options, userOpName) |> Async.AwaitNodeCode /// For a given script file, get the ProjectOptions implied by the #load closure - member _.GetProjectOptionsFromScript(fileName, source, ?previewEnabled, ?loadedTimeStamp, ?otherFlags, ?useFsiAuxLib, ?useSdkRefs, ?assumeDotNetFramework, ?sdkDirOverride, ?optionsStamp: int64, ?userOpName: string) = + member _.GetProjectOptionsFromScript + ( + fileName, + source, + ?previewEnabled, + ?loadedTimeStamp, + ?otherFlags, + ?useFsiAuxLib, + ?useSdkRefs, + ?assumeDotNetFramework, + ?sdkDirOverride, + ?optionsStamp: int64, + ?userOpName: string + ) = let userOpName = defaultArg userOpName "Unknown" - backgroundCompiler.GetProjectOptionsFromScript(fileName, source, previewEnabled, loadedTimeStamp, otherFlags, useFsiAuxLib, useSdkRefs, sdkDirOverride, assumeDotNetFramework, optionsStamp, userOpName) - member _.GetProjectOptionsFromCommandLineArgs(projectFileName, argv, ?loadedTimeStamp, ?isInteractive, ?isEditing) = + backgroundCompiler.GetProjectOptionsFromScript( + fileName, + source, + previewEnabled, + loadedTimeStamp, + otherFlags, + useFsiAuxLib, + useSdkRefs, + sdkDirOverride, + assumeDotNetFramework, + optionsStamp, + userOpName + ) + + member _.GetProjectOptionsFromCommandLineArgs(projectFileName, argv, ?loadedTimeStamp, ?isInteractive, ?isEditing) = let isEditing = defaultArg isEditing false let isInteractive = defaultArg isInteractive false let loadedTimeStamp = defaultArg loadedTimeStamp DateTime.MaxValue // Not 'now', we don't want to force reloading - let argv = - let define = if isInteractive then "--define:INTERACTIVE" else "--define:COMPILED" + + let argv = + let define = + if isInteractive then + "--define:INTERACTIVE" + else + "--define:COMPILED" + Array.append argv [| define |] - let argv = - if isEditing then Array.append argv [| "--define:EDITING" |] else argv - { ProjectFileName = projectFileName - ProjectId = None - SourceFiles = [| |] // the project file names will be inferred from the ProjectOptions - OtherOptions = argv - ReferencedProjects= [| |] - IsIncompleteTypeCheckEnvironment = false - UseScriptResolutionRules = false - LoadTime = loadedTimeStamp - UnresolvedReferences = None - OriginalLoadReferences=[] - Stamp = None } + + let argv = + if isEditing then + Array.append argv [| "--define:EDITING" |] + else + argv + + { + ProjectFileName = projectFileName + ProjectId = None + SourceFiles = [||] // the project file names will be inferred from the ProjectOptions + OtherOptions = argv + ReferencedProjects = [||] + IsIncompleteTypeCheckEnvironment = false + UseScriptResolutionRules = false + LoadTime = loadedTimeStamp + UnresolvedReferences = None + OriginalLoadReferences = [] + Stamp = None + } member _.GetParsingOptionsFromCommandLineArgs(sourceFiles, argv, ?isInteractive, ?isEditing) = let isEditing = defaultArg isEditing false let isInteractive = defaultArg isInteractive false use errorScope = new DiagnosticsScope() - let tcConfigB = - TcConfigBuilder.CreateNew(legacyReferenceResolver, - defaultFSharpBinariesDir=FSharpCheckerResultsSettings.defaultFSharpBinariesDir, - reduceMemoryUsage=ReduceMemoryFlag.Yes, - implicitIncludeDir="", - isInteractive=isInteractive, - isInvalidationSupported=false, - defaultCopyFSharpCore=CopyFSharpCoreFlag.No, - tryGetMetadataSnapshot=tryGetMetadataSnapshot, - sdkDirOverride=None, - rangeForErrors=range0) + + let tcConfigB = + TcConfigBuilder.CreateNew( + legacyReferenceResolver, + defaultFSharpBinariesDir = FSharpCheckerResultsSettings.defaultFSharpBinariesDir, + reduceMemoryUsage = ReduceMemoryFlag.Yes, + implicitIncludeDir = "", + isInteractive = isInteractive, + isInvalidationSupported = false, + defaultCopyFSharpCore = CopyFSharpCoreFlag.No, + tryGetMetadataSnapshot = tryGetMetadataSnapshot, + sdkDirOverride = None, + rangeForErrors = range0 + ) // These defines are implied by the F# compiler - tcConfigB.conditionalDefines <- + tcConfigB.conditionalDefines <- let define = if isInteractive then "INTERACTIVE" else "COMPILED" define :: tcConfigB.conditionalDefines - if isEditing then - tcConfigB.conditionalDefines <- "EDITING":: tcConfigB.conditionalDefines + + if isEditing then + tcConfigB.conditionalDefines <- "EDITING" :: tcConfigB.conditionalDefines // Apply command-line arguments and collect more source files if they are in the arguments let sourceFilesNew = ApplyCommandLineArgs(tcConfigB, sourceFiles, argv) FSharpParsingOptions.FromTcConfigBuilder(tcConfigB, Array.ofList sourceFilesNew, isInteractive), errorScope.Diagnostics member ic.GetParsingOptionsFromCommandLineArgs(argv, ?isInteractive: bool, ?isEditing) = - ic.GetParsingOptionsFromCommandLineArgs([], argv, ?isInteractive=isInteractive, ?isEditing=isEditing) + ic.GetParsingOptionsFromCommandLineArgs([], argv, ?isInteractive = isInteractive, ?isEditing = isEditing) - member _.BeforeBackgroundFileCheck = backgroundCompiler.BeforeBackgroundFileCheck + member _.BeforeBackgroundFileCheck = backgroundCompiler.BeforeBackgroundFileCheck - member _.FileParsed = backgroundCompiler.FileParsed + member _.FileParsed = backgroundCompiler.FileParsed - member _.FileChecked = backgroundCompiler.FileChecked + member _.FileChecked = backgroundCompiler.FileChecked member _.ProjectChecked = backgroundCompiler.ProjectChecked static member ActualParseFileCount = BackgroundCompiler.ActualParseFileCount static member ActualCheckFileCount = BackgroundCompiler.ActualCheckFileCount - - static member Instance with get() = globalInstance.Force() + + static member Instance = globalInstance.Force() member internal _.FrameworkImportsCache = backgroundCompiler.FrameworkImportsCache /// Tokenize a single line, returning token information and a tokenization state represented by an integer - member _.TokenizeLine (line: string, state: FSharpTokenizerLexState) = + member _.TokenizeLine(line: string, state: FSharpTokenizerLexState) = let tokenizer = FSharpSourceTokenizer([], None) let lineTokenizer = tokenizer.CreateLineTokenizer line let mutable state = (None, state) - let tokens = - [| while (state <- lineTokenizer.ScanToken (snd state); (fst state).IsSome) do - yield (fst state).Value |] - tokens, snd state + + let tokens = + [| + while (state <- lineTokenizer.ScanToken(snd state) + (fst state).IsSome) do + yield (fst state).Value + |] + + tokens, snd state /// Tokenize an entire file, line by line - member x.TokenizeFile (source: string) : FSharpTokenInfo[][] = + member x.TokenizeFile(source: string) : FSharpTokenInfo[][] = let lines = source.Split('\n') - let tokens = - [| let mutable state = FSharpTokenizerLexState.Initial - for line in lines do - let tokens, n = x.TokenizeLine(line, state) - state <- n - yield tokens |] + + let tokens = + [| + let mutable state = FSharpTokenizerLexState.Initial + + for line in lines do + let tokens, n = x.TokenizeLine(line, state) + state <- n + yield tokens + |] + tokens namespace FSharp.Compiler @@ -1392,17 +1761,27 @@ type CompilerEnvironment() = // Legacy entry point, no longer used by FSharp.Editor static member DefaultReferencesForOrphanSources assumeDotNetFramework = let currentDirectory = Directory.GetCurrentDirectory() - let fxResolver = FxResolver(assumeDotNetFramework, currentDirectory, rangeForErrors=range0, useSdkRefs=true, isInteractive=false, sdkDirOverride=None) - let references, _ = fxResolver.GetDefaultReferences (useFsiAuxLib=false) + + let fxResolver = + FxResolver( + assumeDotNetFramework, + currentDirectory, + rangeForErrors = range0, + useSdkRefs = true, + isInteractive = false, + sdkDirOverride = None + ) + + let references, _ = fxResolver.GetDefaultReferences(useFsiAuxLib = false) references - + /// Publish compiler-flags parsing logic. Must be fast because its used by the colorizer. - static member GetConditionalDefinesForEditing (parsingOptions: FSharpParsingOptions) = - SourceFileImpl.GetImplicitConditionalDefinesForEditing(parsingOptions.IsInteractive) @ - parsingOptions.ConditionalDefines - + static member GetConditionalDefinesForEditing(parsingOptions: FSharpParsingOptions) = + SourceFileImpl.GetImplicitConditionalDefinesForEditing(parsingOptions.IsInteractive) + @ parsingOptions.ConditionalDefines + /// Return true if this is a subcategory of error or warning message that the language service can emit - static member IsCheckerSupportedSubcategory(subcategory:string) = + static member IsCheckerSupportedSubcategory(subcategory: string) = // Beware: This code logic is duplicated in DocumentTask.cs in the language service PhasedDiagnostic.IsSubcategoryOfCompile(subcategory) @@ -1410,15 +1789,19 @@ type CompilerEnvironment() = /// debugger will use. static member GetDebuggerLanguageID() = Guid(0xAB4F38C9u, 0xB6E6us, 0x43baus, 0xBEuy, 0x3Buy, 0x58uy, 0x08uy, 0x0Buy, 0x2Cuy, 0xCCuy, 0xE3uy) - - static member IsScriptFile (fileName: string) = ParseAndCheckInputs.IsScript fileName + + static member IsScriptFile(fileName: string) = ParseAndCheckInputs.IsScript fileName /// Whether or not this file is compilable static member IsCompilable file = let ext = Path.GetExtension file - compilableExtensions |> List.exists(fun e->0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) + + compilableExtensions + |> List.exists (fun e -> 0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) /// Whether or not this file should be a single-file project static member MustBeSingleFileProject file = let ext = Path.GetExtension file - singleFileProjectExtensions |> List.exists(fun e-> 0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) \ No newline at end of file + + singleFileProjectExtensions + |> List.exists (fun e -> 0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Compiler/Symbols/Exprs.fs b/src/Compiler/Symbols/Exprs.fs index e2416af351e..0de02d99948 100644 --- a/src/Compiler/Symbols/Exprs.fs +++ b/src/Compiler/Symbols/Exprs.fs @@ -348,12 +348,12 @@ module FSharpExprConvert = | TOp.UnionCaseFieldGetAddr (uref, n, _), [arg], _ -> mkUnionCaseFieldGetProvenViaExprAddr (exprOfExprAddr cenv arg, uref, tyargs, n, m) | TOp.ILAsm ([ I_ldflda fspec ], retTypes), [arg], _ -> mkAsmExpr ([ mkNormalLdfld fspec ], tyargs, [exprOfExprAddr cenv arg], retTypes, m) | TOp.ILAsm ([ I_ldsflda fspec ], retTypes), _, _ -> mkAsmExpr ([ mkNormalLdsfld fspec ], tyargs, args, retTypes, m) - | TOp.ILAsm ([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ], _), arr :: idxs, [elemty] -> + | TOp.ILAsm ([ I_ldelema(_ro, _isNativePtr, shape, _tyarg) ], _), arr :: idxs, [elemTy] -> match shape.Rank, idxs with - | 1, [idx1] -> mkCallArrayGet g m elemty arr idx1 - | 2, [idx1; idx2] -> mkCallArray2DGet g m elemty arr idx1 idx2 - | 3, [idx1; idx2; idx3] -> mkCallArray3DGet g m elemty arr idx1 idx2 idx3 - | 4, [idx1; idx2; idx3; idx4] -> mkCallArray4DGet g m elemty arr idx1 idx2 idx3 idx4 + | 1, [idx1] -> mkCallArrayGet g m elemTy arr idx1 + | 2, [idx1; idx2] -> mkCallArray2DGet g m elemTy arr idx1 idx2 + | 3, [idx1; idx2; idx3] -> mkCallArray3DGet g m elemTy arr idx1 idx2 idx3 + | 4, [idx1; idx2; idx3; idx4] -> mkCallArray4DGet g m elemTy arr idx1 idx2 idx3 idx4 | _ -> expr | _ -> expr | _ -> expr @@ -471,12 +471,12 @@ module FSharpExprConvert = // Too few arguments or incorrect tupling? Convert to a lambda and beta-reduce the // partially applied arguments to 'let' bindings - let topValInfo = + let valReprInfo = match vref.ValReprInfo with | None -> failwith ("no arity information found for F# value "+vref.LogicalName) | Some a -> a - let expr, exprTy = AdjustValForExpectedArity g m vref vFlags topValInfo + let expr, exprTy = AdjustValForExpectedArity g m vref vFlags valReprInfo let splitCallExpr = MakeApplicationAndBetaReduce g (expr, exprTy, [tyargs], curriedArgs, m) // tailcall ConvExprPrimLinear cenv env splitCallExpr contF @@ -618,7 +618,7 @@ module FSharpExprConvert = let bodyR = ConvExpr cenv env body FSharpObjectExprOverride(sgn, tpsR, vslR, bodyR) ] let overridesR = ConvertMethods overrides - let iimplsR = List.map (fun (ity, impls) -> ConvType cenv ity, ConvertMethods impls) iimpls + let iimplsR = iimpls |> List.map (fun (intfTy, impls) -> ConvType cenv intfTy, ConvertMethods impls) E.ObjectExpr(ConvType cenv ty, basecallR, overridesR, iimplsR) @@ -702,8 +702,8 @@ module FSharpExprConvert = let argR = ConvExpr cenv env arg E.ILFieldSet(None, typR, fspec.Name, argR) - | TOp.ILAsm ([ ], [tty]), _, [arg] -> - match tty with + | TOp.ILAsm ([ ], [tgtTy]), _, [arg] -> + match tgtTy with | TTypeConvOp cenv convOp -> let ty = tyOfExpr g arg let op = convOp g m ty arg @@ -992,7 +992,7 @@ module FSharpExprConvert = let parent = ILTypeRef.Create(e.Scope, e.Enclosing.Tail, e.Enclosing.Head) Import.ImportILTypeRef cenv.amap m parent, Some e.Name - let enclosingType = generalizedTyconRef g tcref + let enclosingTy = generalizedTyconRef g tcref let makeCall minfo = ConvObjectModelCallLinear cenv env (isNewObj, minfo, enclTypeArgs, methTypeArgs, [], callArgs) id @@ -1000,7 +1000,7 @@ module FSharpExprConvert = let makeFSCall isMember (vr: ValRef) = let memOrVal = if isMember then - let minfo = MethInfo.FSMeth(g, enclosingType, vr, None) + let minfo = MethInfo.FSMeth(g, enclosingTy, vr, None) FSharpMemberOrFunctionOrValue(cenv, minfo) else FSharpMemberOrFunctionOrValue(cenv, vr) @@ -1117,7 +1117,7 @@ module FSharpExprConvert = if tcref.IsILTycon then try let mdef = resolveILMethodRefWithRescope unscopeILType tcref.ILTyconRawMetadata ilMethRef - let minfo = MethInfo.CreateILMeth(cenv.amap, m, enclosingType, mdef) + let minfo = MethInfo.CreateILMeth(cenv.amap, m, enclosingTy, mdef) FSharpMemberOrFunctionOrValue(cenv, minfo) |> makeCall |> Some with _ -> None @@ -1155,12 +1155,12 @@ module FSharpExprConvert = let argTys = [ ilMethRef.ArgTypes |> List.map (ImportILTypeFromMetadata cenv.amap m scoref tinst1 tinst2) ] let retTy = match ImportReturnTypeFromMetadata cenv.amap m ilMethRef.ReturnType (fun _ -> emptyILCustomAttrs) scoref tinst1 tinst2 with - | None -> if isCtor then enclosingType else g.unit_ty + | None -> if isCtor then enclosingTy else g.unit_ty | Some ty -> ty let linkageType = let ty = mkIteratedFunTy g (List.map (mkRefTupledTy g) argTys) retTy - let ty = if isStatic then ty else mkFunTy g enclosingType ty + let ty = if isStatic then ty else mkFunTy g enclosingTy ty mkForallTyIfNeeded (typars1 @ typars2) ty let argCount = List.sum (List.map List.length argTys) + (if isStatic then 0 else 1) @@ -1325,9 +1325,9 @@ module FSharpExprConvert = let env = { env with suppressWitnesses = true } ConvExpr cenv env eq E.IfThenElse (eqR, ConvDecisionTree cenv env dtreeRetTy dtree m, acc) - | DecisionTreeTest.IsInst (_srcty, tgty) -> + | DecisionTreeTest.IsInst (_srcTy, tgtTy) -> let e1R = ConvExpr cenv env inpExpr - E.IfThenElse (E.TypeTest (ConvType cenv tgty, e1R) |> Mk cenv m g.bool_ty, ConvDecisionTree cenv env dtreeRetTy dtree m, acc) + E.IfThenElse (E.TypeTest (ConvType cenv tgtTy, e1R) |> Mk cenv m g.bool_ty, ConvDecisionTree cenv env dtreeRetTy dtree m, acc) | DecisionTreeTest.ActivePatternCase _ -> wfail("unexpected Test.ActivePatternCase test in quoted expression", m) | DecisionTreeTest.ArrayLength _ -> wfail("FSharp.Compiler.Service cannot yet return array pattern matching", m) | DecisionTreeTest.Error m -> wfail("error recovery", m) @@ -1356,8 +1356,8 @@ and FSharpImplementationFileContents(cenv, mimpl) = let rec getBind (bind: Binding) = let v = bind.Var assert v.IsCompiledAsTopLevel - let topValInfo = InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v bind.Expr - let tps, _ctorThisValOpt, _baseValOpt, vsl, body, _bodyty = IteratedAdjustArityOfLambda g cenv.amap topValInfo bind.Expr + let valReprInfo = InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v bind.Expr + let tps, _ctorThisValOpt, _baseValOpt, vsl, body, _bodyty = IteratedAdjustArityOfLambda g cenv.amap valReprInfo bind.Expr let v = FSharpMemberOrFunctionOrValue(cenv, mkLocalValRef v) let gps = v.GenericParameters let vslR = List.mapSquared (FSharpExprConvert.ConvVal cenv) vsl diff --git a/src/Compiler/Symbols/SymbolHelpers.fs b/src/Compiler/Symbols/SymbolHelpers.fs index f65cd4541cc..c265024fc40 100644 --- a/src/Compiler/Symbols/SymbolHelpers.fs +++ b/src/Compiler/Symbols/SymbolHelpers.fs @@ -631,9 +631,9 @@ module internal SymbolHelpers = match item with | Item.Types(_name, tys) -> match tys with - | [AppTy g (tyconRef, _typeInst)] -> - if tyconRef.IsProvidedErasedTycon || tyconRef.IsProvidedGeneratedTycon then - Some tyconRef + | [AppTy g (tcref, _typeInst)] -> + if tcref.IsProvidedErasedTycon || tcref.IsProvidedGeneratedTycon then + Some tcref else None | _ -> None @@ -644,10 +644,10 @@ module internal SymbolHelpers = match item with | Item.Types(_name, tys) -> match tys with - | [AppTy g (tyconRef, _typeInst)] -> - if tyconRef.IsProvidedErasedTycon || tyconRef.IsProvidedGeneratedTycon then + | [AppTy g (tcref, _typeInst)] -> + if tcref.IsProvidedErasedTycon || tcref.IsProvidedGeneratedTycon then let typeBeforeArguments = - match tyconRef.TypeReprInfo with + match tcref.TypeReprInfo with | TProvidedTypeRepr info -> info.ProvidedType | _ -> failwith "unreachable" let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters provider), range=m) diff --git a/src/Compiler/Symbols/SymbolPatterns.fs b/src/Compiler/Symbols/SymbolPatterns.fs index bddfe60e135..e44375cb97c 100644 --- a/src/Compiler/Symbols/SymbolPatterns.fs +++ b/src/Compiler/Symbols/SymbolPatterns.fs @@ -43,7 +43,7 @@ module FSharpSymbolPatterns = if entity.IsFSharpAbbreviation then match entity.AbbreviatedType with | TypeWithDefinition def -> getEntityAbbreviatedType def - | abbreviatedType -> entity, Some abbreviatedType + | abbreviatedTy -> entity, Some abbreviatedTy else entity, None let (|Attribute|_|) (entity: FSharpEntity) = @@ -151,12 +151,12 @@ module FSharpSymbolPatterns = | _ -> false if isMutable then Some() else None - /// Entity (originalEntity, abbreviatedEntity, abbreviatedType) + /// Entity (originalEntity, abbreviatedEntity, abbreviatedTy) let (|FSharpEntity|_|) (symbol: FSharpSymbol) = match symbol with | :? FSharpEntity as entity -> - let abbreviatedEntity, abbreviatedType = getEntityAbbreviatedType entity - Some (entity, abbreviatedEntity, abbreviatedType) + let abbreviatedEntity, abbreviatedTy = getEntityAbbreviatedType entity + Some (entity, abbreviatedEntity, abbreviatedTy) | _ -> None let (|Parameter|_|) (symbol: FSharpSymbol) = diff --git a/src/Compiler/Symbols/Symbols.fs b/src/Compiler/Symbols/Symbols.fs index 58172c2b23f..602ccb7459d 100644 --- a/src/Compiler/Symbols/Symbols.fs +++ b/src/Compiler/Symbols/Symbols.fs @@ -350,7 +350,7 @@ type FSharpSymbol(cenv: SymbolEnv, item: unit -> Item, access: FSharpSymbol -> C member sym.TryGetAttribute<'T>() = sym.Attributes |> Seq.tryFind (fun attr -> attr.IsAttribute<'T>()) -type FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = +type FSharpEntity(cenv: SymbolEnv, entity: EntityRef) = inherit FSharpSymbol(cenv, (fun () -> checkEntityIsResolved entity @@ -423,7 +423,7 @@ type FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = match entity.CompilationPathOpt with | None -> None | Some (CompPath(_, [])) -> None - | Some cp when cp.AccessPath |> List.forall (function _, ModuleOrNamespaceKind.Namespace -> true | _ -> false) -> + | Some cp when cp.AccessPath |> List.forall (function _, ModuleOrNamespaceKind.Namespace _ -> true | _ -> false) -> Some (buildAccessPath (Some cp)) | Some _ -> None @@ -588,8 +588,8 @@ type FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = if isUnresolved() then makeReadOnlyCollection [] else let ty = generalizedTyconRef cenv.g entity DiagnosticsLogger.protectAssemblyExploration [] (fun () -> - [ for ity in GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes cenv.g cenv.amap range0 ty do - yield FSharpType(cenv, ity) ]) + [ for intfTy in GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes cenv.g cenv.amap range0 ty do + yield FSharpType(cenv, intfTy) ]) |> makeReadOnlyCollection member _.AllInterfaces = @@ -642,10 +642,13 @@ type FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = else for minfo in GetImmediateIntrinsicMethInfosOfType (None, AccessibleFromSomeFSharpCode) cenv.g cenv.amap range0 entityTy do yield createMember minfo + let props = GetImmediateIntrinsicPropInfosOfType (None, AccessibleFromSomeFSharpCode) cenv.g cenv.amap range0 entityTy let events = cenv.infoReader.GetImmediateIntrinsicEventsOfType (None, AccessibleFromSomeFSharpCode, range0, entityTy) + for pinfo in props do yield FSharpMemberOrFunctionOrValue(cenv, P pinfo, Item.Property (pinfo.PropertyName, [pinfo])) + for einfo in events do yield FSharpMemberOrFunctionOrValue(cenv, E einfo, Item.Event einfo) @@ -657,8 +660,8 @@ type FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = let vref = mkNestedValRef entity v yield FSharpMemberOrFunctionOrValue(cenv, V vref, Item.Value vref) match v.MemberInfo.Value.MemberFlags.MemberKind, v.ApparentEnclosingEntity with - | SynMemberKind.PropertyGet, Parent p -> - let pinfo = FSProp(cenv.g, generalizedTyconRef cenv.g p, Some vref, None) + | SynMemberKind.PropertyGet, Parent tcref -> + let pinfo = FSProp(cenv.g, generalizedTyconRef cenv.g tcref, Some vref, None) yield FSharpMemberOrFunctionOrValue(cenv, P pinfo, Item.Property (pinfo.PropertyName, [pinfo])) | SynMemberKind.PropertySet, Parent p -> let pinfo = FSProp(cenv.g, generalizedTyconRef cenv.g p, None, Some vref) @@ -747,7 +750,7 @@ type FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = let partsList = [ yield parts match parts with - | ("Microsoft", ModuleOrNamespaceKind.Namespace) :: rest when isDefinedInFSharpCore() -> yield rest + | ("Microsoft", ModuleOrNamespaceKind.Namespace _) :: rest when isDefinedInFSharpCore() -> yield rest | _ -> ()] let mapEachCurrentPath (paths: string list list) path = @@ -837,7 +840,7 @@ type FSharpEntity(cenv: SymbolEnv, entity:EntityRef) = | [] -> acc | (name, ModuleOrNamespaceKind.ModuleOrType) :: accessPath -> getOpenPath accessPath (name :: acc) - | (name, ModuleOrNamespaceKind.Namespace) :: accessPath -> + | (name, ModuleOrNamespaceKind.Namespace _) :: accessPath -> getOpenPath accessPath (name :: acc) | (name, ModuleOrNamespaceKind.FSharpModuleWithSuffix) :: accessPath -> getOpenPath accessPath (name :: acc) @@ -1306,7 +1309,7 @@ type FSharpActivePatternGroup(cenv, apinfo:ActivePatternInfo, ty, valOpt) = |> Option.bind (fun vref -> match vref.DeclaringEntity with | ParentNone -> None - | Parent p -> Some (FSharpEntity(cenv, p))) + | Parent tcref -> Some (FSharpEntity(cenv, tcref))) type FSharpGenericParameter(cenv, v:Typar) = @@ -1411,7 +1414,7 @@ type FSharpAbstractSignature(cenv, info: SlotSig) = member _.Name = info.Name - member _.DeclaringType = FSharpType(cenv, info.ImplementedType) + member _.DeclaringType = FSharpType(cenv, info.DeclaringType) type FSharpGenericParameterMemberConstraint(cenv, info: TraitConstraintInfo) = let (TTrait(tys, nm, flags, atys, retTy, _)) = info @@ -2076,7 +2079,7 @@ type FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item) = | E e -> // INCOMPLETENESS: Attribs is empty here, so we can't look at return attributes for .NET or F# methods let retTy = - try PropTypOfEventInfo cenv.infoReader range0 AccessibleFromSomewhere e + try PropTypeOfEventInfo cenv.infoReader range0 AccessibleFromSomewhere e with _ -> // For non-standard events, just use the delegate type as the ReturnParameter type e.GetDelegateType(cenv.amap, range0) @@ -2197,17 +2200,17 @@ type FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item) = member _.IsValCompiledAsMethod = match d with - | V valRef -> IlxGen.IsFSharpValCompiledAsMethod cenv.g valRef.Deref + | V vref -> IlxGen.IsFSharpValCompiledAsMethod cenv.g vref.Deref | _ -> false member _.IsValue = match d with - | V valRef -> not (isForallFunctionTy cenv.g valRef.Type) + | V vref -> not (isForallFunctionTy cenv.g vref.Type) | _ -> false member _.IsFunction = match d with - | V valRef -> isForallFunctionTy cenv.g valRef.Type + | V vref -> isForallFunctionTy cenv.g vref.Type | _ -> false override x.Equals(other: obj) = @@ -2326,7 +2329,7 @@ type FSharpType(cenv, ty:TType) = DiagnosticsLogger.protectAssemblyExploration true <| fun () -> match stripTyparEqns ty with | TType_app (tcref, _, _) -> FSharpEntity(cenv, tcref).IsUnresolved - | TType_measure (Measure.Con tcref) -> FSharpEntity(cenv, tcref).IsUnresolved + | TType_measure (Measure.Const tcref) -> FSharpEntity(cenv, tcref).IsUnresolved | TType_measure (Measure.Prod _) -> FSharpEntity(cenv, cenv.g.measureproduct_tcr).IsUnresolved | TType_measure Measure.One -> FSharpEntity(cenv, cenv.g.measureone_tcr).IsUnresolved | TType_measure (Measure.Inv _) -> FSharpEntity(cenv, cenv.g.measureinverse_tcr).IsUnresolved @@ -2342,7 +2345,7 @@ type FSharpType(cenv, ty:TType) = isResolved() && protect <| fun () -> match stripTyparEqns ty with - | TType_app _ | TType_measure (Measure.Con _ | Measure.Prod _ | Measure.Inv _ | Measure.One _) -> true + | TType_app _ | TType_measure (Measure.Const _ | Measure.Prod _ | Measure.Inv _ | Measure.One _) -> true | _ -> false member _.IsTupleType = @@ -2363,7 +2366,7 @@ type FSharpType(cenv, ty:TType) = protect <| fun () -> match stripTyparEqns ty with | TType_app (tcref, _, _) -> FSharpEntity(cenv, tcref) - | TType_measure (Measure.Con tcref) -> FSharpEntity(cenv, tcref) + | TType_measure (Measure.Const tcref) -> FSharpEntity(cenv, tcref) | TType_measure (Measure.Prod _) -> FSharpEntity(cenv, cenv.g.measureproduct_tcr) | TType_measure Measure.One -> FSharpEntity(cenv, cenv.g.measureone_tcr) | TType_measure (Measure.Inv _) -> FSharpEntity(cenv, cenv.g.measureinverse_tcr) @@ -2375,8 +2378,8 @@ type FSharpType(cenv, ty:TType) = | TType_anon (_, tyargs) | TType_app (_, tyargs, _) | TType_tuple (_, tyargs) -> (tyargs |> List.map (fun ty -> FSharpType(cenv, ty)) |> makeReadOnlyCollection) - | TType_fun(d, r, _) -> [| FSharpType(cenv, d); FSharpType(cenv, r) |] |> makeReadOnlyCollection - | TType_measure (Measure.Con _) -> [| |] |> makeReadOnlyCollection + | TType_fun(domainTy, rangeTy, _) -> [| FSharpType(cenv, domainTy); FSharpType(cenv, rangeTy) |] |> makeReadOnlyCollection + | TType_measure (Measure.Const _) -> [| |] |> makeReadOnlyCollection | TType_measure (Measure.Prod (t1, t2)) -> [| FSharpType(cenv, TType_measure t1); FSharpType(cenv, TType_measure t2) |] |> makeReadOnlyCollection | TType_measure Measure.One -> [| |] |> makeReadOnlyCollection | TType_measure (Measure.Inv t1) -> [| FSharpType(cenv, TType_measure t1) |] |> makeReadOnlyCollection @@ -2443,8 +2446,8 @@ type FSharpType(cenv, ty:TType) = |> Option.map (fun ty -> FSharpType(cenv, ty)) member _.Instantiate(instantiation:(FSharpGenericParameter * FSharpType) list) = - let typI = instType (instantiation |> List.map (fun (tyv, ty) -> tyv.TypeParameter, ty.Type)) ty - FSharpType(cenv, typI) + let resTy = instType (instantiation |> List.map (fun (tyv, ty) -> tyv.TypeParameter, ty.Type)) ty + FSharpType(cenv, resTy) member _.Type = ty member private x.cenv = cenv @@ -2469,7 +2472,7 @@ type FSharpType(cenv, ty:TType) = | TType_app (tc1, b1, _) -> 10200 + int32 tc1.Stamp + List.sumBy hashType b1 | TType_ucase _ -> 10300 // shouldn't occur in symbols | TType_tuple (_, l1) -> 10400 + List.sumBy hashType l1 - | TType_fun (dty, rty, _) -> 10500 + hashType dty + hashType rty + | TType_fun (domainTy, rangeTy, _) -> 10500 + hashType domainTy + hashType rangeTy | TType_measure _ -> 10600 | TType_anon (_,l1) -> 10800 + List.sumBy hashType l1 hashType ty @@ -2593,9 +2596,9 @@ type FSharpStaticParameter(cenv, sp: Tainted< TypeProviders.ProvidedParameterInf inherit FSharpSymbol(cenv, (fun () -> protect <| fun () -> - let spKind = Import.ImportProvidedType cenv.amap m (sp.PApply((fun x -> x.ParameterType), m)) + let paramTy = Import.ImportProvidedType cenv.amap m (sp.PApply((fun x -> x.ParameterType), m)) let nm = sp.PUntaint((fun p -> p.Name), m) - Item.ArgName((mkSynId m nm, spKind, None))), + Item.ArgName((mkSynId m nm, paramTy, None))), (fun _ _ _ -> true)) member _.Name = diff --git a/src/Compiler/SyntaxTree/LexFilter.fs b/src/Compiler/SyntaxTree/LexFilter.fs index 31f515eead2..9b54f1c9976 100644 --- a/src/Compiler/SyntaxTree/LexFilter.fs +++ b/src/Compiler/SyntaxTree/LexFilter.fs @@ -1744,7 +1744,7 @@ type LexFilterImpl ( // ), 2 // This is a 'unit * int', so for backwards compatibility, do not treat ')' as a continuator, don't apply relaxWhitespace2OffsideRule // Test here: Tests/FSharp.Compiler.ComponentTests/Conformance/LexicalFiltering/Basic/OffsideExceptions.fs, RelaxWhitespace2_AllowedBefore9 | _, CtxtDo offsidePos :: _ - when isSemiSemi || (if (*relaxWhitespace2OffsideRule ||*) isDoContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + when isSemiSemi || (if isDoContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "token at column %d is offside from DO(offsidePos=%a)! delaying token, returning ODECLEND\n" tokenStartCol outputPos offsidePos popCtxt() insertToken ODECLEND @@ -1796,7 +1796,7 @@ type LexFilterImpl ( // 1 // This is not offside for backcompat, don't apply relaxWhitespace2OffsideRule // ] // Test here: Tests/FSharp.Compiler.ComponentTests/Conformance/LexicalFiltering/Basic/OffsideExceptions.fs, RelaxWhitespace2_AllowedBefore9 - | _, CtxtMemberBody offsidePos :: _ when isSemiSemi || (if (*relaxWhitespace2OffsideRule*)false then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + | _, CtxtMemberBody offsidePos :: _ when isSemiSemi || (if false then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "token at column %d is offside from MEMBER/OVERRIDE head with offsidePos %a!\n" tokenStartCol outputPos offsidePos popCtxt() insertToken ODECLEND diff --git a/src/Compiler/SyntaxTree/LexHelpers.fs b/src/Compiler/SyntaxTree/LexHelpers.fs index ad46269bf64..67f6c78f558 100644 --- a/src/Compiler/SyntaxTree/LexHelpers.fs +++ b/src/Compiler/SyntaxTree/LexHelpers.fs @@ -22,24 +22,31 @@ open FSharp.Compiler.Text.Range /// The "mock" file name used by fsi.exe when reading from stdin. /// Has special treatment by the lexer, i.e. __SOURCE_DIRECTORY__ becomes GetCurrentDirectory() -let stdinMockFileName = "stdin" +let stdinMockFileName = "stdin" /// Lexer args: status of #light processing. Mutated when a #light /// directive is processed. This alters the behaviour of the lexfilter. [] -type IndentationAwareSyntaxStatus(initial:bool,warn:bool) = +type IndentationAwareSyntaxStatus(initial: bool, warn: bool) = let mutable status = None - member x.Status - with get() = match status with None -> initial | Some v -> v - and set v = status <- Some(v) + + member x.Status + with get () = + match status with + | None -> initial + | Some v -> v + and set v = status <- Some(v) + member x.ExplicitlySet = status.IsSome member x.WarnOnMultipleTokens = warn - + /// Manage lexer resources (string interning) [] type LexResourceManager(?capacity: int) = - let strings = System.Collections.Concurrent.ConcurrentDictionary(Environment.ProcessorCount, defaultArg capacity 1024) - member x.InternIdentifierToken(s) = + let strings = + System.Collections.Concurrent.ConcurrentDictionary(Environment.ProcessorCount, defaultArg capacity 1024) + + member x.InternIdentifierToken(s) = match strings.TryGetValue s with | true, res -> res | _ -> @@ -47,17 +54,17 @@ type LexResourceManager(?capacity: int) = strings[s] <- res res -/// Lexer parameters -type LexArgs = +/// Lexer parameters +type LexArgs = { - conditionalDefines: string list - resourceManager: LexResourceManager - diagnosticsLogger: DiagnosticsLogger - applyLineDirectives: bool - pathMap: PathMap - mutable ifdefStack: LexerIfdefStack - mutable indentationSyntaxStatus : IndentationAwareSyntaxStatus - mutable stringNest: LexerInterpolatedStringNesting + conditionalDefines: string list + resourceManager: LexResourceManager + diagnosticsLogger: DiagnosticsLogger + applyLineDirectives: bool + pathMap: PathMap + mutable ifdefStack: LexerIfdefStack + mutable indentationSyntaxStatus: IndentationAwareSyntaxStatus + mutable stringNest: LexerInterpolatedStringNesting } /// possible results of lexing a long Unicode escape sequence in a string literal, e.g. "\U0001F47D", @@ -68,33 +75,41 @@ type LongUnicodeLexResult = | Invalid let mkLexargs (conditionalDefines, indentationSyntaxStatus, resourceManager, ifdefStack, diagnosticsLogger, pathMap: PathMap) = - { - conditionalDefines = conditionalDefines - ifdefStack = ifdefStack - indentationSyntaxStatus = indentationSyntaxStatus - resourceManager = resourceManager - diagnosticsLogger = diagnosticsLogger - applyLineDirectives = true - stringNest = [] - pathMap = pathMap + { + conditionalDefines = conditionalDefines + ifdefStack = ifdefStack + indentationSyntaxStatus = indentationSyntaxStatus + resourceManager = resourceManager + diagnosticsLogger = diagnosticsLogger + applyLineDirectives = true + stringNest = [] + pathMap = pathMap } /// Register the lexbuf and call the given function -let reusingLexbufForParsing lexbuf f = +let reusingLexbufForParsing lexbuf f = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse LexbufLocalXmlDocStore.ClearXmlDoc lexbuf LexbufCommentStore.ClearComments lexbuf - + try - f () + f () with e -> - raise (WrappedError(e, (try lexbuf.LexemeRange with _ -> range0))) - -let resetLexbufPos fileName (lexbuf: Lexbuf) = - lexbuf.EndPos <- Position.FirstLine (FileIndex.fileIndexOfFile fileName) + raise ( + WrappedError( + e, + (try + lexbuf.LexemeRange + with _ -> + range0) + ) + ) + +let resetLexbufPos fileName (lexbuf: Lexbuf) = + lexbuf.EndPos <- Position.FirstLine(FileIndex.fileIndexOfFile fileName) /// Reset the lexbuf, configure the initial position with the given file name and call the given function -let usingLexbufForParsing (lexbuf:Lexbuf, fileName) f = +let usingLexbufForParsing (lexbuf: Lexbuf, fileName) f = resetLexbufPos fileName lexbuf reusingLexbufForParsing lexbuf (fun () -> f lexbuf) @@ -104,26 +119,31 @@ let usingLexbufForParsing (lexbuf:Lexbuf, fileName) f = let stringBufferAsString (buf: ByteBuffer) = let buf = buf.AsMemory() - if buf.Length % 2 <> 0 then failwith "Expected even number of bytes" - let chars : char[] = Array.zeroCreate (buf.Length/2) - for i = 0 to (buf.Length/2) - 1 do - let hi = buf.Span[i*2+1] - let lo = buf.Span[i*2] + + if buf.Length % 2 <> 0 then + failwith "Expected even number of bytes" + + let chars: char[] = Array.zeroCreate (buf.Length / 2) + + for i = 0 to (buf.Length / 2) - 1 do + let hi = buf.Span[i * 2 + 1] + let lo = buf.Span[i * 2] let c = char (((int hi) * 256) + (int lo)) chars[i] <- c + String(chars) -/// When lexing bytearrays we don't expect to see any unicode stuff. -/// Likewise when lexing string constants we shouldn't see any trigraphs > 127 -/// So to turn the bytes collected in the string buffer back into a bytearray -/// we just take every second byte we stored. Note all bytes > 127 should have been -/// stored using addIntChar -let stringBufferAsBytes (buf: ByteBuffer) = +/// When lexing bytearrays we don't expect to see any unicode stuff. +/// Likewise when lexing string constants we shouldn't see any trigraphs > 127 +/// So to turn the bytes collected in the string buffer back into a bytearray +/// we just take every second byte we stored. Note all bytes > 127 should have been +/// stored using addIntChar +let stringBufferAsBytes (buf: ByteBuffer) = let bytes = buf.AsMemory() - Array.init (bytes.Length / 2) (fun i -> bytes.Span[i*2]) + Array.init (bytes.Length / 2) (fun i -> bytes.Span[i * 2]) [] -type LexerStringFinisherContext = +type LexerStringFinisherContext = | InterpolatedPart = 1 | Verbatim = 2 | TripleQuote = 4 @@ -132,113 +152,128 @@ type LexerStringFinisher = | LexerStringFinisher of (ByteBuffer -> LexerStringKind -> LexerStringFinisherContext -> LexerContinuation -> token) member fin.Finish (buf: ByteBuffer) kind context cont = - let (LexerStringFinisher f) = fin + let (LexerStringFinisher f) = fin f buf kind context cont static member Default = - LexerStringFinisher (fun buf kind context cont -> + LexerStringFinisher(fun buf kind context cont -> let isPart = context.HasFlag(LexerStringFinisherContext.InterpolatedPart) let isVerbatim = context.HasFlag(LexerStringFinisherContext.Verbatim) let isTripleQuote = context.HasFlag(LexerStringFinisherContext.TripleQuote) - if kind.IsInterpolated then + if kind.IsInterpolated then let s = stringBufferAsString buf + if kind.IsInterpolatedFirst then let synStringKind = - if isTripleQuote then - SynStringKind.TripleQuote - elif isVerbatim then - SynStringKind.Verbatim - else - SynStringKind.Regular - if isPart then - INTERP_STRING_BEGIN_PART (s, synStringKind, cont) - else - INTERP_STRING_BEGIN_END (s, synStringKind, cont) - else + if isTripleQuote then SynStringKind.TripleQuote + elif isVerbatim then SynStringKind.Verbatim + else SynStringKind.Regular + if isPart then - INTERP_STRING_PART (s, cont) + INTERP_STRING_BEGIN_PART(s, synStringKind, cont) else - INTERP_STRING_END (s, cont) + INTERP_STRING_BEGIN_END(s, synStringKind, cont) + else if isPart then + INTERP_STRING_PART(s, cont) + else + INTERP_STRING_END(s, cont) elif kind.IsByteString then - let synByteStringKind = if isVerbatim then SynByteStringKind.Verbatim else SynByteStringKind.Regular - BYTEARRAY (stringBufferAsBytes buf, synByteStringKind, cont) - else - let synStringKind = + let synByteStringKind = if isVerbatim then - SynStringKind.Verbatim - elif isTripleQuote then - SynStringKind.TripleQuote + SynByteStringKind.Verbatim else - SynStringKind.Regular - STRING (stringBufferAsString buf, synStringKind, cont) - ) + SynByteStringKind.Regular -let addUnicodeString (buf: ByteBuffer) (x:string) = - buf.EmitBytes (Encoding.Unicode.GetBytes x) + BYTEARRAY(stringBufferAsBytes buf, synByteStringKind, cont) + else + let synStringKind = + if isVerbatim then SynStringKind.Verbatim + elif isTripleQuote then SynStringKind.TripleQuote + else SynStringKind.Regular -let addIntChar (buf: ByteBuffer) c = - buf.EmitIntAsByte (c % 256) - buf.EmitIntAsByte (c / 256) + STRING(stringBufferAsString buf, synStringKind, cont)) + +let addUnicodeString (buf: ByteBuffer) (x: string) = + buf.EmitBytes(Encoding.Unicode.GetBytes x) + +let addIntChar (buf: ByteBuffer) c = + buf.EmitIntAsByte(c % 256) + buf.EmitIntAsByte(c / 256) let addUnicodeChar buf c = addIntChar buf (int c) -let addByteChar buf (c:char) = addIntChar buf (int32 c % 256) +let addByteChar buf (c: char) = addIntChar buf (int32 c % 256) -/// Sanity check that high bytes are zeros. Further check each low byte <= 127 -let stringBufferIsBytes (buf: ByteBuffer) = +/// Sanity check that high bytes are zeros. Further check each low byte <= 127 +let stringBufferIsBytes (buf: ByteBuffer) = let bytes = buf.AsMemory() - let mutable ok = true - for i = 0 to bytes.Length / 2-1 do - if bytes.Span[i*2+1] <> 0uy then ok <- false + let mutable ok = true + + for i = 0 to bytes.Length / 2 - 1 do + if bytes.Span[i * 2 + 1] <> 0uy then + ok <- false + ok -let newline (lexbuf:LexBuffer<_>) = - lexbuf.EndPos <- lexbuf.EndPos.NextLine +let newline (lexbuf: LexBuffer<_>) = lexbuf.EndPos <- lexbuf.EndPos.NextLine -let advanceColumnBy (lexbuf:LexBuffer<_>) n = +let advanceColumnBy (lexbuf: LexBuffer<_>) n = lexbuf.EndPos <- lexbuf.EndPos.ShiftColumnBy(n) let trigraph c1 c2 c3 = - let digit (c:char) = int c - int '0' + let digit (c: char) = int c - int '0' char (digit c1 * 100 + digit c2 * 10 + digit c3) -let digit d = - if d >= '0' && d <= '9' then int32 d - int32 '0' - else failwith "digit" +let digit d = + if d >= '0' && d <= '9' then + int32 d - int32 '0' + else + failwith "digit" -let hexdigit d = - if d >= '0' && d <= '9' then digit d +let hexdigit d = + if d >= '0' && d <= '9' then digit d elif d >= 'a' && d <= 'f' then int32 d - int32 'a' + 10 elif d >= 'A' && d <= 'F' then int32 d - int32 'A' + 10 - else failwith "hexdigit" + else failwith "hexdigit" + +let unicodeGraphShort (s: string) = + if s.Length <> 4 then + failwith "unicodegraph" -let unicodeGraphShort (s:string) = - if s.Length <> 4 then failwith "unicodegraph" uint16 (hexdigit s[0] * 4096 + hexdigit s[1] * 256 + hexdigit s[2] * 16 + hexdigit s[3]) -let hexGraphShort (s:string) = - if s.Length <> 2 then failwith "hexgraph" +let hexGraphShort (s: string) = + if s.Length <> 2 then + failwith "hexgraph" + uint16 (hexdigit s[0] * 16 + hexdigit s[1]) -let unicodeGraphLong (s:string) = - if s.Length <> 8 then failwith "unicodeGraphLong" - let high = hexdigit s[0] * 4096 + hexdigit s[1] * 256 + hexdigit s[2] * 16 + hexdigit s[3] in - let low = hexdigit s[4] * 4096 + hexdigit s[5] * 256 + hexdigit s[6] * 16 + hexdigit s[7] in +let unicodeGraphLong (s: string) = + if s.Length <> 8 then + failwith "unicodeGraphLong" + + let high = + hexdigit s[0] * 4096 + hexdigit s[1] * 256 + hexdigit s[2] * 16 + hexdigit s[3] in + + let low = + hexdigit s[4] * 4096 + hexdigit s[5] * 256 + hexdigit s[6] * 16 + hexdigit s[7] in // not a surrogate pair - if high = 0 then SingleChar(uint16 low) + if high = 0 then + SingleChar(uint16 low) // invalid encoding - elif high > 0x10 then Invalid + elif high > 0x10 then + Invalid // valid supplementary character: code points U+10000 to U+10FFFF // valid surrogate pair: see http://www.unicode.org/versions/latest/ch03.pdf , "Surrogates" section // high-surrogate code point (U+D800 to U+DBFF) followed by low-surrogate code point (U+DC00 to U+DFFF) else - let codepoint = high * 0x10000 + low - let hiSurr = uint16 (0xD800 + ((codepoint - 0x10000) / 0x400)) - let loSurr = uint16 (0xDC00 + ((codepoint - 0x10000) % 0x400)) - SurrogatePair(hiSurr, loSurr) + let codepoint = high * 0x10000 + low + let hiSurr = uint16 (0xD800 + ((codepoint - 0x10000) / 0x400)) + let loSurr = uint16 (0xDC00 + ((codepoint - 0x10000) % 0x400)) + SurrogatePair(hiSurr, loSurr) -let escape c = +let escape c = match c with | '\\' -> '\\' | '\'' -> '\'' @@ -253,146 +288,171 @@ let escape c = //------------------------------------------------------------------------ // Keyword table -//----------------------------------------------------------------------- +//----------------------------------------------------------------------- exception ReservedKeyword of string * range -module Keywords = +module Keywords = type private compatibilityMode = - | ALWAYS (* keyword *) - | FSHARP (* keyword, but an identifier under --ml-compatibility mode *) - - let private keywordList = - [ FSHARP, "abstract", ABSTRACT - ALWAYS, "and" ,AND - ALWAYS, "as" ,AS - ALWAYS, "assert" ,ASSERT - ALWAYS, "asr" ,INFIX_STAR_STAR_OP "asr" - ALWAYS, "base" ,BASE - ALWAYS, "begin" ,BEGIN - ALWAYS, "class" ,CLASS - FSHARP, "const" ,CONST - FSHARP, "default" ,DEFAULT - FSHARP, "delegate" ,DELEGATE - ALWAYS, "do" ,DO - ALWAYS, "done" ,DONE - FSHARP, "downcast" ,DOWNCAST - ALWAYS, "downto" ,DOWNTO - FSHARP, "elif" ,ELIF - ALWAYS, "else" ,ELSE - ALWAYS, "end" ,END - ALWAYS, "exception" ,EXCEPTION - FSHARP, "extern" ,EXTERN - ALWAYS, "false" ,FALSE - ALWAYS, "finally" ,FINALLY - FSHARP, "fixed" ,FIXED - ALWAYS, "for" ,FOR - ALWAYS, "fun" ,FUN - ALWAYS, "function" ,FUNCTION - FSHARP, "global" ,GLOBAL - ALWAYS, "if" ,IF - ALWAYS, "in" ,IN - ALWAYS, "inherit" ,INHERIT - FSHARP, "inline" ,INLINE - FSHARP, "interface" ,INTERFACE - FSHARP, "internal" ,INTERNAL - ALWAYS, "land" ,INFIX_STAR_DIV_MOD_OP "land" - ALWAYS, "lazy" ,LAZY - ALWAYS, "let" ,LET(false) - ALWAYS, "lor" ,INFIX_STAR_DIV_MOD_OP "lor" - ALWAYS, "lsl" ,INFIX_STAR_STAR_OP "lsl" - ALWAYS, "lsr" ,INFIX_STAR_STAR_OP "lsr" - ALWAYS, "lxor" ,INFIX_STAR_DIV_MOD_OP "lxor" - ALWAYS, "match" ,MATCH - FSHARP, "member" ,MEMBER - ALWAYS, "mod" ,INFIX_STAR_DIV_MOD_OP "mod" - ALWAYS, "module" ,MODULE - ALWAYS, "mutable" ,MUTABLE - FSHARP, "namespace" ,NAMESPACE - ALWAYS, "new" ,NEW - FSHARP, "null" ,NULL - ALWAYS, "of" ,OF - ALWAYS, "open" ,OPEN - ALWAYS, "or" ,OR - FSHARP, "override" ,OVERRIDE - ALWAYS, "private" ,PRIVATE - FSHARP, "public" ,PUBLIC - ALWAYS, "rec" ,REC - FSHARP, "return" ,YIELD(false) - ALWAYS, "sig" ,SIG - FSHARP, "static" ,STATIC - ALWAYS, "struct" ,STRUCT - ALWAYS, "then" ,THEN - ALWAYS, "to" ,TO - ALWAYS, "true" ,TRUE - ALWAYS, "try" ,TRY - ALWAYS, "type" ,TYPE - FSHARP, "upcast" ,UPCAST - FSHARP, "use" ,LET(true) - ALWAYS, "val" ,VAL - FSHARP, "void" ,VOID - ALWAYS, "when" ,WHEN - ALWAYS, "while" ,WHILE - ALWAYS, "with" ,WITH - FSHARP, "yield" ,YIELD(true) - ALWAYS, "_" ,UNDERSCORE - (*------- for prototyping and explaining offside rule *) - FSHARP, "__token_OBLOCKSEP" ,OBLOCKSEP - FSHARP, "__token_OWITH" ,OWITH - FSHARP, "__token_ODECLEND" ,ODECLEND - FSHARP, "__token_OTHEN" ,OTHEN - FSHARP, "__token_OELSE" ,OELSE - FSHARP, "__token_OEND" ,OEND - FSHARP, "__token_ODO" ,ODO - FSHARP, "__token_OLET" ,OLET(true) - FSHARP, "__token_constraint",CONSTRAINT - ] - (*------- reserved keywords which are ml-compatibility ids *) - @ List.map (fun s -> (FSHARP,s,RESERVED)) - [ "break"; "checked"; "component"; "constraint"; "continue" - "fori"; "include"; "mixin" - "parallel"; "params"; "process"; "protected"; "pure" - "sealed"; "trait"; "tailcall"; "virtual" ] + | ALWAYS (* keyword *) + | FSHARP (* keyword, but an identifier under --ml-compatibility mode *) + + let private keywordList = + [ + FSHARP, "abstract", ABSTRACT + ALWAYS, "and", AND + ALWAYS, "as", AS + ALWAYS, "assert", ASSERT + ALWAYS, "asr", INFIX_STAR_STAR_OP "asr" + ALWAYS, "base", BASE + ALWAYS, "begin", BEGIN + ALWAYS, "class", CLASS + FSHARP, "const", CONST + FSHARP, "default", DEFAULT + FSHARP, "delegate", DELEGATE + ALWAYS, "do", DO + ALWAYS, "done", DONE + FSHARP, "downcast", DOWNCAST + ALWAYS, "downto", DOWNTO + FSHARP, "elif", ELIF + ALWAYS, "else", ELSE + ALWAYS, "end", END + ALWAYS, "exception", EXCEPTION + FSHARP, "extern", EXTERN + ALWAYS, "false", FALSE + ALWAYS, "finally", FINALLY + FSHARP, "fixed", FIXED + ALWAYS, "for", FOR + ALWAYS, "fun", FUN + ALWAYS, "function", FUNCTION + FSHARP, "global", GLOBAL + ALWAYS, "if", IF + ALWAYS, "in", IN + ALWAYS, "inherit", INHERIT + FSHARP, "inline", INLINE + FSHARP, "interface", INTERFACE + FSHARP, "internal", INTERNAL + ALWAYS, "land", INFIX_STAR_DIV_MOD_OP "land" + ALWAYS, "lazy", LAZY + ALWAYS, "let", LET(false) + ALWAYS, "lor", INFIX_STAR_DIV_MOD_OP "lor" + ALWAYS, "lsl", INFIX_STAR_STAR_OP "lsl" + ALWAYS, "lsr", INFIX_STAR_STAR_OP "lsr" + ALWAYS, "lxor", INFIX_STAR_DIV_MOD_OP "lxor" + ALWAYS, "match", MATCH + FSHARP, "member", MEMBER + ALWAYS, "mod", INFIX_STAR_DIV_MOD_OP "mod" + ALWAYS, "module", MODULE + ALWAYS, "mutable", MUTABLE + FSHARP, "namespace", NAMESPACE + ALWAYS, "new", NEW + FSHARP, "null", NULL + ALWAYS, "of", OF + ALWAYS, "open", OPEN + ALWAYS, "or", OR + FSHARP, "override", OVERRIDE + ALWAYS, "private", PRIVATE + FSHARP, "public", PUBLIC + ALWAYS, "rec", REC + FSHARP, "return", YIELD(false) + ALWAYS, "sig", SIG + FSHARP, "static", STATIC + ALWAYS, "struct", STRUCT + ALWAYS, "then", THEN + ALWAYS, "to", TO + ALWAYS, "true", TRUE + ALWAYS, "try", TRY + ALWAYS, "type", TYPE + FSHARP, "upcast", UPCAST + FSHARP, "use", LET(true) + ALWAYS, "val", VAL + FSHARP, "void", VOID + ALWAYS, "when", WHEN + ALWAYS, "while", WHILE + ALWAYS, "with", WITH + FSHARP, "yield", YIELD(true) + ALWAYS, "_", UNDERSCORE + (*------- for prototyping and explaining offside rule *) + FSHARP, "__token_OBLOCKSEP", OBLOCKSEP + FSHARP, "__token_OWITH", OWITH + FSHARP, "__token_ODECLEND", ODECLEND + FSHARP, "__token_OTHEN", OTHEN + FSHARP, "__token_OELSE", OELSE + FSHARP, "__token_OEND", OEND + FSHARP, "__token_ODO", ODO + FSHARP, "__token_OLET", OLET(true) + FSHARP, "__token_constraint", CONSTRAINT + ] + (*------- reserved keywords which are ml-compatibility ids *) + @ List.map + (fun s -> (FSHARP, s, RESERVED)) + [ + "break" + "checked" + "component" + "constraint" + "continue" + "fori" + "include" + "mixin" + "parallel" + "params" + "process" + "protected" + "pure" + "sealed" + "trait" + "tailcall" + "virtual" + ] //------------------------------------------------------------------------ // Keywords //----------------------------------------------------------------------- - let keywordNames = - keywordList |> List.map (fun (_, w, _) -> w) + let keywordNames = keywordList |> List.map (fun (_, w, _) -> w) - let keywordTable = + let keywordTable = let tab = System.Collections.Generic.Dictionary(100) - for _, keyword, token in keywordList do + + for _, keyword, token in keywordList do tab.Add(keyword, token) + tab - + let KeywordToken s = keywordTable[s] - let IdentifierToken args (lexbuf:Lexbuf) (s:string) = - if IsCompilerGeneratedName s then - warning(Error(FSComp.SR.lexhlpIdentifiersContainingAtSymbolReserved(), lexbuf.LexemeRange)) + let IdentifierToken args (lexbuf: Lexbuf) (s: string) = + if IsCompilerGeneratedName s then + warning (Error(FSComp.SR.lexhlpIdentifiersContainingAtSymbolReserved (), lexbuf.LexemeRange)) + args.resourceManager.InternIdentifierToken s - let KeywordOrIdentifierToken args (lexbuf:Lexbuf) s = + let KeywordOrIdentifierToken args (lexbuf: Lexbuf) s = match keywordTable.TryGetValue s with | true, v -> - match v with + match v with | RESERVED -> - warning(ReservedKeyword(FSComp.SR.lexhlpIdentifierReserved(s), lexbuf.LexemeRange)) + warning (ReservedKeyword(FSComp.SR.lexhlpIdentifierReserved (s), lexbuf.LexemeRange)) IdentifierToken args lexbuf s | _ -> - match s with - | "land" | "lor" | "lxor" - | "lsl" | "lsr" | "asr" -> + match s with + | "land" + | "lor" + | "lxor" + | "lsl" + | "lsr" + | "asr" -> if lexbuf.SupportsFeature LanguageFeature.MLCompatRevisions then - mlCompatWarning (FSComp.SR.mlCompatKeyword(s)) lexbuf.LexemeRange + mlCompatWarning (FSComp.SR.mlCompatKeyword (s)) lexbuf.LexemeRange | _ -> () + v | _ -> - match s with + match s with | "__SOURCE_DIRECTORY__" -> let fileName = FileIndex.fileOfFileIndex lexbuf.StartPos.FileIndex + let dirname = if String.IsNullOrWhiteSpace(fileName) then String.Empty @@ -403,13 +463,11 @@ module Keywords = |> FileSystem.GetFullPathShim (* asserts that path is already absolute *) |> System.IO.Path.GetDirectoryName - if String.IsNullOrEmpty dirname then dirname - else PathMap.applyDir args.pathMap dirname + if String.IsNullOrEmpty dirname then + dirname + 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)) - | "__LINE__" -> - KEYWORD_STRING (s, string lexbuf.StartPos.Line) - | _ -> - IdentifierToken args lexbuf s - + | "__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/ParseHelpers.fs b/src/Compiler/SyntaxTree/ParseHelpers.fs index aafb8174345..ff7a44e98a4 100644 --- a/src/Compiler/SyntaxTree/ParseHelpers.fs +++ b/src/Compiler/SyntaxTree/ParseHelpers.fs @@ -29,26 +29,24 @@ exception SyntaxError of obj (* ParseErrorContext<_> *) * range: range exception IndentationProblem of string * range -let warningStringOfCoords line column = - sprintf "(%d:%d)" line (column + 1) +let warningStringOfCoords line column = sprintf "(%d:%d)" line (column + 1) -let warningStringOfPos (p: pos) = - warningStringOfCoords p.Line p.Column +let warningStringOfPos (p: pos) = warningStringOfCoords p.Line p.Column //------------------------------------------------------------------------ // Parsing: getting positions from the lexer //------------------------------------------------------------------------ /// Get an F# compiler position from a lexer position -let posOfLexPosition (p: Position) = - mkPos p.Line p.Column +let posOfLexPosition (p: Position) = mkPos p.Line p.Column /// Get an F# compiler range from a lexer range let mkSynRange (p1: Position) (p2: Position) = mkFileIndexRange p1.FileIndex (posOfLexPosition p1) (posOfLexPosition p2) type LexBuffer<'Char> with - member lexbuf.LexemeRange = mkSynRange lexbuf.StartPos lexbuf.EndPos + + member lexbuf.LexemeRange = mkSynRange lexbuf.StartPos lexbuf.EndPos /// Get the range corresponding to the result of a grammar rule while it is being reduced let lhs (parseState: IParseState) = @@ -71,6 +69,7 @@ type IParseState with member x.SynArgNameGenerator = let key = "SynArgNameGenerator" let bls = x.LexBuffer.BufferLocalStore + let gen = match bls.TryGetValue key with | true, gen -> gen @@ -78,6 +77,7 @@ type IParseState with let gen = box (SynArgNameGenerator()) bls[key] <- gen gen + gen :?> SynArgNameGenerator /// Reset the generator used for compiler-generated argument names. @@ -97,13 +97,13 @@ module LexbufLocalXmlDocStore = | true, collector -> collector | _ -> let collector = box (XmlDocCollector()) - lexbuf.BufferLocalStore[xmlDocKey] <- collector + lexbuf.BufferLocalStore[ xmlDocKey ] <- collector collector |> unbox let ClearXmlDoc (lexbuf: Lexbuf) = - lexbuf.BufferLocalStore[xmlDocKey] <- box (XmlDocCollector()) + lexbuf.BufferLocalStore[ xmlDocKey ] <- box (XmlDocCollector()) /// Called from the lexer to save a single line of XML doc comment. let SaveXmlDocLine (lexbuf: Lexbuf, lineText, range: range) = @@ -132,13 +132,12 @@ module LexbufLocalXmlDocStore = /// Called from the parser each time we parse a construct that marks the end of an XML doc comment range, /// e.g. a 'type' declaration. The markerRange is the range of the keyword that delimits the construct. - let GrabXmlDocBeforeMarker (lexbuf: Lexbuf, markerRange: range) = + let GrabXmlDocBeforeMarker (lexbuf: Lexbuf, markerRange: range) = match lexbuf.BufferLocalStore.TryGetValue xmlDocKey with | true, collector -> - let collector = unbox(collector) + let collector = unbox (collector) PreXmlDoc.CreateFromGrabPoint(collector, markerRange.Start) - | _ -> - PreXmlDoc.Empty + | _ -> PreXmlDoc.Empty let ReportInvalidXmlDocPositions (lexbuf: Lexbuf) = let collector = getCollector lexbuf @@ -162,20 +161,21 @@ type LexerIfdefStack = LexerIfdefStackEntries /// it reaches end of line or eof. The options are to continue with 'token' function /// or to continue with 'skip' function. type LexerEndlineContinuation = - | Token + | Token | Skip of int * range: range type LexerIfdefExpression = - | IfdefAnd of LexerIfdefExpression*LexerIfdefExpression - | IfdefOr of LexerIfdefExpression*LexerIfdefExpression + | IfdefAnd of LexerIfdefExpression * LexerIfdefExpression + | IfdefOr of LexerIfdefExpression * LexerIfdefExpression | IfdefNot of LexerIfdefExpression | IfdefId of string -let rec LexerIfdefEval (lookup: string -> bool) = function - | IfdefAnd (l, r) -> (LexerIfdefEval lookup l) && (LexerIfdefEval lookup r) - | IfdefOr (l, r) -> (LexerIfdefEval lookup l) || (LexerIfdefEval lookup r) - | IfdefNot e -> not (LexerIfdefEval lookup e) - | IfdefId id -> lookup id +let rec LexerIfdefEval (lookup: string -> bool) = + function + | IfdefAnd (l, r) -> (LexerIfdefEval lookup l) && (LexerIfdefEval lookup r) + | IfdefOr (l, r) -> (LexerIfdefEval lookup l) || (LexerIfdefEval lookup r) + | IfdefNot e -> not (LexerIfdefEval lookup e) + | IfdefId id -> lookup id /// Ifdef F# lexer/parser state, held in the BufferLocalStore for the lexer. /// Used to capture #if, #else and #endif as syntax trivia. @@ -183,47 +183,47 @@ module LexbufIfdefStore = // The key into the BufferLocalStore used to hold the compiler directives let private ifDefKey = "Ifdef" - let private getStore (lexbuf: Lexbuf): ResizeArray = + let private getStore (lexbuf: Lexbuf) : ResizeArray = match lexbuf.BufferLocalStore.TryGetValue ifDefKey with | true, store -> store | _ -> let store = box (ResizeArray()) - lexbuf.BufferLocalStore[ifDefKey] <- store + lexbuf.BufferLocalStore[ ifDefKey ] <- store store |> unbox> - let private mkRangeWithoutLeadingWhitespace (lexed:string) (m:range): range = - let startColumn = lexed.Length - lexed.TrimStart().Length - mkFileIndexRange m.FileIndex (mkPos m.StartLine startColumn) m.End - - let SaveIfHash (lexbuf: Lexbuf, lexed:string, expr: LexerIfdefExpression, range: range) = + let private mkRangeWithoutLeadingWhitespace (lexed: string) (m: range) : range = + let startColumn = lexed.Length - lexed.TrimStart().Length + mkFileIndexRange m.FileIndex (mkPos m.StartLine startColumn) m.End + + let SaveIfHash (lexbuf: Lexbuf, lexed: string, expr: LexerIfdefExpression, range: range) = let store = getStore lexbuf let expr = let rec visit (expr: LexerIfdefExpression) : IfDirectiveExpression = match expr with - | LexerIfdefExpression.IfdefAnd(l,r) -> IfDirectiveExpression.And(visit l, visit r) - | LexerIfdefExpression.IfdefOr(l, r) -> IfDirectiveExpression.Or(visit l, visit r) + | LexerIfdefExpression.IfdefAnd (l, r) -> IfDirectiveExpression.And(visit l, visit r) + | LexerIfdefExpression.IfdefOr (l, r) -> IfDirectiveExpression.Or(visit l, visit r) | LexerIfdefExpression.IfdefNot e -> IfDirectiveExpression.Not(visit e) | LexerIfdefExpression.IfdefId id -> IfDirectiveExpression.Ident id - + visit expr let m = mkRangeWithoutLeadingWhitespace lexed range - + store.Add(ConditionalDirectiveTrivia.If(expr, m)) - let SaveElseHash (lexbuf: Lexbuf, lexed:string, range: range) = + let SaveElseHash (lexbuf: Lexbuf, lexed: string, range: range) = let store = getStore lexbuf let m = mkRangeWithoutLeadingWhitespace lexed range store.Add(ConditionalDirectiveTrivia.Else(m)) - let SaveEndIfHash (lexbuf: Lexbuf, lexed:string, range: range) = + let SaveEndIfHash (lexbuf: Lexbuf, lexed: string, range: range) = let store = getStore lexbuf let m = mkRangeWithoutLeadingWhitespace lexed range store.Add(ConditionalDirectiveTrivia.EndIf(m)) - let GetTrivia (lexbuf: Lexbuf): ConditionalDirectiveTrivia list = + let GetTrivia (lexbuf: Lexbuf) : ConditionalDirectiveTrivia list = let store = getStore lexbuf Seq.toList store @@ -232,12 +232,12 @@ module LexbufCommentStore = // The key into the BufferLocalStore used to hold the compiler directives let private commentKey = "Comments" - let private getStore (lexbuf: Lexbuf): ResizeArray = + let private getStore (lexbuf: Lexbuf) : ResizeArray = match lexbuf.BufferLocalStore.TryGetValue commentKey with | true, store -> store | _ -> let store = box (ResizeArray()) - lexbuf.BufferLocalStore[commentKey] <- store + lexbuf.BufferLocalStore[ commentKey ] <- store store |> unbox> @@ -251,11 +251,11 @@ module LexbufCommentStore = let m = unionRanges startRange endRange store.Add(CommentTrivia.BlockComment(m)) - let GetComments (lexbuf: Lexbuf): CommentTrivia list = + let GetComments (lexbuf: Lexbuf) : CommentTrivia list = let store = getStore lexbuf Seq.toList store - let ClearComments (lexbuf: Lexbuf): unit = + let ClearComments (lexbuf: Lexbuf) : unit = lexbuf.BufferLocalStore.Remove(commentKey) |> ignore //------------------------------------------------------------------------ @@ -270,13 +270,39 @@ type LexerStringStyle = [] type LexerStringKind = - { IsByteString: bool - IsInterpolated: bool - IsInterpolatedFirst: bool } - static member String = { IsByteString = false; IsInterpolated = false; IsInterpolatedFirst=false } - static member ByteString = { IsByteString = true; IsInterpolated = false; IsInterpolatedFirst=false } - static member InterpolatedStringFirst = { IsByteString = false; IsInterpolated = true; IsInterpolatedFirst=true } - static member InterpolatedStringPart = { IsByteString = false; IsInterpolated = true; IsInterpolatedFirst=false } + { + IsByteString: bool + IsInterpolated: bool + IsInterpolatedFirst: bool + } + + static member String = + { + IsByteString = false + IsInterpolated = false + IsInterpolatedFirst = false + } + + static member ByteString = + { + IsByteString = true + IsInterpolated = false + IsInterpolatedFirst = false + } + + static member InterpolatedStringFirst = + { + IsByteString = false + IsInterpolated = true + IsInterpolatedFirst = true + } + + static member InterpolatedStringPart = + { + IsByteString = false + IsInterpolated = true + IsInterpolatedFirst = false + } /// Represents the degree of nesting of '{..}' and the style of the string to continue afterwards, in an interpolation fill. /// Nesting counters and styles of outer interpolating strings are pushed on this stack. @@ -291,36 +317,46 @@ type LexerInterpolatedStringNesting = (int * LexerStringStyle * range) list type LexerContinuation = | Token of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting | IfDefSkip of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting * int * range: range - | String of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting * style: LexerStringStyle * kind: LexerStringKind * range: range + | String of + ifdef: LexerIfdefStackEntries * + nesting: LexerInterpolatedStringNesting * + style: LexerStringStyle * + kind: LexerStringKind * + range: range | Comment of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting * int * range: range | SingleLineComment of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting * int * range: range - | StringInComment of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting * style: LexerStringStyle * int * range: range + | StringInComment of + ifdef: LexerIfdefStackEntries * + nesting: LexerInterpolatedStringNesting * + style: LexerStringStyle * + int * + range: range | MLOnly of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting * range: range | EndLine of ifdef: LexerIfdefStackEntries * nesting: LexerInterpolatedStringNesting * LexerEndlineContinuation - static member Default = LexCont.Token([],[]) + static member Default = LexCont.Token([], []) member x.LexerIfdefStack = match x with - | LexCont.Token (ifdef=ifd) - | LexCont.IfDefSkip (ifdef=ifd) - | LexCont.String (ifdef=ifd) - | LexCont.Comment (ifdef=ifd) - | LexCont.SingleLineComment (ifdef=ifd) - | LexCont.StringInComment (ifdef=ifd) - | LexCont.EndLine (ifdef=ifd) - | LexCont.MLOnly (ifdef=ifd) -> ifd + | LexCont.Token (ifdef = ifd) + | LexCont.IfDefSkip (ifdef = ifd) + | LexCont.String (ifdef = ifd) + | LexCont.Comment (ifdef = ifd) + | LexCont.SingleLineComment (ifdef = ifd) + | LexCont.StringInComment (ifdef = ifd) + | LexCont.EndLine (ifdef = ifd) + | LexCont.MLOnly (ifdef = ifd) -> ifd member x.LexerInterpStringNesting = match x with - | LexCont.Token (nesting=nesting) - | LexCont.IfDefSkip (nesting=nesting) - | LexCont.String (nesting=nesting) - | LexCont.Comment (nesting=nesting) - | LexCont.SingleLineComment (nesting=nesting) - | LexCont.StringInComment (nesting=nesting) - | LexCont.EndLine (nesting=nesting) - | LexCont.MLOnly (nesting=nesting) -> nesting + | LexCont.Token (nesting = nesting) + | LexCont.IfDefSkip (nesting = nesting) + | LexCont.String (nesting = nesting) + | LexCont.Comment (nesting = nesting) + | LexCont.SingleLineComment (nesting = nesting) + | LexCont.StringInComment (nesting = nesting) + | LexCont.EndLine (nesting = nesting) + | LexCont.MLOnly (nesting = nesting) -> nesting and LexCont = LexerContinuation @@ -328,44 +364,450 @@ and LexCont = LexerContinuation // Parse IL assembly code //------------------------------------------------------------------------ -let ParseAssemblyCodeInstructions s reportLibraryOnlyFeatures langVersion m : IL.ILInstr[] = +let ParseAssemblyCodeInstructions s reportLibraryOnlyFeatures langVersion m : IL.ILInstr[] = #if NO_INLINE_IL_PARSER ignore s ignore isFeatureSupported - errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) - [| |] + errorR (Error((193, "Inline IL not valid in a hosted environment"), m)) + [||] #else try - AsciiParser.ilInstrs - AsciiLexer.token - (StringAsLexbuf(reportLibraryOnlyFeatures, langVersion, s)) + AsciiParser.ilInstrs AsciiLexer.token (StringAsLexbuf(reportLibraryOnlyFeatures, langVersion, s)) with _ -> - errorR(Error(FSComp.SR.astParseEmbeddedILError(), m)); [||] + errorR (Error(FSComp.SR.astParseEmbeddedILError (), m)) + [||] #endif let ParseAssemblyCodeType s reportLibraryOnlyFeatures langVersion m = ignore s #if NO_INLINE_IL_PARSER - errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) + errorR (Error((193, "Inline IL not valid in a hosted environment"), m)) IL.PrimaryAssemblyILGlobals.typ_Object #else try - AsciiParser.ilType - AsciiLexer.token - (StringAsLexbuf(reportLibraryOnlyFeatures, langVersion, s)) + AsciiParser.ilType AsciiLexer.token (StringAsLexbuf(reportLibraryOnlyFeatures, langVersion, s)) with RecoverableParseError -> - errorR(Error(FSComp.SR.astParseEmbeddedILTypeError(), m)); - IL.PrimaryAssemblyILGlobals.typ_Object + errorR (Error(FSComp.SR.astParseEmbeddedILTypeError (), m)) + IL.PrimaryAssemblyILGlobals.typ_Object #endif -let grabXmlDocAtRangeStart(parseState: IParseState, optAttributes: SynAttributeList list, range: range) = +let grabXmlDocAtRangeStart (parseState: IParseState, optAttributes: SynAttributeList list, range: range) = let grabPoint = match optAttributes with | [] -> range | h :: _ -> h.Range + LexbufLocalXmlDocStore.GrabXmlDocBeforeMarker(parseState.LexBuffer, grabPoint) -let grabXmlDoc(parseState: IParseState, optAttributes: SynAttributeList list, elemIdx) = - grabXmlDocAtRangeStart(parseState, optAttributes, rhs parseState elemIdx) +let grabXmlDoc (parseState: IParseState, optAttributes: SynAttributeList list, elemIdx) = + grabXmlDocAtRangeStart (parseState, optAttributes, rhs parseState elemIdx) + +let reportParseErrorAt m s = errorR (Error(s, m)) + +let raiseParseErrorAt m s = + reportParseErrorAt m s + // This initiates error recovery + raise RecoverableParseError + +let (|GetIdent|SetIdent|OtherIdent|) (ident: Ident option) = + match ident with + | Some ident when ident.idText = "get" -> GetIdent ident.idRange + | Some ident when ident.idText = "set" -> SetIdent ident.idRange + | _ -> OtherIdent + +let mkSynMemberDefnGetSet + (parseState: IParseState) + (opt_inline: bool) + (mWith: range) + (classDefnMemberGetSetElements: (bool * SynAttributeList list * (SynPat * range) * SynReturnInfo option * range option * SynExpr * range) list) + (mAnd: range option) + (mWhole: range) + (propertyNameBindingPat: SynPat) + (optPropertyType: SynReturnInfo option) + (visNoLongerUsed: SynAccess option) + (memFlagsBuilder: SynMemberKind -> SynMemberFlags) + (attrs: SynAttributeList list) + (rangeStart: range) + : SynMemberDefn list = + let isMutable = false + let mutable hasGet = false + let mutable hasSet = false + + let xmlDoc = grabXmlDocAtRangeStart (parseState, attrs, rangeStart) + + let tryMkSynMemberDefnMember + ( + optInline, + optAttrs: SynAttributeList list, + (bindingPat, mBindLhs), + optReturnType, + mEquals, + expr, + mExpr + ) : (SynMemberDefn * Ident option) option = + let optInline = opt_inline || optInline + // optional attributes are only applied to getters and setters + // the "top level" attrs will be applied to both + let optAttrs = + optAttrs + |> List.map (fun attrList -> + { attrList with + Attributes = + attrList.Attributes + |> List.map (fun a -> + { a with + AppliesToGetterAndSetter = true + }) + }) + + let attrs = attrs @ optAttrs + + let trivia: SynBindingTrivia = + { + LetKeyword = None + EqualsRange = mEquals + } + + let binding = + mkSynBinding + (xmlDoc, bindingPat) + (visNoLongerUsed, + optInline, + isMutable, + mBindLhs, + DebugPointAtBinding.NoneAtInvisible, + optReturnType, + expr, + mExpr, + [], + attrs, + Some(memFlagsBuilder SynMemberKind.Member), + trivia) + + let (SynBinding (accessibility = vis; isInline = isInline; attributes = attrs; headPat = pv; range = mBindLhs)) = + binding + + let memberKind = + let getset = + let rec go p = + match p with + | SynPat.LongIdent(longDotId = SynLongIdent ([ id ], _, _)) -> id.idText + | SynPat.Named (SynIdent (nm, _), _, _, _) + | SynPat.As (_, SynPat.Named (SynIdent (nm, _), _, _, _), _) -> nm.idText + | SynPat.Typed (p, _, _) -> go p + | SynPat.Attrib (p, _, _) -> go p + | _ -> raiseParseErrorAt mBindLhs (FSComp.SR.parsInvalidDeclarationSyntax ()) + + go pv + + if getset = "get" then + if hasGet then + reportParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired ()) + None + else + hasGet <- true + Some SynMemberKind.PropertyGet + else if getset = "set" then + if hasSet then + reportParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired ()) + None + else + hasSet <- true + Some SynMemberKind.PropertySet + else + raiseParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired ()) + + match memberKind with + | None -> None + | Some memberKind -> + + // REVIEW: It's hard not to ignore the optPropertyType type annotation for 'set' properties. To apply it, + // we should apply it to the last argument, but at this point we've already pushed the patterns that + // make up the arguments onto the RHS. So we just always give a warning. + + (match optPropertyType with + | Some _ -> errorR (Error(FSComp.SR.parsTypeAnnotationsOnGetSet (), mBindLhs)) + | None -> ()) + + let optReturnType = + match (memberKind, optReturnType) with + | SynMemberKind.PropertySet, _ -> optReturnType + | _, None -> optPropertyType + | _ -> optReturnType + + // REDO with the correct member kind + let trivia: SynBindingTrivia = + { + LetKeyword = None + EqualsRange = mEquals + } + + let binding = + mkSynBinding + (PreXmlDoc.Empty, bindingPat) + (vis, + isInline, + isMutable, + mBindLhs, + DebugPointAtBinding.NoneAtInvisible, + optReturnType, + expr, + mExpr, + [], + attrs, + Some(memFlagsBuilder memberKind), + trivia) + + let (SynBinding (vis, _, isInline, _, attrs, doc, valSynData, pv, rhsRetInfo, rhsExpr, mBindLhs, spBind, trivia)) = + binding + + let mWholeBindLhs = + (mBindLhs, attrs) + ||> unionRangeWithListBy (fun (a: SynAttributeList) -> a.Range) + + let (SynValData (_, valSynInfo, _)) = valSynData + + // Setters have all arguments tupled in their internal TAST form, though they don't appear to be + // tupled from the syntax + let memFlags: SynMemberFlags = memFlagsBuilder memberKind + + let valSynInfo = + let adjustValueArg valueArg = + match valueArg with + | [ _ ] -> valueArg + | _ -> SynInfo.unnamedTopArg + + match memberKind, valSynInfo, memFlags.IsInstance with + | SynMemberKind.PropertyGet, SynValInfo ([], _ret), false + | SynMemberKind.PropertyGet, SynValInfo ([ _ ], _ret), true -> + raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsGetterMustHaveAtLeastOneArgument ()) + + | SynMemberKind.PropertyGet, SynValInfo (thisArg :: indexOrUnitArgs :: rest, ret), true -> + if not rest.IsEmpty then + reportParseErrorAt mWholeBindLhs (FSComp.SR.parsGetterAtMostOneArgument ()) + + SynValInfo([ thisArg; indexOrUnitArgs ], ret) + + | SynMemberKind.PropertyGet, SynValInfo (indexOrUnitArgs :: rest, ret), false -> + if not rest.IsEmpty then + reportParseErrorAt mWholeBindLhs (FSComp.SR.parsGetterAtMostOneArgument ()) + + SynValInfo([ indexOrUnitArgs ], ret) + + | SynMemberKind.PropertySet, SynValInfo ([ thisArg; valueArg ], ret), true -> + SynValInfo([ thisArg; adjustValueArg valueArg ], ret) + + | SynMemberKind.PropertySet, SynValInfo (thisArg :: indexArgs :: valueArg :: rest, ret), true -> + if not rest.IsEmpty then + reportParseErrorAt mWholeBindLhs (FSComp.SR.parsSetterAtMostTwoArguments ()) + + SynValInfo([ thisArg; indexArgs @ adjustValueArg valueArg ], ret) + + | SynMemberKind.PropertySet, SynValInfo ([ valueArg ], ret), false -> SynValInfo([ adjustValueArg valueArg ], ret) + + | SynMemberKind.PropertySet, SynValInfo (indexArgs :: valueArg :: rest, ret), _ -> + if not rest.IsEmpty then + reportParseErrorAt mWholeBindLhs (FSComp.SR.parsSetterAtMostTwoArguments ()) + + SynValInfo([ indexArgs @ adjustValueArg valueArg ], ret) + + | _ -> + // should be unreachable, cover just in case + raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsInvalidProperty ()) + + let valSynData = SynValData(Some(memFlags), valSynInfo, None) + + // Fold together the information from the first lambda pattern and the get/set binding + // This uses the 'this' variable from the first and the patterns for the get/set binding, + // replacing the get/set identifier. A little gross. + + let (bindingPatAdjusted, getOrSetIdentOpt), xmlDocAdjusted = + + let trivia: SynBindingTrivia = + { + LetKeyword = None + EqualsRange = mEquals + } + + let bindingOuter = + mkSynBinding + (xmlDoc, propertyNameBindingPat) + (vis, + optInline, + isMutable, + mWholeBindLhs, + spBind, + optReturnType, + expr, + mExpr, + [], + attrs, + Some(memFlagsBuilder SynMemberKind.Member), + trivia) + + let (SynBinding (_, _, _, _, _, doc2, _, bindingPatOuter, _, _, _, _, _)) = + bindingOuter + + let lidOuter, lidVisOuter = + match bindingPatOuter with + | SynPat.LongIdent (lid, _, None, SynArgPats.Pats [], lidVisOuter, _m) -> lid, lidVisOuter + | SynPat.Named (SynIdent (id, _), _, visOuter, _m) + | SynPat.As (_, SynPat.Named (SynIdent (id, _), _, visOuter, _m), _) -> SynLongIdent([ id ], [], [ None ]), visOuter + | _ -> raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsInvalidDeclarationSyntax ()) + + // Merge the visibility from the outer point with the inner point, e.g. + // member this.Size with get () = m_size + + let mergeLidVisOuter lidVisInner = + match lidVisInner, lidVisOuter with + | None, None -> None + | Some lidVisInner, None + | None, Some lidVisInner -> Some lidVisInner + | Some _, Some _ -> + errorR (Error(FSComp.SR.parsMultipleAccessibilitiesForGetSet (), mWholeBindLhs)) + lidVisInner + + // Replace the "get" or the "set" with the right name + let rec go p = + match p with + | SynPat.LongIdent (longDotId = SynLongIdent ([ id ], _, _) + typarDecls = tyargs + argPats = SynArgPats.Pats args + accessibility = lidVisInner + range = m) -> + // Setters have all arguments tupled in their internal form, though they don't + // appear to be tupled from the syntax. Somewhat unfortunate + let args = + if id.idText = "set" then + match args with + | [ SynPat.Paren (SynPat.Tuple (false, indexPats, _), indexPatRange); valuePat ] when id.idText = "set" -> + [ + SynPat.Tuple(false, indexPats @ [ valuePat ], unionRanges indexPatRange valuePat.Range) + ] + | [ indexPat; valuePat ] -> [ SynPat.Tuple(false, args, unionRanges indexPat.Range valuePat.Range) ] + | [ valuePat ] -> [ valuePat ] + | _ -> raiseParseErrorAt m (FSComp.SR.parsSetSyntax ()) + else + args + + SynPat.LongIdent(lidOuter, Some id, tyargs, SynArgPats.Pats args, mergeLidVisOuter lidVisInner, m), Some id + | SynPat.Named (_, _, lidVisInner, m) + | SynPat.As (_, SynPat.Named (_, _, lidVisInner, m), _) -> + SynPat.LongIdent(lidOuter, None, None, SynArgPats.Pats [], mergeLidVisOuter lidVisInner, m), None + | SynPat.Typed (p, ty, m) -> + let p, id = go p + SynPat.Typed(p, ty, m), id + | SynPat.Attrib (p, attribs, m) -> + let p, id = go p + SynPat.Attrib(p, attribs, m), id + | SynPat.Wild m -> SynPat.Wild(m), None + | _ -> raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsInvalidDeclarationSyntax ()) + + go pv, PreXmlDoc.Merge doc2 doc + + let binding = + SynBinding( + vis, + SynBindingKind.Normal, + isInline, + isMutable, + attrs, + xmlDocAdjusted, + valSynData, + bindingPatAdjusted, + rhsRetInfo, + rhsExpr, + mWholeBindLhs, + spBind, + trivia + ) + + let memberRange = + unionRanges rangeStart mWhole |> unionRangeWithXmlDoc xmlDocAdjusted + + Some(SynMemberDefn.Member(binding, memberRange), getOrSetIdentOpt) + + // Iterate over 1 or 2 'get'/'set' entries + match classDefnMemberGetSetElements with + | [ h ] -> + match tryMkSynMemberDefnMember h with + | Some (memberDefn, getSetIdentOpt) -> + match memberDefn, getSetIdentOpt with + | SynMemberDefn.Member _, None -> [ memberDefn ] + | SynMemberDefn.Member (binding, m), Some getOrSet -> + if getOrSet.idText = "get" then + let trivia = + { + WithKeyword = mWith + GetKeyword = Some getOrSet.idRange + AndKeyword = None + SetKeyword = None + } + + [ SynMemberDefn.GetSetMember(Some binding, None, m, trivia) ] + else + let trivia = + { + WithKeyword = mWith + GetKeyword = None + AndKeyword = None + SetKeyword = Some getOrSet.idRange + } + + [ SynMemberDefn.GetSetMember(None, Some binding, m, trivia) ] + | _ -> [] + | None -> [] + | [ g; s ] -> + let getter = tryMkSynMemberDefnMember g + let setter = tryMkSynMemberDefnMember s + + match getter, setter with + | Some (SynMemberDefn.Member (getBinding, m1), GetIdent mGet), Some (SynMemberDefn.Member (setBinding, m2), SetIdent mSet) + | Some (SynMemberDefn.Member (setBinding, m1), SetIdent mSet), Some (SynMemberDefn.Member (getBinding, m2), GetIdent mGet) -> + let range = unionRanges m1 m2 + + let trivia = + { + WithKeyword = mWith + GetKeyword = Some mGet + AndKeyword = mAnd + SetKeyword = Some mSet + } + + [ SynMemberDefn.GetSetMember(Some getBinding, Some setBinding, range, trivia) ] + | Some (SynMemberDefn.Member (binding, m), getOrSet), None + | None, Some (SynMemberDefn.Member (binding, m), getOrSet) -> + let trivia = + match getOrSet with + | GetIdent mGet -> + { + WithKeyword = mWith + GetKeyword = Some mGet + AndKeyword = mAnd + SetKeyword = None + } + | SetIdent mSet -> + { + WithKeyword = mWith + GetKeyword = None + AndKeyword = mAnd + SetKeyword = Some mSet + } + | OtherIdent -> + { + WithKeyword = mWith + AndKeyword = mAnd + GetKeyword = None + SetKeyword = None + } + + if trivia.GetKeyword.IsSome then + [ SynMemberDefn.GetSetMember(Some binding, None, m, trivia) ] + elif trivia.SetKeyword.IsSome then + [ SynMemberDefn.GetSetMember(None, Some binding, m, trivia) ] + else + [] + | _ -> [] + | _ -> [] diff --git a/src/Compiler/SyntaxTree/ParseHelpers.fsi b/src/Compiler/SyntaxTree/ParseHelpers.fsi index 09133a9deb6..c240ab124e5 100644 --- a/src/Compiler/SyntaxTree/ParseHelpers.fsi +++ b/src/Compiler/SyntaxTree/ParseHelpers.fsi @@ -156,3 +156,22 @@ val grabXmlDoc: parseState: IParseState * optAttributes: SynAttributeList list * val ParseAssemblyCodeType: s: string -> reportLibraryOnlyFeatures: bool -> langVersion: LanguageVersion -> m: range -> ILType + +val reportParseErrorAt: range -> (int * string) -> unit + +val raiseParseErrorAt: range -> (int * string) -> 'a + +val mkSynMemberDefnGetSet: + parseState: IParseState -> + opt_inline: bool -> + mWith: range -> + classDefnMemberGetSetElements: (bool * SynAttributeList list * (SynPat * range) * SynReturnInfo option * range option * SynExpr * range) list -> + mAnd: range option -> + mWhole: range -> + propertyNameBindingPat: SynPat -> + optPropertyType: SynReturnInfo option -> + visNoLongerUsed: SynAccess option -> + memFlagsBuilder: (SynMemberKind -> SynMemberFlags) -> + attrs: SynAttributeList list -> + rangeStart: range -> + SynMemberDefn list diff --git a/src/Compiler/SyntaxTree/PrettyNaming.fs b/src/Compiler/SyntaxTree/PrettyNaming.fs index 5039530b7e5..6e25b5c6360 100755 --- a/src/Compiler/SyntaxTree/PrettyNaming.fs +++ b/src/Compiler/SyntaxTree/PrettyNaming.fs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. /// Some general F# utilities for mangling / unmangling / manipulating names. -/// Anything to do with special names of identifiers and other lexical rules +/// Anything to do with special names of identifiers and other lexical rules module public FSharp.Compiler.Syntax.PrettyNaming open System @@ -19,109 +19,123 @@ open FSharp.Compiler.Text.Layout // Operator name compilation //----------------------------------------------------------------------- -let [] parenGet = ".()" -let [] parenSet = ".()<-" -let [] qmark = "?" -let [] qmarkSet = "?<-" +[] +let parenGet = ".()" + +[] +let parenSet = ".()<-" + +[] +let qmark = "?" + +[] +let qmarkSet = "?<-" /// Prefix for compiled (mangled) operator names. -let [] opNamePrefix = "op_" - -let opNameTable = - [|("[]", "op_Nil") - ("::", "op_ColonColon") - ("+", "op_Addition") - ("~%", "op_Splice") - ("~%%", "op_SpliceUntyped") - ("~++", "op_Increment") - ("~--", "op_Decrement") - ("-", "op_Subtraction") - ("*", "op_Multiply") - ("**", "op_Exponentiation") - ("/", "op_Division") - ("@", "op_Append") - ("^", "op_Concatenate") - ("%", "op_Modulus") - ("&&&", "op_BitwiseAnd") - ("|||", "op_BitwiseOr") - ("^^^", "op_ExclusiveOr") - ("<<<", "op_LeftShift") - ("~~~", "op_LogicalNot") - (">>>", "op_RightShift") - ("~+", "op_UnaryPlus") - ("~-", "op_UnaryNegation") - ("~&", "op_AddressOf") - ("~&&", "op_IntegerAddressOf") - ("&&", "op_BooleanAnd") - ("||", "op_BooleanOr") - ("<=", "op_LessThanOrEqual") - ("=", "op_Equality") - ("<>", "op_Inequality") - (">=", "op_GreaterThanOrEqual") - ("<", "op_LessThan") - (">", "op_GreaterThan") - ("|>", "op_PipeRight") - ("||>", "op_PipeRight2") - ("|||>", "op_PipeRight3") - ("<|", "op_PipeLeft") - ("<||", "op_PipeLeft2") - ("<|||", "op_PipeLeft3") - ("!", "op_Dereference") - (">>", "op_ComposeRight") - ("<<", "op_ComposeLeft") - ("<< >>", "op_TypedQuotationUnicode") - ("<<| |>>", "op_ChevronsBar") - ("<@ @>", "op_Quotation") - ("<@@ @@>", "op_QuotationUntyped") - ("+=", "op_AdditionAssignment") - ("-=", "op_SubtractionAssignment") - ("*=", "op_MultiplyAssignment") - ("/=", "op_DivisionAssignment") - ("..", "op_Range") - (".. ..", "op_RangeStep") - (qmark, "op_Dynamic") - (qmarkSet, "op_DynamicAssignment") - (parenGet, "op_ArrayLookup") - (parenSet, "op_ArrayAssign") +[] +let opNamePrefix = "op_" + +let opNameTable = + [| + ("[]", "op_Nil") + ("::", "op_ColonColon") + ("+", "op_Addition") + ("~%", "op_Splice") + ("~%%", "op_SpliceUntyped") + ("~++", "op_Increment") + ("~--", "op_Decrement") + ("-", "op_Subtraction") + ("*", "op_Multiply") + ("**", "op_Exponentiation") + ("/", "op_Division") + ("@", "op_Append") + ("^", "op_Concatenate") + ("%", "op_Modulus") + ("&&&", "op_BitwiseAnd") + ("|||", "op_BitwiseOr") + ("^^^", "op_ExclusiveOr") + ("<<<", "op_LeftShift") + ("~~~", "op_LogicalNot") + (">>>", "op_RightShift") + ("~+", "op_UnaryPlus") + ("~-", "op_UnaryNegation") + ("~&", "op_AddressOf") + ("~&&", "op_IntegerAddressOf") + ("&&", "op_BooleanAnd") + ("||", "op_BooleanOr") + ("<=", "op_LessThanOrEqual") + ("=", "op_Equality") + ("<>", "op_Inequality") + (">=", "op_GreaterThanOrEqual") + ("<", "op_LessThan") + (">", "op_GreaterThan") + ("|>", "op_PipeRight") + ("||>", "op_PipeRight2") + ("|||>", "op_PipeRight3") + ("<|", "op_PipeLeft") + ("<||", "op_PipeLeft2") + ("<|||", "op_PipeLeft3") + ("!", "op_Dereference") + (">>", "op_ComposeRight") + ("<<", "op_ComposeLeft") + ("<< >>", "op_TypedQuotationUnicode") + ("<<| |>>", "op_ChevronsBar") + ("<@ @>", "op_Quotation") + ("<@@ @@>", "op_QuotationUntyped") + ("+=", "op_AdditionAssignment") + ("-=", "op_SubtractionAssignment") + ("*=", "op_MultiplyAssignment") + ("/=", "op_DivisionAssignment") + ("..", "op_Range") + (".. ..", "op_RangeStep") + (qmark, "op_Dynamic") + (qmarkSet, "op_DynamicAssignment") + (parenGet, "op_ArrayLookup") + (parenSet, "op_ArrayAssign") |] let opCharTranslateTable = - [|( '>', "Greater") - ( '<', "Less") - ( '+', "Plus") - ( '-', "Minus") - ( '*', "Multiply") - ( '=', "Equals") - ( '~', "Twiddle") - ( '%', "Percent") - ( '.', "Dot") - ( '$', "Dollar") - ( '&', "Amp") - ( '|', "Bar") - ( '@', "At") - ( '#', "Hash") - ( '^', "Hat") - ( '!', "Bang") - ( '?', "Qmark") - ( '/', "Divide") - ( ':', "Colon") - ( '(', "LParen") - ( ',', "Comma") - ( ')', "RParen") - ( ' ', "Space") - ( '[', "LBrack") - ( ']', "RBrack") |] + [| + ('>', "Greater") + ('<', "Less") + ('+', "Plus") + ('-', "Minus") + ('*', "Multiply") + ('=', "Equals") + ('~', "Twiddle") + ('%', "Percent") + ('.', "Dot") + ('$', "Dollar") + ('&', "Amp") + ('|', "Bar") + ('@', "At") + ('#', "Hash") + ('^', "Hat") + ('!', "Bang") + ('?', "Qmark") + ('/', "Divide") + (':', "Colon") + ('(', "LParen") + (',', "Comma") + (')', "RParen") + (' ', "Space") + ('[', "LBrack") + (']', "RBrack") + |] /// The set of characters usable in custom operators. let opCharSet = let t = HashSet<_>() + for c, _ in opCharTranslateTable do t.Add(c) |> ignore + t - + /// The characters that are allowed to be the first character of an identifier. let IsIdentifierFirstCharacter c = - if c = '_' then true + if c = '_' then + true else match Char.GetUnicodeCategory c with // Letters @@ -135,7 +149,8 @@ let IsIdentifierFirstCharacter c = /// The characters that are allowed to be in an identifier. let IsIdentifierPartCharacter c = - if c = '\'' then true // Tick + if c = '\'' then + true // Tick else match Char.GetUnicodeCategory c with // Letters @@ -155,120 +170,130 @@ let IsIdentifierPartCharacter c = | _ -> false /// Keywords paired with their descriptions. Used in completion and quick info. -let keywordsWithDescription : (string * string) list = - [ "abstract", FSComp.SR.keywordDescriptionAbstract() - "and", FSComp.SR.keyworkDescriptionAnd() - "as", FSComp.SR.keywordDescriptionAs() - "assert", FSComp.SR.keywordDescriptionAssert() - "base", FSComp.SR.keywordDescriptionBase() - "begin", FSComp.SR.keywordDescriptionBegin() - "class", FSComp.SR.keywordDescriptionClass() - "const", FSComp.SR.keywordDescriptionConst() - "default", FSComp.SR.keywordDescriptionDefault() - "delegate", FSComp.SR.keywordDescriptionDelegate() - "do", FSComp.SR.keywordDescriptionDo() - "done", FSComp.SR.keywordDescriptionDone() - "downcast", FSComp.SR.keywordDescriptionDowncast() - "downto", FSComp.SR.keywordDescriptionDownto() - "elif", FSComp.SR.keywordDescriptionElif() - "else", FSComp.SR.keywordDescriptionElse() - "end", FSComp.SR.keywordDescriptionEnd() - "exception", FSComp.SR.keywordDescriptionException() - "extern", FSComp.SR.keywordDescriptionExtern() - "false", FSComp.SR.keywordDescriptionTrueFalse() - "finally", FSComp.SR.keywordDescriptionFinally() - "for", FSComp.SR.keywordDescriptionFor() - "fun", FSComp.SR.keywordDescriptionFun() - "function", FSComp.SR.keywordDescriptionFunction() - "global", FSComp.SR.keywordDescriptionGlobal() - "if", FSComp.SR.keywordDescriptionIf() - "in", FSComp.SR.keywordDescriptionIn() - "inherit", FSComp.SR.keywordDescriptionInherit() - "inline", FSComp.SR.keywordDescriptionInline() - "interface", FSComp.SR.keywordDescriptionInterface() - "internal", FSComp.SR.keywordDescriptionInternal() - "lazy", FSComp.SR.keywordDescriptionLazy() - "let", FSComp.SR.keywordDescriptionLet() - "let!", FSComp.SR.keywordDescriptionLetBang() - "match", FSComp.SR.keywordDescriptionMatch() - "match!", FSComp.SR.keywordDescriptionMatchBang() - "member", FSComp.SR.keywordDescriptionMember() - "module", FSComp.SR.keywordDescriptionModule() - "mutable", FSComp.SR.keywordDescriptionMutable() - "namespace", FSComp.SR.keywordDescriptionNamespace() - "new", FSComp.SR.keywordDescriptionNew() - "not", FSComp.SR.keywordDescriptionNot() - "null", FSComp.SR.keywordDescriptionNull() - "of", FSComp.SR.keywordDescriptionOf() - "open", FSComp.SR.keywordDescriptionOpen() - "or", FSComp.SR.keywordDescriptionOr() - "override", FSComp.SR.keywordDescriptionOverride() - "private", FSComp.SR.keywordDescriptionPrivate() - "public", FSComp.SR.keywordDescriptionPublic() - "rec", FSComp.SR.keywordDescriptionRec() - "return", FSComp.SR.keywordDescriptionReturn() - "return!", FSComp.SR.keywordDescriptionReturnBang() - "static", FSComp.SR.keywordDescriptionStatic() - "struct", FSComp.SR.keywordDescriptionStruct() - "then", FSComp.SR.keywordDescriptionThen() - "to", FSComp.SR.keywordDescriptionTo() - "true", FSComp.SR.keywordDescriptionTrueFalse() - "try", FSComp.SR.keywordDescriptionTry() - "type", FSComp.SR.keywordDescriptionType() - "upcast", FSComp.SR.keywordDescriptionUpcast() - "use", FSComp.SR.keywordDescriptionUse() - "use!", FSComp.SR.keywordDescriptionUseBang() - "val", FSComp.SR.keywordDescriptionVal() - "void", FSComp.SR.keywordDescriptionVoid() - "when", FSComp.SR.keywordDescriptionWhen() - "while", FSComp.SR.keywordDescriptionWhile() - "with", FSComp.SR.keywordDescriptionWith() - "yield", FSComp.SR.keywordDescriptionYield() - "yield!", FSComp.SR.keywordDescriptionYieldBang() - "->", FSComp.SR.keywordDescriptionRightArrow() - "<-", FSComp.SR.keywordDescriptionLeftArrow() - ":>", FSComp.SR.keywordDescriptionCast() - ":?>", FSComp.SR.keywordDescriptionDynamicCast() - "<@", FSComp.SR.keywordDescriptionTypedQuotation() - "@>", FSComp.SR.keywordDescriptionTypedQuotation() - "<@@", FSComp.SR.keywordDescriptionUntypedQuotation() - "@@>", FSComp.SR.keywordDescriptionUntypedQuotation() ] +let keywordsWithDescription: (string * string) list = + [ + "abstract", FSComp.SR.keywordDescriptionAbstract () + "and", FSComp.SR.keyworkDescriptionAnd () + "as", FSComp.SR.keywordDescriptionAs () + "assert", FSComp.SR.keywordDescriptionAssert () + "base", FSComp.SR.keywordDescriptionBase () + "begin", FSComp.SR.keywordDescriptionBegin () + "class", FSComp.SR.keywordDescriptionClass () + "const", FSComp.SR.keywordDescriptionConst () + "default", FSComp.SR.keywordDescriptionDefault () + "delegate", FSComp.SR.keywordDescriptionDelegate () + "do", FSComp.SR.keywordDescriptionDo () + "done", FSComp.SR.keywordDescriptionDone () + "downcast", FSComp.SR.keywordDescriptionDowncast () + "downto", FSComp.SR.keywordDescriptionDownto () + "elif", FSComp.SR.keywordDescriptionElif () + "else", FSComp.SR.keywordDescriptionElse () + "end", FSComp.SR.keywordDescriptionEnd () + "exception", FSComp.SR.keywordDescriptionException () + "extern", FSComp.SR.keywordDescriptionExtern () + "false", FSComp.SR.keywordDescriptionTrueFalse () + "finally", FSComp.SR.keywordDescriptionFinally () + "for", FSComp.SR.keywordDescriptionFor () + "fun", FSComp.SR.keywordDescriptionFun () + "function", FSComp.SR.keywordDescriptionFunction () + "global", FSComp.SR.keywordDescriptionGlobal () + "if", FSComp.SR.keywordDescriptionIf () + "in", FSComp.SR.keywordDescriptionIn () + "inherit", FSComp.SR.keywordDescriptionInherit () + "inline", FSComp.SR.keywordDescriptionInline () + "interface", FSComp.SR.keywordDescriptionInterface () + "internal", FSComp.SR.keywordDescriptionInternal () + "lazy", FSComp.SR.keywordDescriptionLazy () + "let", FSComp.SR.keywordDescriptionLet () + "let!", FSComp.SR.keywordDescriptionLetBang () + "match", FSComp.SR.keywordDescriptionMatch () + "match!", FSComp.SR.keywordDescriptionMatchBang () + "member", FSComp.SR.keywordDescriptionMember () + "module", FSComp.SR.keywordDescriptionModule () + "mutable", FSComp.SR.keywordDescriptionMutable () + "namespace", FSComp.SR.keywordDescriptionNamespace () + "new", FSComp.SR.keywordDescriptionNew () + "not", FSComp.SR.keywordDescriptionNot () + "null", FSComp.SR.keywordDescriptionNull () + "of", FSComp.SR.keywordDescriptionOf () + "open", FSComp.SR.keywordDescriptionOpen () + "or", FSComp.SR.keywordDescriptionOr () + "override", FSComp.SR.keywordDescriptionOverride () + "private", FSComp.SR.keywordDescriptionPrivate () + "public", FSComp.SR.keywordDescriptionPublic () + "rec", FSComp.SR.keywordDescriptionRec () + "return", FSComp.SR.keywordDescriptionReturn () + "return!", FSComp.SR.keywordDescriptionReturnBang () + "static", FSComp.SR.keywordDescriptionStatic () + "struct", FSComp.SR.keywordDescriptionStruct () + "then", FSComp.SR.keywordDescriptionThen () + "to", FSComp.SR.keywordDescriptionTo () + "true", FSComp.SR.keywordDescriptionTrueFalse () + "try", FSComp.SR.keywordDescriptionTry () + "type", FSComp.SR.keywordDescriptionType () + "upcast", FSComp.SR.keywordDescriptionUpcast () + "use", FSComp.SR.keywordDescriptionUse () + "use!", FSComp.SR.keywordDescriptionUseBang () + "val", FSComp.SR.keywordDescriptionVal () + "void", FSComp.SR.keywordDescriptionVoid () + "when", FSComp.SR.keywordDescriptionWhen () + "while", FSComp.SR.keywordDescriptionWhile () + "with", FSComp.SR.keywordDescriptionWith () + "yield", FSComp.SR.keywordDescriptionYield () + "yield!", FSComp.SR.keywordDescriptionYieldBang () + "->", FSComp.SR.keywordDescriptionRightArrow () + "<-", FSComp.SR.keywordDescriptionLeftArrow () + ":>", FSComp.SR.keywordDescriptionCast () + ":?>", FSComp.SR.keywordDescriptionDynamicCast () + "<@", FSComp.SR.keywordDescriptionTypedQuotation () + "@>", FSComp.SR.keywordDescriptionTypedQuotation () + "<@@", FSComp.SR.keywordDescriptionUntypedQuotation () + "@@>", FSComp.SR.keywordDescriptionUntypedQuotation () + ] let keywordLookup = set (List.map fst keywordsWithDescription) // Some legacy compat operator names are not encode using op_XYZ and this -// do not carry sufficient information to distinguish between -// let (or) x y = x || y -// let ``or`` x y = x || y -// let (land) x y = x || y -// let ``land`` x y = x || y +// do not carry sufficient information to distinguish between +// let (or) x y = x || y +// let ``or`` x y = x || y +// let (land) x y = x || y +// let ``land`` x y = x || y // All are deprecated except 'mod'. All except those two get double-backticks -let IsUnencodedOpName (name: string) = +let IsUnencodedOpName (name: string) = match name with | "mod" -> true | _ -> false -let IsUnencodedLegacyOpName (name: string) = +let IsUnencodedLegacyOpName (name: string) = match name with - | "or" | "land" | "lor" | "lsl" - | "lsr" | "asr" | "lxor" -> true + | "or" + | "land" + | "lor" + | "lsl" + | "lsr" + | "asr" + | "lxor" -> true | _ -> false let IsIdentifierName (name: string) = - not (keywordLookup.Contains name) && - not (IsUnencodedOpName name) && - not (IsUnencodedLegacyOpName name) && - let nameLen = name.Length - nameLen > 0 && - IsIdentifierFirstCharacter name[0] && - let rec loop i = (i >= nameLen || (IsIdentifierPartCharacter(name[i]) && loop (i+1))) - loop 1 + not (keywordLookup.Contains name) + && not (IsUnencodedOpName name) + && not (IsUnencodedLegacyOpName name) + && let nameLen = name.Length in + + nameLen > 0 + && IsIdentifierFirstCharacter name[0] + && let rec loop i = + (i >= nameLen || (IsIdentifierPartCharacter(name[i]) && loop (i + 1))) in + loop 1 let rec isCoreActivePatternName (name: string) idx seenNonOpChar = if idx = name.Length - 1 then seenNonOpChar else let c = name[idx] + if opCharSet.Contains(c) && c <> '|' && c <> ' ' then false else @@ -278,12 +303,13 @@ let rec isCoreActivePatternName (name: string) idx seenNonOpChar = let IsActivePatternName (name: string) = // The name must contain at least one character between the starting and ending delimiters. let nameLen = name.Length + if nameLen < 3 || name[0] <> '|' || name[nameLen - 1] <> '|' then false else isCoreActivePatternName name 1 false -/// Returns `true` if given string is an operator display name (DisplayName), e.g. +/// Returns `true` if given string is an operator display name (DisplayName), e.g. /// (::) /// ([]) /// (|>>) @@ -301,6 +327,7 @@ let IsOperatorDisplayName (name: string) = true else let c = name[idx] + if not (opCharSet.Contains(c)) || c = ' ' then false else @@ -308,12 +335,18 @@ let IsOperatorDisplayName (name: string) = let skipParens2 = name.StartsWithOrdinal("( ") && name.EndsWithOrdinal(" )") let skipParens1 = name.StartsWithOrdinal("(") && name.EndsWithOrdinal(")") - let skip = if skipParens2 then 2 elif skipParens1 then 1 else 0 + + let skip = + if skipParens2 then 2 + elif skipParens1 then 1 + else 0 + let startIndex = skip let endIndex = name.Length - skip - (startIndex < endIndex && loop name startIndex endIndex) || - (name = ".. ..") || - (name = "(.. ..)") + + (startIndex < endIndex && loop name startIndex endIndex) + || (name = ".. ..") + || (name = "(.. ..)") //IsOperatorDisplayName "+" //IsOperatorDisplayName "(+)" @@ -325,8 +358,7 @@ let IsOperatorDisplayName (name: string) = //IsOperatorDisplayName "( )" // false //IsOperatorDisplayName "( +)" // false -let IsMangledOpName (name: string) = - name.StartsWithOrdinal(opNamePrefix) +let IsMangledOpName (name: string) = name.StartsWithOrdinal(opNamePrefix) /// Compiles a custom operator into a mangled operator name. /// For example, "!%" becomes "op_DereferencePercent". @@ -336,8 +368,10 @@ let IsMangledOpName (name: string) = let compileCustomOpName = let t2 = let t2 = Dictionary<_, _> opCharTranslateTable.Length + for x, y in opCharTranslateTable do - t2.Add (x, y) + t2.Add(x, y) + t2 /// The maximum length of the name for a custom operator character. @@ -354,28 +388,35 @@ let compileCustomOpName = fun opp -> // Has this operator already been compiled? - compiledOperators.GetOrAdd(opp, fun (op: string) -> - let opLength = op.Length - let sb = StringBuilder(opNamePrefix, opNamePrefix.Length + (opLength * maxOperatorNameLength)) - for i = 0 to opLength - 1 do - let c = op[i] - match t2.TryGetValue c with - | true, x -> - sb.Append(x) |> ignore - | false, _ -> - sb.Append(c) |> ignore - - /// The compiled (mangled) operator name. - let opName = sb.ToString () - - // Cache the compiled name so it can be reused. - opName) + compiledOperators.GetOrAdd( + opp, + fun (op: string) -> + let opLength = op.Length + + let sb = + StringBuilder(opNamePrefix, opNamePrefix.Length + (opLength * maxOperatorNameLength)) + + for i = 0 to opLength - 1 do + let c = op[i] + + match t2.TryGetValue c with + | true, x -> sb.Append(x) |> ignore + | false, _ -> sb.Append(c) |> ignore + + /// The compiled (mangled) operator name. + let opName = sb.ToString() + + // Cache the compiled name so it can be reused. + opName + ) /// Maps the built-in F# operators to their mangled operator names. let standardOpNames = - let opNames = Dictionary<_, _> (opNameTable.Length, StringComparer.Ordinal) + let opNames = Dictionary<_, _>(opNameTable.Length, StringComparer.Ordinal) + for x, y in opNameTable do - opNames.Add (x, y) + opNames.Add(x, y) + opNames let CompileOpName op = @@ -411,17 +452,17 @@ let decompileCustomOpName = | true, op -> op | false, _ -> let opNameLen = opName.Length - + /// Function which decompiles the mangled operator name back into a string of operator characters. /// Returns None if the name contains text which doesn't correspond to an operator - /// otherwise returns Some containing the original operator. - let rec decompile (sb : StringBuilder) idx = + /// otherwise returns Some containing the original operator. + let rec decompile (sb: StringBuilder) idx = // Have we reached the end of 'opName'? if idx = opNameLen then // Finished decompiling. // Cache the decompiled operator before returning so it can be reused. - let decompiledOp = sb.ToString () - decompiledOperators.TryAdd (opName, decompiledOp) |> ignore + let decompiledOp = sb.ToString() + decompiledOperators.TryAdd(opName, decompiledOp) |> ignore decompiledOp else let choice = @@ -430,10 +471,12 @@ let decompileCustomOpName = // If this operator character name is longer than the remaining piece of 'opName', // it's obviously not a match. let opCharNameLen = opCharName.Length - if opNameLen - idx < opCharNameLen then false + + if opNameLen - idx < opCharNameLen then + false else // Does 'opCharName' match the current position in 'opName'? - String.Compare (opName, idx, opCharName, 0, opCharNameLen, StringComparison.Ordinal) = 0) + String.Compare(opName, idx, opCharName, 0, opCharNameLen, StringComparison.Ordinal) = 0) match choice with | None -> @@ -447,21 +490,24 @@ let decompileCustomOpName = decompile sb (idx + opCharName.Length) let opNamePrefixLen = opNamePrefix.Length + let sb = /// The maximum number of operator characters that could be contained in the /// decompiled operator given the length of the mangled custom operator name. let maxPossibleOpCharCount = (opNameLen - opNamePrefixLen) / minOperatorNameLength + StringBuilder maxPossibleOpCharCount // Start decompiling just after the operator prefix. decompile sb opNamePrefixLen - /// Maps the mangled operator names of built-in F# operators back to the operators. let standardOpsDecompile = - let ops = Dictionary (opNameTable.Length, StringComparer.Ordinal) + let ops = Dictionary(opNameTable.Length, StringComparer.Ordinal) + for x, y in opNameTable do ops.Add(y, x) + ops let DecompileOpName opName = @@ -474,33 +520,36 @@ let DecompileOpName opName = opName let DoesIdentifierNeedBackticks (name: string) : bool = - not (IsUnencodedOpName name) && - not (IsIdentifierName name) && - not (IsActivePatternName name) + not (IsUnencodedOpName name) + && not (IsIdentifierName name) + && not (IsActivePatternName name) -/// A utility to help determine if an identifier needs to be quoted +/// A utility to help determine if an identifier needs to be quoted let AddBackticksToIdentifierIfNeeded (name: string) : string = - if DoesIdentifierNeedBackticks name && - not (name.StartsWithOrdinal("`")) && - not (name.EndsWithOrdinal("`")) then - "``" + name + "``" - else + if + DoesIdentifierNeedBackticks name + && not (name.StartsWithOrdinal("`")) + && not (name.EndsWithOrdinal("`")) + then + "``" + name + "``" + else name /// Quote identifier with double backticks if needed, remove unnecessary double backticks quotation. let NormalizeIdentifierBackticks (name: string) : string = let s = if name.StartsWithOrdinal("``") && name.EndsWithOrdinal("``") then - name[2..name.Length - 3] - else name + name[2 .. name.Length - 3] + else + name + AddBackticksToIdentifierIfNeeded s -let ConvertNameToDisplayName name = - AddBackticksToIdentifierIfNeeded name +let ConvertNameToDisplayName name = AddBackticksToIdentifierIfNeeded name let ConvertValNameToDisplayName isBaseVal name = if isBaseVal && name = "base" then - "base" + "base" elif IsUnencodedOpName name || IsMangledOpName name || IsActivePatternName name then let nm = DecompileOpName name // Check for no decompilation, e.g. op_Implicit, op_NotAMangledOpName, op_A-B @@ -514,25 +563,28 @@ let ConvertValNameToDisplayName isBaseVal name = "(" + nm + ")" else ConvertNameToDisplayName name - + let ConvertNameToDisplayLayout nonOpLayout name = if DoesIdentifierNeedBackticks name then - leftL (TaggedText.tagPunctuation "``") ^^ wordL (TaggedText.tagOperator name) ^^ rightL (TaggedText.tagPunctuation "``") + leftL (TaggedText.tagPunctuation "``") + ^^ wordL (TaggedText.tagOperator name) ^^ rightL (TaggedText.tagPunctuation "``") else nonOpLayout name let ConvertValNameToDisplayLayout isBaseVal nonOpLayout name = if isBaseVal && name = "base" then - nonOpLayout "base" + nonOpLayout "base" elif IsUnencodedOpName name || IsMangledOpName name || IsActivePatternName name then let nm = DecompileOpName name // Check for no decompilation, e.g. op_Implicit, op_NotAMangledOpName, op_A-B if IsMangledOpName name && (nm = name) then ConvertNameToDisplayLayout nonOpLayout name elif nm.StartsWithOrdinal "*" || nm.EndsWithOrdinal "*" then - wordL (TaggedText.tagPunctuation "(") ^^ wordL (TaggedText.tagOperator nm) ^^ wordL (TaggedText.tagPunctuation ")") + wordL (TaggedText.tagPunctuation "(") + ^^ wordL (TaggedText.tagOperator nm) ^^ wordL (TaggedText.tagPunctuation ")") else - leftL (TaggedText.tagPunctuation "(") ^^ wordL (TaggedText.tagOperator nm) ^^ rightL (TaggedText.tagPunctuation ")") + leftL (TaggedText.tagPunctuation "(") + ^^ wordL (TaggedText.tagOperator nm) ^^ rightL (TaggedText.tagPunctuation ")") else ConvertNameToDisplayLayout nonOpLayout name @@ -549,72 +601,104 @@ let opNameNullableEquals = CompileOpName "?=" let opNameNullableEqualsNullable = CompileOpName "?=?" /// Is this character a part of a long identifier? -let IsLongIdentifierPartCharacter c = - c = '.' - || IsIdentifierPartCharacter c +let IsLongIdentifierPartCharacter c = c = '.' || IsIdentifierPartCharacter c let isTildeOnlyString (s: string) = let rec loop (s: string) idx = - if idx >= s.Length then - true - elif s[idx] <> '~' then - false - else - loop s (idx + 1) + if idx >= s.Length then true + elif s[idx] <> '~' then false + else loop s (idx + 1) + loop s 0 let IsValidPrefixOperatorUse s = - if String.IsNullOrEmpty s then false else - match s with - | "?+" | "?-" | "+" | "-" | "+." | "-." | "%" | "%%" | "&" | "&&" -> true - | _ -> s[0] = '!' || isTildeOnlyString s - -let IsValidPrefixOperatorDefinitionName s = - if String.IsNullOrEmpty s then false else - - match s[0] with - | '~' -> - isTildeOnlyString s || - + if String.IsNullOrEmpty s then + false + else match s with - | "~?+" | "~?-" | "~+" | "~-" | "~+." | "~-." | "~%" | "~%%" | "~&" | "~&&" -> true - | _ -> false + | "?+" + | "?-" + | "+" + | "-" + | "+." + | "-." + | "%" + | "%%" + | "&" + | "&&" -> true + | _ -> s[0] = '!' || isTildeOnlyString s + +let IsValidPrefixOperatorDefinitionName s = + if String.IsNullOrEmpty s then + false + else - | '!' -> s <> "!=" - | _ -> false + match s[0] with + | '~' -> + isTildeOnlyString s + || + + match s with + | "~?+" + | "~?-" + | "~+" + | "~-" + | "~+." + | "~-." + | "~%" + | "~%%" + | "~&" + | "~&&" -> true + | _ -> false + + | '!' -> s <> "!=" + | _ -> false let IsPrefixOperator s = - if String.IsNullOrEmpty s then false else - let s = DecompileOpName s - IsValidPrefixOperatorDefinitionName s + if String.IsNullOrEmpty s then + false + else + let s = DecompileOpName s + IsValidPrefixOperatorDefinitionName s let IsPunctuation s = - if String.IsNullOrEmpty s then false else - match s with - | "," | ";" | "|" | ":" | "." | "*" - | "(" | ")" - | "[" | "]" - | "{" | "}" - | "<" | ">" - | "[|" | "|]" - | "[<" | ">]" - -> true - | _ -> false + if String.IsNullOrEmpty s then + false + else + match s with + | "," + | ";" + | "|" + | ":" + | "." + | "*" + | "(" + | ")" + | "[" + | "]" + | "{" + | "}" + | "<" + | ">" + | "[|" + | "|]" + | "[<" + | ">]" -> true + | _ -> false -let IsTernaryOperator s = - (DecompileOpName s = qmarkSet) +let IsTernaryOperator s = (DecompileOpName s = qmarkSet) /// EQUALS, INFIX_COMPARE_OP, LESS, GREATER -let relational = [| "=";"!=";"<";">";"$"|] +let relational = [| "="; "!="; "<"; ">"; "$" |] /// INFIX_AT_HAT_OP -let concat = [| "@";"^" |] +let concat = [| "@"; "^" |] /// PLUS_MINUS_OP, MINUS let plusMinus = [| "+"; "-" |] /// PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP -let otherMath = [| "*";"/";"%" |] +let otherMath = [| "*"; "/"; "%" |] /// Characters ignored at the start of the operator name /// when determining whether an operator is an infix operator. @@ -626,88 +710,132 @@ let ignoredChars = [| '.'; '?' |] // The lexer defines the strings that lead to those tokens. //------ // This function recognises these "infix operator" names. -let IsMangledInfixOperator mangled = (* where mangled is assumed to be a compiled name *) - let s = DecompileOpName mangled +let IsMangledInfixOperator mangled = (* where mangled is assumed to be a compiled name *) + let s = DecompileOpName mangled let skipIgnoredChars = s.TrimStart(ignoredChars) - let afterSkipStartsWith prefix = skipIgnoredChars.StartsWithOrdinal(prefix) - let afterSkipStarts prefixes = Array.exists afterSkipStartsWith prefixes + + let afterSkipStartsWith prefix = + skipIgnoredChars.StartsWithOrdinal(prefix) + + let afterSkipStarts prefixes = + Array.exists afterSkipStartsWith prefixes // The following conditions follow the declExpr infix clauses. // The test corresponds to the lexer definition for the token. - s <> mangled && - (s = ":=" || // COLON_EQUALS - afterSkipStartsWith "|" || // BAR_BAR, INFIX_BAR_OP - afterSkipStartsWith "&" || // AMP, AMP_AMP, INFIX_AMP_OP - afterSkipStarts relational || // EQUALS, INFIX_COMPARE_OP, LESS, GREATER - s = "$" || // DOLLAR - afterSkipStarts concat || // INFIX_AT_HAT_OP - s = "::" || // COLON_COLON - afterSkipStarts plusMinus || // PLUS_MINUS_OP, MINUS - afterSkipStarts otherMath || // PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP - s = "**") // INFIX_STAR_STAR_OP + s <> mangled + && ((s = // COLON_EQUALS + ":=") + || + // BAR_BAR, INFIX_BAR_OP + afterSkipStartsWith "|" + || + // AMP, AMP_AMP, INFIX_AMP_OP + afterSkipStartsWith "&" + || + // EQUALS, INFIX_COMPARE_OP, LESS, GREATER + afterSkipStarts relational + || + // DOLLAR + (s = "$") + || + // INFIX_AT_HAT_OP + afterSkipStarts concat + || + // COLON_COLON + (s = "::") + || + // PLUS_MINUS_OP, MINUS + afterSkipStarts plusMinus + || + // PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP + afterSkipStarts otherMath + || + // INFIX_STAR_STAR_OP + (s = "**")) let (|Control|Equality|Relational|Indexer|FixedTypes|Other|) opName = match opName with - | "&" | "or" | "&&" | "||" -> - Control - | "<>" | "=" -> - Equality - | "<" | ">" | "<=" | ">=" -> - Relational - | "<<" | "<|" | "<||" | "<||" | "|>" | "||>" | "|||>" | ">>" | "^" | ":=" | "@" -> - FixedTypes - | ".[]" -> - Indexer - | _ -> - Other - -let [] compilerGeneratedMarker = "@" - -let [] compilerGeneratedMarkerChar = '@' - + | "&" + | "or" + | "&&" + | "||" -> Control + | "<>" + | "=" -> Equality + | "<" + | ">" + | "<=" + | ">=" -> Relational + | "<<" + | "<|" + | "<||" + | "<||" + | "|>" + | "||>" + | "|||>" + | ">>" + | "^" + | ":=" + | "@" -> FixedTypes + | ".[]" -> Indexer + | _ -> Other + +[] +let compilerGeneratedMarker = "@" + +[] +let compilerGeneratedMarkerChar = '@' + let IsCompilerGeneratedName (nm: string) = nm.IndexOf compilerGeneratedMarkerChar <> -1 - + let CompilerGeneratedName nm = - if IsCompilerGeneratedName nm then nm else nm+compilerGeneratedMarker + if IsCompilerGeneratedName nm then + nm + else + nm + compilerGeneratedMarker let GetBasicNameOfPossibleCompilerGeneratedName (name: string) = - match name.IndexOf(compilerGeneratedMarker, StringComparison.Ordinal) with - | -1 | 0 -> name - | n -> name[0..n-1] + match name.IndexOf(compilerGeneratedMarker, StringComparison.Ordinal) with + | -1 + | 0 -> name + | n -> name[0 .. n - 1] let CompilerGeneratedNameSuffix (basicName: string) suffix = - basicName+compilerGeneratedMarker+suffix + basicName + compilerGeneratedMarker + suffix //------------------------------------------------------------------------- // Handle mangled .NET generic type names -//------------------------------------------------------------------------- - -let [] mangledGenericTypeNameSym = '`' +//------------------------------------------------------------------------- + +[] +let mangledGenericTypeNameSym = '`' let TryDemangleGenericNameAndPos (n: string) = - // check what comes after the symbol is a number + // check what comes after the symbol is a number let pos = n.LastIndexOf mangledGenericTypeNameSym - if pos = -1 then ValueNone else - let mutable res = pos < n.Length - 1 - let mutable i = pos + 1 - while res && i < n.Length do - let char = n[i] - if not (char >= '0' && char <= '9') then - res <- false - i <- i + 1 - if res then - ValueSome pos - else + + if pos = -1 then ValueNone + else + let mutable res = pos < n.Length - 1 + let mutable i = pos + 1 + + while res && i < n.Length do + let char = n[i] + + if not (char >= '0' && char <= '9') then + res <- false + + i <- i + 1 + + if res then ValueSome pos else ValueNone type NameArityPair = NameArityPair of string * int -let DemangleGenericTypeNameWithPos pos (mangledName: string) = - mangledName.Substring(0, pos) +let DemangleGenericTypeNameWithPos pos (mangledName: string) = mangledName.Substring(0, pos) let DecodeGenericTypeNameWithPos pos (mangledName: string) = let res = DemangleGenericTypeNameWithPos pos mangledName - let num = mangledName.Substring(pos+1, mangledName.Length - pos - 1) + let num = mangledName.Substring(pos + 1, mangledName.Length - pos - 1) NameArityPair(res, int32 num) let DemangleGenericTypeName (mangledName: string) = @@ -730,53 +858,53 @@ let chopStringTo (s: string) (c: char) = /// Try to chop "get_" or "set_" from a string let TryChopPropertyName (s: string) = // extract the logical name from any mangled name produced by MakeMemberDataAndMangledNameForMemberVal - if s.Length <= 4 then None else - if s.StartsWithOrdinal("get_") || - s.StartsWithOrdinal("set_") - then Some (s.Substring(4, s.Length - 4)) + if s.Length <= 4 then + None + else if s.StartsWithOrdinal("get_") || s.StartsWithOrdinal("set_") then + Some(s.Substring(4, s.Length - 4)) else - let s = chopStringTo s '.' - if s.StartsWithOrdinal("get_") || - s.StartsWithOrdinal("set_") - then Some (s.Substring(4, s.Length - 4)) - else None + let s = chopStringTo s '.' + + if s.StartsWithOrdinal("get_") || s.StartsWithOrdinal("set_") then + Some(s.Substring(4, s.Length - 4)) + else + None /// Try to chop "get_" or "set_" from a string. /// If the string does not start with "get_" or "set_", this function raises an exception. let ChopPropertyName s = - match TryChopPropertyName s with - | None -> - failwithf "Invalid internal property name: '%s'" s + match TryChopPropertyName s with + | None -> failwithf "Invalid internal property name: '%s'" s | Some res -> res -let SplitNamesForILPath (s : string) : string list = - if s.StartsWithOrdinal("``") && s.EndsWithOrdinal("``") && s.Length > 4 then [s.Substring(2, s.Length-4)] // identifier is enclosed in `` .. ``, so it is only a single element (this is very approximate) - else s.Split [| '.' ; '`' |] |> Array.toList // '.' chops members / namespaces / modules; '`' chops generic parameters for .NET types - +let SplitNamesForILPath (s: string) : string list = + if s.StartsWithOrdinal("``") && s.EndsWithOrdinal("``") && s.Length > 4 then + [ s.Substring(2, s.Length - 4) ] // identifier is enclosed in `` .. ``, so it is only a single element (this is very approximate) + else + s.Split [| '.'; '`' |] |> Array.toList // '.' chops members / namespaces / modules; '`' chops generic parameters for .NET types + /// Return a string array delimited by the given separator. -/// Note that a quoted string is not going to be mangled into pieces. -let inline isNotQuotedQuotation (text: string) n = n > 0 && text[n-1] <> '\\' +/// Note that a quoted string is not going to be mangled into pieces. +let inline isNotQuotedQuotation (text: string) n = n > 0 && text[n - 1] <> '\\' let splitAroundQuotation (text: string) (separator: char) = let length = text.Length let result = ResizeArray() let mutable insideQuotation = false let mutable start = 0 + for i = 0 to length - 1 do match text[i], insideQuotation with // split when seeing a separator - | c, false when c = separator -> + | c, false when c = separator -> result.Add(text.Substring(start, i - start)) insideQuotation <- false start <- i + 1 - | _, _ when i = length - 1 -> - result.Add(text.Substring(start, i - start + 1)) + | _, _ when i = length - 1 -> result.Add(text.Substring(start, i - start + 1)) // keep reading if a separator is inside quotation - | c, true when c = separator -> - insideQuotation <- true + | c, true when c = separator -> insideQuotation <- true // open or close quotation - | '\"', _ when isNotQuotedQuotation text i -> - insideQuotation <- not insideQuotation + | '\"', _ when isNotQuotedQuotation text i -> insideQuotation <- not insideQuotation // keep reading | _ -> () @@ -784,63 +912,84 @@ let splitAroundQuotation (text: string) (separator: char) = /// Return a string array delimited by the given separator up to the maximum number. /// Note that a quoted string is not going to be mangled into pieces. -let splitAroundQuotationWithCount (text: string) (separator: char) (count: int)= - if count <= 1 then [| text |] else - let mangledText = splitAroundQuotation text separator - match mangledText.Length > count with - | true -> Array.append mangledText[0..(count-2)] [| mangledText[(count-1)..] |> String.concat (Char.ToString separator) |] - | false -> mangledText +let splitAroundQuotationWithCount (text: string) (separator: char) (count: int) = + if count <= 1 then + [| text |] + else + let mangledText = splitAroundQuotation text separator + + match mangledText.Length > count with + | true -> Array.append mangledText[0 .. (count - 2)] [| mangledText[(count - 1) ..] |> String.concat (Char.ToString separator) |] + | false -> mangledText [] let FSharpModuleSuffix = "Module" [] let MangledGlobalName = "`global`" - -let IllegalCharactersInTypeAndNamespaceNames = [| '.'; '+'; '$'; '&'; '['; ']'; '/'; '\\'; '*'; '\"'; '`' |] -type ActivePatternInfo = - | APInfo of bool * (string * range) list * range +let IllegalCharactersInTypeAndNamespaceNames = + [| '.'; '+'; '$'; '&'; '['; ']'; '/'; '\\'; '*'; '\"'; '`' |] - member x.IsTotal = let (APInfo(p, _, _)) = x in p +type ActivePatternInfo = + | APInfo of bool * (string * range) list * range - member x.ActiveTags = let (APInfo(_, tags, _)) = x in List.map fst tags + member x.IsTotal = let (APInfo (p, _, _)) = x in p - member x.ActiveTagsWithRanges = let (APInfo(_, tags, _)) = x in tags + member x.ActiveTags = let (APInfo (_, tags, _)) = x in List.map fst tags - member x.Range = let (APInfo(_, _, m)) = x in m + member x.ActiveTagsWithRanges = let (APInfo (_, tags, _)) = x in tags -let ActivePatternInfoOfValName nm (m: range) = + member x.Range = let (APInfo (_, _, m)) = x in m + +let ActivePatternInfoOfValName nm (m: range) = // Note: The approximate range calculations in this code assume the name is of the form "(|A|B|)" not "(| A | B |)" // The ranges are used for IDE refactoring support etc. If names of the second type are used, // renaming may be inaccurate/buggy. However names of the first form are dominant in F# code. - let rec loop (nm: string) (mp: range) = + let rec loop (nm: string) (mp: range) = let n = nm.IndexOf '|' - if n > 0 then - let m1 = Range.mkRange mp.FileName mp.Start (Position.mkPos mp.StartLine (mp.StartColumn + n)) - let m2 = Range.mkRange mp.FileName (Position.mkPos mp.StartLine (mp.StartColumn + n + 1)) mp.End - (nm[0..n-1], m1) :: loop nm[n+1..] m2 + + if n > 0 then + let m1 = + Range.mkRange mp.FileName mp.Start (Position.mkPos mp.StartLine (mp.StartColumn + n)) + + let m2 = + Range.mkRange mp.FileName (Position.mkPos mp.StartLine (mp.StartColumn + n + 1)) mp.End + + (nm[0 .. n - 1], m1) :: loop nm[n + 1 ..] m2 else - let m1 = Range.mkRange mp.FileName mp.Start (Position.mkPos mp.StartLine (mp.StartColumn + nm.Length)) - [(nm, m1)] + let m1 = + Range.mkRange mp.FileName mp.Start (Position.mkPos mp.StartLine (mp.StartColumn + nm.Length)) + + [ (nm, m1) ] + let nm = DecompileOpName nm - if IsActivePatternName nm then + + if IsActivePatternName nm then // Skip the '|' at each end when recovering ranges - let m0 = Range.mkRange m.FileName (Position.mkPos m.StartLine (m.StartColumn + 1)) (Position.mkPos m.EndLine (m.EndColumn - 1)) - let names = loop nm[1..nm.Length-2] m0 + let m0 = + Range.mkRange m.FileName (Position.mkPos m.StartLine (m.StartColumn + 1)) (Position.mkPos m.EndLine (m.EndColumn - 1)) + + let names = loop nm[1 .. nm.Length - 2] m0 let resH, resT = List.frontAndBack names - Some(if fst resT = "_" then APInfo(false, resH, m) else APInfo(true, names, m)) - else + + Some( + if fst resT = "_" then + APInfo(false, resH, m) + else + APInfo(true, names, m) + ) + else None - -let mangleStaticStringArg (nm: string, v: string) = + +let mangleStaticStringArg (nm: string, v: string) = nm + "=" + "\"" + v.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"" let tryDemangleStaticStringArg (mangledText: string) = match splitAroundQuotationWithCount mangledText '=' 2 with | [| nm; v |] -> if v.Length >= 2 then - Some(nm, v[1..v.Length-2].Replace("\\\\", "\\").Replace("\\\"", "\"")) + Some(nm, v[ 1 .. v.Length - 2 ].Replace("\\\\", "\\").Replace("\\\"", "\"")) else Some(nm, v) | _ -> None @@ -848,26 +997,26 @@ let tryDemangleStaticStringArg (mangledText: string) = exception InvalidMangledStaticArg of string /// Demangle the static parameters -let demangleProvidedTypeName (typeLogicalName: string) = - if typeLogicalName.Contains "," then +let demangleProvidedTypeName (typeLogicalName: string) = + if typeLogicalName.Contains "," then let pieces = splitAroundQuotation typeLogicalName ',' + match pieces with - | [| x; "" |] -> x, [| |] + | [| x; "" |] -> x, [||] | _ -> let argNamesAndValues = pieces[1..] |> Array.choose tryDemangleStaticStringArg + if argNamesAndValues.Length = (pieces.Length - 1) then pieces[0], argNamesAndValues else - typeLogicalName, [| |] - else - typeLogicalName, [| |] + typeLogicalName, [||] + else + typeLogicalName, [||] /// Mangle the static parameters for a provided type or method -let mangleProvidedTypeName (typeLogicalName, nonDefaultArgs) = - let nonDefaultArgsText = - nonDefaultArgs - |> Array.map mangleStaticStringArg - |> String.concat "," +let mangleProvidedTypeName (typeLogicalName, nonDefaultArgs) = + let nonDefaultArgsText = + nonDefaultArgs |> Array.map mangleStaticStringArg |> String.concat "," if nonDefaultArgsText = "" then typeLogicalName @@ -875,15 +1024,17 @@ let mangleProvidedTypeName (typeLogicalName, nonDefaultArgs) = typeLogicalName + "," + nonDefaultArgsText /// Mangle the static parameters for a provided type or method -let computeMangledNameWithoutDefaultArgValues(nm, staticArgs, defaultArgValues) = - let nonDefaultArgs = - (staticArgs, defaultArgValues) - ||> Array.zip - |> Array.choose (fun (staticArg, (defaultArgName, defaultArgValue)) -> - let actualArgValue = string staticArg - match defaultArgValue with +let computeMangledNameWithoutDefaultArgValues (nm, staticArgs, defaultArgValues) = + let nonDefaultArgs = + (staticArgs, defaultArgValues) + ||> Array.zip + |> Array.choose (fun (staticArg, (defaultArgName, defaultArgValue)) -> + let actualArgValue = string staticArg + + match defaultArgValue with | Some v when v = actualArgValue -> None - | _ -> Some (defaultArgName, actualArgValue)) + | _ -> Some(defaultArgName, actualArgValue)) + mangleProvidedTypeName (nm, nonDefaultArgs) let outArgCompilerGeneratedName = "outArg" @@ -892,33 +1043,29 @@ let ExtraWitnessMethodName nm = nm + "$W" /// Reuses generated union case field name objects for common field numbers let mkUnionCaseFieldName = - let names = - [| 1 .. 10 |] - |> Array.map (fun i -> "Item" + string i) + let names = [| 1..10 |] |> Array.map (fun i -> "Item" + string i) fun nFields i -> match nFields with - | 0 | 1 -> "Item" + | 0 + | 1 -> "Item" | _ -> if i < 10 then names[i] else "Item" + string (i + 1) /// Reuses generated exception field name objects for common field numbers let mkExceptionFieldName = - let names = - [| 0 .. 9 |] - |> Array.map (fun i -> "Data" + string i) + let names = [| 0..9 |] |> Array.map (fun i -> "Data" + string i) - fun i -> - if i < 10 then names[i] else "Data" + string i + fun i -> if i < 10 then names[i] else "Data" + string i /// The prefix of the names used for the fake namespace path added to all dynamic code entries in FSI.EXE let FsiDynamicModulePrefix = "FSI_" [] module FSharpLib = - let Root = "Microsoft.FSharp" - let RootPath = IL.splitNamespace Root - let Core = Root + ".Core" - let CorePath = IL.splitNamespace Core + let Root = "Microsoft.FSharp" + let RootPath = IL.splitNamespace Root + let Core = Root + ".Core" + let CorePath = IL.splitNamespace Core [] module CustomOperations = @@ -927,7 +1074,8 @@ module CustomOperations = let unassignedTyparName = "?" -let FormatAndOtherOverloadsString remainingOverloads = FSComp.SR.typeInfoOtherOverloads(remainingOverloads) +let FormatAndOtherOverloadsString remainingOverloads = + FSComp.SR.typeInfoOtherOverloads (remainingOverloads) let GetLongNameFromString x = SplitNamesForILPath x @@ -939,16 +1087,18 @@ let FSharpOptimizationDataResourceName = "FSharpOptimizationData." let FSharpSignatureDataResourceName = "FSharpSignatureData." -// For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers +// For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers // don't complain when they see the resource. The prefix of these names must not be 'FSharpOptimizationData' // or 'FSharpSignatureData' -let FSharpOptimizationDataResourceName2 = "FSharpOptimizationInfo." +let FSharpOptimizationDataResourceName2 = "FSharpOptimizationInfo." let FSharpSignatureDataResourceName2 = "FSharpSignatureInfo." -let [] suffixForVariablesThatMayNotBeEliminated = "$cont" - -let [] suffixForTupleElementAssignmentTarget = "$tupleElem" +[] +let suffixForVariablesThatMayNotBeEliminated = "$cont" -let [] stackVarPrefix = "__stack_" +[] +let suffixForTupleElementAssignmentTarget = "$tupleElem" +[] +let stackVarPrefix = "__stack_" diff --git a/src/Compiler/SyntaxTree/SyntaxTree.fs b/src/Compiler/SyntaxTree/SyntaxTree.fs index 750a17580f6..9bcc3a8efe8 100644 --- a/src/Compiler/SyntaxTree/SyntaxTree.fs +++ b/src/Compiler/SyntaxTree/SyntaxTree.fs @@ -12,13 +12,12 @@ open FSharp.Compiler.Xml open FSharp.Compiler.SyntaxTrivia [] -type Ident (text: string, range: range) = - member _.idText = text - member _.idRange = range - override _.ToString() = text +type Ident(text: string, range: range) = + member _.idText = text + member _.idRange = range + override _.ToString() = text -type SynIdent = - | SynIdent of ident:Ident * trivia:IdentTrivia option +type SynIdent = SynIdent of ident: Ident * trivia: IdentTrivia option type LongIdent = Ident list @@ -26,48 +25,61 @@ type SynLongIdent = | SynLongIdent of id: LongIdent * dotRanges: range list * trivia: IdentTrivia option list member this.Range = - match this with - | SynLongIdent([], _, _) -> failwith "rangeOfLidwd" - | SynLongIdent([id], [], _) -> id.idRange - | SynLongIdent([id], [m], _) -> unionRanges id.idRange m - | SynLongIdent(h :: t, [], _) -> unionRanges h.idRange (List.last t).idRange - | SynLongIdent(h :: t, dotRanges, _) -> unionRanges h.idRange (List.last t).idRange |> unionRanges (List.last dotRanges) - - member this.LongIdent = match this with SynLongIdent(lid, _, _) -> lid - - member this.Dots = match this with SynLongIdent(dotRanges = dots) -> dots - + match this with + | SynLongIdent ([], _, _) -> failwith "rangeOfLidwd" + | SynLongIdent ([ id ], [], _) -> id.idRange + | SynLongIdent ([ id ], [ m ], _) -> unionRanges id.idRange m + | SynLongIdent (h :: t, [], _) -> unionRanges h.idRange (List.last t).idRange + | SynLongIdent (h :: t, dotRanges, _) -> unionRanges h.idRange (List.last t).idRange |> unionRanges (List.last dotRanges) + + member this.LongIdent = + match this with + | SynLongIdent (lid, _, _) -> lid + + member this.Dots = + match this with + | SynLongIdent (dotRanges = dots) -> dots + member this.Trivia = match this with - | SynLongIdent(trivia = trivia) -> List.choose id trivia + | SynLongIdent (trivia = trivia) -> List.choose id trivia member this.IdentsWithTrivia = - let (SynLongIdent(lid, _, trivia)) = this + let (SynLongIdent (lid, _, trivia)) = this + if lid.Length <> trivia.Length then failwith "difference between idents and trivia" else - List.zip lid trivia - |> List.map SynIdent + List.zip lid trivia |> List.map SynIdent - member this.ThereIsAnExtraDotAtTheEnd = match this with SynLongIdent(lid, dots, _) -> lid.Length = dots.Length + member this.ThereIsAnExtraDotAtTheEnd = + match this with + | SynLongIdent (lid, dots, _) -> lid.Length = dots.Length member this.RangeWithoutAnyExtraDot = - match this with - | SynLongIdent([], _, _) -> failwith "rangeOfLidwd" - | SynLongIdent([id], _, _) -> id.idRange - | SynLongIdent(h :: t, dotRanges, _) -> - let nonExtraDots = if dotRanges.Length = t.Length then dotRanges else List.truncate t.Length dotRanges - unionRanges h.idRange (List.last t).idRange |> unionRanges (List.last nonExtraDots) + match this with + | SynLongIdent ([], _, _) -> failwith "rangeOfLidwd" + | SynLongIdent ([ id ], _, _) -> id.idRange + | SynLongIdent (h :: t, dotRanges, _) -> + let nonExtraDots = + if dotRanges.Length = t.Length then + dotRanges + else + List.truncate t.Length dotRanges + + unionRanges h.idRange (List.last t).idRange + |> unionRanges (List.last nonExtraDots) [] module SynLongIdentHelpers = [] let (|LongIdentWithDots|) = function - | SynLongIdent(lid, dots, _) -> lid, dots + | SynLongIdent (lid, dots, _) -> lid, dots [] - let LongIdentWithDots (lid, dots) = SynLongIdent(lid, dots, List.replicate lid.Length None) + let LongIdentWithDots (lid, dots) = + SynLongIdent(lid, dots, List.replicate lid.Length None) [] type ParserDetail = @@ -87,8 +99,7 @@ type SynTypar = member this.Range = match this with - | SynTypar(id, _, _) -> - id.idRange + | SynTypar (id, _, _) -> id.idRange [] type SynStringKind = @@ -138,21 +149,21 @@ type SynConst = | UserNum of value: string * suffix: string - | String of text: string * synStringKind :SynStringKind * range: range + | String of text: string * synStringKind: SynStringKind * range: range | Bytes of bytes: byte[] * synByteStringKind: SynByteStringKind * range: range | UInt16s of uint16[] | Measure of constant: SynConst * constantRange: range * SynMeasure - + | SourceIdentifier of constant: string * value: string * range: range member c.Range dflt = match c with | SynConst.String (_, _, m0) | SynConst.Bytes (_, _, m0) - | SynConst.SourceIdentifier(_, _, m0) -> m0 + | SynConst.SourceIdentifier (_, _, m0) -> m0 | _ -> dflt [] @@ -173,12 +184,12 @@ type SynMeasure = | Anon of range: range | Var of typar: SynTypar * range: range - + | Paren of measure: SynMeasure * range: range [] type SynRationalConst = - + | Integer of value: int32 | Rational of numerator: int32 * denominator: int32 * range: range @@ -187,17 +198,23 @@ type SynRationalConst = [] type SynAccess = - | Public + | Public of range: range - | Internal + | Internal of range: range - | Private + | Private of range: range + + override this.ToString() = + match this with + | Public _ -> "Public" + | Internal _ -> "Internal" + | Private _ -> "Private" - override this.ToString () = + member this.Range: range = match this with - | Public -> "Public" - | Internal -> "Internal" - | Private -> "Private" + | Public m + | Internal m + | Private m -> m [] type DebugPointAtTarget = @@ -217,8 +234,7 @@ type DebugPointAtTry = | No [] -type DebugPointAtLeafExpr = - | Yes of range +type DebugPointAtLeafExpr = Yes of range [] type DebugPointAtWith = @@ -259,12 +275,11 @@ type DebugPointAtBinding = member x.Combine(y: DebugPointAtBinding) = match x, y with - | DebugPointAtBinding.Yes _ as g, _ -> g - | _, (DebugPointAtBinding.Yes _ as g) -> g + | DebugPointAtBinding.Yes _ as g, _ -> g + | _, (DebugPointAtBinding.Yes _ as g) -> g | _ -> x -type SeqExprOnly = - | SeqExprOnly of bool +type SeqExprOnly = SeqExprOnly of bool type BlockSeparator = range * pos option @@ -290,74 +305,46 @@ type SynBindingKind = | Do [] -type SynTyparDecl = - | SynTyparDecl of attributes: SynAttributes * SynTypar +type SynTyparDecl = SynTyparDecl of attributes: SynAttributes * SynTypar [] type SynTypeConstraint = - | WhereTyparIsValueType of - typar: SynTypar * - range: range + | WhereTyparIsValueType of typar: SynTypar * range: range - | WhereTyparIsReferenceType of - typar: SynTypar * - range: range + | WhereTyparIsReferenceType of typar: SynTypar * range: range - | WhereTyparIsUnmanaged of - typar: SynTypar * - range: range + | WhereTyparIsUnmanaged of typar: SynTypar * range: range - | WhereTyparSupportsNull of - typar: SynTypar * - range: range + | WhereTyparSupportsNull of typar: SynTypar * range: range - | WhereTyparIsComparable of - typar: SynTypar * - range: range + | WhereTyparIsComparable of typar: SynTypar * range: range - | WhereTyparIsEquatable of - typar: SynTypar * - range: range + | WhereTyparIsEquatable of typar: SynTypar * range: range - | WhereTyparDefaultsToType of - typar: SynTypar * - typeName: SynType * - range: range + | WhereTyparDefaultsToType of typar: SynTypar * typeName: SynType * range: range - | WhereTyparSubtypeOfType of - typar: SynTypar * - typeName: SynType * - range: range + | WhereTyparSubtypeOfType of typar: SynTypar * typeName: SynType * range: range - | WhereTyparSupportsMember of - typars: SynType list * - memberSig: SynMemberSig * - range: range + | WhereTyparSupportsMember of typars: SynType list * memberSig: SynMemberSig * range: range - | WhereTyparIsEnum of - typar: SynTypar * - typeArgs: SynType list * - range: range + | WhereTyparIsEnum of typar: SynTypar * typeArgs: SynType list * range: range - | WhereTyparIsDelegate of - typar: SynTypar * - typeArgs: SynType list * - range: range + | WhereTyparIsDelegate of typar: SynTypar * typeArgs: SynType list * range: range member x.Range = match x with - | WhereTyparIsValueType(range=range) - | WhereTyparIsReferenceType(range=range) - | WhereTyparIsUnmanaged(range=range) - | WhereTyparSupportsNull(range=range) - | WhereTyparIsComparable(range=range) - | WhereTyparIsEquatable(range=range) - | WhereTyparDefaultsToType(range=range) - | WhereTyparSubtypeOfType(range=range) - | WhereTyparSupportsMember(range=range) - | WhereTyparIsEnum(range=range) - | WhereTyparIsDelegate(range=range) -> range + | WhereTyparIsValueType (range = range) + | WhereTyparIsReferenceType (range = range) + | WhereTyparIsUnmanaged (range = range) + | WhereTyparSupportsNull (range = range) + | WhereTyparIsComparable (range = range) + | WhereTyparIsEquatable (range = range) + | WhereTyparDefaultsToType (range = range) + | WhereTyparSubtypeOfType (range = range) + | WhereTyparSupportsMember (range = range) + | WhereTyparIsEnum (range = range) + | WhereTyparIsDelegate (range = range) -> range [] type SynTyparDecls = @@ -367,32 +354,31 @@ type SynTyparDecls = member x.TyparDecls = match x with - | PostfixList (decls=decls) - | PrefixList (decls=decls) -> decls - | SinglePrefix (decl, _) -> [decl] + | PostfixList (decls = decls) + | PrefixList (decls = decls) -> decls + | SinglePrefix (decl, _) -> [ decl ] member x.Constraints = match x with - | PostfixList (constraints=constraints) -> constraints + | PostfixList (constraints = constraints) -> constraints | _ -> [] member x.Range = match x with - | PostfixList (range=range) - | PrefixList (range=range) -> range - | SinglePrefix (range=range) -> range + | PostfixList (range = range) + | PrefixList (range = range) -> range + | SinglePrefix (range = range) -> range -[] -type SynType = - - | LongIdent of - longDotId: SynLongIdent +[] +type SynType = + + | LongIdent of longDotId: SynLongIdent | App of typeName: SynType * lessRange: range option * typeArgs: SynType list * - commaRanges: range list * // interstitial commas + commaRanges: range list * // interstitial commas greaterRange: range option * isPostfix: bool * range: range @@ -402,161 +388,102 @@ type SynType = longDotId: SynLongIdent * lessRange: range option * typeArgs: SynType list * - commaRanges: range list * // interstitial commas + commaRanges: range list * // interstitial commas greaterRange: range option * range: range - | Tuple of - isStruct: bool * - elementTypes:(bool*SynType) list * - range: range + | Tuple of isStruct: bool * elementTypes: (bool * SynType) list * range: range - | AnonRecd of - isStruct: bool * - fields:(Ident * SynType) list * - range: range + | AnonRecd of isStruct: bool * fields: (Ident * SynType) list * range: range - | Array of - rank: int * - elementType: SynType * - range: range + | Array of rank: int * elementType: SynType * range: range - | Fun of - argType: SynType * - returnType: SynType * - range: range + | Fun of argType: SynType * returnType: SynType * range: range * trivia: SynTypeFunTrivia - | Var of - typar: SynTypar * - range: range + | Var of typar: SynTypar * range: range | Anon of range: range - | WithGlobalConstraints of - typeName: SynType * - constraints: SynTypeConstraint list * - range: range + | WithGlobalConstraints of typeName: SynType * constraints: SynTypeConstraint list * range: range - | HashConstraint of - innerType: SynType * - range: range + | HashConstraint of innerType: SynType * range: range - | MeasureDivide of - dividend: SynType * - divisor: SynType * - range: range + | MeasureDivide of dividend: SynType * divisor: SynType * range: range - | MeasurePower of - baseMeasure: SynType * - exponent: SynRationalConst * - range: range + | MeasurePower of baseMeasure: SynType * exponent: SynRationalConst * range: range - | StaticConstant of - constant: SynConst * - range: range + | StaticConstant of constant: SynConst * range: range - | StaticConstantExpr of - expr: SynExpr * - range: range + | StaticConstantExpr of expr: SynExpr * range: range - | StaticConstantNamed of - ident: SynType * - value: SynType * - range: range + | StaticConstantNamed of ident: SynType * value: SynType * range: range - | Paren of - innerType: SynType * - range: range + | Paren of innerType: SynType * range: range member x.Range = match x with - | SynType.App (range=m) - | SynType.LongIdentApp (range=m) - | SynType.Tuple (range=m) - | SynType.Array (range=m) - | SynType.AnonRecd (range=m) - | SynType.Fun (range=m) - | SynType.Var (range=m) - | SynType.Anon (range=m) - | SynType.WithGlobalConstraints (range=m) - | SynType.StaticConstant (range=m) - | SynType.StaticConstantExpr (range=m) - | SynType.StaticConstantNamed (range=m) - | SynType.HashConstraint (range=m) - | SynType.MeasureDivide (range=m) - | SynType.MeasurePower (range=m) - | SynType.Paren (range=m) -> m + | SynType.App (range = m) + | SynType.LongIdentApp (range = m) + | SynType.Tuple (range = m) + | SynType.Array (range = m) + | SynType.AnonRecd (range = m) + | SynType.Fun (range = m) + | SynType.Var (range = m) + | SynType.Anon (range = m) + | SynType.WithGlobalConstraints (range = m) + | SynType.StaticConstant (range = m) + | SynType.StaticConstantExpr (range = m) + | SynType.StaticConstantNamed (range = m) + | SynType.HashConstraint (range = m) + | SynType.MeasureDivide (range = m) + | SynType.MeasurePower (range = m) + | SynType.Paren (range = m) -> m | SynType.LongIdent lidwd -> lidwd.Range -[] +[] type SynExpr = - | Paren of - expr: SynExpr * - leftParenRange: range * - rightParenRange: range option * - range: range + | Paren of expr: SynExpr * leftParenRange: range * rightParenRange: range option * range: range - | Quote of - operator: SynExpr * - isRaw: bool * - quotedExpr: SynExpr * - isFromQueryExpression: bool * - range: range + | Quote of operator: SynExpr * isRaw: bool * quotedExpr: SynExpr * isFromQueryExpression: bool * range: range - | Const of - constant: SynConst * - range: range + | Const of constant: SynConst * range: range - | Typed of - expr: SynExpr * - targetType: SynType * - range: range + | Typed of expr: SynExpr * targetType: SynType * range: range | Tuple of isStruct: bool * exprs: SynExpr list * - commaRanges: range list * // interstitial commas - range: range + commaRanges: range list * // interstitial commas + range: range | AnonRecd of isStruct: bool * - copyInfo:(SynExpr * BlockSeparator) option * - recordFields:(Ident * range option * SynExpr) list * + copyInfo: (SynExpr * BlockSeparator) option * + recordFields: (Ident * range option * SynExpr) list * range: range - | ArrayOrList of - isArray: bool * - exprs: SynExpr list * - range: range + | ArrayOrList of isArray: bool * exprs: SynExpr list * range: range | Record of - baseInfo:(SynType * SynExpr * range * BlockSeparator option * range) option * - copyInfo:(SynExpr * BlockSeparator) option * + baseInfo: (SynType * SynExpr * range * BlockSeparator option * range) option * + copyInfo: (SynExpr * BlockSeparator) option * recordFields: SynExprRecordField list * range: range - | New of - isProtected: bool * - targetType: SynType * - expr: SynExpr * - range: range + | New of isProtected: bool * targetType: SynType * expr: SynExpr * range: range | ObjExpr of objType: SynType * - argOptions:(SynExpr * Ident option) option * + argOptions: (SynExpr * Ident option) option * withKeyword: range option * bindings: SynBinding list * - members: SynMemberDefn list * + members: SynMemberDefns * extraImpls: SynInterfaceImpl list * newExprRange: range * range: range - | While of - whileDebugPoint: DebugPointAtWhile * - whileExpr: SynExpr * - doExpr: SynExpr * - range: range + | While of whileDebugPoint: DebugPointAtWhile * whileExpr: SynExpr * doExpr: SynExpr * range: range | For of forDebugPoint: DebugPointAtFor * @@ -579,27 +506,13 @@ type SynExpr = bodyExpr: SynExpr * range: range - | ArrayOrListComputed of - isArray: bool * - expr: SynExpr * - range: range + | ArrayOrListComputed of isArray: bool * expr: SynExpr * range: range - | IndexRange of - expr1: SynExpr option * - opm: range * - expr2: SynExpr option* - range1: range * - range2: range * - range: range + | IndexRange of expr1: SynExpr option * opm: range * expr2: SynExpr option * range1: range * range2: range * range: range - | IndexFromEnd of - expr: SynExpr * - range: range + | IndexFromEnd of expr: SynExpr * range: range - | ComputationExpr of - hasSeqBuilder: bool * - expr: SynExpr * - range: range + | ComputationExpr of hasSeqBuilder: bool * expr: SynExpr * range: range | Lambda of fromMethod: bool * @@ -624,20 +537,11 @@ type SynExpr = range: range * trivia: SynExprMatchTrivia - | Do of - expr: SynExpr * - range: range + | Do of expr: SynExpr * range: range - | Assert of - expr: SynExpr * - range: range + | Assert of expr: SynExpr * range: range - | App of - flag: ExprAtomicFlag * - isInfix: bool * - funcExpr: SynExpr * - argExpr: SynExpr * - range: range + | App of flag: ExprAtomicFlag * isInfix: bool * funcExpr: SynExpr * argExpr: SynExpr * range: range | TypeApp of expr: SynExpr * @@ -648,13 +552,7 @@ type SynExpr = typeArgsRange: range * range: range - | LetOrUse of - isRecursive: bool * - isUse: bool * - bindings: SynBinding list * - body: SynExpr * - range: range * - trivia: SynExprLetOrUseTrivia + | LetOrUse of isRecursive: bool * isUse: bool * bindings: SynBinding list * body: SynExpr * range: range * trivia: SynExprLetOrUseTrivia | TryWith of tryExpr: SynExpr * @@ -672,16 +570,9 @@ type SynExpr = finallyDebugPoint: DebugPointAtFinally * trivia: SynExprTryFinallyTrivia - | Lazy of - expr: SynExpr * - range: range + | Lazy of expr: SynExpr * range: range - | Sequential of - debugPoint: DebugPointAtSequential * - isTrueSeq: bool * - expr1: SynExpr * - expr2: SynExpr * - range: range + | Sequential of debugPoint: DebugPointAtSequential * isTrueSeq: bool * expr1: SynExpr * expr2: SynExpr * range: range | IfThenElse of ifExpr: SynExpr * @@ -692,42 +583,19 @@ type SynExpr = range: range * trivia: SynExprIfThenElseTrivia - | Ident of - ident: Ident + | Ident of ident: Ident - | LongIdent of - isOptional: bool * - longDotId: SynLongIdent * - altNameRefCell: SynSimplePatAlternativeIdInfo ref option * - range: range + | LongIdent of isOptional: bool * longDotId: SynLongIdent * altNameRefCell: SynSimplePatAlternativeIdInfo ref option * range: range - | LongIdentSet of - longDotId: SynLongIdent * - expr: SynExpr * - range: range + | LongIdentSet of longDotId: SynLongIdent * expr: SynExpr * range: range - | DotGet of - expr: SynExpr * - rangeOfDot: range * - longDotId: SynLongIdent * - range: range + | DotGet of expr: SynExpr * rangeOfDot: range * longDotId: SynLongIdent * range: range - | DotSet of - targetExpr: SynExpr * - longDotId: SynLongIdent * - rhsExpr: SynExpr * - range: range + | DotSet of targetExpr: SynExpr * longDotId: SynLongIdent * rhsExpr: SynExpr * range: range - | Set of - targetExpr: SynExpr * - rhsExpr: SynExpr * - range: range + | Set of targetExpr: SynExpr * rhsExpr: SynExpr * range: range - | DotIndexedGet of - objectExpr: SynExpr * - indexArgs: SynExpr * - dotRange: range * - range: range + | DotIndexedGet of objectExpr: SynExpr * indexArgs: SynExpr * dotRange: range * range: range | DotIndexedSet of objectExpr: SynExpr * @@ -737,82 +605,35 @@ type SynExpr = dotRange: range * range: range - | NamedIndexedPropertySet of - longDotId: SynLongIdent * - expr1: SynExpr * - expr2: SynExpr * - range: range + | NamedIndexedPropertySet of longDotId: SynLongIdent * expr1: SynExpr * expr2: SynExpr * range: range - | DotNamedIndexedPropertySet of - targetExpr: SynExpr * - longDotId: SynLongIdent * - argExpr: SynExpr * - rhsExpr: SynExpr * - range: range + | DotNamedIndexedPropertySet of targetExpr: SynExpr * longDotId: SynLongIdent * argExpr: SynExpr * rhsExpr: SynExpr * range: range - | TypeTest of - expr: SynExpr * - targetType: SynType * - range: range + | TypeTest of expr: SynExpr * targetType: SynType * range: range - | Upcast of - expr: SynExpr * - targetType: SynType * - range: range + | Upcast of expr: SynExpr * targetType: SynType * range: range - | Downcast of - expr: SynExpr * - targetType: SynType * - range: range + | Downcast of expr: SynExpr * targetType: SynType * range: range - | InferredUpcast of - expr: SynExpr * - range: range + | InferredUpcast of expr: SynExpr * range: range - | InferredDowncast of - expr: SynExpr * - range: range + | InferredDowncast of expr: SynExpr * range: range - | Null of - range: range + | Null of range: range - | AddressOf of - isByref: bool * - expr: SynExpr * - opRange: range * - range: range + | AddressOf of isByref: bool * expr: SynExpr * opRange: range * range: range - | TraitCall of - supportTys: SynTypar list * - traitSig: SynMemberSig * - argExpr: SynExpr * - range: range + | TraitCall of supportTys: SynTypar list * traitSig: SynMemberSig * argExpr: SynExpr * range: range - | JoinIn of - lhsExpr: SynExpr * - lhsRange: range * - rhsExpr: SynExpr * - range: range + | JoinIn of lhsExpr: SynExpr * lhsRange: range * rhsExpr: SynExpr * range: range - | ImplicitZero of - range: range + | ImplicitZero of range: range - | SequentialOrImplicitYield of - debugPoint:DebugPointAtSequential * - expr1:SynExpr * - expr2:SynExpr * - ifNotStmt:SynExpr * - range:range + | SequentialOrImplicitYield of debugPoint: DebugPointAtSequential * expr1: SynExpr * expr2: SynExpr * ifNotStmt: SynExpr * range: range - | YieldOrReturn of - flags: (bool * bool) * - expr: SynExpr * - range: range + | YieldOrReturn of flags: (bool * bool) * expr: SynExpr * range: range - | YieldOrReturnFrom of - flags: (bool * bool) * - expr: SynExpr * - range: range + | YieldOrReturnFrom of flags: (bool * bool) * expr: SynExpr * range: range | LetOrUseBang of bindDebugPoint: DebugPointAtBinding * @@ -821,7 +642,7 @@ type SynExpr = pat: SynPat * rhs: SynExpr * andBangs: SynExprAndBang list * - body:SynExpr * + body: SynExpr * range: range * trivia: SynExprLetOrUseBangTrivia @@ -832,12 +653,10 @@ type SynExpr = range: range * trivia: SynExprMatchBangTrivia - | DoBang of - expr: SynExpr * - range: range + | DoBang of expr: SynExpr * range: range | LibraryOnlyILAssembly of - ilCode: obj * // this type is ILInstr[] but is hidden to avoid the representation of AbstractIL being public + ilCode: obj * // this type is ILInstr[] but is hidden to avoid the representation of AbstractIL being public typeArgs: SynType list * args: SynExpr list * retTy: SynType list * @@ -849,117 +668,94 @@ type SynExpr = optimizedExpr: SynExpr * range: range - | LibraryOnlyUnionCaseFieldGet of - expr: SynExpr * - longId: LongIdent * - fieldNum: int * - range: range + | LibraryOnlyUnionCaseFieldGet of expr: SynExpr * longId: LongIdent * fieldNum: int * range: range - | LibraryOnlyUnionCaseFieldSet of - expr: SynExpr * - longId: LongIdent * - fieldNum: int * - rhsExpr: SynExpr * - range: range + | LibraryOnlyUnionCaseFieldSet of expr: SynExpr * longId: LongIdent * fieldNum: int * rhsExpr: SynExpr * range: range - | ArbitraryAfterError of - debugStr: string * - range: range + | ArbitraryAfterError of debugStr: string * range: range - | FromParseError of - expr: SynExpr * - range: range + | FromParseError of expr: SynExpr * range: range - | DiscardAfterMissingQualificationAfterDot of - expr: SynExpr * - range: range + | DiscardAfterMissingQualificationAfterDot of expr: SynExpr * range: range - | Fixed of - expr: SynExpr * - range: range + | Fixed of expr: SynExpr * range: range - | InterpolatedString of - contents: SynInterpolatedStringPart list * - synStringKind :SynStringKind * - range: range + | InterpolatedString of contents: SynInterpolatedStringPart list * synStringKind: SynStringKind * range: range - | DebugPoint of - debugPoint: DebugPointAtLeafExpr * - isControlFlow: bool * - innerExpr: SynExpr + | DebugPoint of debugPoint: DebugPointAtLeafExpr * isControlFlow: bool * innerExpr: SynExpr | Dynamic of funcExpr: SynExpr * qmark: range * argExpr: SynExpr * range: range - + member e.Range = match e with | SynExpr.Paren (_, leftParenRange, rightParenRange, r) -> match rightParenRange with | Some rightParenRange when leftParenRange.FileIndex <> rightParenRange.FileIndex -> leftParenRange | _ -> r - | SynExpr.Quote (range=m) - | SynExpr.Const (range=m) - | SynExpr.Typed (range=m) - | SynExpr.Tuple (range=m) - | SynExpr.AnonRecd (range=m) - | SynExpr.ArrayOrList (range=m) - | SynExpr.Record (range=m) - | SynExpr.New (range=m) - | SynExpr.ObjExpr (range=m) - | SynExpr.While (range=m) - | SynExpr.For (range=m) - | SynExpr.ForEach (range=m) - | SynExpr.ComputationExpr (range=m) - | SynExpr.ArrayOrListComputed (range=m) - | SynExpr.Lambda (range=m) - | SynExpr.Match (range=m) - | SynExpr.MatchLambda (range=m) - | SynExpr.Do (range=m) - | SynExpr.Assert (range=m) - | SynExpr.App (range=m) - | SynExpr.TypeApp (range=m) - | SynExpr.LetOrUse (range=m) - | SynExpr.TryWith (range=m) - | SynExpr.TryFinally (range=m) - | SynExpr.Sequential (range=m) - | SynExpr.SequentialOrImplicitYield (range=m) - | SynExpr.ArbitraryAfterError (range=m) - | SynExpr.FromParseError (range=m) - | SynExpr.DiscardAfterMissingQualificationAfterDot (range=m) - | SynExpr.IfThenElse (range=m) - | SynExpr.LongIdent (range=m) - | SynExpr.LongIdentSet (range=m) - | SynExpr.NamedIndexedPropertySet (range=m) - | SynExpr.DotIndexedGet (range=m) - | SynExpr.DotIndexedSet (range=m) - | SynExpr.DotGet (range=m) - | SynExpr.DotSet (range=m) - | SynExpr.Set (range=m) - | SynExpr.DotNamedIndexedPropertySet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldSet (range=m) - | SynExpr.LibraryOnlyILAssembly (range=m) - | SynExpr.LibraryOnlyStaticOptimization (range=m) - | SynExpr.IndexRange (range=m) - | SynExpr.IndexFromEnd (range=m) - | SynExpr.TypeTest (range=m) - | SynExpr.Upcast (range=m) - | SynExpr.AddressOf (range=m) - | SynExpr.Downcast (range=m) - | SynExpr.JoinIn (range=m) - | SynExpr.InferredUpcast (range=m) - | SynExpr.InferredDowncast (range=m) - | SynExpr.Null (range=m) - | SynExpr.Lazy (range=m) - | SynExpr.TraitCall (range=m) - | SynExpr.ImplicitZero (range=m) - | SynExpr.YieldOrReturn (range=m) - | SynExpr.YieldOrReturnFrom (range=m) - | SynExpr.LetOrUseBang (range=m) - | SynExpr.MatchBang (range=m) - | SynExpr.DoBang (range=m) - | SynExpr.Fixed (range=m) - | SynExpr.InterpolatedString (range=m) - | SynExpr.Dynamic(range=m) -> m + | SynExpr.Quote (range = m) + | SynExpr.Const (range = m) + | SynExpr.Typed (range = m) + | SynExpr.Tuple (range = m) + | SynExpr.AnonRecd (range = m) + | SynExpr.ArrayOrList (range = m) + | SynExpr.Record (range = m) + | SynExpr.New (range = m) + | SynExpr.ObjExpr (range = m) + | SynExpr.While (range = m) + | SynExpr.For (range = m) + | SynExpr.ForEach (range = m) + | SynExpr.ComputationExpr (range = m) + | SynExpr.ArrayOrListComputed (range = m) + | SynExpr.Lambda (range = m) + | SynExpr.Match (range = m) + | SynExpr.MatchLambda (range = m) + | SynExpr.Do (range = m) + | SynExpr.Assert (range = m) + | SynExpr.App (range = m) + | SynExpr.TypeApp (range = m) + | SynExpr.LetOrUse (range = m) + | SynExpr.TryWith (range = m) + | SynExpr.TryFinally (range = m) + | SynExpr.Sequential (range = m) + | SynExpr.SequentialOrImplicitYield (range = m) + | SynExpr.ArbitraryAfterError (range = m) + | SynExpr.FromParseError (range = m) + | SynExpr.DiscardAfterMissingQualificationAfterDot (range = m) + | SynExpr.IfThenElse (range = m) + | SynExpr.LongIdent (range = m) + | SynExpr.LongIdentSet (range = m) + | SynExpr.NamedIndexedPropertySet (range = m) + | SynExpr.DotIndexedGet (range = m) + | SynExpr.DotIndexedSet (range = m) + | SynExpr.DotGet (range = m) + | SynExpr.DotSet (range = m) + | SynExpr.Set (range = m) + | SynExpr.DotNamedIndexedPropertySet (range = m) + | SynExpr.LibraryOnlyUnionCaseFieldGet (range = m) + | SynExpr.LibraryOnlyUnionCaseFieldSet (range = m) + | SynExpr.LibraryOnlyILAssembly (range = m) + | SynExpr.LibraryOnlyStaticOptimization (range = m) + | SynExpr.IndexRange (range = m) + | SynExpr.IndexFromEnd (range = m) + | SynExpr.TypeTest (range = m) + | SynExpr.Upcast (range = m) + | SynExpr.AddressOf (range = m) + | SynExpr.Downcast (range = m) + | SynExpr.JoinIn (range = m) + | SynExpr.InferredUpcast (range = m) + | SynExpr.InferredDowncast (range = m) + | SynExpr.Null (range = m) + | SynExpr.Lazy (range = m) + | SynExpr.TraitCall (range = m) + | SynExpr.ImplicitZero (range = m) + | SynExpr.YieldOrReturn (range = m) + | SynExpr.YieldOrReturnFrom (range = m) + | SynExpr.LetOrUseBang (range = m) + | SynExpr.MatchBang (range = m) + | SynExpr.DoBang (range = m) + | SynExpr.Fixed (range = m) + | SynExpr.InterpolatedString (range = m) + | SynExpr.Dynamic (range = m) -> m | SynExpr.Ident id -> id.idRange | SynExpr.DebugPoint (_, _, innerExpr) -> innerExpr.Range @@ -980,9 +776,8 @@ type SynExpr = | SynExpr.Paren (_, m, _, _) -> m | SynExpr.Sequential (_, _, e1, _, _) | SynExpr.SequentialOrImplicitYield (_, e1, _, _, _) - | SynExpr.App (_, _, e1, _, _) -> - e1.RangeOfFirstPortion - | SynExpr.ForEach (pat=pat; range=r) -> + | SynExpr.App (_, _, e1, _, _) -> e1.RangeOfFirstPortion + | SynExpr.ForEach (pat = pat; range = r) -> let start = r.Start let e = (pat.Range: range).Start mkRange r.FileName start e @@ -1027,21 +822,15 @@ type SynSimplePat = isOptional: bool * range: range - | Typed of - pat: SynSimplePat * - targetType: SynType * - range: range + | Typed of pat: SynSimplePat * targetType: SynType * range: range - | Attrib of - pat: SynSimplePat * - attributes: SynAttributes * - range: range + | Attrib of pat: SynSimplePat * attributes: SynAttributes * range: range member x.Range = match x with - | SynSimplePat.Id(range=range) - | SynSimplePat.Typed(range=range) - | SynSimplePat.Attrib(range=range) -> range + | SynSimplePat.Id (range = range) + | SynSimplePat.Typed (range = range) + | SynSimplePat.Attrib (range = range) -> range [] type SynSimplePatAlternativeIdInfo = @@ -1053,179 +842,116 @@ type SynSimplePatAlternativeIdInfo = [] type SynStaticOptimizationConstraint = - | WhenTyparTyconEqualsTycon of - typar: SynTypar * - rhsType: SynType * - range: range + | WhenTyparTyconEqualsTycon of typar: SynTypar * rhsType: SynType * range: range - | WhenTyparIsStruct of - typar: SynTypar * - range: range + | WhenTyparIsStruct of typar: SynTypar * range: range -[] +[] type SynSimplePats = - | SimplePats of - pats: SynSimplePat list * - range: range + | SimplePats of pats: SynSimplePat list * range: range - | Typed of - pats: SynSimplePats * - targetType: SynType * - range: range + | Typed of pats: SynSimplePats * targetType: SynType * range: range member x.Range = match x with - | SynSimplePats.SimplePats(range=range) - | SynSimplePats.Typed(range=range) -> range + | SynSimplePats.SimplePats (range = range) + | SynSimplePats.Typed (range = range) -> range [] type SynArgPats = - | Pats of - pats: SynPat list + | Pats of pats: SynPat list - | NamePatPairs of - pats: (Ident * range * SynPat) list * - range: range + | NamePatPairs of pats: (Ident * range * SynPat) list * range: range member x.Patterns = match x with | Pats pats -> pats - | NamePatPairs (pats, _) -> pats |> List.map (fun (_,_, pat) -> pat) + | NamePatPairs (pats, _) -> pats |> List.map (fun (_, _, pat) -> pat) -[] +[] type SynPat = - | Const of - constant: SynConst * - range: range + | Const of constant: SynConst * range: range - | Wild of - range: range + | Wild of range: range - | Named of - ident: SynIdent * - isThisVal: bool * - accessibility: SynAccess option * - range: range + | Named of ident: SynIdent * isThisVal: bool * accessibility: SynAccess option * range: range - | Typed of - pat: SynPat * - targetType: SynType * - range: range + | Typed of pat: SynPat * targetType: SynType * range: range - | Attrib of - pat: SynPat * - attributes: SynAttributes * - range: range + | Attrib of pat: SynPat * attributes: SynAttributes * range: range - | Or of - lhsPat: SynPat * - rhsPat: SynPat * - range: range * - trivia: SynPatOrTrivia + | Or of lhsPat: SynPat * rhsPat: SynPat * range: range * trivia: SynPatOrTrivia - | Ands of - pats: SynPat list * - range: range - - | As of - lhsPat: SynPat * - rhsPat: SynPat * - range: range + | Ands of pats: SynPat list * range: range + + | As of lhsPat: SynPat * rhsPat: SynPat * range: range | LongIdent of longDotId: SynLongIdent * - propertyKeyword: PropertyKeyword option * - extraId: Ident option * // holds additional ident for tooling - typarDecls: SynValTyparDecls option * // usually None: temporary used to parse "f<'a> x = x" + extraId: Ident option * // holds additional ident for tooling + typarDecls: SynValTyparDecls option * // usually None: temporary used to parse "f<'a> x = x" argPats: SynArgPats * accessibility: SynAccess option * range: range - | Tuple of - isStruct: bool * - elementPats: SynPat list * - range: range + | Tuple of isStruct: bool * elementPats: SynPat list * range: range - | Paren of - pat: SynPat * - range: range + | Paren of pat: SynPat * range: range - | ArrayOrList of - isArray: bool * - elementPats: SynPat list * - range: range + | ArrayOrList of isArray: bool * elementPats: SynPat list * range: range - | Record of - fieldPats: ((LongIdent * Ident) * range * SynPat) list * - range: range + | Record of fieldPats: ((LongIdent * Ident) * range * SynPat) list * range: range - | Null of - range: range + | Null of range: range - | OptionalVal of - ident: Ident * - range: range + | OptionalVal of ident: Ident * range: range - | IsInst of - pat: SynType * - range: range + | IsInst of pat: SynType * range: range - | QuoteExpr of - expr: SynExpr * - range: range + | QuoteExpr of expr: SynExpr * range: range - | DeprecatedCharRange of - startChar: char * - endChar: char * - range: range + | DeprecatedCharRange of startChar: char * endChar: char * range: range | InstanceMember of thisId: Ident * memberId: Ident * - toolingId: Ident option * // holds additional ident for tooling + toolingId: Ident option * // holds additional ident for tooling accessibility: SynAccess option * range: range - | FromParseError of - pat: SynPat * - range: range + | FromParseError of pat: SynPat * range: range member p.Range = - match p with - | SynPat.Const (range=m) - | SynPat.Wild (range=m) - | SynPat.Named (range=m) - | SynPat.Or (range=m) - | SynPat.Ands (range=m) - | SynPat.As (range=m) - | SynPat.LongIdent (range=m) - | SynPat.ArrayOrList (range=m) - | SynPat.Tuple (range=m) - | SynPat.Typed (range=m) - | SynPat.Attrib (range=m) - | SynPat.Record (range=m) - | SynPat.DeprecatedCharRange (range=m) - | SynPat.Null (range=m) - | SynPat.IsInst (range=m) - | SynPat.QuoteExpr (range=m) - | SynPat.InstanceMember (range=m) - | SynPat.OptionalVal (range=m) - | SynPat.Paren (range=m) - | SynPat.FromParseError (range=m) -> m + match p with + | SynPat.Const (range = m) + | SynPat.Wild (range = m) + | SynPat.Named (range = m) + | SynPat.Or (range = m) + | SynPat.Ands (range = m) + | SynPat.As (range = m) + | SynPat.LongIdent (range = m) + | SynPat.ArrayOrList (range = m) + | SynPat.Tuple (range = m) + | SynPat.Typed (range = m) + | SynPat.Attrib (range = m) + | SynPat.Record (range = m) + | SynPat.DeprecatedCharRange (range = m) + | SynPat.Null (range = m) + | SynPat.IsInst (range = m) + | SynPat.QuoteExpr (range = m) + | SynPat.InstanceMember (range = m) + | SynPat.OptionalVal (range = m) + | SynPat.Paren (range = m) + | SynPat.FromParseError (range = m) -> m -[] -type PropertyKeyword = - | With of range - | And of range - -[] +[] type SynInterfaceImpl = | SynInterfaceImpl of interfaceTy: SynType * withKeyword: range option * bindings: SynBinding list * - members: SynMemberDefn list * + members: SynMemberDefns * range: range [] @@ -1240,46 +966,44 @@ type SynMatchClause = member this.RangeOfGuardAndRhs = match this with - | SynMatchClause(whenExpr=eo; resultExpr=e) -> + | SynMatchClause (whenExpr = eo; resultExpr = e) -> match eo with | None -> e.Range | Some x -> unionRanges e.Range x.Range member this.Range = match this with - | SynMatchClause(range = m) -> m + | SynMatchClause (range = m) -> m [] type SynAttribute = - { TypeName: SynLongIdent + { + TypeName: SynLongIdent - ArgExpr: SynExpr + ArgExpr: SynExpr - Target: Ident option + Target: Ident option - AppliesToGetterAndSetter: bool + AppliesToGetterAndSetter: bool - Range: range + Range: range } [] type SynAttributeList = - { - Attributes: SynAttribute list - - Range: range + { + Attributes: SynAttribute list + + Range: range } type SynAttributes = SynAttributeList list [] type SynValData = - | SynValData of - memberFlags: SynMemberFlags option * - valInfo: SynValInfo * - thisIdOpt: Ident option + | SynValData of memberFlags: SynMemberFlags option * valInfo: SynValInfo * thisIdOpt: Ident option - member x.SynValInfo = (let (SynValData(_flags, synValInfo, _)) = x in synValInfo) + member x.SynValInfo = (let (SynValData (_flags, synValInfo, _)) = x in synValInfo) [] type SynBinding = @@ -1293,7 +1017,7 @@ type SynBinding = valData: SynValData * headPat: SynPat * returnInfo: SynBindingReturnInfo option * - expr: SynExpr * + expr: SynExpr * range: range * debugPoint: DebugPointAtBinding * trivia: SynBindingTrivia @@ -1302,35 +1026,32 @@ type SynBinding = // - for everything else, the 'range' member that appears last/second-to-last is the 'full range' of the whole tree construct // - but for Binding, the 'range' is only the range of the left-hand-side, the right-hand-side range is in the SynExpr // - so we use explicit names to avoid confusion - member x.RangeOfBindingWithoutRhs = let (SynBinding(range=m)) = x in m + member x.RangeOfBindingWithoutRhs = let (SynBinding (range = m)) = x in m - member x.RangeOfBindingWithRhs = let (SynBinding(expr=e; range=m)) = x in unionRanges e.Range m + member x.RangeOfBindingWithRhs = + let (SynBinding (expr = e; range = m)) = x in unionRanges e.Range m - member x.RangeOfHeadPattern = let (SynBinding(headPat=headPat)) = x in headPat.Range + member x.RangeOfHeadPattern = let (SynBinding (headPat = headPat)) = x in headPat.Range [] -type SynBindingReturnInfo = - | SynBindingReturnInfo of - typeName: SynType * - range: range * - attributes: SynAttributes +type SynBindingReturnInfo = SynBindingReturnInfo of typeName: SynType * range: range * attributes: SynAttributes [] type SynMemberFlags = - { - IsInstance: bool + { + IsInstance: bool + + IsDispatchSlot: bool - IsDispatchSlot: bool + IsOverrideOrExplicitImpl: bool - IsOverrideOrExplicitImpl: bool + IsFinal: bool - IsFinal: bool + MemberKind: SynMemberKind - MemberKind: SynMemberKind - - Trivia: SynMemberFlagsTrivia + Trivia: SynMemberFlagsTrivia } - + override this.Equals other = match other with | :? SynMemberFlags as other -> @@ -1341,12 +1062,12 @@ type SynMemberFlags = && this.MemberKind = other.MemberKind | _ -> false - override this.GetHashCode () = - hash this.IsInstance + - hash this.IsDispatchSlot + - hash this.IsOverrideOrExplicitImpl + - hash this.IsFinal + - hash this.MemberKind + override this.GetHashCode() = + hash this.IsInstance + + hash this.IsDispatchSlot + + hash this.IsOverrideOrExplicitImpl + + hash this.IsFinal + + hash this.MemberKind [] type SynMemberKind = @@ -1366,34 +1087,23 @@ type SynMemberKind = [] type SynMemberSig = - | Member of - memberSig: SynValSig * - flags: SynMemberFlags * - range: range + | Member of memberSig: SynValSig * flags: SynMemberFlags * range: range - | Interface of - interfaceType: SynType * - range: range + | Interface of interfaceType: SynType * range: range - | Inherit of - inheritedType: SynType * - range: range + | Inherit of inheritedType: SynType * range: range - | ValField of - field: SynField * - range: range + | ValField of field: SynField * range: range - | NestedType of - nestedType: SynTypeDefnSig * - range: range + | NestedType of nestedType: SynTypeDefnSig * range: range member d.Range = match d with - | SynMemberSig.Member (range=m) - | SynMemberSig.Interface (range=m) - | SynMemberSig.Inherit (range=m) - | SynMemberSig.ValField (range=m) - | SynMemberSig.NestedType (range=m) -> m + | SynMemberSig.Member (range = m) + | SynMemberSig.Interface (range = m) + | SynMemberSig.Inherit (range = m) + | SynMemberSig.ValField (range = m) + | SynMemberSig.NestedType (range = m) -> m [] type SynTypeDefnKind = @@ -1412,19 +1122,11 @@ type SynTypeDefnKind = [] type SynTypeDefnSimpleRepr = - | Union of - accessibility: SynAccess option * - unionCases: SynUnionCase list * - range: range + | Union of accessibility: SynAccess option * unionCases: SynUnionCase list * range: range - | Enum of - cases: SynEnumCase list * - range: range + | Enum of cases: SynEnumCase list * range: range - | Record of - accessibility: SynAccess option * - recordFields: SynField list * - range: range + | Record of accessibility: SynAccess option * recordFields: SynField list * range: range | General of kind: SynTypeDefnKind * @@ -1437,29 +1139,24 @@ type SynTypeDefnSimpleRepr = range: range | LibraryOnlyILAssembly of - ilType: obj * // this type is ILType but is hidden to avoid the representation of AbstractIL being public + ilType: obj * // this type is ILType but is hidden to avoid the representation of AbstractIL being public range: range - | TypeAbbrev of - detail: ParserDetail * - rhsType: SynType * - range: range + | TypeAbbrev of detail: ParserDetail * rhsType: SynType * range: range - | None of - range: range + | None of range: range - | Exception of - exnRepr: SynExceptionDefnRepr + | Exception of exnRepr: SynExceptionDefnRepr member this.Range = match this with - | Union (range=m) - | Enum (range=m) - | Record (range=m) - | General (range=m) - | LibraryOnlyILAssembly (range=m) - | TypeAbbrev (range=m) - | None (range=m) -> m + | Union (range = m) + | Enum (range = m) + | Record (range = m) + | General (range = m) + | LibraryOnlyILAssembly (range = m) + | TypeAbbrev (range = m) + | None (range = m) -> m | Exception t -> t.Range [] @@ -1476,7 +1173,7 @@ type SynEnumCase = member this.Range = match this with - | SynEnumCase (range=m) -> m + | SynEnumCase (range = m) -> m [] type SynUnionCase = @@ -1492,37 +1189,28 @@ type SynUnionCase = member this.Range = match this with - | SynUnionCase (range=m) -> m + | SynUnionCase (range = m) -> m [] type SynUnionCaseKind = - | Fields of - cases: SynField list + | Fields of cases: SynField list - | FullType of - fullType: SynType * - fullTypeInfo: SynValInfo + | FullType of fullType: SynType * fullTypeInfo: SynValInfo [] type SynTypeDefnSigRepr = - | ObjectModel of - kind: SynTypeDefnKind * - memberSigs: SynMemberSig list * - range: range + | ObjectModel of kind: SynTypeDefnKind * memberSigs: SynMemberSig list * range: range - | Simple of - repr: SynTypeDefnSimpleRepr * - range: range + | Simple of repr: SynTypeDefnSimpleRepr * range: range - | Exception of - repr: SynExceptionDefnRepr + | Exception of repr: SynExceptionDefnRepr member this.Range = match this with - | ObjectModel (range=m) - | Simple (range=m) -> m + | ObjectModel (range = m) + | Simple (range = m) -> m | Exception e -> e.Range [] @@ -1538,7 +1226,7 @@ type SynTypeDefnSig = member this.Range = match this with - | SynTypeDefnSig(range=m) -> m + | SynTypeDefnSig (range = m) -> m [] type SynField = @@ -1566,7 +1254,7 @@ type SynComponentInfo = member this.Range = match this with - | SynComponentInfo (range=m) -> m + | SynComponentInfo (range = m) -> m [] type SynValSig = @@ -1584,47 +1272,40 @@ type SynValSig = range: range * trivia: SynValSigTrivia - member x.RangeOfId = let (SynValSig(ident=SynIdent(id, _))) = x in id.idRange + member x.RangeOfId = let (SynValSig(ident = SynIdent (id, _))) = x in id.idRange - member x.SynInfo = let (SynValSig(arity=v)) = x in v + member x.SynInfo = let (SynValSig (arity = v)) = x in v - member x.SynType = let (SynValSig(synType=ty)) = x in ty + member x.SynType = let (SynValSig (synType = ty)) = x in ty [] type SynValInfo = | SynValInfo of curriedArgInfos: SynArgInfo list list * returnInfo: SynArgInfo - member x.CurriedArgInfos = (let (SynValInfo(args, _)) = x in args) + member x.CurriedArgInfos = (let (SynValInfo (args, _)) = x in args) member x.ArgNames = - x.CurriedArgInfos - |> List.concat - |> List.map (fun info -> info.Ident) - |> List.choose id + x.CurriedArgInfos + |> List.concat + |> List.map (fun info -> info.Ident) + |> List.choose id |> List.map (fun id -> id.idText) [] type SynArgInfo = - | SynArgInfo of - attributes: SynAttributes * - optional: bool * - ident: Ident option + | SynArgInfo of attributes: SynAttributes * optional: bool * ident: Ident option - member x.Ident : Ident option = let (SynArgInfo(_,_,id)) = x in id + member x.Ident: Ident option = let (SynArgInfo (_, _, id)) = x in id - member x.Attributes : SynAttributes = let (SynArgInfo(attrs,_,_)) = x in attrs + member x.Attributes: SynAttributes = let (SynArgInfo (attrs, _, _)) = x in attrs [] -type SynValTyparDecls = - | SynValTyparDecls of - typars: SynTyparDecls option * - canInfer: bool +type SynValTyparDecls = SynValTyparDecls of typars: SynTyparDecls option * canInfer: bool [] -type SynReturnInfo = - | SynReturnInfo of returnType: (SynType * SynArgInfo) * range: range +type SynReturnInfo = SynReturnInfo of returnType: (SynType * SynArgInfo) * range: range [] type SynExceptionDefnRepr = @@ -1637,40 +1318,32 @@ type SynExceptionDefnRepr = accessibility: SynAccess option * range: range - member this.Range = match this with SynExceptionDefnRepr (range=m) -> m + member this.Range = + match this with + | SynExceptionDefnRepr (range = m) -> m [] type SynExceptionDefn = - | SynExceptionDefn of - exnRepr: SynExceptionDefnRepr * - withKeyword: range option * - members: SynMemberDefns * - range: range + | SynExceptionDefn of exnRepr: SynExceptionDefnRepr * withKeyword: range option * members: SynMemberDefns * range: range member this.Range = match this with - | SynExceptionDefn (range=m) -> m + | SynExceptionDefn (range = m) -> m [] type SynTypeDefnRepr = - | ObjectModel of - kind: SynTypeDefnKind * - members: SynMemberDefns * - range: range + | ObjectModel of kind: SynTypeDefnKind * members: SynMemberDefns * range: range - | Simple of - simpleRepr: SynTypeDefnSimpleRepr * - range: range + | Simple of simpleRepr: SynTypeDefnSimpleRepr * range: range - | Exception of - exnRepr: SynExceptionDefnRepr + | Exception of exnRepr: SynExceptionDefnRepr member this.Range = match this with - | ObjectModel (range=m) - | Simple (range=m) -> m + | ObjectModel (range = m) + | Simple (range = m) -> m | Exception t -> t.Range [] @@ -1685,18 +1358,20 @@ type SynTypeDefn = member this.Range = match this with - | SynTypeDefn (range=m) -> m + | SynTypeDefn (range = m) -> m [] type SynMemberDefn = - | Open of - target: SynOpenDeclTarget * - range: range + | Open of target: SynOpenDeclTarget * range: range - | Member of - memberDefn: SynBinding * - range: range + | Member of memberDefn: SynBinding * range: range + + | GetSetMember of + memberDefnForGet: SynBinding option * + memberDefnForSet: SynBinding option * + range: range * + trivia: SynMemberGetSetTrivia | ImplicitCtor of accessibility: SynAccess option * @@ -1706,42 +1381,19 @@ type SynMemberDefn = xmlDoc: PreXmlDoc * range: range - | ImplicitInherit of - inheritType: SynType * - inheritArgs: SynExpr * - inheritAlias: Ident option * - range: range + | ImplicitInherit of inheritType: SynType * inheritArgs: SynExpr * inheritAlias: Ident option * range: range - | LetBindings of - bindings: SynBinding list * - isStatic: bool * - isRecursive: bool * - range: range + | LetBindings of bindings: SynBinding list * isStatic: bool * isRecursive: bool * range: range - | AbstractSlot of - slotSig: SynValSig * - flags: SynMemberFlags * - range: range + | AbstractSlot of slotSig: SynValSig * flags: SynMemberFlags * range: range - | Interface of - interfaceType: SynType * - withKeyword: range option * - members: SynMemberDefns option * - range: range + | Interface of interfaceType: SynType * withKeyword: range option * members: SynMemberDefns option * range: range - | Inherit of - baseType: SynType * - asIdent: Ident option * - range: range + | Inherit of baseType: SynType * asIdent: Ident option * range: range - | ValField of - fieldInfo: SynField * - range: range + | ValField of fieldInfo: SynField * range: range - | NestedType of - typeDefn: SynTypeDefn * - accessibility: SynAccess option * - range: range + | NestedType of typeDefn: SynTypeDefn * accessibility: SynAccess option * range: range | AutoProperty of attributes: SynAttributes * @@ -1749,7 +1401,7 @@ type SynMemberDefn = ident: Ident * typeOpt: SynType option * propKind: SynMemberKind * - memberFlags:(SynMemberKind -> SynMemberFlags) * + memberFlags: (SynMemberKind -> SynMemberFlags) * xmlDoc: PreXmlDoc * accessibility: SynAccess option * equalsRange: range * @@ -1760,27 +1412,25 @@ type SynMemberDefn = member d.Range = match d with - | SynMemberDefn.Member (range=m) - | SynMemberDefn.Interface (range=m) - | SynMemberDefn.Open (range=m) - | SynMemberDefn.LetBindings (range=m) - | SynMemberDefn.ImplicitCtor (range=m) - | SynMemberDefn.ImplicitInherit (range=m) - | SynMemberDefn.AbstractSlot (range=m) - | SynMemberDefn.Inherit (range=m) - | SynMemberDefn.ValField (range=m) - | SynMemberDefn.AutoProperty (range=m) - | SynMemberDefn.NestedType (range=m) -> m + | SynMemberDefn.Member (range = m) + | SynMemberDefn.GetSetMember (range = m) + | SynMemberDefn.Interface (range = m) + | SynMemberDefn.Open (range = m) + | SynMemberDefn.LetBindings (range = m) + | SynMemberDefn.ImplicitCtor (range = m) + | SynMemberDefn.ImplicitInherit (range = m) + | SynMemberDefn.AbstractSlot (range = m) + | SynMemberDefn.Inherit (range = m) + | SynMemberDefn.ValField (range = m) + | SynMemberDefn.AutoProperty (range = m) + | SynMemberDefn.NestedType (range = m) -> m type SynMemberDefns = SynMemberDefn list -[] +[] type SynModuleDecl = - | ModuleAbbrev of - ident: Ident * - longId: LongIdent * - range: range + | ModuleAbbrev of ident: Ident * longId: LongIdent * range: range | NestedModule of moduleInfo: SynComponentInfo * @@ -1790,53 +1440,37 @@ type SynModuleDecl = range: range * trivia: SynModuleDeclNestedModuleTrivia - | Let of - isRecursive: bool * - bindings: SynBinding list * - range: range + | Let of isRecursive: bool * bindings: SynBinding list * range: range - | Expr of - expr: SynExpr * - range: range + | Expr of expr: SynExpr * range: range - | Types of - typeDefns: SynTypeDefn list * - range: range + | Types of typeDefns: SynTypeDefn list * range: range - | Exception of - exnDefn: SynExceptionDefn * - range: range + | Exception of exnDefn: SynExceptionDefn * range: range - | Open of - target: SynOpenDeclTarget * - range: range + | Open of target: SynOpenDeclTarget * range: range - | Attributes of - attributes: SynAttributes * - range: range + | Attributes of attributes: SynAttributes * range: range - | HashDirective of - hashDirective: ParsedHashDirective * - range: range + | HashDirective of hashDirective: ParsedHashDirective * range: range - | NamespaceFragment of - fragment: SynModuleOrNamespace + | NamespaceFragment of fragment: SynModuleOrNamespace member d.Range = match d with - | SynModuleDecl.ModuleAbbrev (range=m) - | SynModuleDecl.NestedModule (range=m) - | SynModuleDecl.Let (range=m) - | SynModuleDecl.Expr (range=m) - | SynModuleDecl.Types (range=m) - | SynModuleDecl.Exception (range=m) - | SynModuleDecl.Open (range=m) - | SynModuleDecl.HashDirective (range=m) - | SynModuleDecl.NamespaceFragment (SynModuleOrNamespace (range=m)) - | SynModuleDecl.Attributes (range=m) -> m + | SynModuleDecl.ModuleAbbrev (range = m) + | SynModuleDecl.NestedModule (range = m) + | SynModuleDecl.Let (range = m) + | SynModuleDecl.Expr (range = m) + | SynModuleDecl.Types (range = m) + | SynModuleDecl.Exception (range = m) + | SynModuleDecl.Open (range = m) + | SynModuleDecl.HashDirective (range = m) + | SynModuleDecl.NamespaceFragment (SynModuleOrNamespace (range = m)) + | SynModuleDecl.Attributes (range = m) -> m [] -type SynOpenDeclTarget = +type SynOpenDeclTarget = | ModuleOrNamespace of longId: LongIdent * range: range @@ -1844,24 +1478,17 @@ type SynOpenDeclTarget = member this.Range = match this with - | ModuleOrNamespace (range=m) -> m - | Type (range=m) -> m + | ModuleOrNamespace (range = m) -> m + | Type (range = m) -> m [] type SynExceptionSig = - | SynExceptionSig of - exnRepr: SynExceptionDefnRepr * - withKeyword: range option * - members: SynMemberSig list * - range: range + | SynExceptionSig of exnRepr: SynExceptionDefnRepr * withKeyword: range option * members: SynMemberSig list * range: range [] type SynModuleSigDecl = - | ModuleAbbrev of - ident: Ident * - longId: LongIdent * - range: range + | ModuleAbbrev of ident: Ident * longId: LongIdent * range: range | NestedModule of moduleInfo: SynComponentInfo * @@ -1870,38 +1497,28 @@ type SynModuleSigDecl = range: range * trivia: SynModuleSigDeclNestedModuleTrivia - | Val of - valSig: SynValSig * range: range + | Val of valSig: SynValSig * range: range - | Types of - types: SynTypeDefnSig list * - range: range + | Types of types: SynTypeDefnSig list * range: range - | Exception of - exnSig: SynExceptionSig * - range: range + | Exception of exnSig: SynExceptionSig * range: range - | Open of - target: SynOpenDeclTarget * - range: range + | Open of target: SynOpenDeclTarget * range: range - | HashDirective of - hashDirective: ParsedHashDirective * - range: range + | HashDirective of hashDirective: ParsedHashDirective * range: range - | NamespaceFragment of - SynModuleOrNamespaceSig + | NamespaceFragment of SynModuleOrNamespaceSig member d.Range = match d with - | SynModuleSigDecl.ModuleAbbrev (range=m) - | SynModuleSigDecl.NestedModule (range=m) - | SynModuleSigDecl.Val (range=m) - | SynModuleSigDecl.Types (range=m) - | SynModuleSigDecl.Exception (range=m) - | SynModuleSigDecl.Open (range=m) - | SynModuleSigDecl.NamespaceFragment (SynModuleOrNamespaceSig.SynModuleOrNamespaceSig(range=m)) - | SynModuleSigDecl.HashDirective (range=m) -> m + | SynModuleSigDecl.ModuleAbbrev (range = m) + | SynModuleSigDecl.NestedModule (range = m) + | SynModuleSigDecl.Val (range = m) + | SynModuleSigDecl.Types (range = m) + | SynModuleSigDecl.Exception (range = m) + | SynModuleSigDecl.Open (range = m) + | SynModuleSigDecl.NamespaceFragment (SynModuleOrNamespaceSig.SynModuleOrNamespaceSig (range = m)) + | SynModuleSigDecl.HashDirective (range = m) -> m [] type SynModuleOrNamespaceKind = @@ -1915,7 +1532,8 @@ type SynModuleOrNamespaceKind = member x.IsModule = match x with - | NamedModule | AnonModule -> true + | NamedModule + | AnonModule -> true | _ -> false [] @@ -1933,7 +1551,7 @@ type SynModuleOrNamespace = member this.Range = match this with - | SynModuleOrNamespace (range=m) -> m + | SynModuleOrNamespace (range = m) -> m [] type SynModuleOrNamespaceSig = @@ -1950,34 +1568,27 @@ type SynModuleOrNamespaceSig = member this.Range = match this with - | SynModuleOrNamespaceSig (range=m) -> m + | SynModuleOrNamespaceSig (range = m) -> m [] type ParsedHashDirectiveArgument = - | String of value: string * stringKind: SynStringKind * range: range - | SourceIdentifier of constant: string * value: string * range: range + | String of value: string * stringKind: SynStringKind * range: range + | SourceIdentifier of constant: string * value: string * range: range - member this.Range = - match this with - | ParsedHashDirectiveArgument.String (range=m) - | ParsedHashDirectiveArgument.SourceIdentifier (range=m) -> m + member this.Range = + match this with + | ParsedHashDirectiveArgument.String (range = m) + | ParsedHashDirectiveArgument.SourceIdentifier (range = m) -> m [] -type ParsedHashDirective = - | ParsedHashDirective of - ident: string * - args: ParsedHashDirectiveArgument list * - range: range +type ParsedHashDirective = ParsedHashDirective of ident: string * args: ParsedHashDirectiveArgument list * range: range [] type ParsedImplFileFragment = - | AnonModule of - decls: SynModuleDecl list * - range: range + | AnonModule of decls: SynModuleDecl list * range: range - | NamedModule of - namedModule: SynModuleOrNamespace + | NamedModule of namedModule: SynModuleOrNamespace | NamespaceFragment of longId: LongIdent * @@ -1992,12 +1603,9 @@ type ParsedImplFileFragment = [] type ParsedSigFileFragment = - | AnonModule of - decls: SynModuleSigDecl list * - range: range + | AnonModule of decls: SynModuleSigDecl list * range: range - | NamedModule of - namedModule: SynModuleOrNamespaceSig + | NamedModule of namedModule: SynModuleOrNamespaceSig | NamespaceFragment of longId: LongIdent * @@ -2011,29 +1619,18 @@ type ParsedSigFileFragment = [] type ParsedScriptInteraction = - | Definitions of - defns: SynModuleDecl list * - range: range + | Definitions of defns: SynModuleDecl list * range: range - | HashDirective of - hashDirective: ParsedHashDirective * - range: range + | HashDirective of hashDirective: ParsedHashDirective * range: range [] -type ParsedImplFile = - | ParsedImplFile of - hashDirectives: ParsedHashDirective list * - fragments: ParsedImplFileFragment list +type ParsedImplFile = ParsedImplFile of hashDirectives: ParsedHashDirective list * fragments: ParsedImplFileFragment list [] -type ParsedSigFile = - | ParsedSigFile of - hashDirectives: ParsedHashDirective list * - fragments: ParsedSigFileFragment list +type ParsedSigFile = ParsedSigFile of hashDirectives: ParsedHashDirective list * fragments: ParsedSigFileFragment list [] -type ScopedPragma = - | WarningOff of range: range * warningNumber: int +type ScopedPragma = WarningOff of range: range * warningNumber: int [] type QualifiedNameOfFile = @@ -2075,12 +1672,12 @@ type ParsedInput = member inp.FileName = match inp with - | ParsedInput.ImplFile (ParsedImplFileInput (fileName=fileName)) - | ParsedInput.SigFile (ParsedSigFileInput (fileName=fileName)) -> fileName + | ParsedInput.ImplFile (ParsedImplFileInput (fileName = fileName)) + | ParsedInput.SigFile (ParsedSigFileInput (fileName = fileName)) -> fileName member inp.Range = match inp with - | ParsedInput.ImplFile (ParsedImplFileInput (modules=SynModuleOrNamespace(range=m) :: _)) - | ParsedInput.SigFile (ParsedSigFileInput (modules=SynModuleOrNamespaceSig(range=m) :: _)) -> m - | ParsedInput.ImplFile (ParsedImplFileInput (fileName=fileName)) - | ParsedInput.SigFile (ParsedSigFileInput (fileName=fileName)) -> rangeN fileName 0 + | ParsedInput.ImplFile (ParsedImplFileInput(modules = SynModuleOrNamespace (range = m) :: _)) + | ParsedInput.SigFile (ParsedSigFileInput(modules = SynModuleOrNamespaceSig (range = m) :: _)) -> m + | ParsedInput.ImplFile (ParsedImplFileInput (fileName = fileName)) + | ParsedInput.SigFile (ParsedSigFileInput (fileName = fileName)) -> rangeN fileName 0 diff --git a/src/Compiler/SyntaxTree/SyntaxTree.fsi b/src/Compiler/SyntaxTree/SyntaxTree.fsi index 9f18a1488d1..357823b658e 100644 --- a/src/Compiler/SyntaxTree/SyntaxTree.fsi +++ b/src/Compiler/SyntaxTree/SyntaxTree.fsi @@ -224,13 +224,15 @@ type SynRationalConst = [] type SynAccess = /// A construct marked or assumed 'public' - | Public + | Public of range: range /// A construct marked or assumed 'internal' - | Internal + | Internal of range: range /// A construct marked or assumed 'private' - | Private + | Private of range: range + + member Range: range /// Represents whether a debug point should be present for the target /// of a decision tree, that is whether the construct corresponds to a debug @@ -469,7 +471,7 @@ type SynType = | Array of rank: int * elementType: SynType * range: range /// F# syntax: type -> type - | Fun of argType: SynType * returnType: SynType * range: range + | Fun of argType: SynType * returnType: SynType * range: range * trivia: SynTypeFunTrivia /// F# syntax: 'Var | Var of typar: SynTypar * range: range @@ -563,7 +565,7 @@ type SynExpr = argOptions: (SynExpr * Ident option) option * withKeyword: range option * bindings: SynBinding list * - members: SynMemberDefn list * + members: SynMemberDefns * extraImpls: SynInterfaceImpl list * newExprRange: range * range: range @@ -1039,7 +1041,6 @@ type SynPat = /// A long identifier pattern possibly with argument patterns | LongIdent of longDotId: SynLongIdent * - propertyKeyword: PropertyKeyword option * extraId: Ident option * // holds additional ident for tooling typarDecls: SynValTyparDecls option * // usually None: temporary used to parse "f<'a> x = x" argPats: SynArgPats * @@ -1087,12 +1088,6 @@ type SynPat = /// Gets the syntax range of this construct member Range: range -/// Represents a used keyword for a property member -[] -type PropertyKeyword = - | With of range - | And of range - /// Represents a set of bindings that implement an interface [] type SynInterfaceImpl = @@ -1100,7 +1095,7 @@ type SynInterfaceImpl = interfaceTy: SynType * withKeyword: range option * bindings: SynBinding list * - members: SynMemberDefn list * + members: SynMemberDefns * range: range /// Represents a clause in a 'match' expression @@ -1554,6 +1549,13 @@ type SynMemberDefn = /// A 'member' definition within a type | Member of memberDefn: SynBinding * range: range + /// A 'member' definition with get/set accessors within a type + | GetSetMember of + memberDefnForGet: SynBinding option * + memberDefnForSet: SynBinding option * + range: range * + trivia: SynMemberGetSetTrivia + /// An implicit constructor definition | ImplicitCtor of accessibility: SynAccess option * diff --git a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs index 98fe80ac938..1834bb0fbf7 100644 --- a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs +++ b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs @@ -16,7 +16,10 @@ type SynArgNameGenerator() = let mutable count = 0 let generatedArgNamePrefix = "_arg" - member _.New() : string = count <- count + 1; generatedArgNamePrefix + string count + member _.New() : string = + count <- count + 1 + generatedArgNamePrefix + string count + member _.Reset() = count <- 0 let ident (s, r) = Ident(s, r) @@ -34,76 +37,84 @@ let textOfLid lid = textOfPath (pathOfLid lid) let rangeOfLid (lid: Ident list) = match lid with | [] -> failwith "rangeOfLid" - | [id] -> id.idRange + | [ id ] -> id.idRange | h :: t -> unionRanges h.idRange (List.last t).idRange let mkSynId m s = Ident(s, m) let pathToSynLid m p = List.map (mkSynId m) p -let mkSynIdGet m n = SynExpr.Ident (mkSynId m n) +let mkSynIdGet m n = SynExpr.Ident(mkSynId m n) let mkSynLidGet m path n = - let lid = pathToSynLid m path @ [mkSynId m n] + let lid = pathToSynLid m path @ [ mkSynId m n ] let dots = List.replicate (lid.Length - 1) m let trivia: IdentTrivia option list = List.replicate lid.Length None - SynExpr.LongIdent (false, SynLongIdent(lid, dots, trivia), None, m) + SynExpr.LongIdent(false, SynLongIdent(lid, dots, trivia), None, m) let mkSynIdGetWithAlt m id altInfo = match altInfo with | None -> SynExpr.Ident id - | _ -> SynExpr.LongIdent (false, SynLongIdent([id], [], [None]), altInfo, m) + | _ -> SynExpr.LongIdent(false, SynLongIdent([ id ], [], [ None ]), altInfo, m) -let mkSynSimplePatVar isOpt id = SynSimplePat.Id (id, None, false, false, isOpt, id.idRange) +let mkSynSimplePatVar isOpt id = + SynSimplePat.Id(id, None, false, false, isOpt, id.idRange) -let mkSynCompGenSimplePatVar id = SynSimplePat.Id (id, None, true, false, false, id.idRange) +let mkSynCompGenSimplePatVar id = + SynSimplePat.Id(id, None, true, false, false, id.idRange) + +let (|SynSingleIdent|_|) x = + match x with + | SynLongIdent ([ id ], _, _) -> Some id + | _ -> None /// Match a long identifier, including the case for single identifiers which gets a more optimized node in the syntax tree. let (|LongOrSingleIdent|_|) inp = match inp with - | SynExpr.LongIdent (isOpt, lidwd, altId, _m) -> Some (isOpt, lidwd, altId, lidwd.RangeWithoutAnyExtraDot) - | SynExpr.Ident id -> Some (false, SynLongIdent([id], [], [None]), None, id.idRange) + | SynExpr.LongIdent (isOpt, lidwd, altId, _m) -> Some(isOpt, lidwd, altId, lidwd.RangeWithoutAnyExtraDot) + | SynExpr.Ident id -> Some(false, SynLongIdent([ id ], [], [ None ]), None, id.idRange) | _ -> None let (|SingleIdent|_|) inp = match inp with - | SynExpr.LongIdent (false, SynLongIdent([id], _, _), None, _) -> Some id + | SynExpr.LongIdent (false, SynSingleIdent (id), None, _) -> Some id | SynExpr.Ident id -> Some id | _ -> None let (|SynBinOp|_|) input = match input with - | SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent (longDotId = SynLongIdent(id = [synId])), x1, _m1), x2, _m2) -> - Some (synId, x1, x2) + | SynExpr.App (ExprAtomicFlag.NonAtomic, + false, + SynExpr.App (ExprAtomicFlag.NonAtomic, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ synId ])), x1, _m1), + x2, + _m2) -> Some(synId, x1, x2) | _ -> None let (|SynPipeRight|_|) input = match input with - | SynBinOp (synId, x1, x2) when synId.idText = "op_PipeRight" -> Some (x1, x2) + | SynBinOp (synId, x1, x2) when synId.idText = "op_PipeRight" -> Some(x1, x2) | _ -> None let (|SynPipeRight2|_|) input = match input with - | SynBinOp (synId, SynExpr.Paren(SynExpr.Tuple(false, [x1a; x1b], _, _), _, _, _), x2) - when synId.idText = "op_PipeRight2" -> - Some (x1a, x1b, x2) + | SynBinOp (synId, SynExpr.Paren (SynExpr.Tuple (false, [ x1a; x1b ], _, _), _, _, _), x2) when synId.idText = "op_PipeRight2" -> + Some(x1a, x1b, x2) | _ -> None let (|SynPipeRight3|_|) input = match input with - | SynBinOp (synId, SynExpr.Paren(SynExpr.Tuple(false, [x1a; x1b; x1c], _, _), _, _, _), x2) - when synId.idText = "op_PipeRight3" -> - Some (x1a, x1b, x1c, x2) + | SynBinOp (synId, SynExpr.Paren (SynExpr.Tuple (false, [ x1a; x1b; x1c ], _, _), _, _, _), x2) when synId.idText = "op_PipeRight3" -> + Some(x1a, x1b, x1c, x2) | _ -> None let (|SynAndAlso|_|) input = match input with - | SynBinOp (synId, x1, x2) when synId.idText = "op_BooleanAnd" -> Some (x1, x2) + | SynBinOp (synId, x1, x2) when synId.idText = "op_BooleanAnd" -> Some(x1, x2) | _ -> None let (|SynOrElse|_|) input = match input with - | SynBinOp (synId, x1, x2) when synId.idText = "op_BooleanOr" -> Some (x1, x2) + | SynBinOp (synId, x1, x2) when synId.idText = "op_BooleanOr" -> Some(x1, x2) | _ -> None /// This affects placement of debug points @@ -147,37 +158,44 @@ let rec IsControlFlowExpression e = // However these do not have side-effect and do not get a debug point recognised by ValidateBreakpointLocation. let IsDebugPointBinding synPat synExpr = - not (IsControlFlowExpression synExpr) && - // Don't yield the binding sequence point if there are any arguments, i.e. we're defining a function or a method - let isFunction = - match synPat with - | SynPat.LongIdent (argPats=SynArgPats.Pats args; typarDecls=typarDecls) when not args.IsEmpty || typarDecls.IsSome -> true - | _ -> false - not isFunction + not (IsControlFlowExpression synExpr) + && let isFunction = + match synPat with + | SynPat.LongIdent (argPats = SynArgPats.Pats args; typarDecls = typarDecls) when not args.IsEmpty || typarDecls.IsSome -> true + | _ -> false in + not isFunction let inline unionRangeWithXmlDoc (xmlDoc: PreXmlDoc) range = - if xmlDoc.IsEmpty then range else unionRanges xmlDoc.Range range + if xmlDoc.IsEmpty then + range + else + unionRanges xmlDoc.Range range -let mkSynAnonField (ty: SynType, xmlDoc) = SynField([], false, None, ty, false, xmlDoc, None, unionRangeWithXmlDoc xmlDoc ty.Range) +let mkSynAnonField (ty: SynType, xmlDoc) = + SynField([], false, None, ty, false, xmlDoc, None, unionRangeWithXmlDoc xmlDoc ty.Range) -let mkSynNamedField (ident, ty: SynType, xmlDoc, m) = SynField([], false, Some ident, ty, false, xmlDoc, None, m) +let mkSynNamedField (ident, ty: SynType, xmlDoc, m) = + SynField([], false, Some ident, ty, false, xmlDoc, None, m) -let mkSynPatVar vis (id: Ident) = SynPat.Named (SynIdent(id, None), false, vis, id.idRange) +let mkSynPatVar vis (id: Ident) = + SynPat.Named(SynIdent(id, None), false, vis, id.idRange) -let mkSynThisPatVar (id: Ident) = SynPat.Named (SynIdent(id, None), true, None, id.idRange) +let mkSynThisPatVar (id: Ident) = + SynPat.Named(SynIdent(id, None), true, None, id.idRange) -let mkSynPatMaybeVar lidwd vis m = SynPat.LongIdent (lidwd, None, None, None, SynArgPats.Pats [], vis, m) +let mkSynPatMaybeVar lidwd vis m = + SynPat.LongIdent(lidwd, None, None, SynArgPats.Pats [], vis, m) /// Extract the argument for patterns corresponding to the declaration of 'new ... = ...' let (|SynPatForConstructorDecl|_|) x = match x with - | SynPat.LongIdent (longDotId=SynLongIdent([_], _, _); argPats=SynArgPats.Pats [arg]) -> Some arg + | SynPat.LongIdent (longDotId = SynSingleIdent _; argPats = SynArgPats.Pats [ arg ]) -> Some arg | _ -> None /// Recognize the '()' in 'new()' let (|SynPatForNullaryArgs|_|) x = match x with - | SynPat.Paren(SynPat.Const(SynConst.Unit, _), _) -> Some() + | SynPat.Paren (SynPat.Const (SynConst.Unit, _), _) -> Some() | _ -> None let (|SynExprErrorSkip|) (p: SynExpr) = @@ -187,35 +205,29 @@ let (|SynExprErrorSkip|) (p: SynExpr) = let (|SynExprParen|_|) (e: SynExpr) = match e with - | SynExpr.Paren (SynExprErrorSkip e, a, b, c) -> Some (e, a, b, c) + | SynExpr.Paren (SynExprErrorSkip e, a, b, c) -> Some(e, a, b, c) | _ -> None let (|SynPatErrorSkip|) (p: SynPat) = match p with - | SynPat.FromParseError(p, _) -> p + | SynPat.FromParseError (p, _) -> p | _ -> p /// Push non-simple parts of a patten match over onto the r.h.s. of a lambda. /// Return a simple pattern and a function to build a match on the r.h.s. if the pattern is complex let rec SimplePatOfPat (synArgNameGenerator: SynArgNameGenerator) p = match p with - | SynPat.Typed(p', ty, m) -> + | SynPat.Typed (p', ty, m) -> let p2, laterF = SimplePatOfPat synArgNameGenerator p' - SynSimplePat.Typed(p2, ty, m), - laterF + SynSimplePat.Typed(p2, ty, m), laterF - | SynPat.Attrib(p', attribs, m) -> + | SynPat.Attrib (p', attribs, m) -> let p2, laterF = SimplePatOfPat synArgNameGenerator p' - SynSimplePat.Attrib(p2, attribs, m), - laterF + SynSimplePat.Attrib(p2, attribs, m), laterF - | SynPat.Named (SynIdent(v,_), thisV, _, m) -> - SynSimplePat.Id (v, None, false, thisV, false, m), - None + | SynPat.Named (SynIdent (v, _), thisV, _, m) -> SynSimplePat.Id(v, None, false, thisV, false, m), None - | SynPat.OptionalVal (v, m) -> - SynSimplePat.Id (v, None, false, false, true, m), - None + | SynPat.OptionalVal (v, m) -> SynSimplePat.Id(v, None, false, false, true, m), None | SynPat.Paren (p, _) -> SimplePatOfPat synArgNameGenerator p @@ -223,18 +235,21 @@ let rec SimplePatOfPat (synArgNameGenerator: SynArgNameGenerator) p = | _ -> let m = p.Range + let isCompGen, altNameRefCell, id, item = match p with - | SynPat.LongIdent(longDotId=SynLongIdent([id], _, _); typarDecls=None; argPats=SynArgPats.Pats []; accessibility=None) -> + | SynPat.LongIdent (longDotId = SynSingleIdent (id); typarDecls = None; argPats = SynArgPats.Pats []; accessibility = None) -> // The pattern is 'V' or some other capitalized identifier. // It may be a real variable, in which case we want to maintain its name. // But it may also be a nullary union case or some other identifier. // In this case, we want to use an alternate compiler generated name for the hidden variable. - let altNameRefCell = Some (ref (SynSimplePatAlternativeIdInfo.Undecided (mkSynId m (synArgNameGenerator.New())))) + let altNameRefCell = + Some(ref (SynSimplePatAlternativeIdInfo.Undecided(mkSynId m (synArgNameGenerator.New())))) + let item = mkSynIdGetWithAlt m id altNameRefCell false, altNameRefCell, id, item - | SynPat.Named(SynIdent(ident,_), _, _, _) - | SynPat.As(_, SynPat.Named(SynIdent(ident,_), _, _, _), _) -> + | SynPat.Named (SynIdent (ident, _), _, _, _) + | SynPat.As (_, SynPat.Named (SynIdent (ident, _), _, _, _), _) -> // named pats should be referred to as their name in docs, tooltips, etc. let item = mkSynIdGet m ident.idText false, None, ident, item @@ -243,58 +258,67 @@ let rec SimplePatOfPat (synArgNameGenerator: SynArgNameGenerator) p = let id = mkSynId m nm let item = mkSynIdGet m nm true, None, id, item + let fn = match p with | SynPat.Wild _ -> None | _ -> - Some (fun e -> - let clause = SynMatchClause(p, None, e, m, DebugPointAtTarget.No, SynMatchClauseTrivia.Zero) + Some(fun e -> + let clause = + SynMatchClause(p, None, e, m, DebugPointAtTarget.No, SynMatchClauseTrivia.Zero) + let artificialMatchRange = (unionRanges m e.Range).MakeSynthetic() - SynExpr.Match (DebugPointAtBinding.NoneAtInvisible, item, [clause], artificialMatchRange, { MatchKeyword = artificialMatchRange - WithKeyword = artificialMatchRange })) - SynSimplePat.Id (id, altNameRefCell, isCompGen, false, false, id.idRange), fn + let trivia = + { + MatchKeyword = artificialMatchRange + WithKeyword = artificialMatchRange + } -let appFunOpt funOpt x = match funOpt with None -> x | Some f -> f x + SynExpr.Match(DebugPointAtBinding.NoneAtInvisible, item, [ clause ], artificialMatchRange, trivia)) -let composeFunOpt funOpt1 funOpt2 = match funOpt2 with None -> funOpt1 | Some f -> Some (fun x -> appFunOpt funOpt1 (f x)) + SynSimplePat.Id(id, altNameRefCell, isCompGen, false, false, id.idRange), fn + +let appFunOpt funOpt x = + match funOpt with + | None -> x + | Some f -> f x + +let composeFunOpt funOpt1 funOpt2 = + match funOpt2 with + | None -> funOpt1 + | Some f -> Some(fun x -> appFunOpt funOpt1 (f x)) let rec SimplePatsOfPat synArgNameGenerator p = match p with | SynPat.FromParseError (p, _) -> SimplePatsOfPat synArgNameGenerator p - | SynPat.Typed(p', ty, m) -> + | SynPat.Typed (p', ty, m) -> let p2, laterF = SimplePatsOfPat synArgNameGenerator p' - SynSimplePats.Typed(p2, ty, m), - laterF + SynSimplePats.Typed(p2, ty, m), laterF | SynPat.Tuple (false, ps, m) - | SynPat.Paren(SynPat.Tuple (false, ps, _), m) -> + | SynPat.Paren (SynPat.Tuple (false, ps, _), m) -> + let sps = List.map (SimplePatOfPat synArgNameGenerator) ps + let ps2, laterF = - List.foldBack - (fun (p', rhsf) (ps', rhsf') -> - p':: ps', - (composeFunOpt rhsf rhsf')) - (List.map (SimplePatOfPat synArgNameGenerator) ps) - ([], None) - SynSimplePats.SimplePats (ps2, m), - laterF + List.foldBack (fun (p', rhsf) (ps', rhsf') -> p' :: ps', (composeFunOpt rhsf rhsf')) sps ([], None) + + SynSimplePats.SimplePats(ps2, m), laterF - | SynPat.Paren(SynPat.Const (SynConst.Unit, m), _) + | SynPat.Paren (SynPat.Const (SynConst.Unit, m), _) - | SynPat.Const (SynConst.Unit, m) -> - SynSimplePats.SimplePats ([], m), - None + | SynPat.Const (SynConst.Unit, m) -> SynSimplePats.SimplePats([], m), None | _ -> let m = p.Range let sp, laterF = SimplePatOfPat synArgNameGenerator p - SynSimplePats.SimplePats ([sp], m), laterF + SynSimplePats.SimplePats([ sp ], m), laterF let PushPatternToExpr synArgNameGenerator isMember pat (rhs: SynExpr) = let nowPats, laterF = SimplePatsOfPat synArgNameGenerator pat - nowPats, SynExpr.Lambda (isMember, false, nowPats, appFunOpt laterF rhs, None, rhs.Range, SynExprLambdaTrivia.Zero) + nowPats, SynExpr.Lambda(isMember, false, nowPats, appFunOpt laterF rhs, None, rhs.Range, SynExprLambdaTrivia.Zero) let private isSimplePattern pat = let _nowPats, laterF = SimplePatsOfPat (SynArgNameGenerator()) pat @@ -311,66 +335,72 @@ let PushCurriedPatternsToExpr synArgNameGenerator wholem isMember pats arrow rhs // First phase: Fold back, from right to left, pushing patterns into r.h.s. expr let spatsl, rhs = (pats, ([], rhs)) - ||> List.foldBack (fun arg (spatsl, body) -> - let spats, bodyf = SimplePatsOfPat synArgNameGenerator arg - // accumulate the body. This builds "let (UnionCase y) = tmp2 in body" - let body = appFunOpt bodyf body - // accumulate the patterns - let spatsl = spats :: spatsl - (spatsl, body)) + ||> List.foldBack (fun arg (spatsl, body) -> + let spats, bodyf = SimplePatsOfPat synArgNameGenerator arg + // accumulate the body. This builds "let (UnionCase y) = tmp2 in body" + let body = appFunOpt bodyf body + // accumulate the patterns + let spatsl = spats :: spatsl + (spatsl, body)) // Second phase: build lambdas. Mark subsequent ones with "true" indicating they are part of an iterated sequence of lambdas let expr = match spatsl with | [] -> rhs | h :: t -> - let expr = List.foldBack (fun spats e -> SynExpr.Lambda (isMember, true, spats, e, None, wholem, { ArrowRange = arrow })) t rhs - let expr = SynExpr.Lambda (isMember, false, h, expr, Some (pats, rhs), wholem, { ArrowRange = arrow }) + let expr = + List.foldBack (fun spats e -> SynExpr.Lambda(isMember, true, spats, e, None, wholem, { ArrowRange = arrow })) t rhs + + let expr = + SynExpr.Lambda(isMember, false, h, expr, Some(pats, rhs), wholem, { ArrowRange = arrow }) + expr + spatsl, expr -let opNameParenGet = CompileOpName parenGet +let opNameParenGet = CompileOpName parenGet let opNameQMark = CompileOpName qmark -let mkSynOperator (opm:range) (oper:string) = +let mkSynOperator (opm: range) (oper: string) = let trivia = if oper.StartsWith("~") && ((opm.EndColumn - opm.StartColumn) = (oper.Length - 1)) then // PREFIX_OP token where the ~ was actually absent - IdentTrivia.OriginalNotation (string(oper.[1..])) + IdentTrivia.OriginalNotation(string (oper.[1..])) else IdentTrivia.OriginalNotation oper - - SynExpr.LongIdent(false, SynLongIdent([ident(CompileOpName oper, opm)], [], [Some trivia]), None, opm) + + SynExpr.LongIdent(false, SynLongIdent([ ident (CompileOpName oper, opm) ], [], [ Some trivia ]), None, opm) let mkSynInfix opm (l: SynExpr) oper (r: SynExpr) = let firstTwoRange = unionRanges l.Range opm - let wholeRange = unionRanges l.Range r.Range - let app1 = SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator opm oper, l, firstTwoRange) - SynExpr.App (ExprAtomicFlag.NonAtomic, false, app1, r, wholeRange) + let mWhole = unionRanges l.Range r.Range + + let app1 = + SynExpr.App(ExprAtomicFlag.NonAtomic, true, mkSynOperator opm oper, l, firstTwoRange) + + SynExpr.App(ExprAtomicFlag.NonAtomic, false, app1, r, mWhole) let mkSynBifix m oper x1 x2 = - let app1 = SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m) - SynExpr.App (ExprAtomicFlag.NonAtomic, false, app1, x2, m) + let app1 = SynExpr.App(ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m) + SynExpr.App(ExprAtomicFlag.NonAtomic, false, app1, x2, m) -let mkSynTrifix m oper x1 x2 x3 = - let app1 = SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m) - let app2 = SynExpr.App (ExprAtomicFlag.NonAtomic, false, app1, x2, m) - SynExpr.App (ExprAtomicFlag.NonAtomic, false, app2, x3, m) +let mkSynTrifix m oper x1 x2 x3 = + let app1 = SynExpr.App(ExprAtomicFlag.NonAtomic, true, mkSynOperator m oper, x1, m) + let app2 = SynExpr.App(ExprAtomicFlag.NonAtomic, false, app1, x2, m) + SynExpr.App(ExprAtomicFlag.NonAtomic, false, app2, x3, m) let mkSynPrefixPrim opm m oper x = - SynExpr.App (ExprAtomicFlag.NonAtomic, false, mkSynOperator opm oper, x, m) + SynExpr.App(ExprAtomicFlag.NonAtomic, false, mkSynOperator opm oper, x, m) let mkSynPrefix opm m oper x = - if oper = "~&" then - SynExpr.AddressOf (true, x, opm, m) - elif oper = "~&&" then - SynExpr.AddressOf (false, x, opm, m) - else - mkSynPrefixPrim opm m oper x + if oper = "~&" then SynExpr.AddressOf(true, x, opm, m) + elif oper = "~&&" then SynExpr.AddressOf(false, x, opm, m) + else mkSynPrefixPrim opm m oper x -let mkSynCaseName m n = [mkSynId m (CompileOpName n)] +let mkSynCaseName m n = [ mkSynId m (CompileOpName n) ] -let mkSynApp1 f x1 m = SynExpr.App (ExprAtomicFlag.NonAtomic, false, f, x1, m) +let mkSynApp1 f x1 m = + SynExpr.App(ExprAtomicFlag.NonAtomic, false, f, x1, m) let mkSynApp2 f x1 x2 m = mkSynApp1 (mkSynApp1 f x1 m) x2 m @@ -378,106 +408,98 @@ let mkSynApp3 f x1 x2 x3 m = mkSynApp1 (mkSynApp2 f x1 x2 m) x3 m let mkSynApp4 f x1 x2 x3 x4 m = mkSynApp1 (mkSynApp3 f x1 x2 x3 m) x4 m -let mkSynApp5 f x1 x2 x3 x4 x5 m = mkSynApp1 (mkSynApp4 f x1 x2 x3 x4 m) x5 m +let mkSynApp5 f x1 x2 x3 x4 x5 m = + mkSynApp1 (mkSynApp4 f x1 x2 x3 x4 m) x5 m -let mkSynDotParenSet m a b c = mkSynTrifix m parenSet a b c +let mkSynDotParenSet m a b c = mkSynTrifix m parenSet a b c -let mkSynDotBrackGet m mDot a b = SynExpr.DotIndexedGet (a, b, mDot, m) +let mkSynDotBrackGet m mDot a b = SynExpr.DotIndexedGet(a, b, mDot, m) let mkSynQMarkSet m a b c = mkSynTrifix m qmarkSet a b c -let mkSynDotParenGet lhsm dotm a b = +let mkSynDotParenGet mLhs mDot a b = match b with - | SynExpr.Tuple (false, [_;_], _, _) -> - errorR(Deprecated(FSComp.SR.astDeprecatedIndexerNotation(), lhsm)) - SynExpr.Const (SynConst.Unit, lhsm) + | SynExpr.Tuple (false, [ _; _ ], _, _) -> + errorR (Deprecated(FSComp.SR.astDeprecatedIndexerNotation (), mLhs)) + SynExpr.Const(SynConst.Unit, mLhs) - | SynExpr.Tuple (false, [_;_;_], _, _) -> - errorR(Deprecated(FSComp.SR.astDeprecatedIndexerNotation(), lhsm)) - SynExpr.Const (SynConst.Unit, lhsm) + | SynExpr.Tuple (false, [ _; _; _ ], _, _) -> + errorR (Deprecated(FSComp.SR.astDeprecatedIndexerNotation (), mLhs)) + SynExpr.Const(SynConst.Unit, mLhs) - | _ -> mkSynInfix dotm a parenGet b + | _ -> mkSynInfix mDot a parenGet b -let mkSynUnit m = SynExpr.Const (SynConst.Unit, m) +let mkSynUnit m = SynExpr.Const(SynConst.Unit, m) let mkSynUnitPat m = SynPat.Const(SynConst.Unit, m) let mkSynDelay m e = - SynExpr.Lambda (false, false, SynSimplePats.SimplePats ([mkSynCompGenSimplePatVar (mkSynId m "unitVar")], m), e, None, m, SynExprLambdaTrivia.Zero) + let svar = mkSynCompGenSimplePatVar (mkSynId m "unitVar") + SynExpr.Lambda(false, false, SynSimplePats.SimplePats([ svar ], m), e, None, m, SynExprLambdaTrivia.Zero) let mkSynAssign (l: SynExpr) (r: SynExpr) = let m = unionRanges l.Range r.Range + match l with //| SynExpr.Paren (l2, m2) -> mkSynAssign m l2 r - | LongOrSingleIdent(false, v, None, _) -> SynExpr.LongIdentSet (v, r, m) - | SynExpr.DotGet (e, _, v, _) -> SynExpr.DotSet (e, v, r, m) - | SynExpr.DotIndexedGet (e1, e2, mDot, mLeft) -> SynExpr.DotIndexedSet (e1, e2, r, mLeft, mDot, m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (x, y, z, _) -> SynExpr.LibraryOnlyUnionCaseFieldSet (x, y, z, r, m) - | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent nm, a, _), b, _) when nm.idText = opNameQMark -> - mkSynQMarkSet m a b r - | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent nm, a, _), b, _) when nm.idText = opNameParenGet -> - mkSynDotParenSet m a b r - | SynExpr.App (_, _, SynExpr.LongIdent (false, v, None, _), x, _) -> SynExpr.NamedIndexedPropertySet (v, x, r, m) - | SynExpr.App (_, _, SynExpr.DotGet (e, _, v, _), x, _) -> SynExpr.DotNamedIndexedPropertySet (e, v, x, r, m) - | l -> SynExpr.Set (l, r, m) - -let mkSynDot dotm m l (SynIdent(r, rTrivia)) = + | LongOrSingleIdent (false, v, None, _) -> SynExpr.LongIdentSet(v, r, m) + | SynExpr.DotGet (e, _, v, _) -> SynExpr.DotSet(e, v, r, m) + | SynExpr.DotIndexedGet (e1, e2, mDot, mLeft) -> SynExpr.DotIndexedSet(e1, e2, r, mLeft, mDot, m) + | SynExpr.LibraryOnlyUnionCaseFieldGet (x, y, z, _) -> SynExpr.LibraryOnlyUnionCaseFieldSet(x, y, z, r, m) + | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent nm, a, _), b, _) when nm.idText = opNameQMark -> mkSynQMarkSet m a b r + | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent nm, a, _), b, _) when nm.idText = opNameParenGet -> mkSynDotParenSet m a b r + | SynExpr.App (_, _, SynExpr.LongIdent (false, v, None, _), x, _) -> SynExpr.NamedIndexedPropertySet(v, x, r, m) + | SynExpr.App (_, _, SynExpr.DotGet (e, _, v, _), x, _) -> SynExpr.DotNamedIndexedPropertySet(e, v, x, r, m) + | l -> SynExpr.Set(l, r, m) + +let mkSynDot mDot m l (SynIdent (r, rTrivia)) = match l with - | SynExpr.LongIdent (isOpt, SynLongIdent(lid, dots, trivia), None, _) -> + | SynExpr.LongIdent (isOpt, SynLongIdent (lid, dots, trivia), None, _) -> // REVIEW: MEMORY PERFORMANCE: This list operation is memory intensive (we create a lot of these list nodes) - SynExpr.LongIdent (isOpt, SynLongIdent(lid@[r], dots@[dotm], trivia@[rTrivia]), None, m) - | SynExpr.Ident id -> - SynExpr.LongIdent (false, SynLongIdent([id;r], [dotm], [None; rTrivia]), None, m) - | SynExpr.DotGet (e, dm, SynLongIdent(lid, dots, trivia), _) -> + SynExpr.LongIdent(isOpt, SynLongIdent(lid @ [ r ], dots @ [ mDot ], trivia @ [ rTrivia ]), None, m) + | SynExpr.Ident id -> SynExpr.LongIdent(false, SynLongIdent([ id; r ], [ mDot ], [ None; rTrivia ]), None, m) + | SynExpr.DotGet (e, dm, SynLongIdent (lid, dots, trivia), _) -> // REVIEW: MEMORY PERFORMANCE: This is memory intensive (we create a lot of these list nodes) - SynExpr.DotGet (e, dm, SynLongIdent(lid@[r], dots@[dotm], trivia@[rTrivia]), m) - | expr -> - SynExpr.DotGet (expr, dotm, SynLongIdent([r], [], [rTrivia]), m) + SynExpr.DotGet(e, dm, SynLongIdent(lid @ [ r ], dots @ [ mDot ], trivia @ [ rTrivia ]), m) + | expr -> SynExpr.DotGet(expr, mDot, SynLongIdent([ r ], [], [ rTrivia ]), m) -let mkSynDotMissing dotm m l = +let mkSynDotMissing mDot m l = match l with - | SynExpr.LongIdent (isOpt, SynLongIdent(lid, dots, trivia), None, _) -> - // REVIEW: MEMORY PERFORMANCE: This list operation is memory intensive (we create a lot of these list nodes) - SynExpr.LongIdent (isOpt, SynLongIdent(lid, dots@[dotm], trivia), None, m) - | SynExpr.Ident id -> - SynExpr.LongIdent (false, SynLongIdent([id], [dotm], []), None, m) - | SynExpr.DotGet (e, dm, SynLongIdent(lid, dots, trivia), _) -> - SynExpr.DotGet (e, dm, SynLongIdent(lid, dots@[dotm], trivia), m)// REVIEW: MEMORY PERFORMANCE: This is memory intensive (we create a lot of these list nodes) - | expr -> - SynExpr.DiscardAfterMissingQualificationAfterDot (expr, m) + | SynExpr.LongIdent (isOpt, SynLongIdent (lid, dots, trivia), None, _) -> + // REVIEW: MEMORY PERFORMANCE: This list operation is memory intensive (we create a lot of these list nodes) + SynExpr.LongIdent(isOpt, SynLongIdent(lid, dots @ [ mDot ], trivia), None, m) + | SynExpr.Ident id -> SynExpr.LongIdent(false, SynLongIdent([ id ], [ mDot ], []), None, m) + | SynExpr.DotGet (e, dm, SynLongIdent (lid, dots, trivia), _) -> SynExpr.DotGet(e, dm, SynLongIdent(lid, dots @ [ mDot ], trivia), m) // REVIEW: MEMORY PERFORMANCE: This is memory intensive (we create a lot of these list nodes) + | expr -> SynExpr.DiscardAfterMissingQualificationAfterDot(expr, m) let mkSynFunMatchLambdas synArgNameGenerator isMember wholem ps arrow e = - let _, e = PushCurriedPatternsToExpr synArgNameGenerator wholem isMember ps arrow e + let _, e = PushCurriedPatternsToExpr synArgNameGenerator wholem isMember ps arrow e e -let arbExpr (debugStr, range: range) = SynExpr.ArbitraryAfterError (debugStr, range.MakeSynthetic()) +let arbExpr (debugStr, range: range) = + SynExpr.ArbitraryAfterError(debugStr, range.MakeSynthetic()) -let unionRangeWithListBy projectRangeFromThing m listOfThing = - (m, listOfThing) ||> List.fold (fun m thing -> unionRanges m (projectRangeFromThing thing)) +let unionRangeWithListBy projectRangeFromThing m listOfThing = + (m, listOfThing) + ||> List.fold (fun m thing -> unionRanges m (projectRangeFromThing thing)) let mkAttributeList attrs range : SynAttributeList list = - [{ Attributes = attrs - Range = range }] + [ { Attributes = attrs; Range = range } ] let ConcatAttributesLists (attrsLists: SynAttributeList list) = - attrsLists - |> List.map (fun x -> x.Attributes) - |> List.concat + attrsLists |> List.map (fun x -> x.Attributes) |> List.concat -let (|Attributes|) synAttributes = - ConcatAttributesLists synAttributes +let (|Attributes|) synAttributes = ConcatAttributesLists synAttributes let (|TyparDecls|) (typarDecls: SynTyparDecls option) = - typarDecls - |> Option.map (fun x -> x.TyparDecls) - |> Option.defaultValue [] + typarDecls |> Option.map (fun x -> x.TyparDecls) |> Option.defaultValue [] let (|TyparsAndConstraints|) (typarDecls: SynTyparDecls option) = typarDecls |> Option.map (fun x -> x.TyparDecls, x.Constraints) |> Option.defaultValue ([], []) -let (|ValTyparDecls|) (SynValTyparDecls(typarDecls, canInfer)) = +let (|ValTyparDecls|) (SynValTyparDecls (typarDecls, canInfer)) = typarDecls |> Option.map (fun x -> x.TyparDecls, x.Constraints, canInfer) |> Option.defaultValue ([], [], canInfer) @@ -490,8 +512,7 @@ let rec stripParenTypes synType = | SynType.Paren (innerType, _) -> stripParenTypes innerType | _ -> synType -let (|StripParenTypes|) synType = - stripParenTypes synType +let (|StripParenTypes|) synType = stripParenTypes synType /// Operations related to the syntactic analysis of arguments of value, function and member definitions and signatures. module SynInfo = @@ -500,7 +521,7 @@ module SynInfo = let unnamedTopArg1 = SynArgInfo([], false, None) /// The argument information for a curried argument without a name - let unnamedTopArg = [unnamedTopArg1] + let unnamedTopArg = [ unnamedTopArg1 ] /// The argument information for a '()' argument let unitArgData = unnamedTopArg @@ -512,53 +533,55 @@ module SynInfo = let selfMetadata = unnamedTopArg /// Determine if a syntactic information represents a member without arguments (which is implicitly a property getter) - let HasNoArgs (SynValInfo(args, _)) = isNil args + let HasNoArgs (SynValInfo (args, _)) = isNil args /// Check if one particular argument is an optional argument. Used when adjusting the /// types of optional arguments for function and member signatures. - let IsOptionalArg (SynArgInfo(_, isOpt, _)) = isOpt + let IsOptionalArg (SynArgInfo (_, isOpt, _)) = isOpt /// Check if there are any optional arguments in the syntactic argument information. Used when adjusting the /// types of optional arguments for function and member signatures. - let HasOptionalArgs (SynValInfo(args, _)) = List.exists (List.exists IsOptionalArg) args + let HasOptionalArgs (SynValInfo (args, _)) = + List.exists (List.exists IsOptionalArg) args /// Add a parameter entry to the syntactic value information to represent the '()' argument to a property getter. This is /// used for the implicit '()' argument in property getter signature specifications. - let IncorporateEmptyTupledArgForPropertyGetter (SynValInfo(args, retInfo)) = SynValInfo([] :: args, retInfo) + let IncorporateEmptyTupledArgForPropertyGetter (SynValInfo (args, retInfo)) = SynValInfo([] :: args, retInfo) /// Add a parameter entry to the syntactic value information to represent the 'this' argument. This is /// used for the implicit 'this' argument in member signature specifications. - let IncorporateSelfArg (SynValInfo(args, retInfo)) = SynValInfo(selfMetadata :: args, retInfo) + let IncorporateSelfArg (SynValInfo (args, retInfo)) = + SynValInfo(selfMetadata :: args, retInfo) /// Add a parameter entry to the syntactic value information to represent the value argument for a property setter. This is /// used for the implicit value argument in property setter signature specifications. - let IncorporateSetterArg (SynValInfo(args, retInfo)) = - let args = - match args with - | [] -> [unnamedTopArg] - | [arg] -> [arg@[unnamedTopArg1]] - | _ -> failwith "invalid setter type" - SynValInfo(args, retInfo) + let IncorporateSetterArg (SynValInfo (args, retInfo)) = + let args = + match args with + | [] -> [ unnamedTopArg ] + | [ arg ] -> [ arg @ [ unnamedTopArg1 ] ] + | _ -> failwith "invalid setter type" + + SynValInfo(args, retInfo) /// Get the argument counts for each curried argument group. Used in some adhoc places in tc.fs. - let AritiesOfArgs (SynValInfo(args, _)) = List.map List.length args + let AritiesOfArgs (SynValInfo (args, _)) = List.map List.length args /// Get the argument attributes from the syntactic information for an argument. - let AttribsOfArgData (SynArgInfo(Attributes attribs, _, _)) = attribs + let AttribsOfArgData (SynArgInfo (Attributes attribs, _, _)) = attribs /// Infer the syntactic argument info for a single argument from a simple pattern. let rec InferSynArgInfoFromSimplePat attribs p = match p with - | SynSimplePat.Id(nm, _, isCompGen, _, isOpt, _) -> - SynArgInfo(attribs, isOpt, (if isCompGen then None else Some nm)) - | SynSimplePat.Typed(a, _, _) -> InferSynArgInfoFromSimplePat attribs a - | SynSimplePat.Attrib(a, attribs2, _) -> InferSynArgInfoFromSimplePat (attribs @ attribs2) a + | SynSimplePat.Id (nm, _, isCompGen, _, isOpt, _) -> SynArgInfo(attribs, isOpt, (if isCompGen then None else Some nm)) + | SynSimplePat.Typed (a, _, _) -> InferSynArgInfoFromSimplePat attribs a + | SynSimplePat.Attrib (a, attribs2, _) -> InferSynArgInfoFromSimplePat (attribs @ attribs2) a /// Infer the syntactic argument info for one or more arguments one or more simple patterns. let rec InferSynArgInfoFromSimplePats x = match x with - | SynSimplePats.SimplePats(ps, _) -> List.map (InferSynArgInfoFromSimplePat []) ps - | SynSimplePats.Typed(ps, _, _) -> InferSynArgInfoFromSimplePats ps + | SynSimplePats.SimplePats (ps, _) -> List.map (InferSynArgInfoFromSimplePat []) ps + | SynSimplePats.Typed (ps, _, _) -> InferSynArgInfoFromSimplePats ps /// Infer the syntactic argument info for one or more arguments a pattern. let InferSynArgInfoFromPat p = @@ -569,8 +592,12 @@ module SynInfo = /// Make sure only a solitary unit argument has unit elimination let AdjustArgsForUnitElimination infosForArgs = match infosForArgs with - | [[]] -> infosForArgs - | _ -> infosForArgs |> List.map (function [] -> unitArgData | x -> x) + | [ [] ] -> infosForArgs + | _ -> + infosForArgs + |> List.map (function + | [] -> unitArgData + | x -> x) /// Transform a property declared using '[static] member P = expr' to a method taking a "unit" argument. /// This is similar to IncorporateEmptyTupledArgForPropertyGetter, but applies to member definitions @@ -584,18 +611,20 @@ module SynInfo = /// is an immediate 'fun ... -> ...' or 'function ...' expression. This is noted in the F# language specification. /// This does not apply to member definitions nor to returns with attributes let InferLambdaArgs (retInfo: SynArgInfo) origRhsExpr = - if retInfo.Attributes.Length > 0 then [] else - let rec loop e = - match e with - | SynExpr.Lambda (fromMethod=false; args=spats; body=rest) -> - InferSynArgInfoFromSimplePats spats :: loop rest - | _ -> [] - loop origRhsExpr + if retInfo.Attributes.Length > 0 then + [] + else + let rec loop e = + match e with + | SynExpr.Lambda (fromMethod = false; args = spats; body = rest) -> InferSynArgInfoFromSimplePats spats :: loop rest + | _ -> [] + + loop origRhsExpr let InferSynReturnData (retInfo: SynReturnInfo option) = match retInfo with | None -> unnamedRetVal - | Some(SynReturnInfo((_, retInfo), _)) -> retInfo + | Some (SynReturnInfo ((_, retInfo), _)) -> retInfo let private emptySynValInfo = SynValInfo([], unnamedRetVal) @@ -608,12 +637,12 @@ module SynInfo = let infosForExplicitArgs = match pat with - | Some(SynPat.LongIdent(argPats=SynArgPats.Pats curriedArgs)) -> List.map InferSynArgInfoFromPat curriedArgs + | Some (SynPat.LongIdent(argPats = SynArgPats.Pats curriedArgs)) -> List.map InferSynArgInfoFromPat curriedArgs | _ -> [] let explicitArgsAreSimple = match pat with - | Some(SynPat.LongIdent(argPats=SynArgPats.Pats curriedArgs)) -> List.forall isSimplePattern curriedArgs + | Some (SynPat.LongIdent(argPats = SynArgPats.Pats curriedArgs)) -> List.forall isSimplePattern curriedArgs | _ -> true let retInfo = InferSynReturnData retInfo @@ -621,13 +650,16 @@ module SynInfo = match memberFlagsOpt with | None -> let infosForLambdaArgs = InferLambdaArgs retInfo origRhsExpr - let infosForArgs = infosForExplicitArgs @ (if explicitArgsAreSimple then infosForLambdaArgs else []) + + let infosForArgs = + infosForExplicitArgs + @ (if explicitArgsAreSimple then infosForLambdaArgs else []) + let infosForArgs = AdjustArgsForUnitElimination infosForArgs SynValData(None, SynValInfo(infosForArgs, retInfo), None) - | Some memFlags -> - let infosForObjArgs = - if memFlags.IsInstance then [ selfMetadata ] else [] + | Some memFlags -> + let infosForObjArgs = if memFlags.IsInstance then [ selfMetadata ] else [] let infosForArgs = AdjustMemberArgs memFlags.MemberKind infosForExplicitArgs let infosForArgs = AdjustArgsForUnitElimination infosForArgs @@ -636,259 +668,302 @@ module SynInfo = SynValData(Some memFlags, SynValInfo(argInfos, retInfo), None) let mkSynBindingRhs staticOptimizations rhsExpr mRhs retInfo = - let rhsExpr = List.foldBack (fun (c, e1) e2 -> SynExpr.LibraryOnlyStaticOptimization (c, e1, e2, mRhs)) staticOptimizations rhsExpr + let rhsExpr = + List.foldBack (fun (c, e1) e2 -> SynExpr.LibraryOnlyStaticOptimization(c, e1, e2, mRhs)) staticOptimizations rhsExpr + let rhsExpr, retTyOpt = match retInfo with - | Some (SynReturnInfo((ty, SynArgInfo(rAttribs, _, _)), tym)) -> - SynExpr.Typed (rhsExpr, ty, rhsExpr.Range), Some(SynBindingReturnInfo(ty, tym, rAttribs) ) + | Some (SynReturnInfo ((ty, SynArgInfo (rAttribs, _, _)), tym)) -> + SynExpr.Typed(rhsExpr, ty, rhsExpr.Range), Some(SynBindingReturnInfo(ty, tym, rAttribs)) | None -> rhsExpr, None + rhsExpr, retTyOpt -let mkSynBinding (xmlDoc: PreXmlDoc, headPat) (vis, isInline, isMutable, mBind, spBind, retInfo, origRhsExpr, mRhs, staticOptimizations, attrs, memberFlagsOpt, trivia) = - let info = SynInfo.InferSynValData (memberFlagsOpt, Some headPat, retInfo, origRhsExpr) +let mkSynBinding + (xmlDoc: PreXmlDoc, headPat) + (vis, isInline, isMutable, mBind, spBind, retInfo, origRhsExpr, mRhs, staticOptimizations, attrs, memberFlagsOpt, trivia) + = + let info = + SynInfo.InferSynValData(memberFlagsOpt, Some headPat, retInfo, origRhsExpr) + let rhsExpr, retTyOpt = mkSynBindingRhs staticOptimizations origRhsExpr mRhs retInfo let mBind = unionRangeWithXmlDoc xmlDoc mBind - SynBinding (vis, SynBindingKind.Normal, isInline, isMutable, attrs, xmlDoc, info, headPat, retTyOpt, rhsExpr, mBind, spBind, trivia) + SynBinding(vis, SynBindingKind.Normal, isInline, isMutable, attrs, xmlDoc, info, headPat, retTyOpt, rhsExpr, mBind, spBind, trivia) let NonVirtualMemberFlags trivia k : SynMemberFlags = - { MemberKind=k - IsInstance=true - IsDispatchSlot=false - IsOverrideOrExplicitImpl=false - IsFinal=false - Trivia=trivia } + { + MemberKind = k + IsInstance = true + IsDispatchSlot = false + IsOverrideOrExplicitImpl = false + IsFinal = false + Trivia = trivia + } let CtorMemberFlags trivia : SynMemberFlags = - { MemberKind=SynMemberKind.Constructor - IsInstance=false - IsDispatchSlot=false - IsOverrideOrExplicitImpl=false - IsFinal=false - Trivia=trivia } + { + MemberKind = SynMemberKind.Constructor + IsInstance = false + IsDispatchSlot = false + IsOverrideOrExplicitImpl = false + IsFinal = false + Trivia = trivia + } let ClassCtorMemberFlags trivia : SynMemberFlags = - { MemberKind=SynMemberKind.ClassConstructor - IsInstance=false - IsDispatchSlot=false - IsOverrideOrExplicitImpl=false - IsFinal=false - Trivia=trivia } + { + MemberKind = SynMemberKind.ClassConstructor + IsInstance = false + IsDispatchSlot = false + IsOverrideOrExplicitImpl = false + IsFinal = false + Trivia = trivia + } let OverrideMemberFlags trivia k : SynMemberFlags = - { MemberKind=k - IsInstance=true - IsDispatchSlot=false - IsOverrideOrExplicitImpl=true - IsFinal=false - Trivia=trivia } + { + MemberKind = k + IsInstance = true + IsDispatchSlot = false + IsOverrideOrExplicitImpl = true + IsFinal = false + Trivia = trivia + } let AbstractMemberFlags trivia k : SynMemberFlags = - { MemberKind=k - IsInstance=true - IsDispatchSlot=true - IsOverrideOrExplicitImpl=false - IsFinal=false - Trivia=trivia } + { + MemberKind = k + IsInstance = true + IsDispatchSlot = true + IsOverrideOrExplicitImpl = false + IsFinal = false + Trivia = trivia + } let StaticMemberFlags trivia k : SynMemberFlags = - { MemberKind=k - IsInstance=false - IsDispatchSlot=false - IsOverrideOrExplicitImpl=false - IsFinal=false - Trivia=trivia } + { + MemberKind = k + IsInstance = false + IsDispatchSlot = false + IsOverrideOrExplicitImpl = false + IsFinal = false + Trivia = trivia + } let MemberSynMemberFlagsTrivia (mMember: range) : SynMemberFlagsTrivia = - { MemberRange = Some mMember - OverrideRange = None - AbstractRange = None - StaticRange = None - DefaultRange = None } + { + MemberRange = Some mMember + OverrideRange = None + AbstractRange = None + StaticRange = None + DefaultRange = None + } let OverrideSynMemberFlagsTrivia (mOverride: range) : SynMemberFlagsTrivia = - { MemberRange = None - OverrideRange = Some mOverride - AbstractRange = None - StaticRange = None - DefaultRange = None } + { + MemberRange = None + OverrideRange = Some mOverride + AbstractRange = None + StaticRange = None + DefaultRange = None + } let StaticMemberSynMemberFlagsTrivia (mStatic: range) (mMember: range) : SynMemberFlagsTrivia = - { MemberRange = Some mMember - OverrideRange = None - AbstractRange = None - StaticRange = Some mStatic - DefaultRange = None } + { + MemberRange = Some mMember + OverrideRange = None + AbstractRange = None + StaticRange = Some mStatic + DefaultRange = None + } let DefaultSynMemberFlagsTrivia (mDefault: range) : SynMemberFlagsTrivia = - { MemberRange = None - OverrideRange = None - AbstractRange = None - StaticRange = None - DefaultRange = Some mDefault } + { + MemberRange = None + OverrideRange = None + AbstractRange = None + StaticRange = None + DefaultRange = Some mDefault + } let AbstractSynMemberFlagsTrivia (mAbstract: range) : SynMemberFlagsTrivia = - { MemberRange = None - OverrideRange = None - AbstractRange = Some mAbstract - StaticRange = None - DefaultRange = None } + { + MemberRange = None + OverrideRange = None + AbstractRange = Some mAbstract + StaticRange = None + DefaultRange = None + } let AbstractMemberSynMemberFlagsTrivia (mAbstract: range) (mMember: range) : SynMemberFlagsTrivia = - { MemberRange = Some mMember - OverrideRange = None - AbstractRange = Some mAbstract - StaticRange = None - DefaultRange = None } + { + MemberRange = Some mMember + OverrideRange = None + AbstractRange = Some mAbstract + StaticRange = None + DefaultRange = None + } let inferredTyparDecls = SynValTyparDecls(None, true) let noInferredTypars = SynValTyparDecls(None, false) -let unionBindingAndMembers (bindings: SynBinding list) (members: SynMemberDefn list): SynBinding list = - [ yield! bindings - yield! List.choose (function | SynMemberDefn.Member(b,_) -> Some b | _ -> None) members ] +let unionBindingAndMembers (bindings: SynBinding list) (members: SynMemberDefn list) : SynBinding list = + [ + yield! bindings + yield! + List.choose + (function + | SynMemberDefn.Member (b, _) -> Some b + | _ -> None) + members + ] let rec synExprContainsError inpExpr = - let rec walkBind (SynBinding(expr=synExpr)) = walkExpr synExpr + let rec walkBind (SynBinding (expr = synExpr)) = walkExpr synExpr and walkExprs es = es |> List.exists walkExpr and walkBinds es = es |> List.exists walkBind and walkMatchClauses cl = - cl |> List.exists (fun (SynMatchClause(whenExpr=whenExpr; resultExpr=e)) -> walkExprOpt whenExpr || walkExpr e) + cl + |> List.exists (fun (SynMatchClause (whenExpr = whenExpr; resultExpr = e)) -> walkExprOpt whenExpr || walkExpr e) and walkExprOpt eOpt = eOpt |> Option.exists walkExpr and walkExpr e = - match e with - | SynExpr.FromParseError _ - | SynExpr.DiscardAfterMissingQualificationAfterDot _ - | SynExpr.ArbitraryAfterError _ -> true - - | SynExpr.LongIdent _ - | SynExpr.Quote _ - | SynExpr.LibraryOnlyILAssembly _ - | SynExpr.LibraryOnlyStaticOptimization _ - | SynExpr.Null _ - | SynExpr.Ident _ - | SynExpr.ImplicitZero _ - | SynExpr.Const _ - | SynExpr.Dynamic _ -> false - - | SynExpr.TypeTest (e, _, _) - | SynExpr.Upcast (e, _, _) - | SynExpr.AddressOf (_, e, _, _) - | SynExpr.ComputationExpr (_, e, _) - | SynExpr.ArrayOrListComputed (_, e, _) - | SynExpr.Typed (e, _, _) - | SynExpr.FromParseError (e, _) - | SynExpr.Do (e, _) - | SynExpr.Assert (e, _) - | SynExpr.DotGet (e, _, _, _) - | SynExpr.LongIdentSet (_, e, _) - | SynExpr.New (_, _, e, _) - | SynExpr.TypeApp (e, _, _, _, _, _, _) - | SynExpr.LibraryOnlyUnionCaseFieldGet (e, _, _, _) - | SynExpr.Downcast (e, _, _) - | SynExpr.InferredUpcast (e, _) - | SynExpr.InferredDowncast (e, _) - | SynExpr.Lazy (e, _) - | SynExpr.TraitCall (_, _, e, _) - | SynExpr.YieldOrReturn (_, e, _) - | SynExpr.YieldOrReturnFrom (_, e, _) - | SynExpr.DoBang (e, _) - | SynExpr.Fixed (e, _) - | SynExpr.DebugPoint (_, _, e) - | SynExpr.Paren (e, _, _, _) -> - walkExpr e - - | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) - | SynExpr.DotSet (e1, _, e2, _) - | SynExpr.Set (e1, e2, _) - | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, _, _, e2, _) - | SynExpr.JoinIn (e1, _, e2, _) - | SynExpr.App (_, _, e1, e2, _) -> - walkExpr e1 || walkExpr e2 - - | SynExpr.ArrayOrList (_, es, _) - | SynExpr.Tuple (_, es, _, _) -> - walkExprs es - - | SynExpr.AnonRecd (_, origExpr, flds, _) -> - (match origExpr with Some (e, _) -> walkExpr e | None -> false) || - walkExprs (List.map (fun (_, _, e) -> e) flds) - - | SynExpr.Record (_, origExpr, fs, _) -> - (match origExpr with Some (e, _) -> walkExpr e | None -> false) || - let flds = fs |> List.choose (fun (SynExprRecordField(expr=v)) -> v) - walkExprs flds - - | SynExpr.ObjExpr (bindings=bs; members=ms; extraImpls=is) -> - let bs = unionBindingAndMembers bs ms - walkBinds bs || walkBinds [ for SynInterfaceImpl(bindings=bs) in is do yield! bs ] - - | SynExpr.ForEach (_, _, _, _, _, e1, e2, _) - | SynExpr.While (_, e1, e2, _) -> - walkExpr e1 || walkExpr e2 - - | SynExpr.For (identBody=e1; toBody=e2; doBody=e3) -> - walkExpr e1 || walkExpr e2 || walkExpr e3 - - | SynExpr.MatchLambda (_, _, cl, _, _) -> - walkMatchClauses cl - - | SynExpr.Lambda (body = e) -> - walkExpr e - - | SynExpr.Match (expr=e; clauses=cl) -> - walkExpr e || walkMatchClauses cl - - | SynExpr.LetOrUse (bindings=bs; body=e) -> - walkBinds bs || walkExpr e - - | SynExpr.TryWith (tryExpr=e; withCases=cl) -> - walkExpr e || walkMatchClauses cl - - | SynExpr.TryFinally (tryExpr=e1; finallyExpr=e2) -> - walkExpr e1 || walkExpr e2 - - | SynExpr.Sequential (_, _, e1, e2, _) -> - walkExpr e1 || walkExpr e2 - - | SynExpr.SequentialOrImplicitYield (_, e1, e2, _, _) -> - walkExpr e1 || walkExpr e2 - - | SynExpr.IfThenElse (ifExpr=e1; thenExpr=e2; elseExpr=e3opt) -> - walkExpr e1 || walkExpr e2 || walkExprOpt e3opt - - | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> - (match expr1 with Some e -> walkExpr e | None -> false) || - (match expr2 with Some e -> walkExpr e | None -> false) - - | SynExpr.IndexFromEnd (e, _) -> - walkExpr e - - | SynExpr.DotIndexedGet (e1, indexArgs, _, _) -> - walkExpr e1 || walkExpr indexArgs - - | SynExpr.DotIndexedSet (e1, indexArgs, e2, _, _, _) -> - walkExpr e1 || walkExpr indexArgs || walkExpr e2 - - | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> - walkExpr e1 || walkExpr e2 || walkExpr e3 - - | SynExpr.MatchBang (expr=e; clauses=cl) -> - walkExpr e || walkMatchClauses cl - - | SynExpr.LetOrUseBang (rhs=e1;body=e2;andBangs=es) -> - walkExpr e1 || walkExprs [ for SynExprAndBang(body=e) in es do yield e ] || walkExpr e2 - - | SynExpr.InterpolatedString (parts, _, _m) -> - walkExprs - (parts |> List.choose (function - | SynInterpolatedStringPart.String _ -> None - | SynInterpolatedStringPart.FillExpr (x, _) -> Some x)) + match e with + | SynExpr.FromParseError _ + | SynExpr.DiscardAfterMissingQualificationAfterDot _ + | SynExpr.ArbitraryAfterError _ -> true + + | SynExpr.LongIdent _ + | SynExpr.Quote _ + | SynExpr.LibraryOnlyILAssembly _ + | SynExpr.LibraryOnlyStaticOptimization _ + | SynExpr.Null _ + | SynExpr.Ident _ + | SynExpr.ImplicitZero _ + | SynExpr.Const _ + | SynExpr.Dynamic _ -> false + + | SynExpr.TypeTest (e, _, _) + | SynExpr.Upcast (e, _, _) + | SynExpr.AddressOf (_, e, _, _) + | SynExpr.ComputationExpr (_, e, _) + | SynExpr.ArrayOrListComputed (_, e, _) + | SynExpr.Typed (e, _, _) + | SynExpr.FromParseError (e, _) + | SynExpr.Do (e, _) + | SynExpr.Assert (e, _) + | SynExpr.DotGet (e, _, _, _) + | SynExpr.LongIdentSet (_, e, _) + | SynExpr.New (_, _, e, _) + | SynExpr.TypeApp (e, _, _, _, _, _, _) + | SynExpr.LibraryOnlyUnionCaseFieldGet (e, _, _, _) + | SynExpr.Downcast (e, _, _) + | SynExpr.InferredUpcast (e, _) + | SynExpr.InferredDowncast (e, _) + | SynExpr.Lazy (e, _) + | SynExpr.TraitCall (_, _, e, _) + | SynExpr.YieldOrReturn (_, e, _) + | SynExpr.YieldOrReturnFrom (_, e, _) + | SynExpr.DoBang (e, _) + | SynExpr.Fixed (e, _) + | SynExpr.DebugPoint (_, _, e) + | SynExpr.Paren (e, _, _, _) -> walkExpr e + + | SynExpr.NamedIndexedPropertySet (_, e1, e2, _) + | SynExpr.DotSet (e1, _, e2, _) + | SynExpr.Set (e1, e2, _) + | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, _, _, e2, _) + | SynExpr.JoinIn (e1, _, e2, _) + | SynExpr.App (_, _, e1, e2, _) -> walkExpr e1 || walkExpr e2 + + | SynExpr.ArrayOrList (_, es, _) + | SynExpr.Tuple (_, es, _, _) -> walkExprs es + + | SynExpr.AnonRecd (_, origExpr, flds, _) -> + (match origExpr with + | Some (e, _) -> walkExpr e + | None -> false) + || walkExprs (List.map (fun (_, _, e) -> e) flds) + + | SynExpr.Record (_, origExpr, fs, _) -> + (match origExpr with + | Some (e, _) -> walkExpr e + | None -> false) + || (let flds = fs |> List.choose (fun (SynExprRecordField (expr = v)) -> v) + walkExprs flds) + + | SynExpr.ObjExpr (bindings = bs; members = ms; extraImpls = is) -> + let bs = unionBindingAndMembers bs ms + + let binds = + [ + for SynInterfaceImpl (bindings = bs) in is do + yield! bs + ] + + walkBinds bs || walkBinds binds + + | SynExpr.ForEach (_, _, _, _, _, e1, e2, _) + | SynExpr.While (_, e1, e2, _) -> walkExpr e1 || walkExpr e2 + + | SynExpr.For (identBody = e1; toBody = e2; doBody = e3) -> walkExpr e1 || walkExpr e2 || walkExpr e3 + + | SynExpr.MatchLambda (_, _, cl, _, _) -> walkMatchClauses cl + + | SynExpr.Lambda (body = e) -> walkExpr e + + | SynExpr.Match (expr = e; clauses = cl) -> walkExpr e || walkMatchClauses cl + + | SynExpr.LetOrUse (bindings = bs; body = e) -> walkBinds bs || walkExpr e + + | SynExpr.TryWith (tryExpr = e; withCases = cl) -> walkExpr e || walkMatchClauses cl + + | SynExpr.TryFinally (tryExpr = e1; finallyExpr = e2) -> walkExpr e1 || walkExpr e2 + + | SynExpr.Sequential (_, _, e1, e2, _) -> walkExpr e1 || walkExpr e2 + + | SynExpr.SequentialOrImplicitYield (_, e1, e2, _, _) -> walkExpr e1 || walkExpr e2 + + | SynExpr.IfThenElse (ifExpr = e1; thenExpr = e2; elseExpr = e3opt) -> walkExpr e1 || walkExpr e2 || walkExprOpt e3opt + + | SynExpr.IndexRange (expr1, _, expr2, _, _, _) -> + (match expr1 with + | Some e -> walkExpr e + | None -> false) + || (match expr2 with + | Some e -> walkExpr e + | None -> false) + + | SynExpr.IndexFromEnd (e, _) -> walkExpr e + + | SynExpr.DotIndexedGet (e1, indexArgs, _, _) -> walkExpr e1 || walkExpr indexArgs + + | SynExpr.DotIndexedSet (e1, indexArgs, e2, _, _, _) -> walkExpr e1 || walkExpr indexArgs || walkExpr e2 + + | SynExpr.DotNamedIndexedPropertySet (e1, _, e2, e3, _) -> walkExpr e1 || walkExpr e2 || walkExpr e3 + + | SynExpr.MatchBang (expr = e; clauses = cl) -> walkExpr e || walkMatchClauses cl + + | SynExpr.LetOrUseBang (rhs = e1; body = e2; andBangs = es) -> + walkExpr e1 + || walkExprs + [ + for SynExprAndBang (body = e) in es do + yield e + ] + || walkExpr e2 + + | SynExpr.InterpolatedString (parts, _, _m) -> + parts + |> List.choose (function + | SynInterpolatedStringPart.String _ -> None + | SynInterpolatedStringPart.FillExpr (x, _) -> Some x) + |> walkExprs walkExpr inpExpr @@ -899,15 +974,46 @@ let (|ParsedHashDirectiveArguments|) (input: ParsedHashDirectiveArgument list) = | ParsedHashDirectiveArgument.SourceIdentifier (_, v, _) -> v) input -let prependIdentInLongIdentWithTrivia (SynIdent(ident, identTrivia)) dotm lid = +let prependIdentInLongIdentWithTrivia (SynIdent (ident, identTrivia)) mDot lid = match lid with - | SynLongIdent(lid, dots, trivia) -> - SynLongIdent(ident :: lid, dotm :: dots, identTrivia :: trivia) + | SynLongIdent (lid, dots, trivia) -> SynLongIdent(ident :: lid, mDot :: dots, identTrivia :: trivia) let mkDynamicArgExpr expr = match expr with | SynExpr.Ident ident -> - let con = SynConst.String (ident.idText, SynStringKind.Regular, ident.idRange) - SynExpr.Const (con, con.Range ident.idRange) - | SynExpr.Paren(expr = e) -> e - | e -> e \ No newline at end of file + let con = SynConst.String(ident.idText, SynStringKind.Regular, ident.idRange) + SynExpr.Const(con, con.Range ident.idRange) + | SynExpr.Paren (expr = e) -> e + | e -> e + +let rec normalizeTupleExpr exprs commas : SynExpr list * range list = + match exprs with + | SynExpr.Tuple (false, innerExprs, innerCommas, _) :: rest -> + let innerExprs, innerCommas = + normalizeTupleExpr (List.rev innerExprs) (List.rev innerCommas) + + innerExprs @ rest, innerCommas @ commas + | _ -> exprs, commas + +/// Remove all members that were captures as SynMemberDefn.GetSetMember +let rec desugarGetSetMembers (memberDefns: SynMemberDefns) = + memberDefns + |> List.collect (fun md -> + match md with + | SynMemberDefn.GetSetMember (Some (SynBinding _ as getBinding), + Some (SynBinding _ as setBinding), + m, + { + GetKeyword = Some mGet + SetKeyword = Some mSet + }) -> + if Position.posLt mGet.Start mSet.Start then + [ SynMemberDefn.Member(getBinding, m); SynMemberDefn.Member(setBinding, m) ] + else + [ SynMemberDefn.Member(setBinding, m); SynMemberDefn.Member(getBinding, m) ] + | SynMemberDefn.GetSetMember (Some binding, None, m, _) + | SynMemberDefn.GetSetMember (None, Some binding, m, _) -> [ SynMemberDefn.Member(binding, m) ] + | SynMemberDefn.Interface (interfaceType, withKeyword, members, m) -> + let members = Option.map desugarGetSetMembers members + [ SynMemberDefn.Interface(interfaceType, withKeyword, members, m) ] + | md -> [ md ]) diff --git a/src/Compiler/SyntaxTree/SyntaxTreeOps.fsi b/src/Compiler/SyntaxTree/SyntaxTreeOps.fsi index dfff0392bcf..0c7010b40fa 100644 --- a/src/Compiler/SyntaxTree/SyntaxTreeOps.fsi +++ b/src/Compiler/SyntaxTree/SyntaxTreeOps.fsi @@ -143,7 +143,7 @@ val mkSynQMarkSet: m: range -> a: SynExpr -> b: SynExpr -> c: SynExpr -> SynExpr //val mkSynDotBrackSeqSliceGet: m:range -> mDot:range -> arr:SynExpr -> argsList:SynIndexerArg list -> SynExpr -val mkSynDotParenGet: lhsm: range -> dotm: range -> a: SynExpr -> b: SynExpr -> SynExpr +val mkSynDotParenGet: mLhs: range -> mDot: range -> a: SynExpr -> b: SynExpr -> SynExpr val mkSynUnit: m: range -> SynExpr @@ -153,9 +153,9 @@ val mkSynDelay: m: range -> e: SynExpr -> SynExpr val mkSynAssign: l: SynExpr -> r: SynExpr -> SynExpr -val mkSynDot: dotm: range -> m: range -> l: SynExpr -> r: SynIdent -> SynExpr +val mkSynDot: mDot: range -> m: range -> l: SynExpr -> r: SynIdent -> SynExpr -val mkSynDotMissing: dotm: range -> m: range -> l: SynExpr -> SynExpr +val mkSynDotMissing: mDot: range -> m: range -> l: SynExpr -> SynExpr val mkSynFunMatchLambdas: synArgNameGenerator: SynArgNameGenerator -> @@ -337,6 +337,10 @@ val (|SynPipeRight2|_|): SynExpr -> (SynExpr * SynExpr * SynExpr) option /// 'e1 |||> e2' val (|SynPipeRight3|_|): SynExpr -> (SynExpr * SynExpr * SynExpr * SynExpr) option -val prependIdentInLongIdentWithTrivia: ident: SynIdent -> dotm: range -> lid: SynLongIdent -> SynLongIdent +val prependIdentInLongIdentWithTrivia: ident: SynIdent -> mDot: range -> lid: SynLongIdent -> SynLongIdent val mkDynamicArgExpr: expr: SynExpr -> SynExpr + +val normalizeTupleExpr: exprs: SynExpr list -> commas: range list -> SynExpr list * range List + +val desugarGetSetMembers: memberDefns: SynMemberDefns -> SynMemberDefns diff --git a/src/Compiler/SyntaxTree/SyntaxTrivia.fs b/src/Compiler/SyntaxTree/SyntaxTrivia.fs index b3662eb39a7..679ec9156a7 100644 --- a/src/Compiler/SyntaxTree/SyntaxTrivia.fs +++ b/src/Compiler/SyntaxTree/SyntaxTrivia.fs @@ -7,21 +7,21 @@ open FSharp.Compiler.Text [] type IdentTrivia = | OriginalNotation of text: string - | OriginalNotationWithParen of leftParenRange: range * text:string * rightParenRange: range + | OriginalNotationWithParen of leftParenRange: range * text: string * rightParenRange: range | HasParenthesis of leftParenRange: range * rightParenRange: range [] type ConditionalDirectiveTrivia = - | If of expr:IfDirectiveExpression * range:range - | Else of range:range - | EndIf of range:range + | If of expr: IfDirectiveExpression * range: range + | Else of range: range + | EndIf of range: range and [] IfDirectiveExpression = | And of IfDirectiveExpression * IfDirectiveExpression | Or of IfDirectiveExpression * IfDirectiveExpression | Not of IfDirectiveExpression | Ident of string - + [] type CommentTrivia = | LineComment of range: range @@ -29,69 +29,92 @@ type CommentTrivia = [] type ParsedImplFileInputTrivia = - { ConditionalDirectives: ConditionalDirectiveTrivia list - CodeComments: CommentTrivia list } + { + ConditionalDirectives: ConditionalDirectiveTrivia list + CodeComments: CommentTrivia list + } [] type ParsedSigFileInputTrivia = - { ConditionalDirectives: ConditionalDirectiveTrivia list - CodeComments: CommentTrivia list } + { + ConditionalDirectives: ConditionalDirectiveTrivia list + CodeComments: CommentTrivia list + } [] type SynExprTryWithTrivia = - { TryKeyword: range - TryToWithRange: range - WithKeyword: range - WithToEndRange: range } + { + TryKeyword: range + TryToWithRange: range + WithKeyword: range + WithToEndRange: range + } [] type SynExprTryFinallyTrivia = - { TryKeyword: range - FinallyKeyword: range } + { + TryKeyword: range + FinallyKeyword: range + } [] type SynExprIfThenElseTrivia = - { IfKeyword: range - IsElif: bool - ThenKeyword: range - ElseKeyword: range option - IfToThenRange: range } + { + IfKeyword: range + IsElif: bool + ThenKeyword: range + ElseKeyword: range option + IfToThenRange: range + } [] type SynExprLambdaTrivia = - { ArrowRange: range option } + { + ArrowRange: range option + } + static member Zero: SynExprLambdaTrivia = { ArrowRange = None } [] -type SynExprLetOrUseTrivia = - { InKeyword: range option } +type SynExprLetOrUseTrivia = { InKeyword: range option } [] type SynExprLetOrUseBangTrivia = - { EqualsRange: range option } - static member Zero: SynExprLetOrUseBangTrivia = - { EqualsRange = None } + { + EqualsRange: range option + } + + static member Zero: SynExprLetOrUseBangTrivia = { EqualsRange = None } [] type SynExprMatchTrivia = - { MatchKeyword: range - WithKeyword: range } - + { + MatchKeyword: range + WithKeyword: range + } + [] type SynExprMatchBangTrivia = - { MatchBangKeyword: range - WithKeyword: range } + { + MatchBangKeyword: range + WithKeyword: range + } [] type SynMatchClauseTrivia = - { ArrowRange: range option - BarRange: range option } + { + ArrowRange: range option + BarRange: range option + } + static member Zero: SynMatchClauseTrivia = { ArrowRange = None; BarRange = None } [] type SynEnumCaseTrivia = - { BarRange: range option - EqualsRange: range } + { + BarRange: range option + EqualsRange: range + } [] type SynUnionCaseTrivia = { BarRange: range option } @@ -101,65 +124,121 @@ type SynPatOrTrivia = { BarRange: range } [] type SynTypeDefnTrivia = - { TypeKeyword: range option - EqualsRange: range option - WithKeyword: range option } + { + TypeKeyword: range option + EqualsRange: range option + WithKeyword: range option + } + static member Zero: SynTypeDefnTrivia = - { TypeKeyword = None - EqualsRange = None - WithKeyword = None } + { + TypeKeyword = None + EqualsRange = None + WithKeyword = None + } [] type SynBindingTrivia = - { LetKeyword: range option - EqualsRange: range option } + { + LetKeyword: range option + EqualsRange: range option + } + static member Zero: SynBindingTrivia = - { LetKeyword = None - EqualsRange = None } + { + LetKeyword = None + EqualsRange = None + } [] type SynMemberFlagsTrivia = - { MemberRange: range option - OverrideRange: range option - AbstractRange: range option - StaticRange: range option - DefaultRange: range option } + { + MemberRange: range option + OverrideRange: range option + AbstractRange: range option + StaticRange: range option + DefaultRange: range option + } + static member Zero: SynMemberFlagsTrivia = - { MemberRange = None - OverrideRange = None - AbstractRange = None - StaticRange = None - DefaultRange = None } + { + MemberRange = None + OverrideRange = None + AbstractRange = None + StaticRange = None + DefaultRange = None + } [] type SynExprAndBangTrivia = - { EqualsRange: range - InKeyword: range option } + { + EqualsRange: range + InKeyword: range option + } [] type SynModuleDeclNestedModuleTrivia = - { ModuleKeyword: range option - EqualsRange: range option } - static member Zero: SynModuleDeclNestedModuleTrivia = { ModuleKeyword = None; EqualsRange = None } + { + ModuleKeyword: range option + EqualsRange: range option + } + + static member Zero: SynModuleDeclNestedModuleTrivia = + { + ModuleKeyword = None + EqualsRange = None + } [] type SynModuleSigDeclNestedModuleTrivia = - { ModuleKeyword: range option - EqualsRange: range option } - static member Zero: SynModuleSigDeclNestedModuleTrivia = { ModuleKeyword = None; EqualsRange = None } + { + ModuleKeyword: range option + EqualsRange: range option + } + + static member Zero: SynModuleSigDeclNestedModuleTrivia = + { + ModuleKeyword = None + EqualsRange = None + } [] type SynModuleOrNamespaceTrivia = - { ModuleKeyword: range option - NamespaceKeyword: range option } + { + ModuleKeyword: range option + NamespaceKeyword: range option + } [] type SynModuleOrNamespaceSigTrivia = - { ModuleKeyword: range option - NamespaceKeyword: range option } + { + ModuleKeyword: range option + NamespaceKeyword: range option + } [] type SynValSigTrivia = - { ValKeyword: range option - WithKeyword: range option } - static member Zero: SynValSigTrivia = { ValKeyword = None; WithKeyword = None } + { + ValKeyword: range option + WithKeyword: range option + EqualsRange: range option + } + + static member Zero: SynValSigTrivia = + { + ValKeyword = None + WithKeyword = None + EqualsRange = None + } + +[] +type SynTypeFunTrivia = { ArrowRange: range } + +[] +type SynMemberGetSetTrivia = + { + WithKeyword: range + GetKeyword: range option + AndKeyword: range option + SetKeyword: range option + } diff --git a/src/Compiler/SyntaxTree/SyntaxTrivia.fsi b/src/Compiler/SyntaxTree/SyntaxTrivia.fsi index e9ba9b8929d..4490e0ec57c 100644 --- a/src/Compiler/SyntaxTree/SyntaxTrivia.fsi +++ b/src/Compiler/SyntaxTree/SyntaxTrivia.fsi @@ -318,6 +318,34 @@ type SynValSigTrivia = /// The syntax range of the `with` keyword WithKeyword: range option + + /// The syntax range of the `=` token. + EqualsRange: range option } static member Zero: SynValSigTrivia + +/// Represents additional information for SynType.Fun +[] +type SynTypeFunTrivia = + { + /// The syntax range of the `->` token. + ArrowRange: range + } + +/// Represents additional information for SynMemberDefn.GetSetMember +[] +type SynMemberGetSetTrivia = + { + /// The syntax range of the `with` keyword + WithKeyword: range + + /// The syntax range of the `get` keyword + GetKeyword: range option + + /// The syntax range of the `and` keyword + AndKeyword: range option + + /// The syntax range of the `set` keyword + SetKeyword: range option + } diff --git a/src/Compiler/SyntaxTree/XmlDoc.fs b/src/Compiler/SyntaxTree/XmlDoc.fs index 81caa767298..72c657d2911 100644 --- a/src/Compiler/SyntaxTree/XmlDoc.fs +++ b/src/Compiler/SyntaxTree/XmlDoc.fs @@ -22,13 +22,15 @@ type XmlDoc(unprocessedLines: string[], range: range) = match lines with | [] -> [] | lineA :: rest as lines -> - let lineAT = lineA.TrimStart([|' '|]) - if lineAT = "" then processLines rest - elif lineAT.StartsWithOrdinal("<") then lines + let lineAT = lineA.TrimStart([| ' ' |]) + + if lineAT = "" then + processLines rest + elif lineAT.StartsWithOrdinal("<") then + lines else - [""] @ - (lines |> List.map Internal.Utilities.XmlAdapters.escape) @ - [""] + [ "" ] + @ (lines |> List.map Internal.Utilities.XmlAdapters.escape) @ [ "" ] /// Get the lines before insertion of implicit summary tags and encoding member _.UnprocessedLines = unprocessedLines @@ -45,13 +47,12 @@ type XmlDoc(unprocessedLines: string[], range: range) = static member Empty = XmlDocStatics.Empty - member _.IsEmpty = - unprocessedLines |> Array.forall String.IsNullOrWhiteSpace + member _.IsEmpty = unprocessedLines |> Array.forall String.IsNullOrWhiteSpace member doc.NonEmpty = not doc.IsEmpty static member Merge (doc1: XmlDoc) (doc2: XmlDoc) = - let range = + let range = if doc1.IsEmpty then doc2.Range elif doc2.IsEmpty then doc1.Range else unionRanges doc1.Range doc2.Range @@ -59,17 +60,16 @@ type XmlDoc(unprocessedLines: string[], range: range) = XmlDoc(Array.append doc1.UnprocessedLines doc2.UnprocessedLines, range) member doc.GetXmlText() = - if doc.IsEmpty then "" + if doc.IsEmpty then + "" else - doc.GetElaboratedXmlLines() - |> String.concat Environment.NewLine + doc.GetElaboratedXmlLines() |> String.concat Environment.NewLine member doc.Check(paramNamesOpt: string list option) = try // We must wrap with in order to have only one root element let xml = - XDocument.Parse("\n"+doc.GetXmlText()+"\n", - LoadOptions.SetLineInfo ||| LoadOptions.PreserveWhitespace) + XDocument.Parse("\n" + doc.GetXmlText() + "\n", LoadOptions.SetLineInfo ||| LoadOptions.PreserveWhitespace) // The parameter names are checked for consistency, so parameter references and // parameter documentation must match an actual parameter. In addition, if any parameters @@ -79,93 +79,115 @@ type XmlDoc(unprocessedLines: string[], range: range) = | Some paramNames -> for p in xml.Descendants(XName.op_Implicit "param") do match p.Attribute(XName.op_Implicit "name") with - | null -> - warning (Error (FSComp.SR.xmlDocMissingParameterName(), doc.Range)) + | null -> warning (Error(FSComp.SR.xmlDocMissingParameterName (), doc.Range)) | attr -> let nm = attr.Value + if not (paramNames |> List.contains nm) then - warning (Error (FSComp.SR.xmlDocInvalidParameterName(nm), doc.Range)) + warning (Error(FSComp.SR.xmlDocInvalidParameterName (nm), doc.Range)) let paramsWithDocs = - [ for p in xml.Descendants(XName.op_Implicit "param") do - match p.Attribute(XName.op_Implicit "name") with - | null -> () - | attr -> attr.Value ] + [ + for p in xml.Descendants(XName.op_Implicit "param") do + match p.Attribute(XName.op_Implicit "name") with + | null -> () + | attr -> attr.Value + ] if paramsWithDocs.Length > 0 then for p in paramNames do if not (paramsWithDocs |> List.contains p) then - warning (Error (FSComp.SR.xmlDocMissingParameter(p), doc.Range)) + warning (Error(FSComp.SR.xmlDocMissingParameter (p), doc.Range)) let duplicates = paramsWithDocs |> List.duplicates for d in duplicates do - warning (Error (FSComp.SR.xmlDocDuplicateParameter(d), doc.Range)) + warning (Error(FSComp.SR.xmlDocDuplicateParameter (d), doc.Range)) for pref in xml.Descendants(XName.op_Implicit "paramref") do match pref.Attribute(XName.op_Implicit "name") with - | null -> warning (Error (FSComp.SR.xmlDocMissingParameterName(), doc.Range)) + | null -> warning (Error(FSComp.SR.xmlDocMissingParameterName (), doc.Range)) | attr -> let nm = attr.Value + if not (paramNames |> List.contains nm) then - warning (Error (FSComp.SR.xmlDocInvalidParameterName(nm), doc.Range)) + warning (Error(FSComp.SR.xmlDocInvalidParameterName (nm), doc.Range)) with e -> - warning (Error (FSComp.SR.xmlDocBadlyFormed(e.Message), doc.Range)) + warning (Error(FSComp.SR.xmlDocBadlyFormed (e.Message), doc.Range)) #if CREF_ELABORATION - member doc.Elaborate (crefResolver) = - for see in seq { yield! xml.Descendants(XName.op_Implicit "see") - yield! xml.Descendants(XName.op_Implicit "seealso") - yield! xml.Descendants(XName.op_Implicit "exception") } do - match see.Attribute(XName.op_Implicit "cref") with - | null -> warning (Error (FSComp.SR.xmlDocMissingCrossReference(), doc.Range)) - | attr -> - let cref = attr.Value - if cref.StartsWith("T:") || cref.StartsWith("P:") || cref.StartsWith("M:") || - cref.StartsWith("E:") || cref.StartsWith("F:") then - () - else - match crefResolver cref with - | None -> - warning (Error (FSComp.SR.xmlDocUnresolvedCrossReference(nm), doc.Range)) - | Some text -> - attr.Value <- text - modified <- true - if modified then - let m = doc.Range - let newLines = - [| for e in xml.Elements() do - yield! e.ToString().Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) |] - lines <- newLines + member doc.Elaborate(crefResolver) = + for see in + seq { + yield! xml.Descendants(XName.op_Implicit "see") + yield! xml.Descendants(XName.op_Implicit "seealso") + yield! xml.Descendants(XName.op_Implicit "exception") + } do + match see.Attribute(XName.op_Implicit "cref") with + | null -> warning (Error(FSComp.SR.xmlDocMissingCrossReference (), doc.Range)) + | attr -> + let cref = attr.Value + + if + cref.StartsWith("T:") + || cref.StartsWith("P:") + || cref.StartsWith("M:") + || cref.StartsWith("E:") + || cref.StartsWith("F:") + then + () + else + match crefResolver cref with + | None -> warning (Error(FSComp.SR.xmlDocUnresolvedCrossReference (nm), doc.Range)) + | Some text -> + attr.Value <- text + modified <- true + + if modified then + let m = doc.Range + + let newLines = + [| + for e in xml.Elements() do + yield! e.ToString().Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) + |] + + lines <- newLines #endif // Discriminated unions can't contain statics, so we use a separate type and XmlDocStatics() = - static let empty = XmlDoc ([| |], range0) + static let empty = XmlDoc([||], range0) static member Empty = empty /// Used to collect XML documentation during lexing and parsing. type XmlDocCollector() = let mutable savedLines = ResizeArray() - let mutable savedGrabPoints = Dictionary() + let mutable savedGrabPoints = Dictionary() let mutable currentGrabPointCommentsCount = 0 let mutable delayedGrabPoint = ValueNone member _.AddGrabPoint(pos: pos) = - if currentGrabPointCommentsCount = 0 then () else - let xmlDocBlock = struct(savedLines.Count - currentGrabPointCommentsCount, savedLines.Count - 1, false) - savedGrabPoints.Add(pos, xmlDocBlock) - currentGrabPointCommentsCount <- 0 - delayedGrabPoint <- ValueNone + if currentGrabPointCommentsCount = 0 then + () + else + let xmlDocBlock = + struct (savedLines.Count - currentGrabPointCommentsCount, savedLines.Count - 1, false) + + savedGrabPoints.Add(pos, xmlDocBlock) + currentGrabPointCommentsCount <- 0 + delayedGrabPoint <- ValueNone member _.AddGrabPointDelayed(pos: pos) = - if currentGrabPointCommentsCount = 0 then () else - match delayedGrabPoint with - | ValueNone -> delayedGrabPoint <- ValueSome(pos) - | _ -> () + if currentGrabPointCommentsCount = 0 then + () + else + match delayedGrabPoint with + | ValueNone -> delayedGrabPoint <- ValueSome(pos) + | _ -> () member x.AddXmlDocLine(line, range) = match delayedGrabPoint with @@ -177,16 +199,18 @@ type XmlDocCollector() = member _.LinesBefore grabPointPos = match savedGrabPoints.TryGetValue grabPointPos with - | true, struct(startIndex, endIndex, _) -> + | true, struct (startIndex, endIndex, _) -> let linesBefore = Array.create (endIndex - startIndex + 1) ("", range0) - for i in startIndex .. endIndex do + + for i in startIndex..endIndex do linesBefore[i - startIndex] <- savedLines[i] + linesBefore | false, _ -> [||] member _.LinesRange grabPointPos = match savedGrabPoints.TryGetValue grabPointPos with - | true, struct(startIndex, endIndex, _) -> + | true, struct (startIndex, endIndex, _) -> let startRange = savedLines[startIndex] |> snd let endRange = savedLines[endIndex] |> snd unionRanges startRange endRange @@ -194,8 +218,7 @@ type XmlDocCollector() = member _.SetXmlDocValidity(grabPointPos, isValid) = match savedGrabPoints.TryGetValue grabPointPos with - | true, struct(startIndex, endIndex, _) -> - savedGrabPoints[grabPointPos] <- struct(startIndex, endIndex, isValid) + | true, struct (startIndex, endIndex, _) -> savedGrabPoints[grabPointPos] <- struct (startIndex, endIndex, isValid) | _ -> () member _.HasComments grabPointPos = @@ -205,13 +228,16 @@ type XmlDocCollector() = let comments = ResizeArray(savedLines.Count) for startIndex, endIndex, isValid in savedGrabPoints.Values do - if isValid then () else - let _, startRange = savedLines[startIndex] - let _, endRange = savedLines[endIndex] - let range = unionRanges startRange endRange - informationalWarning (Error(FSComp.SR.invalidXmlDocPosition(), range)) - // Collect invalid triple slash comment ranges, to later transform these to trivia - [ startIndex .. endIndex ] |> List.iter (fun idx -> savedLines[idx] |> snd |> comments.Add) + if isValid then + () + else + let _, startRange = savedLines[startIndex] + let _, endRange = savedLines[endIndex] + let range = unionRanges startRange endRange + informationalWarning (Error(FSComp.SR.invalidXmlDocPosition (), range)) + // Collect invalid triple slash comment ranges, to later transform these to trivia + [ startIndex..endIndex ] + |> List.iter (fun idx -> savedLines[idx] |> snd |> comments.Add) List.ofSeq comments @@ -224,28 +250,28 @@ type PreXmlDoc = member x.ToXmlDoc(check: bool, paramNamesOpt: string list option) = match x with - | PreXmlDirect (lines, m) -> - XmlDoc(lines, m) - | PreXmlMerge(a, b) -> - XmlDoc.Merge (a.ToXmlDoc(check, paramNamesOpt)) (b.ToXmlDoc(check, paramNamesOpt)) - | PreXmlDocEmpty -> - XmlDoc.Empty + | PreXmlDirect (lines, m) -> XmlDoc(lines, m) + | PreXmlMerge (a, b) -> XmlDoc.Merge (a.ToXmlDoc(check, paramNamesOpt)) (b.ToXmlDoc(check, paramNamesOpt)) + | PreXmlDocEmpty -> XmlDoc.Empty | PreXmlDoc (pos, collector) -> let preLines = collector.LinesBefore pos + if preLines.Length = 0 then XmlDoc.Empty else let lines = Array.map fst preLines let m = Array.reduce unionRanges (Array.map snd preLines) - let doc = XmlDoc (lines, m) + let doc = XmlDoc(lines, m) + if check then - doc.Check(paramNamesOpt) + doc.Check(paramNamesOpt) + doc member internal x.Range = match x with | PreXmlDirect (_, m) -> m - | PreXmlMerge(part1, part2) -> + | PreXmlMerge (part1, part2) -> if part1.IsEmpty then part2.Range elif part2.IsEmpty then part1.Range else unionRanges part1.Range part2.Range @@ -255,7 +281,7 @@ type PreXmlDoc = member x.IsEmpty = match x with | PreXmlDirect (lines, _) -> lines |> Array.forall String.IsNullOrWhiteSpace - | PreXmlMerge(a, b) -> a.IsEmpty && b.IsEmpty + | PreXmlMerge (a, b) -> a.IsEmpty && b.IsEmpty | PreXmlDocEmpty -> true | PreXmlDoc (pos, collector) -> not (collector.HasComments pos) @@ -272,7 +298,7 @@ type PreXmlDoc = static member Create(unprocessedLines, range) = PreXmlDirect(unprocessedLines, range) - static member Merge a b = PreXmlMerge (a, b) + static member Merge a b = PreXmlMerge(a, b) [] type XmlDocumentationInfo private (tryGetXmlDocument: unit -> XmlDocument option) = @@ -280,17 +306,22 @@ type XmlDocumentationInfo private (tryGetXmlDocument: unit -> XmlDocument option // 2 and 4 are arbitrary but should be reasonable enough [] static let cacheStrongSize = 2 + [] static let cacheMaxSize = 4 static let cacheAreSimilar ((str1: string, dt1: DateTime), (str2: string, dt2: DateTime)) = - str1.Equals(str2, StringComparison.OrdinalIgnoreCase) && - dt1 = dt2 + str1.Equals(str2, StringComparison.OrdinalIgnoreCase) && dt1 = dt2 - static let cache = AgedLookup(keepStrongly=cacheStrongSize, areSimilar=cacheAreSimilar, keepMax=cacheMaxSize) + static let cache = + AgedLookup( + keepStrongly = cacheStrongSize, + areSimilar = cacheAreSimilar, + keepMax = cacheMaxSize + ) let tryGetSummaryNode xmlDocSig = - tryGetXmlDocument() + tryGetXmlDocument () |> Option.bind (fun doc -> match doc.SelectSingleNode(sprintf "doc/members/member[@name='%s']" xmlDocSig) with | null -> None @@ -302,20 +333,25 @@ type XmlDocumentationInfo private (tryGetXmlDocument: unit -> XmlDocument option |> Option.map (fun node -> let childNodes = node.ChildNodes let lines = Array.zeroCreate childNodes.Count + for i = 0 to childNodes.Count - 1 do let childNode = childNodes[i] lines[i] <- childNode.OuterXml - XmlDoc(lines, range0) - ) + + XmlDoc(lines, range0)) static member TryCreateFromFile(xmlFileName: string) = - if not (FileSystem.FileExistsShim(xmlFileName)) || not (String.Equals(Path.GetExtension(xmlFileName), ".xml", StringComparison.OrdinalIgnoreCase)) then + if + not (FileSystem.FileExistsShim(xmlFileName)) + || not (String.Equals(Path.GetExtension(xmlFileName), ".xml", StringComparison.OrdinalIgnoreCase)) + then None else let tryGetXmlDocument () = try let lastWriteTime = FileSystem.GetLastWriteTimeShim(xmlFileName) let cacheKey = (xmlFileName, lastWriteTime) + match cache.TryGet((), cacheKey) with | Some doc -> Some doc | _ -> @@ -326,6 +362,7 @@ type XmlDocumentationInfo private (tryGetXmlDocument: unit -> XmlDocument option Some doc with _ -> None + Some(XmlDocumentationInfo(tryGetXmlDocument)) type IXmlDocumentationInfoLoader = diff --git a/src/Compiler/TypedTree/TcGlobals.fs b/src/Compiler/TypedTree/TcGlobals.fs index 28000926c3a..1e35881ec44 100755 --- a/src/Compiler/TypedTree/TcGlobals.fs +++ b/src/Compiler/TypedTree/TcGlobals.fs @@ -565,8 +565,8 @@ type TcGlobals( let tryDecodeTupleTy tupInfo l = match l with - | [t1;t2;t3;t4;t5;t6;t7;marker] -> - match marker with + | [t1;t2;t3;t4;t5;t6;t7;markerTy] -> + match markerTy with | TType_app(tcref, [t8], _) when tyconRefEq tcref v_ref_tuple1_tcr -> mkRawRefTupleTy [t1;t2;t3;t4;t5;t6;t7;t8] |> Some | TType_app(tcref, [t8], _) when tyconRefEq tcref v_struct_tuple1_tcr -> mkRawStructTupleTy [t1;t2;t3;t4;t5;t6;t7;t8] |> Some | TType_tuple (_structness2, t8plus) -> TType_tuple (tupInfo, [t1;t2;t3;t4;t5;t6;t7] @ t8plus) |> Some @@ -1835,11 +1835,11 @@ type TcGlobals( let info = makeOtherIntrinsicValRef (fslib_MFOperators_nleref, lower, None, Some nm, [vara], ([[varaTy]], varaTy)) let tyargs = [aty] Some (info, tyargs, argExprs) - | "get_Item", [arrTy; _], Some rty, [_; _] when isArrayTy g arrTy -> - Some (g.array_get_info, [rty], argExprs) - | "set_Item", [arrTy; _; ety], _, [_; _; _] when isArrayTy g arrTy -> - Some (g.array_set_info, [ety], argExprs) - | "get_Item", [sty; _; _], _, [_; _] when isStringTy g sty -> + | "get_Item", [arrTy; _], Some retTy, [_; _] when isArrayTy g arrTy -> + Some (g.array_get_info, [retTy], argExprs) + | "set_Item", [arrTy; _; elemTy], _, [_; _; _] when isArrayTy g arrTy -> + Some (g.array_set_info, [elemTy], argExprs) + | "get_Item", [stringTy; _; _], _, [_; _] when isStringTy g stringTy -> Some (g.getstring_info, [], argExprs) | "op_UnaryPlus", [aty], _, [_] -> // Call Operators.id diff --git a/src/Compiler/TypedTree/TypedTree.fs b/src/Compiler/TypedTree/TypedTree.fs index 191d658f371..d71fd222745 100644 --- a/src/Compiler/TypedTree/TypedTree.fs +++ b/src/Compiler/TypedTree/TypedTree.fs @@ -481,7 +481,10 @@ type ModuleOrNamespaceKind = | ModuleOrType /// Indicates that a 'module' is really a namespace - | Namespace + | Namespace of + /// Indicates that the sourcecode had a namespace. + /// If false, this namespace was implicitly constructed during type checking. + isExplicit: bool /// A public path records where a construct lives within the global namespace /// of a CCU. @@ -867,10 +870,13 @@ type Entity = member x.IsModuleOrNamespace = x.entity_flags.IsModuleOrNamespace /// Indicates if the entity is a namespace - member x.IsNamespace = x.IsModuleOrNamespace && (match x.ModuleOrNamespaceType.ModuleOrNamespaceKind with Namespace -> true | _ -> false) + member x.IsNamespace = x.IsModuleOrNamespace && (match x.ModuleOrNamespaceType.ModuleOrNamespaceKind with Namespace _ -> true | _ -> false) + + /// Indicates if the entity has an implicit namespace + member x.IsImplicitNamespace = (match x.ModuleOrNamespaceType.ModuleOrNamespaceKind with Namespace false -> true | _ -> false) /// Indicates if the entity is an F# module definition - member x.IsModule = x.IsModuleOrNamespace && (match x.ModuleOrNamespaceType.ModuleOrNamespaceKind with Namespace -> false | _ -> true) + member x.IsModule = x.IsModuleOrNamespace && (match x.ModuleOrNamespaceType.ModuleOrNamespaceKind with Namespace _ -> false | _ -> true) #if !NO_TYPEPROVIDERS /// Indicates if the entity is a provided type or namespace definition @@ -1150,7 +1156,7 @@ type Entity = member x.MembersOfFSharpTyconSorted = x.TypeContents.tcaug_adhoc |> NameMultiMap.rangeReversingEachBucket - |> List.filter (fun v -> not v.IsCompilerGenerated) + |> List.filter (fun vref -> not vref.IsCompilerGenerated) /// Gets all immediate members of an F# type definition keyed by name, including compiler-generated ones. /// Note: result is a indexed table, and for each name the results are in reverse declaration order @@ -1173,16 +1179,16 @@ type Entity = member x.AllGeneratedValues = [ match x.GeneratedCompareToValues with | None -> () - | Some (v1, v2) -> yield v1; yield v2 + | Some (vref1, vref2) -> yield vref1; yield vref2 match x.GeneratedCompareToWithComparerValues with | None -> () | Some v -> yield v match x.GeneratedHashAndEqualsValues with | None -> () - | Some (v1, v2) -> yield v1; yield v2 + | Some (vref1, vref2) -> yield vref1; yield vref2 match x.GeneratedHashAndEqualsWithComparerValues with | None -> () - | Some (v1, v2, v3) -> yield v1; yield v2; yield v3 ] + | Some (vref1, vref2, vref3) -> yield vref1; yield vref2; yield vref3 ] /// Gets the data indicating the compiled representation of a type or module in terms of Abstract IL data structures. @@ -2482,6 +2488,9 @@ type ValOptionalData = /// Used to implement [] mutable val_defn: Expr option + /// Records the "extra information" for a value compiled as a method (rather + /// than a closure or a local), including argument names, attributes etc. + // // MUTABILITY CLEANUP: mutability of this field is used by // -- adjustAllUsesOfRecValue // -- TLR optimizations @@ -2491,6 +2500,10 @@ type ValOptionalData = // type-checked expression. mutable val_repr_info: ValReprInfo option + /// Records the "extra information" for display purposes for expression-level function definitions + /// that may be compiled as closures (that is are not necessarily compiled as top-level methods). + mutable val_repr_info_for_display: ValReprInfo option + /// How visible is this? /// MUTABILITY: for unpickle linkage mutable val_access: Accessibility @@ -2550,6 +2563,7 @@ type Val = val_const = None val_defn = None val_repr_info = None + val_repr_info_for_display = None val_access = TAccess [] val_xmldoc = XmlDoc.Empty val_member_info = None @@ -2614,6 +2628,11 @@ type Val = | Some optData -> optData.val_repr_info | _ -> None + member x.ValReprInfoForDisplay: ValReprInfo option = + match x.val_opt_data with + | Some optData -> optData.val_repr_info_for_display + | _ -> None + member x.Id = ident(x.LogicalName, x.Range) /// Is this represented as a "top level" static binding (i.e. a static field, static member, @@ -2992,6 +3011,11 @@ type Val = | Some optData -> optData.val_repr_info <- info | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_repr_info = info } + member x.SetValReprInfoForDisplay info = + match x.val_opt_data with + | Some optData -> optData.val_repr_info_for_display <- info + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_repr_info_for_display = info } + member x.SetType ty = x.val_type <- ty member x.SetOtherRange m = @@ -3049,6 +3073,7 @@ type Val = val_other_range = tg.val_other_range val_const = tg.val_const val_defn = tg.val_defn + val_repr_info_for_display = tg.val_repr_info_for_display val_repr_info = tg.val_repr_info val_access = tg.val_access val_xmldoc = tg.val_xmldoc @@ -3206,12 +3231,12 @@ type NonLocalEntityRef = entity.ModuleOrNamespaceType.AddProvidedTypeEntity newEntity newEntity else - let cpath = entity.CompilationPath.NestedCompPath entity.LogicalName ModuleOrNamespaceKind.Namespace + let cpath = entity.CompilationPath.NestedCompPath entity.LogicalName (ModuleOrNamespaceKind.Namespace false) let newEntity = Construct.NewModuleOrNamespace (Some cpath) (TAccess []) (ident(path[k], m)) XmlDoc.Empty [] - (MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType Namespace)) + (MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType (Namespace true))) entity.ModuleOrNamespaceType.AddModuleOrNamespaceByMutation newEntity injectNamespacesFromIToJ newEntity (k+1) let newEntity = injectNamespacesFromIToJ entity i @@ -3695,32 +3720,32 @@ type ValRef = member x.ResolvedTarget = x.binding /// Dereference the ValRef to a Val. - member vr.Deref = - if obj.ReferenceEquals(vr.binding, null) then + member x.Deref = + if obj.ReferenceEquals(x.binding, null) then let res = - let nlr = vr.nlr + let nlr = x.nlr let e = nlr.EnclosingEntity.Deref let possible = e.ModuleOrNamespaceType.TryLinkVal(nlr.EnclosingEntity.nlr.Ccu, nlr.ItemKey) match possible with | ValueNone -> error (InternalUndefinedItemRef (FSComp.SR.tastUndefinedItemRefVal, e.DisplayNameWithStaticParameters, nlr.AssemblyName, sprintf "%+A" nlr.ItemKey.PartialKey)) | ValueSome h -> h - vr.binding <- nullableSlotFull res + x.binding <- nullableSlotFull res res - else vr.binding + else x.binding /// Dereference the ValRef to a Val option. - member vr.TryDeref = - if obj.ReferenceEquals(vr.binding, null) then + member x.TryDeref = + if obj.ReferenceEquals(x.binding, null) then let resOpt = - match vr.nlr.EnclosingEntity.TryDeref with + match x.nlr.EnclosingEntity.TryDeref with | ValueNone -> ValueNone - | ValueSome e -> e.ModuleOrNamespaceType.TryLinkVal(vr.nlr.EnclosingEntity.nlr.Ccu, vr.nlr.ItemKey) + | ValueSome e -> e.ModuleOrNamespaceType.TryLinkVal(x.nlr.EnclosingEntity.nlr.Ccu, x.nlr.ItemKey) match resOpt with | ValueNone -> () | ValueSome res -> - vr.binding <- nullableSlotFull res + x.binding <- nullableSlotFull res resOpt - else ValueSome vr.binding + else ValueSome x.binding /// The type of the value. May be a TType_forall for a generic value. /// May be a type variable or type containing type variables during type inference. @@ -3917,7 +3942,7 @@ type ValRef = /// Represents a reference to a case of a union type [] type UnionCaseRef = - | UnionCaseRef of TyconRef * string + | UnionCaseRef of tyconRef: TyconRef * caseName: string /// Get a reference to the type containing this union case member x.TyconRef = let (UnionCaseRef(tcref, _)) = x in tcref @@ -3976,7 +4001,7 @@ type UnionCaseRef = /// Represents a reference to a field in a record, class or struct [] type RecdFieldRef = - | RecdFieldRef of tcref: TyconRef * id: string + | RecdFieldRef of tyconRef: TyconRef * fieldName: string /// Get a reference to the type containing this union case member x.TyconRef = let (RecdFieldRef(tcref, _)) = x in tcref @@ -4073,7 +4098,7 @@ type TType = | TType_anon (anonInfo, _tinst) -> defaultArg anonInfo.Assembly.QualifiedName "" | TType_fun _ -> "" | TType_measure _ -> "" - | TType_var (tp, _) -> tp.Solution |> function Some sln -> sln.GetAssemblyName() | None -> "" + | TType_var (tp, _) -> tp.Solution |> function Some slnTy -> slnTy.GetAssemblyName() | None -> "" | TType_ucase (_uc, _tinst) -> let (TILObjectReprData(scope, _nesting, _definition)) = _uc.Tycon.ILTyconInfo scope.QualifiedName @@ -4095,7 +4120,7 @@ type TType = | TupInfo.Const false -> "" | TupInfo.Const true -> "struct ") + "{|" + String.concat "," (Seq.map2 (fun nm ty -> nm + " " + string ty + ";") anonInfo.SortedNames tinst) + ")" + "|}" - | TType_fun (d, r, _) -> "(" + string d + " -> " + string r + ")" + | TType_fun (domainTy, retTy, _) -> "(" + string domainTy + " -> " + string retTy + ")" | TType_ucase (uc, tinst) -> "ucase " + uc.CaseName + (match tinst with [] -> "" | tys -> "<" + String.concat "," (List.map string tys) + ">") | TType_var (tp, _) -> match tp.Solution with @@ -4172,7 +4197,7 @@ type Measure = | Var of typar: Typar /// A constant, leaf unit-of-measure such as 'kg' or 'm' - | Con of tyconRef: TyconRef + | Const of tyconRef: TyconRef /// A product of two units of measure | Prod of measure1: Measure * measure2: Measure @@ -5036,7 +5061,7 @@ type ObjExprMethod = type SlotSig = | TSlotSig of methodName: string * - implementedType: TType * + declaringType: TType * classTypars: Typars * methodTypars: Typars * formalParams: SlotParam list list * @@ -5046,7 +5071,7 @@ type SlotSig = member ss.Name = let (TSlotSig(nm, _, _, _, _, _)) = ss in nm /// The (instantiated) type which the slot is logically a part of - member ss.ImplementedType = let (TSlotSig(_, ty, _, _, _, _)) = ss in ty + member ss.DeclaringType = let (TSlotSig(_, ty, _, _, _, _)) = ss in ty /// The class type parameters of the slot member ss.ClassTypars = let (TSlotSig(_, _, ctps, _, _, _)) = ss in ctps @@ -5666,7 +5691,7 @@ type Construct() = | None -> let ilScopeRef = st.TypeProviderAssemblyRef let enclosingName = GetFSharpPathToProvidedType(st, m) - CompPath(ilScopeRef, enclosingName |> List.map(fun id->id, ModuleOrNamespaceKind.Namespace)) + CompPath(ilScopeRef, enclosingName |> List.map(fun id->id, ModuleOrNamespaceKind.Namespace true)) | Some p -> p let pubpath = cpath.NestedPublicPath id @@ -5681,7 +5706,7 @@ type Construct() = entity_typars= LazyWithContext.NotLazy [] entity_tycon_repr = repr entity_tycon_tcaug=TyconAugmentation.Create() - entity_modul_type = MaybeLazy.Lazy (lazy ModuleOrNamespaceType(Namespace, QueueList.ofList [], QueueList.ofList [])) + entity_modul_type = MaybeLazy.Lazy (lazy ModuleOrNamespaceType(Namespace true, QueueList.ofList [], QueueList.ofList [])) // Generated types get internal accessibility entity_pubpath = Some pubpath entity_cpath = Some cpath diff --git a/src/Compiler/TypedTree/TypedTree.fsi b/src/Compiler/TypedTree/TypedTree.fsi index e7085c99a0b..57037ba27d8 100644 --- a/src/Compiler/TypedTree/TypedTree.fsi +++ b/src/Compiler/TypedTree/TypedTree.fsi @@ -301,7 +301,10 @@ type ModuleOrNamespaceKind = | ModuleOrType /// Indicates that a 'module' is really a namespace - | Namespace + | Namespace of + /// Indicates that the sourcecode had a namespace. + /// If false, this namespace was implicitly constructed during type checking. + isExplicit: bool /// A public path records where a construct lives within the global namespace /// of a CCU. @@ -641,9 +644,13 @@ type Entity = /// Indicates if the entity is a namespace member IsNamespace: bool + /// Indicates if the entity has an implicit namespace + member IsImplicitNamespace: bool + /// Indicates the type prefers the "tycon" syntax for display etc. member IsPrefixDisplay: bool +#if !NO_TYPEPROVIDERS /// Indicates if the entity is a provided type or namespace definition member IsProvided: bool @@ -655,11 +662,14 @@ type Entity = /// Indicates if the entity is a provided namespace fragment member IsProvidedNamespace: bool +#endif /// Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. member IsRecordTycon: bool +#if !NO_TYPEPROVIDERS member IsStaticInstantiationTycon: bool +#endif /// Indicates if this is a struct or enum type definition, i.e. a value type definition member IsStructOrEnumTycon: bool @@ -875,6 +885,7 @@ type TyconRepresentation = /// Indicates the type is parameterized on a measure (e.g. float<_>) but erases to some other type (e.g. float) | TMeasureableRepr of TType +#if !NO_TYPEPROVIDERS /// TProvidedTypeRepr /// /// Indicates the representation information for a provided type. @@ -882,6 +893,7 @@ type TyconRepresentation = /// Indicates the representation information for a provided namespace. | TProvidedNamespaceRepr of ResolutionEnvironment * Tainted list +#endif /// The 'NoRepr' value here has four meanings: /// (1) it indicates 'not yet known' during the first 2 phases of establishing type definitions @@ -904,6 +916,8 @@ type TILObjectReprData = [] member DebugText: string +#if !NO_TYPEPROVIDERS + /// The information kept about a provided type [] type TProvidedTypeInfo = @@ -965,6 +979,8 @@ type TProvidedTypeInfo = /// Indicates if the provided type is generated, i.e. not erased member IsGenerated: bool +#endif + type TyconFSharpObjModelKind = /// Indicates the type is an F#-declared class (also used for units-of-measure) @@ -1302,8 +1318,10 @@ type ModuleOrNamespaceType = /// Mutation used during compilation of FSharp.Core.dll member AddModuleOrNamespaceByMutation: modul: ModuleOrNamespace -> unit +#if !NO_TYPEPROVIDERS /// Mutation used in hosting scenarios to hold the hosted types in this module or namespace member AddProvidedTypeEntity: entity: Entity -> unit +#endif /// Return a new module or namespace type with a value added. member AddVal: vspec: Val -> ModuleOrNamespaceType @@ -1759,8 +1777,15 @@ type ValOptionalData = /// What is the original, unoptimized, closed-term definition, if any? /// Used to implement [] mutable val_defn: Expr option + + /// Records the "extra information" for a value compiled as a method (rather + /// than a closure or a local), including argument names, attributes etc. mutable val_repr_info: ValReprInfo option + /// Records the "extra information" for display purposes for expression-level function definitions + /// that may be compiled as closures (that is are not necessarily compiled as top-level methods). + mutable val_repr_info_for_display: ValReprInfo option + /// How visible is this? /// MUTABILITY: for unpickle linkage mutable val_access: Accessibility @@ -1870,6 +1895,8 @@ type Val = member SetValReprInfo: info: ValReprInfo option -> unit + member SetValReprInfoForDisplay: info: ValReprInfo option -> unit + override ToString: unit -> string /// How visible is this value, function or member? @@ -2116,6 +2143,10 @@ type Val = /// represent as "top level" bindings. member ValReprInfo: ValReprInfo option + /// Records the "extra information" for display purposes for expression-level function definitions + /// that may be compiled as closures (that is are not necessarily compiled as top-level methods). + member ValReprInfoForDisplay: ValReprInfo option + /// Get the declared documentation for the value member XmlDoc: XmlDoc @@ -2186,9 +2217,11 @@ type NonLocalEntityRef = /// Try to find the entity corresponding to the given path in the given CCU static member TryDerefEntityPath: ccu: CcuThunk * path: string[] * i: int * entity: Entity -> Entity voption +#if !NO_TYPEPROVIDERS /// Try to find the entity corresponding to the given path, using type-providers to link the data static member TryDerefEntityPathViaProvidedType: ccu: CcuThunk * path: string[] * i: int * entity: Entity -> Entity voption +#endif override ToString: unit -> string @@ -2440,6 +2473,7 @@ type EntityRef = /// Indicates the type prefers the "tycon" syntax for display etc. member IsPrefixDisplay: bool +#if !NO_TYPEPROVIDERS /// Indicates if the entity is a provided namespace fragment member IsProvided: bool @@ -2451,6 +2485,7 @@ type EntityRef = /// Indicates if the entity is a provided namespace fragment member IsProvidedNamespace: bool +#endif /// Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. member IsRecordTycon: bool @@ -2458,8 +2493,10 @@ type EntityRef = /// Indicates if the reference has been resolved member IsResolved: bool +#if !NO_TYPEPROVIDERS /// Indicates if the entity is an erased provided type definition that incorporates a static instantiation (type therefore in some sense compiler generated) member IsStaticInstantiationTycon: bool +#endif /// Indicates if this is a struct or enum type definition, i.e. a value type definition member IsStructOrEnumTycon: bool @@ -2781,7 +2818,7 @@ type ValRef = /// Represents a reference to a case of a union type [] type UnionCaseRef = - | UnionCaseRef of TyconRef * string + | UnionCaseRef of tyconRef: TyconRef * caseName: string /// Get a field of the union case by index member FieldByIndex: n: int -> RecdField @@ -2830,7 +2867,7 @@ type UnionCaseRef = /// Represents a reference to a field in a record, class or struct [] type RecdFieldRef = - | RecdFieldRef of tcref: TyconRef * id: string + | RecdFieldRef of tyconRef: TyconRef * fieldName: string override ToString: unit -> string @@ -2953,7 +2990,7 @@ type Measure = | Var of typar: Typar /// A constant, leaf unit-of-measure such as 'kg' or 'm' - | Con of tyconRef: TyconRef + | Const of tyconRef: TyconRef /// A product of two units of measure | Prod of measure1: Measure * measure2: Measure @@ -3651,7 +3688,7 @@ type ObjExprMethod = type SlotSig = | TSlotSig of methodName: string * - implementedType: TType * + declaringType: TType * classTypars: Typars * methodTypars: Typars * formalParams: SlotParam list list * @@ -3672,7 +3709,7 @@ type SlotSig = member FormalReturnType: TType option /// The (instantiated) type which the slot is logically a part of - member ImplementedType: TType + member DeclaringType: TType /// The method type parameters of the slot member MethodTypars: Typars @@ -3861,6 +3898,7 @@ type CcuData = /// Indicates that this DLL was compiled using the F# compiler type has F# metadata IsFSharp: bool +#if !NO_TYPEPROVIDERS /// Is the CCu an assembly injected by a type provider IsProviderGenerated: bool @@ -3870,6 +3908,7 @@ type CcuData = /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality /// logic in tastops.fs ImportProvidedType: Tainted -> TType +#endif /// Indicates that this DLL uses pre-F#-4.0 quotation literals somewhere. This is used to implement a restriction on static linking mutable UsesFSharp20PlusQuotations: bool @@ -3938,8 +3977,10 @@ type CcuThunk = /// Fixup a CCU to have the given contents member Fixup: avail: CcuThunk -> unit +#if !NO_TYPEPROVIDERS /// Used to make 'forward' calls into the loader during linking member ImportProvidedType: ty: Tainted -> TType +#endif /// Used to make forward calls into the type/assembly loader when comparing member signatures during linking member MemberSignatureEquality: ty1: TType * ty2: TType -> bool @@ -3974,8 +4015,10 @@ type CcuThunk = /// Indicates that this DLL was compiled using the F# compiler type has F# metadata member IsFSharp: bool +#if !NO_TYPEPROVIDERS /// Is this a provider-injected assembly member IsProviderGenerated: bool +#endif /// Indicates if this assembly reference is unresolved member IsUnresolvedReference: bool @@ -4114,9 +4157,11 @@ type Construct = new: unit -> Construct +#if !NO_TYPEPROVIDERS /// Compute the definition location of a provided item static member ComputeDefinitionLocationOfProvidedItem: p: Tainted<#IProvidedCustomAttributeProvider> -> Text.range option +#endif /// Key a Tycon or TyconRef by both mangled type demangled name. /// Generic types can be accessed either by 'List' or 'List`1'. @@ -4201,6 +4246,7 @@ type Construct = static member NewModuleOrNamespaceType: mkind: ModuleOrNamespaceKind -> tycons: Entity list -> vals: Val list -> ModuleOrNamespaceType +#if !NO_TYPEPROVIDERS /// Create a new entity node for a provided type definition static member NewProvidedTycon: resolutionEnvironment: ResolutionEnvironment * @@ -4220,6 +4266,7 @@ type Construct = isSuppressRelocate: bool * m: Text.range -> TyconRepresentation +#endif /// Create a new TAST RecdField node for an F# class, struct or record field static member NewRecdField: diff --git a/src/Compiler/TypedTree/TypedTreeBasics.fs b/src/Compiler/TypedTree/TypedTreeBasics.fs index b0020664ff7..63a45fb9b9a 100644 --- a/src/Compiler/TypedTree/TypedTreeBasics.fs +++ b/src/Compiler/TypedTree/TypedTreeBasics.fs @@ -26,7 +26,7 @@ let getNameOfScopeRef sref = | ILScopeRef.Assembly aref -> aref.Name | ILScopeRef.PrimaryAssembly -> "" -/// Metadata on values (names of arguments etc. +/// Metadata on values (names of arguments etc.) module ValReprInfo = let unnamedTopArg1: ArgReprInfo = { Attribs=[]; Name=None } @@ -41,6 +41,11 @@ module ValReprInfo = let emptyValData = ValReprInfo([], [], unnamedRetVal) + let IsEmpty info = + match info with + | ValReprInfo([], [], { Attribs = []; Name=None }) -> true + | _ -> false + let InferTyparInfo (tps: Typar list) = tps |> List.map (fun tp -> TyparReprInfo(tp.Id, tp.Kind)) let InferArgReprInfo (v: Val) : ArgReprInfo = { Attribs = []; Name= Some v.Id } @@ -59,7 +64,18 @@ let typesOfVals (v: Val list) = v |> List.map (fun v -> v.Type) let nameOfVal (v: Val) = v.LogicalName -let arityOfVal (v: Val) = (match v.ValReprInfo with None -> ValReprInfo.emptyValData | Some arities -> arities) +let arityOfVal (v: Val) = + match v.ValReprInfo with + | None -> ValReprInfo.emptyValData + | Some info -> info + +let arityOfValForDisplay (v: Val) = + match v.ValReprInfoForDisplay with + | Some info -> info + | None -> + match v.ValReprInfo with + | None -> ValReprInfo.emptyValData + | Some info -> info let tupInfoRef = TupInfo.Const false @@ -77,24 +93,24 @@ let mkRawStructTupleTy tys = TType_tuple (tupInfoStruct, tys) // Equality relations on locally defined things //--------------------------------------------------------------------------- -let typarEq (lv1: Typar) (lv2: Typar) = (lv1.Stamp = lv2.Stamp) +let typarEq (tp1: Typar) (tp2: Typar) = (tp1.Stamp = tp2.Stamp) /// Equality on type variables, implemented as reference equality. This should be equivalent to using typarEq. let typarRefEq (tp1: Typar) (tp2: Typar) = (tp1 === tp2) /// Equality on value specs, implemented as reference equality -let valEq (lv1: Val) (lv2: Val) = (lv1 === lv2) +let valEq (v1: Val) (v2: Val) = (v1 === v2) /// Equality on CCU references, implemented as reference equality except when unresolved -let ccuEq (mv1: CcuThunk) (mv2: CcuThunk) = - (mv1 === mv2) || - (if mv1.IsUnresolvedReference || mv2.IsUnresolvedReference then - mv1.AssemblyName = mv2.AssemblyName +let ccuEq (ccu1: CcuThunk) (ccu2: CcuThunk) = + (ccu1 === ccu2) || + (if ccu1.IsUnresolvedReference || ccu2.IsUnresolvedReference then + ccu1.AssemblyName = ccu2.AssemblyName else - mv1.Contents === mv2.Contents) + ccu1.Contents === ccu2.Contents) /// For dereferencing in the middle of a pattern -let (|ValDeref|) (vr: ValRef) = vr.Deref +let (|ValDeref|) (vref: ValRef) = vref.Deref //-------------------------------------------------------------------------- // Make references to TAST items diff --git a/src/Compiler/TypedTree/TypedTreeBasics.fsi b/src/Compiler/TypedTree/TypedTreeBasics.fsi index 246a9e74baa..e739aec4062 100644 --- a/src/Compiler/TypedTree/TypedTreeBasics.fsi +++ b/src/Compiler/TypedTree/TypedTreeBasics.fsi @@ -29,6 +29,8 @@ module ValReprInfo = val emptyValData: ValReprInfo + val IsEmpty: ValReprInfo -> bool + val InferTyparInfo: tps: Typar list -> TyparReprInfo list val InferArgReprInfo: v: Val -> ArgReprInfo @@ -45,6 +47,8 @@ val nameOfVal: v: Val -> string val arityOfVal: v: Val -> ValReprInfo +val arityOfValForDisplay: v: Val -> ValReprInfo + val tupInfoRef: TupInfo val tupInfoStruct: TupInfo @@ -57,19 +61,19 @@ val mkRawRefTupleTy: tys: TTypes -> TType val mkRawStructTupleTy: tys: TTypes -> TType -val typarEq: lv1: Typar -> lv2: Typar -> bool +val typarEq: tp1: Typar -> tp2: Typar -> bool /// Equality on type variables, implemented as reference equality. This should be equivalent to using typarEq. val typarRefEq: tp1: Typar -> tp2: Typar -> bool /// Equality on value specs, implemented as reference equality -val valEq: lv1: Val -> lv2: Val -> bool +val valEq: v1: Val -> v2: Val -> bool /// Equality on CCU references, implemented as reference equality except when unresolved -val ccuEq: mv1: CcuThunk -> mv2: CcuThunk -> bool +val ccuEq: ccu1: CcuThunk -> ccu2: CcuThunk -> bool /// For dereferencing in the middle of a pattern -val (|ValDeref|): vr: ValRef -> Val +val (|ValDeref|): vref: ValRef -> Val val mkRecdFieldRef: tcref: TyconRef -> f: string -> RecdFieldRef diff --git a/src/Compiler/TypedTree/TypedTreeOps.fs b/src/Compiler/TypedTree/TypedTreeOps.fs index caaff282912..8229107c74a 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.fs @@ -45,32 +45,32 @@ type TyparMap<'T> = | TPMap of StampMap<'T> member tm.Item - with get (v: Typar) = + with get (tp: Typar) = let (TPMap m) = tm - m[v.Stamp] + m[tp.Stamp] - member tm.ContainsKey (v: Typar) = + member tm.ContainsKey (tp: Typar) = let (TPMap m) = tm - m.ContainsKey(v.Stamp) + m.ContainsKey(tp.Stamp) - member tm.TryFind (v: Typar) = + member tm.TryFind (tp: Typar) = let (TPMap m) = tm - m.TryFind(v.Stamp) + m.TryFind(tp.Stamp) - member tm.Add (v: Typar, x) = + member tm.Add (tp: Typar, x) = let (TPMap m) = tm - TPMap (m.Add(v.Stamp, x)) + TPMap (m.Add(tp.Stamp, x)) static member Empty: TyparMap<'T> = TPMap Map.empty [] type TyconRefMap<'T>(imap: StampMap<'T>) = - member m.Item with get (v: TyconRef) = imap[v.Stamp] - member m.TryFind (v: TyconRef) = imap.TryFind v.Stamp - member m.ContainsKey (v: TyconRef) = imap.ContainsKey v.Stamp - member m.Add (v: TyconRef) x = TyconRefMap (imap.Add (v.Stamp, x)) - member m.Remove (v: TyconRef) = TyconRefMap (imap.Remove v.Stamp) - member m.IsEmpty = imap.IsEmpty + member _.Item with get (tcref: TyconRef) = imap[tcref.Stamp] + member _.TryFind (tcref: TyconRef) = imap.TryFind tcref.Stamp + member _.ContainsKey (tcref: TyconRef) = imap.ContainsKey tcref.Stamp + member _.Add (tcref: TyconRef) x = TyconRefMap (imap.Add (tcref.Stamp, x)) + member _.Remove (tcref: TyconRef) = TyconRefMap (imap.Remove tcref.Stamp) + member _.IsEmpty = imap.IsEmpty static member Empty: TyconRefMap<'T> = TyconRefMap Map.empty static member OfList vs = (vs, TyconRefMap<'T>.Empty) ||> List.foldBack (fun (x, y) acc -> acc.Add x y) @@ -79,14 +79,14 @@ type TyconRefMap<'T>(imap: StampMap<'T>) = [] type ValMap<'T>(imap: StampMap<'T>) = - member m.Contents = imap - member m.Item with get (v: Val) = imap[v.Stamp] - member m.TryFind (v: Val) = imap.TryFind v.Stamp - member m.ContainsVal (v: Val) = imap.ContainsKey v.Stamp - member m.Add (v: Val) x = ValMap (imap.Add(v.Stamp, x)) - member m.Remove (v: Val) = ValMap (imap.Remove(v.Stamp)) + member _.Contents = imap + member _.Item with get (v: Val) = imap[v.Stamp] + member _.TryFind (v: Val) = imap.TryFind v.Stamp + member _.ContainsVal (v: Val) = imap.ContainsKey v.Stamp + member _.Add (v: Val) x = ValMap (imap.Add(v.Stamp, x)) + member _.Remove (v: Val) = ValMap (imap.Remove(v.Stamp)) static member Empty = ValMap<'T> Map.empty - member m.IsEmpty = imap.IsEmpty + member _.IsEmpty = imap.IsEmpty static member OfList vs = (vs, ValMap<'T>.Empty) ||> List.foldBack (fun (x, y) acc -> acc.Add x y) //-------------------------------------------------------------------------- @@ -207,11 +207,11 @@ let rec remapTypeAux (tyenv: Remap) (ty: TType) = if tupInfo === tupInfoR && l === lR then ty else TType_tuple (tupInfoR, lR) - | TType_fun (d, r, flags) as ty -> - let dR = remapTypeAux tyenv d - let rR = remapTypeAux tyenv r - if d === dR && r === rR then ty else - TType_fun (dR, rR, flags) + | TType_fun (domainTy, rangeTy, flags) as ty -> + let domainTyR = remapTypeAux tyenv domainTy + let retTyR = remapTypeAux tyenv rangeTy + if domainTy === domainTyR && rangeTy === retTyR then ty else + TType_fun (domainTyR, retTyR, flags) | TType_forall (tps, ty) -> let tpsR, tyenv = copyAndRemapAndBindTypars tyenv tps @@ -224,9 +224,9 @@ let rec remapTypeAux (tyenv: Remap) (ty: TType) = and remapMeasureAux tyenv unt = match unt with | Measure.One -> unt - | Measure.Con tcref -> + | Measure.Const tcref -> match tyenv.tyconRefRemap.TryFind tcref with - | Some tcref -> Measure.Con tcref + | Some tcref -> Measure.Const tcref | None -> unt | Measure.Prod(u1, u2) -> Measure.Prod(remapMeasureAux tyenv u1, remapMeasureAux tyenv u2) | Measure.RationalPower(u, q) -> Measure.RationalPower(remapMeasureAux tyenv u, q) @@ -235,8 +235,8 @@ and remapMeasureAux tyenv unt = match tp.Solution with | None -> match ListAssoc.tryFind typarEq tp tyenv.tpinst with - | Some v -> - match v with + | Some tpTy -> + match tpTy with | TType_measure unt -> unt | _ -> failwith "remapMeasureAux: incorrect kinds" | None -> unt @@ -257,10 +257,10 @@ and remapTyparConstraintsAux tyenv cs = Some(TyparConstraint.MayResolveMember (remapTraitInfo tyenv traitInfo, m)) | TyparConstraint.DefaultsTo(priority, ty, m) -> Some(TyparConstraint.DefaultsTo(priority, remapTypeAux tyenv ty, m)) - | TyparConstraint.IsEnum(uty, m) -> - Some(TyparConstraint.IsEnum(remapTypeAux tyenv uty, m)) - | TyparConstraint.IsDelegate(uty1, uty2, m) -> - Some(TyparConstraint.IsDelegate(remapTypeAux tyenv uty1, remapTypeAux tyenv uty2, m)) + | TyparConstraint.IsEnum(underlyingTy, m) -> + Some(TyparConstraint.IsEnum(remapTypeAux tyenv underlyingTy, m)) + | TyparConstraint.IsDelegate(argTys, retTy, m) -> + Some(TyparConstraint.IsDelegate(remapTypeAux tyenv argTys, remapTypeAux tyenv retTy, m)) | TyparConstraint.SimpleChoice(tys, m) -> Some(TyparConstraint.SimpleChoice(remapTypesAux tyenv tys, m)) | TyparConstraint.SupportsComparison _ @@ -443,7 +443,7 @@ let reduceTyconRefAbbrevMeasureable (tcref: TyconRef) = let rec stripUnitEqnsFromMeasureAux canShortcut unt = match stripUnitEqnsAux canShortcut unt with - | Measure.Con tcref when tcref.IsTypeAbbrev -> + | Measure.Const tcref when tcref.IsTypeAbbrev -> stripUnitEqnsFromMeasureAux canShortcut (reduceTyconRefAbbrevMeasureable tcref) | m -> m @@ -456,7 +456,7 @@ let stripUnitEqnsFromMeasure m = stripUnitEqnsFromMeasureAux false m /// What is the contribution of unit-of-measure constant ucref to unit-of-measure expression measure? let rec MeasureExprConExponent g abbrev ucref unt = match (if abbrev then stripUnitEqnsFromMeasure unt else stripUnitEqns unt) with - | Measure.Con ucrefR -> if tyconRefEq g ucrefR ucref then OneRational else ZeroRational + | Measure.Const ucrefR -> if tyconRefEq g ucrefR ucref then OneRational else ZeroRational | Measure.Inv untR -> NegRational(MeasureExprConExponent g abbrev ucref untR) | Measure.Prod(unt1, unt2) -> AddRational(MeasureExprConExponent g abbrev ucref unt1) (MeasureExprConExponent g abbrev ucref unt2) | Measure.RationalPower(untR, q) -> MulRational (MeasureExprConExponent g abbrev ucref untR) q @@ -466,7 +466,7 @@ let rec MeasureExprConExponent g abbrev ucref unt = /// after remapping tycons? let rec MeasureConExponentAfterRemapping g r ucref unt = match stripUnitEqnsFromMeasure unt with - | Measure.Con ucrefR -> if tyconRefEq g (r ucrefR) ucref then OneRational else ZeroRational + | Measure.Const ucrefR -> if tyconRefEq g (r ucrefR) ucref then OneRational else ZeroRational | Measure.Inv untR -> NegRational(MeasureConExponentAfterRemapping g r ucref untR) | Measure.Prod(unt1, unt2) -> AddRational(MeasureConExponentAfterRemapping g r ucref unt1) (MeasureConExponentAfterRemapping g r ucref unt2) | Measure.RationalPower(untR, q) -> MulRational (MeasureConExponentAfterRemapping g r ucref untR) q @@ -511,7 +511,7 @@ let ListMeasureVarOccsWithNonZeroExponents untexpr = let ListMeasureConOccsWithNonZeroExponents g eraseAbbrevs untexpr = let rec gather acc unt = match (if eraseAbbrevs then stripUnitEqnsFromMeasure unt else stripUnitEqns unt) with - | Measure.Con c -> + | Measure.Const c -> if List.exists (fun (cR, _) -> tyconRefEq g c cR) acc then acc else let e = MeasureExprConExponent g eraseAbbrevs c untexpr if e = ZeroRational then acc else (c, e) :: acc @@ -526,7 +526,7 @@ let ListMeasureConOccsWithNonZeroExponents g eraseAbbrevs untexpr = let ListMeasureConOccsAfterRemapping g r unt = let rec gather acc unt = match stripUnitEqnsFromMeasure unt with - | Measure.Con c -> if List.exists (tyconRefEq g (r c)) acc then acc else r c :: acc + | Measure.Const c -> if List.exists (tyconRefEq g (r c)) acc then acc else r c :: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.RationalPower(untR, _) -> gather acc untR | Measure.Inv untR -> gather acc untR @@ -552,8 +552,8 @@ let ProdMeasures ms = | [] -> Measure.One | m :: ms -> List.foldBack MeasureProdOpt ms m -let isDimensionless g tyarg = - match stripTyparEqns tyarg with +let isDimensionless g ty = + match stripTyparEqns ty with | TType_measure unt -> isNil (ListMeasureVarOccsWithNonZeroExponents unt) && isNil (ListMeasureConOccsWithNonZeroExponents g true unt) @@ -581,7 +581,7 @@ let normalizeMeasure g ms = match vs, cs with | [], [] -> Measure.One | [(v, e)], [] when e = OneRational -> Measure.Var v - | vs, cs -> List.foldBack (fun (v, e) -> fun m -> Measure.Prod (Measure.RationalPower (Measure.Var v, e), m)) vs (List.foldBack (fun (c, e) -> fun m -> Measure.Prod (Measure.RationalPower (Measure.Con c, e), m)) cs Measure.One) + | vs, cs -> List.foldBack (fun (v, e) -> fun m -> Measure.Prod (Measure.RationalPower (Measure.Var v, e), m)) vs (List.foldBack (fun (c, e) -> fun m -> Measure.Prod (Measure.RationalPower (Measure.Const c, e), m)) cs Measure.One) let tryNormalizeMeasureInType g ty = match ty with @@ -789,8 +789,8 @@ let rec stripTyEqnsAndErase eraseFuncAndTuple (g: TcGlobals) ty = else ty - | TType_fun(a, b, flags) when eraseFuncAndTuple -> - TType_app(g.fastFunc_tcr, [ a; b ], flags) + | TType_fun(domainTy, rangeTy, flags) when eraseFuncAndTuple -> + TType_app(g.fastFunc_tcr, [ domainTy; rangeTy ], flags) | TType_tuple(tupInfo, l) when eraseFuncAndTuple -> mkCompiledTupleTy g (evalTupInfoIsStruct tupInfo) l @@ -816,7 +816,7 @@ let rec stripExnEqns (eref: TyconRef) = let primDestForallTy g ty = ty |> stripTyEqns g |> (function TType_forall (tyvs, tau) -> (tyvs, tau) | _ -> failwith "primDestForallTy: not a forall type") -let destFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (tyv, tau, _) -> (tyv, tau) | _ -> failwith "destFunTy: not a function type") +let destFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (domainTy, rangeTy, _) -> (domainTy, rangeTy) | _ -> failwith "destFunTy: not a function type") let destAnyTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, l) -> tupInfo, l | _ -> failwith "destAnyTupleTy: not a tuple type") @@ -880,7 +880,7 @@ let argsOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(_, tinst, _) - let tryDestTyparTy g ty = ty |> stripTyEqns g |> (function TType_var (v, _) -> ValueSome v | _ -> ValueNone) -let tryDestFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (tyv, tau, _) -> ValueSome(tyv, tau) | _ -> ValueNone) +let tryDestFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (domainTy, rangeTy, _) -> ValueSome(domainTy, rangeTy) | _ -> ValueNone) let tryTcrefOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _, _) -> ValueSome tcref | _ -> ValueNone) @@ -900,14 +900,14 @@ let tryNiceEntityRefOfTy ty = let ty = stripTyparEqnsAux false ty match ty with | TType_app (tcref, _, _) -> ValueSome tcref - | TType_measure (Measure.Con tcref) -> ValueSome tcref + | TType_measure (Measure.Const tcref) -> ValueSome tcref | _ -> ValueNone let tryNiceEntityRefOfTyOption ty = let ty = stripTyparEqnsAux false ty match ty with | TType_app (tcref, _, _) -> Some tcref - | TType_measure (Measure.Con tcref) -> Some tcref + | TType_measure (Measure.Const tcref) -> Some tcref | _ -> None let mkInstForAppTy g ty = @@ -931,12 +931,12 @@ let convertToTypeWithMetadataIfPossible g ty = // TType modifications //--------------------------------------------------------------------------- -let stripMeasuresFromTType g tt = - match tt with - | TType_app(a, b, flags) -> - let bR = b |> List.filter (isMeasureTy g >> not) - TType_app(a, bR, flags) - | _ -> tt +let stripMeasuresFromTy g ty = + match ty with + | TType_app(tcref, tinst, flags) -> + let tinstR = tinst |> List.filter (isMeasureTy g >> not) + TType_app(tcref, tinstR, flags) + | _ -> ty //--------------------------------------------------------------------------- // Equivalence of types up to alpha-equivalence @@ -990,30 +990,29 @@ and traitKeysAEquivAux erasureFlag g aenv witnessInfo1 witnessInfo2 = and returnTypesAEquivAux erasureFlag g aenv retTy retTy2 = match retTy, retTy2 with | None, None -> true - | Some t1, Some t2 -> typeAEquivAux erasureFlag g aenv t1 t2 + | Some ty1, Some ty2 -> typeAEquivAux erasureFlag g aenv ty1 ty2 | _ -> false - and typarConstraintsAEquivAux erasureFlag g aenv tpc1 tpc2 = match tpc1, tpc2 with - | TyparConstraint.CoercesTo(acty, _), - TyparConstraint.CoercesTo(fcty, _) -> - typeAEquivAux erasureFlag g aenv acty fcty + | TyparConstraint.CoercesTo(tgtTy1, _), + TyparConstraint.CoercesTo(tgtTy2, _) -> + typeAEquivAux erasureFlag g aenv tgtTy1 tgtTy2 | TyparConstraint.MayResolveMember(trait1, _), TyparConstraint.MayResolveMember(trait2, _) -> traitsAEquivAux erasureFlag g aenv trait1 trait2 - | TyparConstraint.DefaultsTo(_, acty, _), - TyparConstraint.DefaultsTo(_, fcty, _) -> - typeAEquivAux erasureFlag g aenv acty fcty + | TyparConstraint.DefaultsTo(_, dfltTy1, _), + TyparConstraint.DefaultsTo(_, dfltTy2, _) -> + typeAEquivAux erasureFlag g aenv dfltTy1 dfltTy2 - | TyparConstraint.IsEnum(uty1, _), TyparConstraint.IsEnum(uty2, _) -> - typeAEquivAux erasureFlag g aenv uty1 uty2 + | TyparConstraint.IsEnum(underlyingTy1, _), TyparConstraint.IsEnum(underlyingTy2, _) -> + typeAEquivAux erasureFlag g aenv underlyingTy1 underlyingTy2 - | TyparConstraint.IsDelegate(aty1, bty1, _), TyparConstraint.IsDelegate(aty2, bty2, _) -> - typeAEquivAux erasureFlag g aenv aty1 aty2 && - typeAEquivAux erasureFlag g aenv bty1 bty2 + | TyparConstraint.IsDelegate(argTys1, retTy1, _), TyparConstraint.IsDelegate(argTys2, retTy2, _) -> + typeAEquivAux erasureFlag g aenv argTys1 argTys2 && + typeAEquivAux erasureFlag g aenv retTy1 retTy2 | TyparConstraint.SimpleChoice (tys1, _), TyparConstraint.SimpleChoice(tys2, _) -> ListSet.equals (typeAEquivAux erasureFlag g aenv) tys1 tys2 @@ -1036,9 +1035,9 @@ and typarsAEquivAux erasureFlag g (aenv: TypeEquivEnv) tps1 tps2 = let aenv = aenv.BindEquivTypars tps1 tps2 List.forall2 (typarConstraintSetsAEquivAux erasureFlag g aenv) tps1 tps2 -and tcrefAEquiv g aenv tc1 tc2 = - tyconRefEq g tc1 tc2 || - (match aenv.EquivTycons.TryFind tc1 with Some v -> tyconRefEq g v tc2 | None -> false) +and tcrefAEquiv g aenv tcref1 tcref2 = + tyconRefEq g tcref1 tcref2 || + (match aenv.EquivTycons.TryFind tcref1 with Some v -> tyconRefEq g v tcref2 | None -> false) and typeAEquivAux erasureFlag g aenv ty1 ty2 = let ty1 = stripTyEqnsWrtErasure erasureFlag g ty1 @@ -1052,27 +1051,27 @@ and typeAEquivAux erasureFlag g aenv ty1 ty2 = | TType_var (tp1, _), _ -> match aenv.EquivTypars.TryFind tp1 with - | Some v -> typeEquivAux erasureFlag g v ty2 + | Some tpTy1 -> typeEquivAux erasureFlag g tpTy1 ty2 | None -> false - | TType_app (tc1, b1, _), TType_app (tc2, b2, _) -> - tcrefAEquiv g aenv tc1 tc2 && - typesAEquivAux erasureFlag g aenv b1 b2 + | TType_app (tcref1, tinst1, _), TType_app (tcref2, tinst2, _) -> + tcrefAEquiv g aenv tcref1 tcref2 && + typesAEquivAux erasureFlag g aenv tinst1 tinst2 - | TType_ucase (UnionCaseRef(tc1, n1), b1), TType_ucase (UnionCaseRef(tc2, n2), b2) -> - n1=n2 && - tcrefAEquiv g aenv tc1 tc2 && - typesAEquivAux erasureFlag g aenv b1 b2 + | TType_ucase (UnionCaseRef(tcref1, ucase1), tinst1), TType_ucase (UnionCaseRef(tcref2, ucase2), tinst2) -> + ucase1=ucase2 && + tcrefAEquiv g aenv tcref1 tcref2 && + typesAEquivAux erasureFlag g aenv tinst1 tinst2 - | TType_tuple (s1, l1), TType_tuple (s2, l2) -> - structnessAEquiv s1 s2 && typesAEquivAux erasureFlag g aenv l1 l2 + | TType_tuple (tupInfo1, l1), TType_tuple (tupInfo2, l2) -> + structnessAEquiv tupInfo1 tupInfo2 && typesAEquivAux erasureFlag g aenv l1 l2 | TType_anon (anonInfo1, l1), TType_anon (anonInfo2, l2) -> anonInfoEquiv anonInfo1 anonInfo2 && typesAEquivAux erasureFlag g aenv l1 l2 - | TType_fun (dtys1, rty1, _), TType_fun (dtys2, retTy2, _) -> - typeAEquivAux erasureFlag g aenv dtys1 dtys2 && typeAEquivAux erasureFlag g aenv rty1 retTy2 + | TType_fun (domainTy1, rangeTy1, _), TType_fun (domainTy2, rangeTy2, _) -> + typeAEquivAux erasureFlag g aenv domainTy1 domainTy2 && typeAEquivAux erasureFlag g aenv rangeTy1 rangeTy2 | TType_measure m1, TType_measure m2 -> match erasureFlag with @@ -1081,7 +1080,6 @@ and typeAEquivAux erasureFlag g aenv ty1 ty2 = | _ -> false - and anonInfoEquiv (anonInfo1: AnonRecdTypeInfo) (anonInfo2: AnonRecdTypeInfo) = ccuEq anonInfo1.Assembly anonInfo2.Assembly && structnessAEquiv anonInfo1.TupInfo anonInfo2.TupInfo && @@ -1094,7 +1092,7 @@ and structnessAEquiv un1 un2 = and measureAEquiv g aenv un1 un2 = let vars1 = ListMeasureVarOccs un1 let trans tp1 = if aenv.EquivTypars.ContainsKey tp1 then destAnyParTy g aenv.EquivTypars[tp1] else tp1 - let remapTyconRef tc = if aenv.EquivTycons.ContainsKey tc then aenv.EquivTycons[tc] else tc + let remapTyconRef tcref = if aenv.EquivTycons.ContainsKey tcref then aenv.EquivTycons[tcref] else tcref let vars1R = List.map trans vars1 let vars2 = ListSet.subtract typarEq (ListMeasureVarOccs un2) vars1R let cons1 = ListMeasureConOccsAfterRemapping g remapTyconRef un1 @@ -1161,7 +1159,9 @@ let rec getErasedTypes g ty = //--------------------------------------------------------------------------- let valOrder = { new IComparer with member _.Compare(v1, v2) = compare v1.Stamp v2.Stamp } -let tyconOrder = { new IComparer with member _.Compare(tc1, tc2) = compare tc1.Stamp tc2.Stamp } + +let tyconOrder = { new IComparer with member _.Compare(tycon1, tycon2) = compare tycon1.Stamp tycon2.Stamp } + let recdFieldRefOrder = { new IComparer with member _.Compare(RecdFieldRef(tcref1, nm1), RecdFieldRef(tcref2, nm2)) = @@ -1180,8 +1180,8 @@ let unionCaseRefOrder = // Make some common types //--------------------------------------------------------------------------- -let mkFunTy (g: TcGlobals) d r = - TType_fun (d, r, g.knownWithoutNull) +let mkFunTy (g: TcGlobals) domainTy rangeTy = + TType_fun (domainTy, rangeTy, g.knownWithoutNull) let mkForallTy d r = TType_forall (d, r) @@ -1220,7 +1220,7 @@ let ensureCcuHasModuleOrNamespaceAtPath (ccu: CcuThunk) path (CompPath(_, cpath) let smodul = Construct.NewModuleOrNamespace (Some cpath) taccessPublic hpath xml [] (MaybeLazy.Strict mty) mtype.AddModuleOrNamespaceByMutation smodul let modul = Map.find modName mtype.AllEntitiesByCompiledAndLogicalMangledNames - loop (prior_cpath @ [(modName, Namespace)]) tpath tcpath modul + loop (prior_cpath @ [(modName, Namespace true)]) tpath tcpath modul | _ -> () @@ -1396,7 +1396,7 @@ let NormalizeDeclaredTyparsForEquiRecursiveInference g tps = type GeneralizedType = GeneralizedType of Typars * TType let mkGenericBindRhs g m generalizedTyparsForRecursiveBlock typeScheme bodyExpr = - let (GeneralizedType(generalizedTypars, tauType)) = typeScheme + let (GeneralizedType(generalizedTypars, tauTy)) = typeScheme // Normalize the generalized typars let generalizedTypars = NormalizeDeclaredTyparsForEquiRecursiveInference g generalizedTypars @@ -1414,7 +1414,7 @@ let mkGenericBindRhs g m generalizedTyparsForRecursiveBlock typeScheme bodyExpr // We record an expression node that indicates that a free choice can be made // for these. This expression node effectively binds the type variables. let freeChoiceTypars = ListSet.subtract typarEq generalizedTyparsForRecursiveBlock generalizedTypars - mkTypeLambda m generalizedTypars (mkTypeChoose m freeChoiceTypars bodyExpr, tauType) + mkTypeLambda m generalizedTypars (mkTypeChoose m freeChoiceTypars bodyExpr, tauTy) let isBeingGeneralized tp typeScheme = let (GeneralizedType(generalizedTypars, _)) = typeScheme @@ -1512,36 +1512,36 @@ let mkExnCaseFieldGet (e1, ecref, j, m) = let mkExnCaseFieldSet (e1, ecref, j, e2, m) = Expr.Op (TOp.ExnFieldSet (ecref, j), [], [e1;e2], m) -let mkDummyLambda (g: TcGlobals) (e: Expr, ety) = - let m = e.Range - mkLambda m (fst (mkCompGenLocal m "unitVar" g.unit_ty)) (e, ety) +let mkDummyLambda (g: TcGlobals) (bodyExpr: Expr, bodyExprTy) = + let m = bodyExpr.Range + mkLambda m (fst (mkCompGenLocal m "unitVar" g.unit_ty)) (bodyExpr, bodyExprTy) -let mkWhile (g: TcGlobals) (spWhile, marker, e1, e2, m) = - Expr.Op (TOp.While (spWhile, marker), [], [mkDummyLambda g (e1, g.bool_ty);mkDummyLambda g (e2, g.unit_ty)], m) +let mkWhile (g: TcGlobals) (spWhile, marker, guardExpr, bodyExpr, m) = + Expr.Op (TOp.While (spWhile, marker), [], [mkDummyLambda g (guardExpr, g.bool_ty);mkDummyLambda g (bodyExpr, g.unit_ty)], m) -let mkIntegerForLoop (g: TcGlobals) (spFor, spIn, v, e1, dir, e2, e3: Expr, m) = - Expr.Op (TOp.IntegerForLoop (spFor, spIn, dir), [], [mkDummyLambda g (e1, g.int_ty) ;mkDummyLambda g (e2, g.int_ty);mkLambda e3.Range v (e3, g.unit_ty)], m) +let mkIntegerForLoop (g: TcGlobals) (spFor, spIn, v, startExpr, dir, finishExpr, bodyExpr: Expr, m) = + Expr.Op (TOp.IntegerForLoop (spFor, spIn, dir), [], [mkDummyLambda g (startExpr, g.int_ty) ;mkDummyLambda g (finishExpr, g.int_ty);mkLambda bodyExpr.Range v (bodyExpr, g.unit_ty)], m) -let mkTryWith g (e1, vf, ef: Expr, vh, eh: Expr, m, ty, spTry, spWith) = - Expr.Op (TOp.TryWith (spTry, spWith), [ty], [mkDummyLambda g (e1, ty);mkLambda ef.Range vf (ef, ty);mkLambda eh.Range vh (eh, ty)], m) +let mkTryWith g (bodyExpr, filterVal, filterExpr: Expr, handlerVal, handlerExpr: Expr, m, ty, spTry, spWith) = + Expr.Op (TOp.TryWith (spTry, spWith), [ty], [mkDummyLambda g (bodyExpr, ty);mkLambda filterExpr.Range filterVal (filterExpr, ty);mkLambda handlerExpr.Range handlerVal (handlerExpr, ty)], m) -let mkTryFinally (g: TcGlobals) (e1, e2, m, ty, spTry, spFinally) = - Expr.Op (TOp.TryFinally (spTry, spFinally), [ty], [mkDummyLambda g (e1, ty);mkDummyLambda g (e2, g.unit_ty)], m) +let mkTryFinally (g: TcGlobals) (bodyExpr, finallyExpr, m, ty, spTry, spFinally) = + Expr.Op (TOp.TryFinally (spTry, spFinally), [ty], [mkDummyLambda g (bodyExpr, ty);mkDummyLambda g (finallyExpr, g.unit_ty)], m) let mkDefault (m, ty) = Expr.Const (Const.Zero, m, ty) -let mkValSet m v e = - Expr.Op (TOp.LValueOp (LSet, v), [], [e], m) +let mkValSet m vref e = + Expr.Op (TOp.LValueOp (LSet, vref), [], [e], m) -let mkAddrSet m v e = - Expr.Op (TOp.LValueOp (LByrefSet, v), [], [e], m) +let mkAddrSet m vref e = + Expr.Op (TOp.LValueOp (LByrefSet, vref), [], [e], m) -let mkAddrGet m v = - Expr.Op (TOp.LValueOp (LByrefGet, v), [], [], m) +let mkAddrGet m vref = + Expr.Op (TOp.LValueOp (LByrefGet, vref), [], [], m) -let mkValAddr m readonly v = - Expr.Op (TOp.LValueOp (LAddrOf readonly, v), [], [], m) +let mkValAddr m readonly vref = + Expr.Op (TOp.LValueOp (LAddrOf readonly, vref), [], [], m) //-------------------------------------------------------------------------- // Maps tracking extra information for values @@ -1682,9 +1682,9 @@ let tryDestForallTy g ty = let rec stripFunTy g ty = if isFunTy g ty then - let d, r = destFunTy g ty - let more, rty = stripFunTy g r - d :: more, rty + let domainTy, rangeTy = destFunTy g ty + let more, retTy = stripFunTy g rangeTy + domainTy :: more, retTy else [], ty let applyForallTy g ty tyargs = @@ -1696,23 +1696,24 @@ let reduceIteratedFunTy g ty args = if not (isFunTy g ty) then failwith "reduceIteratedFunTy" snd (destFunTy g ty)) ty args -let applyTyArgs g functy tyargs = - if isForallTy g functy then applyForallTy g functy tyargs else functy +let applyTyArgs g ty tyargs = + if isForallTy g ty then applyForallTy g ty tyargs else ty -let applyTys g functy (tyargs, argTys) = - let afterTyappTy = applyTyArgs g functy tyargs +let applyTys g funcTy (tyargs, argTys) = + let afterTyappTy = applyTyArgs g funcTy tyargs reduceIteratedFunTy g afterTyappTy argTys -let formalApplyTys g functy (tyargs, args) = +let formalApplyTys g funcTy (tyargs, args) = reduceIteratedFunTy g - (if isNil tyargs then functy else snd (destForallTy g functy)) + (if isNil tyargs then funcTy else snd (destForallTy g funcTy)) args let rec stripFunTyN g n ty = assert (n >= 0) if n > 0 && isFunTy g ty then let d, r = destFunTy g ty - let more, rty = stripFunTyN g (n-1) r in d :: more, rty + let more, retTy = stripFunTyN g (n-1) r + d :: more, retTy else [], ty let tryDestAnyTupleTy g ty = @@ -1750,8 +1751,8 @@ let destTopForallTy g (ValReprInfo (ntps, _, _)) ty = let tps = NormalizeDeclaredTyparsForEquiRecursiveInference g tps tps, tau -let GetTopValTypeInFSharpForm g (ValReprInfo(_, argInfos, retInfo) as topValInfo) ty m = - let tps, tau = destTopForallTy g topValInfo ty +let GetTopValTypeInFSharpForm g (ValReprInfo(_, argInfos, retInfo) as valReprInfo) ty m = + let tps, tau = destTopForallTy g valReprInfo ty let curriedArgTys, returnTy = GetTopTauTypeInFSharpForm g argInfos tau m tps, curriedArgTys, returnTy, retInfo @@ -1796,10 +1797,10 @@ let destListTy (g: TcGlobals) ty = | ValueSome (tcref, [ty]) when tyconRefEq g tcref g.list_tcr_canon -> ty | _ -> failwith "destListTy" -let tyconRefEqOpt g tcOpt tc = - match tcOpt with +let tyconRefEqOpt g tcrefOpt tcref = + match tcrefOpt with | None -> false - | Some tc2 -> tyconRefEq g tc2 tc + | Some tcref2 -> tyconRefEq g tcref2 tcref let isStringTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _, _) -> tyconRefEq g tcref g.system_String_tcref | _ -> false) @@ -1830,13 +1831,13 @@ let isByrefTy g ty = let isInByrefTag g ty = ty |> stripTyEqns g |> (function TType_app(tcref, [], _) -> tyconRefEq g g.byrefkind_In_tcr tcref | _ -> false) let isInByrefTy g ty = ty |> stripTyEqns g |> (function - | TType_app(tcref, [_; tag], _) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isInByrefTag g tag + | TType_app(tcref, [_; tagTy], _) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isInByrefTag g tagTy | _ -> false) let isOutByrefTag g ty = ty |> stripTyEqns g |> (function TType_app(tcref, [], _) -> tyconRefEq g g.byrefkind_Out_tcr tcref | _ -> false) let isOutByrefTy g ty = ty |> stripTyEqns g |> (function - | TType_app(tcref, [_; tag], _) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isOutByrefTag g tag + | TType_app(tcref, [_; tagTy], _) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isOutByrefTag g tagTy | _ -> false) #if !NO_TYPEPROVIDERS @@ -2059,7 +2060,7 @@ let MemberIsExplicitImpl g (membInfo: ValMemberInfo) = membInfo.MemberFlags.IsOverrideOrExplicitImpl && match membInfo.ImplementedSlotSigs with | [] -> false - | slotsigs -> slotsigs |> List.forall (fun slotsig -> isInterfaceTy g slotsig.ImplementedType) + | slotsigs -> slotsigs |> List.forall (fun slotsig -> isInterfaceTy g slotsig.DeclaringType) let ValIsExplicitImpl g (v: Val) = match v.MemberInfo with @@ -2239,8 +2240,8 @@ and accFreeInTyparConstraint opts tpc acc = | TyparConstraint.MayResolveMember (traitInfo, _) -> accFreeInTrait opts traitInfo acc | TyparConstraint.DefaultsTo(_, defaultTy, _) -> accFreeInType opts defaultTy acc | TyparConstraint.SimpleChoice(tys, _) -> accFreeInTypes opts tys acc - | TyparConstraint.IsEnum(uty, _) -> accFreeInType opts uty acc - | TyparConstraint.IsDelegate(aty, bty, _) -> accFreeInType opts aty (accFreeInType opts bty acc) + | TyparConstraint.IsEnum(underlyingTy, _) -> accFreeInType opts underlyingTy acc + | TyparConstraint.IsDelegate(argTys, retTy, _) -> accFreeInType opts argTys (accFreeInType opts retTy acc) | TyparConstraint.SupportsComparison _ | TyparConstraint.SupportsEquality _ | TyparConstraint.SupportsNull _ @@ -2302,18 +2303,18 @@ and accFreeInType opts ty acc = | TType_anon (anonInfo, l) -> accFreeInTypes opts l (accFreeInTupInfo opts anonInfo.TupInfo acc) - | TType_app (tc, tinst, _) -> - let acc = accFreeTycon opts tc acc + | TType_app (tcref, tinst, _) -> + let acc = accFreeTycon opts tcref acc match tinst with | [] -> acc // optimization to avoid unneeded call | [h] -> accFreeInType opts h acc // optimization to avoid unneeded call | _ -> accFreeInTypes opts tinst acc - | TType_ucase (UnionCaseRef(tc, _), tinst) -> - accFreeInTypes opts tinst (accFreeTycon opts tc acc) + | TType_ucase (UnionCaseRef(tcref, _), tinst) -> + accFreeInTypes opts tinst (accFreeTycon opts tcref acc) - | TType_fun (d, r, _) -> - accFreeInType opts d (accFreeInType opts r acc) + | TType_fun (domainTy, rangeTy, _) -> + accFreeInType opts domainTy (accFreeInType opts rangeTy acc) | TType_var (r, _) -> accFreeTyparRef opts r acc @@ -2375,10 +2376,10 @@ and accFreeInTyparConstraintLeftToRight g cxFlag thruFlag acc tpc = accFreeInTypeLeftToRight g cxFlag thruFlag acc defaultTy | TyparConstraint.SimpleChoice(tys, _) -> accFreeInTypesLeftToRight g cxFlag thruFlag acc tys - | TyparConstraint.IsEnum(uty, _) -> - accFreeInTypeLeftToRight g cxFlag thruFlag acc uty - | TyparConstraint.IsDelegate(aty, bty, _) -> - accFreeInTypeLeftToRight g cxFlag thruFlag (accFreeInTypeLeftToRight g cxFlag thruFlag acc aty) bty + | TyparConstraint.IsEnum(underlyingTy, _) -> + accFreeInTypeLeftToRight g cxFlag thruFlag acc underlyingTy + | TyparConstraint.IsDelegate(argTys, retTy, _) -> + accFreeInTypeLeftToRight g cxFlag thruFlag (accFreeInTypeLeftToRight g cxFlag thruFlag acc argTys) retTy | TyparConstraint.SupportsComparison _ | TyparConstraint.SupportsEquality _ | TyparConstraint.SupportsNull _ @@ -2419,9 +2420,9 @@ and accFreeInTypeLeftToRight g cxFlag thruFlag acc ty = | TType_ucase (_, tinst) -> accFreeInTypesLeftToRight g cxFlag thruFlag acc tinst - | TType_fun (d, r, _) -> - let dacc = accFreeInTypeLeftToRight g cxFlag thruFlag acc d - accFreeInTypeLeftToRight g cxFlag thruFlag dacc r + | TType_fun (domainTy, rangeTy, _) -> + let dacc = accFreeInTypeLeftToRight g cxFlag thruFlag acc domainTy + accFreeInTypeLeftToRight g cxFlag thruFlag dacc rangeTy | TType_var (r, _) -> accFreeTyparRefLeftToRight g cxFlag thruFlag acc r @@ -2512,12 +2513,12 @@ let CountEnclosingTyparsOfActualParentOfVal (v: Val) = elif not v.IsMember then 0 else v.MemberApparentEntity.TyparsNoRange.Length -let GetTopValTypeInCompiledForm g topValInfo numEnclosingTypars ty m = - let tps, paramArgInfos, retTy, retInfo = GetTopValTypeInFSharpForm g topValInfo ty m +let GetTopValTypeInCompiledForm g valReprInfo numEnclosingTypars ty m = + let tps, paramArgInfos, retTy, retInfo = GetTopValTypeInFSharpForm g valReprInfo ty m let witnessInfos = GetTraitWitnessInfosOfTypars g numEnclosingTypars tps // Eliminate lone single unit arguments let paramArgInfos = - match paramArgInfos, topValInfo.ArgInfos with + match paramArgInfos, valReprInfo.ArgInfos with // static member and module value unit argument elimination | [[(_argType, _)]], [[]] -> //assert isUnitTy g argType @@ -2539,19 +2540,19 @@ let GetTopValTypeInCompiledForm g topValInfo numEnclosingTypars ty m = // This is used not only for the compiled form - it's also used for all type checking and object model // logic such as determining if abstract methods have been implemented or not, and how // many arguments the method takes etc. -let GetMemberTypeInMemberForm g memberFlags topValInfo numEnclosingTypars ty m = - let tps, paramArgInfos, retTy, retInfo = GetMemberTypeInFSharpForm g memberFlags topValInfo ty m +let GetMemberTypeInMemberForm g memberFlags valReprInfo numEnclosingTypars ty m = + let tps, paramArgInfos, retTy, retInfo = GetMemberTypeInFSharpForm g memberFlags valReprInfo ty m let witnessInfos = GetTraitWitnessInfosOfTypars g numEnclosingTypars tps // Eliminate lone single unit arguments let paramArgInfos = - match paramArgInfos, topValInfo.ArgInfos with + match paramArgInfos, valReprInfo.ArgInfos with // static member and module value unit argument elimination - | [[(argType, _)]], [[]] -> - assert isUnitTy g argType + | [[(argTy, _)]], [[]] -> + assert isUnitTy g argTy [[]] // instance member unit argument elimination - | [[(argType, _)]], [[_objArg];[]] -> - assert isUnitTy g argType + | [[(argTy, _)]], [[_objArg];[]] -> + assert isUnitTy g argTy [[]] | _ -> paramArgInfos @@ -2560,13 +2561,13 @@ let GetMemberTypeInMemberForm g memberFlags topValInfo numEnclosingTypars ty m = let GetTypeOfMemberInMemberForm g (vref: ValRef) = //assert (not vref.IsExtensionMember) - let membInfo, topValInfo = checkMemberValRef vref + let membInfo, valReprInfo = checkMemberValRef vref let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal vref.Deref - GetMemberTypeInMemberForm g membInfo.MemberFlags topValInfo numEnclosingTypars vref.Type vref.Range + GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars vref.Type vref.Range let GetTypeOfMemberInFSharpForm g (vref: ValRef) = - let membInfo, topValInfo = checkMemberValRef vref - GetMemberTypeInFSharpForm g membInfo.MemberFlags topValInfo vref.Type vref.Range + let membInfo, valReprInfo = checkMemberValRef vref + GetMemberTypeInFSharpForm g membInfo.MemberFlags valReprInfo vref.Type vref.Range let PartitionValTyparsForApparentEnclosingType g (v: Val) = match v.ValReprInfo with @@ -2598,9 +2599,9 @@ let PartitionValRefTypars g (vref: ValRef) = PartitionValTypars g vref.Deref /// Get the arguments for an F# value that represents an object model method let ArgInfosOfMemberVal g (v: Val) = - let membInfo, topValInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range + let membInfo, valReprInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v - let _, _, arginfos, _, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags topValInfo numEnclosingTypars v.Type v.Range + let _, _, arginfos, _, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range arginfos let ArgInfosOfMember g (vref: ValRef) = @@ -2615,18 +2616,18 @@ let GetFSharpViewOfReturnType (g: TcGlobals) retTy = /// Get the property "type" (getter return type) for an F# value that represents a getter or setter /// of an object model property. let ReturnTypeOfPropertyVal g (v: Val) = - let membInfo, topValInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range + let membInfo, valReprInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range match membInfo.MemberFlags.MemberKind with | SynMemberKind.PropertySet -> let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v - let _, _, arginfos, _, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags topValInfo numEnclosingTypars v.Type v.Range + let _, _, arginfos, _, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range if not arginfos.IsEmpty && not arginfos.Head.IsEmpty then arginfos.Head |> List.last |> fst else error(Error(FSComp.SR.tastValueDoesNotHaveSetterType(), v.Range)) | SynMemberKind.PropertyGet -> let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v - let _, _, _, retTy, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags topValInfo numEnclosingTypars v.Type v.Range + let _, _, _, retTy, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range GetFSharpViewOfReturnType g retTy | _ -> error(InternalError("ReturnTypeOfPropertyVal", v.Range)) @@ -2634,13 +2635,13 @@ let ReturnTypeOfPropertyVal g (v: Val) = /// Get the property arguments for an F# value that represents a getter or setter /// of an object model property. let ArgInfosOfPropertyVal g (v: Val) = - let membInfo, topValInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range + let membInfo, valReprInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range match membInfo.MemberFlags.MemberKind with | SynMemberKind.PropertyGet -> ArgInfosOfMemberVal g v |> List.concat | SynMemberKind.PropertySet -> let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v - let _, _, arginfos, _, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags topValInfo numEnclosingTypars v.Type v.Range + let _, _, arginfos, _, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range if not arginfos.IsEmpty && not arginfos.Head.IsEmpty then arginfos.Head |> List.frontAndBack |> fst else @@ -2770,10 +2771,10 @@ module PrettyTypes = let niceTypars, renaming = NewPrettyTypars [] ftps names // strip universal types for printing - let getTauStayTau t = - match t with + let getTauStayTau ty = + match ty with | TType_forall (_, tau) -> tau - | _ -> t + | _ -> ty let tauThings = mapTys getTauStayTau things let prettyThings = mapTys (instType renaming) tauThings @@ -2858,8 +2859,8 @@ module SimplifyTypes = let ty = stripTyparEqns ty let z = f z ty match ty with - | TType_forall (_, body) -> - foldTypeButNotConstraints f z body + | TType_forall (_, bodyTy) -> + foldTypeButNotConstraints f z bodyTy | TType_app (_, tys, _) | TType_ucase (_, tys) @@ -2867,8 +2868,8 @@ module SimplifyTypes = | TType_tuple (_, tys) -> List.fold (foldTypeButNotConstraints f) z tys - | TType_fun (s, t, _) -> - foldTypeButNotConstraints f (foldTypeButNotConstraints f z s) t + | TType_fun (domainTy, rangeTy, _) -> + foldTypeButNotConstraints f (foldTypeButNotConstraints f z domainTy) rangeTy | TType_var _ -> z @@ -3184,7 +3185,7 @@ let tyconRefToFullName (tcref:TyconRef) = seq { yield! namespaceParts; yield tcref.DisplayName } |> String.concat "." let rec qualifiedInterfaceImplementationNameAux g (x:TType) : string = - match stripMeasuresFromTType g (stripTyEqnsAndErase true g x) with + match stripMeasuresFromTy g (stripTyEqnsAndErase true g x) with | TType_app (a, [], _) -> tyconRefToFullName a @@ -3203,8 +3204,8 @@ let rec qualifiedInterfaceImplementationNameAux g (x:TType) : string = failwithf "unexpected: expected TType_app but got %O" (x.GetType()) /// for types in the global namespace, `global is prepended (note the backtick) -let qualifiedInterfaceImplementationName g (tt:TType) memberName = - let interfaceName = tt |> qualifiedInterfaceImplementationNameAux g +let qualifiedInterfaceImplementationName g (ty: TType) memberName = + let interfaceName = ty |> qualifiedInterfaceImplementationNameAux g sprintf "%s.%s" interfaceName memberName let qualifiedMangledNameOfTyconRef tcref nm = @@ -3702,7 +3703,10 @@ let (|SeqExpr|_|) g expr = // DEBUG layout //--------------------------------------------------------------------------- module DebugPrint = - let layoutRanges = ref false + let mutable layoutRanges = false + let mutable layoutTypes = false + let mutable layoutStamps = false + let mutable layoutValReprInfo = false let squareAngleL l = LeftL.leftBracketAngle ^^ l ^^ RightL.rightBracketAngle @@ -3724,8 +3728,9 @@ module DebugPrint = let lvalopL x = match x with - | LAddrOf readonly -> wordL (tagText (sprintf "LAddrOf(%b)" readonly)) - | LByrefGet -> wordL (tagText "LByrefGet") + | LAddrOf false -> wordL (tagText "&") + | LAddrOf true -> wordL (tagText "&!") + | LByrefGet -> wordL (tagText "*") | LSet -> wordL (tagText "LSet") | LByrefSet -> wordL (tagText "LByrefSet") @@ -3743,8 +3748,8 @@ module DebugPrint = else stat stat - let stampL _n w = - w + let stampL (n: Stamp) w = + if layoutStamps then w ^^ wordL (tagText ("#" + string n)) else w let layoutTyconRef (tcref: TyconRef) = wordL (tagText tcref.DisplayNameWithStaticParameters) |> stampL tcref.Stamp @@ -3930,14 +3935,20 @@ module DebugPrint = match env.postfixConstraints with | [] -> auxTypeL env tau | _ -> (auxTypeL env tau --- auxTyparConstraintsL env env.postfixConstraints) - and layoutTyparDecls tps = angleBracketListL (List.map typarDeclL tps) + and layoutTyparDecls tps = + match tps with + | [] -> emptyL + | _ -> angleBracketListL (List.map typarDeclL tps) let rangeL m = wordL (tagText (stringOfRange m)) let instL tyL tys = - match tys with - | [] -> emptyL - | tys -> sepL (tagText "@[") ^^ commaListL (List.map tyL tys) ^^ rightL (tagText "]") + if layoutTypes then + match tys with + | [] -> emptyL + | tys -> sepL (tagText "@[") ^^ commaListL (List.map tyL tys) ^^ rightL (tagText "]") + else + emptyL let valRefL (vr: ValRef) = wordL (tagText vr.LogicalName) |> stampL vr.Stamp @@ -3951,9 +3962,9 @@ module DebugPrint = let layoutAttribs attribs = aboveListL (List.map layoutAttrib attribs) - let arityInfoL (ValReprInfo (tpNames, _, _) as tvd) = - let ns = tvd.AritiesOfArgs in - leftL (tagText "arity<") ^^ intL tpNames.Length ^^ sepL (tagText ">[") ^^ commaListL (List.map intL ns) ^^ rightL (tagText "]") + let valReprInfoL (ValReprInfo (tpNames, _, _) as tvd) = + let ns = tvd.AritiesOfArgs + leftL (tagText "<") ^^ intL tpNames.Length ^^ sepL (tagText ">[") ^^ commaListL (List.map intL ns) ^^ rightL (tagText "]") let valL (v: Val) = let vsL = wordL (tagText (DecompileOpName v.LogicalName)) |> stampL v.Stamp @@ -3961,10 +3972,10 @@ module DebugPrint = vsL let typeOfValL (v: Val) = - (valL v + valL v ^^ (if v.MustInline then wordL (tagText "inline ") else emptyL) ^^ (if v.IsMutable then wordL(tagText "mutable ") else emptyL) - ^^ wordL (tagText ":")) -- typeL v.Type + ^^ (if layoutTypes then wordL (tagText ":") ^^ typeL v.Type else emptyL) let tslotparamL (TSlotParam(nmOpt, ty, inFlag, outFlag, _, _)) = (optionL (tagText >> wordL) nmOpt) ^^ @@ -3995,14 +4006,19 @@ module DebugPrint = [ wordL(tagText "compiled_name! = ") ^^ wordL (tagText (v.CompiledName g.CompilerGlobalState)) wordL(tagText "membInfo-slotsig! = ") ^^ listL slotSigL membInfo.ImplementedSlotSigs ] - and valAtBindL g v = + and valAtBindL v = let vL = valL v - let mutL = (if v.IsMutable then wordL(tagText "mutable") ++ vL else vL) - mutL --- - aboveListL - [ yield wordL(tagText ":") ^^ typeL v.Type - match v.MemberInfo with None -> () | Some mem_info -> yield wordL(tagText "!") ^^ memberL g v mem_info - match v.ValReprInfo with None -> () | Some arity_info -> yield wordL(tagText "#") ^^ arityInfoL arity_info] + let vL = (if v.IsMutable then wordL(tagText "mutable") ++ vL else vL) + let vL = + if layoutTypes then + vL ^^ wordL(tagText ":") ^^ typeL v.Type + else + vL + let vL = + match v.ValReprInfo with + | Some info when layoutValReprInfo -> vL ^^ wordL(tagText "!") ^^ valReprInfoL info + | _ -> vL + vL let unionCaseRefL (ucr: UnionCaseRef) = wordL (tagText ucr.CaseName) @@ -4042,174 +4058,161 @@ module DebugPrint = | Const.Zero -> "default" wordL (tagText str) - let rec tyconL g (tycon: Tycon) = - if tycon.IsModuleOrNamespace then entityL g tycon else - - let lhsL = wordL (tagText (match tycon.TypeOrMeasureKind with TyparKind.Measure -> "[] type" | TyparKind.Type -> "type")) ^^ wordL (tagText tycon.DisplayName) ^^ layoutTyparDecls tycon.TyparsNoRange - let lhsL = lhsL --- layoutAttribs tycon.Attribs - let memberLs = - let adhoc = - tycon.MembersOfFSharpTyconSorted - |> List.filter (fun v -> not v.IsDispatchSlot) - |> List.filter (fun v -> not v.Deref.IsClassConstructor) - // Don't print individual methods forming interface implementations - these are currently never exported - |> List.filter (fun v -> isNil (Option.get v.MemberInfo).ImplementedSlotSigs) - let iimpls = - match tycon.TypeReprInfo with - | TFSharpObjectRepr r when (match r.fsobjmodel_kind with TFSharpInterface -> true | _ -> false) -> [] - | _ -> tycon.ImmediateInterfacesOfFSharpTycon - let iimpls = iimpls |> List.filter (fun (_, compgen, _) -> not compgen) - // if TFSharpInterface, the iimpls should be printed as inherited interfaces - if isNil adhoc && isNil iimpls then - emptyL - else - let iimplsLs = iimpls |> List.map (fun (ty, _, _) -> wordL(tagText "interface") --- typeL ty) - let adhocLs = adhoc |> List.map (fun vref -> valAtBindL g vref.Deref) - (wordL(tagText "with") @@-- aboveListL (iimplsLs @ adhocLs)) @@ wordL(tagText "end") - let layoutUnionCaseArgTypes argTys = sepListL (wordL(tagText "*")) (List.map typeL argTys) + let layoutUnionCaseArgTypes argTys = sepListL (wordL(tagText "*")) (List.map typeL argTys) - let ucaseL prefixL (ucase: UnionCase) = - let nmL = wordL (tagText ucase.DisplayName) - match ucase.RecdFields |> List.map (fun rfld -> rfld.FormalType) with - | [] -> (prefixL ^^ nmL) - | argTys -> (prefixL ^^ nmL ^^ wordL(tagText "of")) --- layoutUnionCaseArgTypes argTys + let ucaseL prefixL (ucase: UnionCase) = + let nmL = wordL (tagText ucase.DisplayName) + match ucase.RecdFields |> List.map (fun rfld -> rfld.FormalType) with + | [] -> (prefixL ^^ nmL) + | argTys -> (prefixL ^^ nmL ^^ wordL(tagText "of")) --- layoutUnionCaseArgTypes argTys - let layoutUnionCases ucases = - let prefixL = if not (isNilOrSingleton ucases) then wordL(tagText "|") else emptyL - List.map (ucaseL prefixL) ucases + let layoutUnionCases ucases = + let prefixL = if not (isNilOrSingleton ucases) then wordL(tagText "|") else emptyL + List.map (ucaseL prefixL) ucases - let layoutRecdField (fld: RecdField) = - let lhs = wordL (tagText fld.LogicalName) - let lhs = if fld.IsMutable then wordL(tagText "mutable") --- lhs else lhs - (lhs ^^ rightL(tagText ":")) --- typeL fld.FormalType - - let tyconReprL (repr, tycon: Tycon) = - match repr with - | TFSharpRecdRepr _ -> - tycon.TrueFieldsAsList |> List.map (fun fld -> layoutRecdField fld ^^ rightL(tagText ";")) |> aboveListL - | TFSharpObjectRepr r -> - match r.fsobjmodel_kind with - | TFSharpDelegate _ -> - wordL(tagText "delegate ...") - | _ -> - let start = - match r.fsobjmodel_kind with - | TFSharpClass -> "class" - | TFSharpInterface -> "interface" - | TFSharpStruct -> "struct" - | TFSharpEnum -> "enum" - | _ -> failwith "???" - let inherits = - match r.fsobjmodel_kind, tycon.TypeContents.tcaug_super with - | TFSharpClass, Some super -> [wordL(tagText "inherit") ^^ (typeL super)] - | TFSharpInterface, _ -> - tycon.ImmediateInterfacesOfFSharpTycon - |> List.filter (fun (_, compgen, _) -> not compgen) - |> List.map (fun (ity, _, _) -> wordL(tagText "inherit") ^^ (typeL ity)) - | _ -> [] - let vsprs = - tycon.MembersOfFSharpTyconSorted - |> List.filter (fun v -> v.IsDispatchSlot) - |> List.map (fun vref -> valAtBindL g vref.Deref) - let vals = tycon.TrueFieldsAsList |> List.map (fun f -> (if f.IsStatic then wordL(tagText "static") else emptyL) ^^ wordL(tagText "val") ^^ layoutRecdField f) - let alldecls = inherits @ vsprs @ vals - let emptyMeasure = match tycon.TypeOrMeasureKind with TyparKind.Measure -> isNil alldecls | _ -> false - if emptyMeasure then emptyL else (wordL (tagText start) @@-- aboveListL alldecls) @@ wordL(tagText "end") - | TFSharpUnionRepr _ -> tycon.UnionCasesAsList |> layoutUnionCases |> aboveListL - | TAsmRepr _ -> wordL(tagText "(# ... #)") - | TMeasureableRepr ty -> typeL ty - | TILObjectRepr (TILObjectReprData(_, _, td)) -> wordL (tagText td.Name) - | _ -> failwith "unreachable" - - let reprL = - match tycon.TypeReprInfo with -#if !NO_TYPEPROVIDERS - | TProvidedTypeRepr _ - | TProvidedNamespaceRepr _ -#endif - | TNoRepr -> - match tycon.TypeAbbrev with - | None -> lhsL @@-- memberLs - | Some a -> (lhsL ^^ wordL(tagText "=")) --- (typeL a @@ memberLs) - | a -> - let rhsL = tyconReprL (a, tycon) @@ memberLs - (lhsL ^^ wordL(tagText "=")) @@-- rhsL - reprL + let layoutRecdField (fld: RecdField) = + let lhs = wordL (tagText fld.LogicalName) + let lhs = if fld.IsMutable then wordL(tagText "mutable") --- lhs else lhs + let lhs = if layoutTypes then lhs ^^ rightL(tagText ":") ^^ typeL fld.FormalType else lhs + lhs + + let tyconReprL (repr, tycon: Tycon) = + match repr with + | TFSharpRecdRepr _ -> + tycon.TrueFieldsAsList |> List.map (fun fld -> layoutRecdField fld ^^ rightL(tagText ";")) |> aboveListL + + | TFSharpObjectRepr r -> + match r.fsobjmodel_kind with + | TFSharpDelegate _ -> + wordL(tagText "delegate ...") + | _ -> + let start = + match r.fsobjmodel_kind with + | TFSharpClass -> "class" + | TFSharpInterface -> "interface" + | TFSharpStruct -> "struct" + | TFSharpEnum -> "enum" + | _ -> failwith "???" + + let inherits = + match r.fsobjmodel_kind, tycon.TypeContents.tcaug_super with + | TFSharpClass, Some super -> [wordL(tagText "inherit") ^^ (typeL super)] + | TFSharpInterface, _ -> + tycon.ImmediateInterfacesOfFSharpTycon + |> List.filter (fun (_, compgen, _) -> not compgen) + |> List.map (fun (ity, _, _) -> wordL(tagText "inherit") ^^ (typeL ity)) + | _ -> [] + + let vsprs = + tycon.MembersOfFSharpTyconSorted + |> List.filter (fun v -> v.IsDispatchSlot) + |> List.map (fun vref -> valAtBindL vref.Deref) + + let vals = tycon.TrueFieldsAsList |> List.map (fun f -> (if f.IsStatic then wordL(tagText "static") else emptyL) ^^ wordL(tagText "val") ^^ layoutRecdField f) + + let alldecls = inherits @ vsprs @ vals + + let emptyMeasure = match tycon.TypeOrMeasureKind with TyparKind.Measure -> isNil alldecls | _ -> false + + if emptyMeasure then emptyL else (wordL (tagText start) @@-- aboveListL alldecls) @@ wordL(tagText "end") + + | TFSharpUnionRepr _ -> tycon.UnionCasesAsList |> layoutUnionCases |> aboveListL + | TAsmRepr _ -> wordL(tagText "(# ... #)") + | TMeasureableRepr ty -> typeL ty + | TILObjectRepr (TILObjectReprData(_, _, td)) -> wordL (tagText td.Name) + | _ -> failwith "unreachable" - and bindingL g (TBind(v, repr, _)) = - (valAtBindL g v ^^ wordL(tagText "=")) @@-- exprL g repr + let rec bindingL (TBind(v, repr, _)) = + (valAtBindL v ^^ wordL(tagText "=")) @@-- exprL repr - and exprL g expr = exprWrapL g false expr + and exprL expr = + exprWrapL false expr - and atomL g expr = exprWrapL g true expr // true means bracket if needed to be atomic expr + and atomL expr = + // true means bracket if needed to be atomic expr + exprWrapL true expr - and letRecL g binds bodyL = + and letRecL binds bodyL = let eqnsL = binds - |> List.mapHeadTail (fun bind -> wordL(tagText "rec") ^^ bindingL g bind ^^ wordL(tagText "in")) - (fun bind -> wordL(tagText "and") ^^ bindingL g bind ^^ wordL(tagText "in")) + |> List.mapHeadTail (fun bind -> wordL(tagText "rec") ^^ bindingL bind ^^ wordL(tagText "in")) + (fun bind -> wordL(tagText "and") ^^ bindingL bind ^^ wordL(tagText "in")) (aboveListL eqnsL @@ bodyL) - and letL g bind bodyL = - let eqnL = wordL(tagText "let") ^^ bindingL g bind + and letL bind bodyL = + let eqnL = wordL(tagText "let") ^^ bindingL bind (eqnL @@ bodyL) - and exprWrapL g isAtomic expr = - let atomL args = atomL g args - let exprL expr = exprL g expr - let valAtBindL v = valAtBindL g v - let targetL targets = targetL g targets + and exprWrapL isAtomic expr = let wrap = bracketIfL isAtomic // wrap iff require atomic expr let lay = match expr with | Expr.Const (c, _, _) -> constL c + | Expr.Val (v, flags, _) -> let xL = valL v.Deref let xL = match flags with - | PossibleConstrainedCall _ -> xL ^^ rightL(tagText "") - | CtorValUsedAsSelfInit -> xL ^^ rightL(tagText "") - | CtorValUsedAsSuperInit -> xL ^^ rightL(tagText "") - | VSlotDirectCall -> xL ^^ rightL(tagText "") - | NormalValUse -> xL + | PossibleConstrainedCall _ -> xL ^^ rightL(tagText "") + | CtorValUsedAsSelfInit -> xL ^^ rightL(tagText "") + | CtorValUsedAsSuperInit -> xL ^^ rightL(tagText "") + | VSlotDirectCall -> xL ^^ rightL(tagText "") + | NormalValUse -> xL xL + | Expr.Sequential (expr1, expr2, flag, _) -> - let flag = + aboveListL [ + exprL expr1 match flag with - | NormalSeq -> ";" - | ThenDoSeq -> "; ThenDo" - ((exprL expr1 ^^ rightL (tagText flag)) @@ exprL expr2) |> wrap + | NormalSeq -> () + | ThenDoSeq -> wordL (tagText "ThenDo") + exprL expr2 + ] + |> wrap + | Expr.Lambda (_, _, baseValOpt, argvs, body, _, _) -> - let formalsL = spaceListL (List.map valAtBindL argvs) in + let formalsL = spaceListL (List.map valAtBindL argvs) let bindingL = match baseValOpt with - | None -> wordL(tagText "lam") ^^ formalsL ^^ rightL(tagText ".") - | Some basev -> wordL(tagText "lam") ^^ (leftL(tagText "base=") ^^ valAtBindL basev) --- formalsL ^^ rightL(tagText ".") in - (bindingL ++ exprL body) |> wrap + | None -> wordL(tagText "fun") ^^ formalsL ^^ wordL(tagText "->") + | Some basev -> wordL(tagText "fun") ^^ (leftL(tagText "base=") ^^ valAtBindL basev) --- formalsL ^^ wordL(tagText "->") + (bindingL @@-- exprL body) |> wrap + | Expr.TyLambda (_, tps, body, _, _) -> - ((wordL(tagText "LAM") ^^ spaceListL (List.map typarL tps) ^^ rightL(tagText ".")) ++ exprL body) |> wrap + ((wordL(tagText "FUN") ^^ layoutTyparDecls tps ^^ wordL(tagText "->")) ++ exprL body) |> wrap + | Expr.TyChoose (tps, body, _) -> - ((wordL(tagText "CHOOSE") ^^ spaceListL (List.map typarL tps) ^^ rightL(tagText ".")) ++ exprL body) |> wrap + ((wordL(tagText "CHOOSE") ^^ layoutTyparDecls tps ^^ wordL(tagText "->")) ++ exprL body) |> wrap + | Expr.App (f, _, tys, argTys, _) -> let flayout = atomL f - appL g flayout tys argTys |> wrap + appL flayout tys argTys |> wrap + | Expr.LetRec (binds, body, _, _) -> - letRecL g binds (exprL body) |> wrap + letRecL binds (exprL body) |> wrap + | Expr.Let (bind, body, _, _) -> - letL g bind (exprL body) |> wrap + letL bind (exprL body) |> wrap + | Expr.Link rX -> - (wordL(tagText "RecLink") --- atomL rX.Value) |> wrap - | Expr.DebugPoint (_, rX) -> - (wordL(tagText "DebugPoint") --- atomL rX) |> wrap + exprL rX.Value |> wrap + + | Expr.DebugPoint (DebugPointAtLeafExpr.Yes m, rX) -> + aboveListL [ wordL(tagText "__debugPoint(") ^^ rangeL m ^^ wordL (tagText ")"); exprL rX ] |> wrap + | Expr.Match (_, _, dtree, targets, _, _) -> - leftL(tagText "[") ^^ (decisionTreeL g dtree @@ aboveListL (List.mapi targetL (targets |> Array.toList)) ^^ rightL(tagText "]")) + leftL(tagText "[") ^^ (decisionTreeL dtree @@ aboveListL (List.mapi targetL (targets |> Array.toList)) ^^ rightL(tagText "]")) + | Expr.Op (TOp.UnionCase c, _, args, _) -> (unionCaseRefL c ++ spaceListL (List.map atomL args)) |> wrap + | Expr.Op (TOp.ExnConstr ecref, _, args, _) -> wordL (tagText ecref.LogicalName) ^^ bracketL (commaListL (List.map atomL args)) + | Expr.Op (TOp.Tuple _, _, xs, _) -> tupleL (List.map exprL xs) + | Expr.Op (TOp.Recd (ctor, tcref), _, xs, _) -> let fields = tcref.TrueInstanceFieldsAsList let lay fs x = (wordL (tagText fs.rfield_id.idText) ^^ sepL(tagText "=")) --- (exprL x) @@ -4217,183 +4220,261 @@ module DebugPrint = match ctor with | RecdExpr -> emptyL | RecdExprIsObjInit-> wordL(tagText "(new)") - leftL(tagText "{") ^^ semiListL (List.map2 lay fields xs) ^^ rightL(tagText "}") ^^ ctorL + leftL(tagText "{") ^^ aboveListL (List.map2 lay fields xs) ^^ rightL(tagText "}") ^^ ctorL + | Expr.Op (TOp.ValFieldSet rf, _, [rx;x], _) -> (atomL rx --- wordL(tagText ".")) ^^ (recdFieldRefL rf ^^ wordL(tagText "<-") --- exprL x) + | Expr.Op (TOp.ValFieldSet rf, _, [x], _) -> - (recdFieldRefL rf ^^ wordL(tagText "<-") --- exprL x) + recdFieldRefL rf ^^ wordL(tagText "<-") --- exprL x + | Expr.Op (TOp.ValFieldGet rf, _, [rx], _) -> - (atomL rx ^^ rightL(tagText ".#") ^^ recdFieldRefL rf) + atomL rx ^^ rightL(tagText ".#") ^^ recdFieldRefL rf + | Expr.Op (TOp.ValFieldGet rf, _, [], _) -> recdFieldRefL rf + | Expr.Op (TOp.ValFieldGetAddr (rf, _), _, [rx], _) -> leftL(tagText "&") ^^ bracketL (atomL rx ^^ rightL(tagText ".!") ^^ recdFieldRefL rf) + | Expr.Op (TOp.ValFieldGetAddr (rf, _), _, [], _) -> leftL(tagText "&") ^^ (recdFieldRefL rf) + | Expr.Op (TOp.UnionCaseTagGet tycr, _, [x], _) -> - wordL (tagText ("#" + tycr.LogicalName + ".tag")) ^^ atomL x + wordL (tagText (tycr.LogicalName + ".tag")) ^^ atomL x + | Expr.Op (TOp.UnionCaseProof c, _, [x], _) -> - wordL (tagText ("#" + c.CaseName + ".cast")) ^^ atomL x + wordL (tagText (c.CaseName + ".proof")) ^^ atomL x + | Expr.Op (TOp.UnionCaseFieldGet (c, i), _, [x], _) -> - wordL (tagText ("#" + c.CaseName + "." + string i)) --- atomL x + wordL (tagText (c.CaseName + "." + string i)) --- atomL x + | Expr.Op (TOp.UnionCaseFieldSet (c, i), _, [x;y], _) -> ((atomL x --- (rightL (tagText ("#" + c.CaseName + "." + string i)))) ^^ wordL(tagText ":=")) --- exprL y + | Expr.Op (TOp.TupleFieldGet (_, i), _, [x], _) -> wordL (tagText ("#" + string i)) --- atomL x + | Expr.Op (TOp.Coerce, [ty;_], [x], _) -> atomL x --- (wordL(tagText ":>") ^^ typeL ty) + | Expr.Op (TOp.Reraise, [_], [], _) -> - wordL(tagText "Rethrow!") + wordL(tagText "Reraise") + | Expr.Op (TOp.ILAsm (instrs, retTypes), tyargs, args, _) -> let instrs = instrs |> List.map (sprintf "%+A" >> tagText >> wordL) |> spaceListL // %+A has + since instrs are from an "internal" type let instrs = leftL(tagText "(#") ^^ instrs ^^ rightL(tagText "#)") - (appL g instrs tyargs args --- - wordL(tagText ":") ^^ spaceListL (List.map typeAtomL retTypes)) |> wrap + let instrL = appL instrs tyargs args + let instrL = if layoutTypes then instrL ^^ wordL(tagText ":") ^^ spaceListL (List.map typeAtomL retTypes) else instrL + instrL |> wrap + | Expr.Op (TOp.LValueOp (lvop, vr), _, args, _) -> (lvalopL lvop ^^ valRefL vr --- bracketL (commaListL (List.map atomL args))) |> wrap - | Expr.Op (TOp.ILCall (_, _, _, _, _, _, _, ilMethRef, enclTypeInst, methInst, _), tyargs, args, _) -> + + | Expr.Op (TOp.ILCall (_, _, _, _, _, _, _, ilMethRef, _enclTypeInst, _methInst, _), _tyargs, args, _) -> let meth = ilMethRef.Name - wordL(tagText "ILCall") ^^ - aboveListL - [ yield wordL (tagText ilMethRef.DeclaringTypeRef.FullName) ^^ sepL(tagText ".") ^^ wordL (tagText meth) - if not enclTypeInst.IsEmpty then yield wordL(tagText "tinst ") --- listL typeL enclTypeInst - if not methInst.IsEmpty then yield wordL (tagText "minst ") --- listL typeL methInst - if not tyargs.IsEmpty then yield wordL (tagText "tyargs") --- listL typeL tyargs - if not args.IsEmpty then yield listL exprL args ] - |> wrap + (wordL (tagText ilMethRef.DeclaringTypeRef.FullName) ^^ sepL(tagText ".") ^^ wordL (tagText meth)) ---- + (if args.IsEmpty then wordL (tagText "()") else listL exprL args) + //if not enclTypeInst.IsEmpty then yield wordL(tagText "tinst ") --- listL typeL enclTypeInst + //if not methInst.IsEmpty then yield wordL (tagText "minst ") --- listL typeL methInst + //if not tyargs.IsEmpty then yield wordL (tagText "tyargs") --- listL typeL tyargs + + |> wrap + | Expr.Op (TOp.Array, [_], xs, _) -> leftL(tagText "[|") ^^ commaListL (List.map exprL xs) ^^ rightL(tagText "|]") + | Expr.Op (TOp.While _, [], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], x2, _, _)], _) -> - (wordL(tagText "while") ^^ exprL x1 ^^ wordL(tagText "do")) @@-- exprL x2 + let headerL = wordL(tagText "while") ^^ exprL x1 ^^ wordL(tagText "do") + headerL @@-- exprL x2 + | Expr.Op (TOp.IntegerForLoop _, [], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], x2, _, _);Expr.Lambda (_, _, _, [_], x3, _, _)], _) -> - wordL(tagText "for") ^^ aboveListL [(exprL x1 ^^ wordL(tagText "to") ^^ exprL x2 ^^ wordL(tagText "do")); exprL x3 ] ^^ rightL(tagText "done") + let headerL = wordL(tagText "for") ^^ exprL x1 ^^ wordL(tagText "to") ^^ exprL x2 ^^ wordL(tagText "do") + headerL @@-- exprL x3 + | Expr.Op (TOp.TryWith _, [_], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], xf, _, _);Expr.Lambda (_, _, _, [_], xh, _, _)], _) -> (wordL (tagText "try") @@-- exprL x1) @@ (wordL(tagText "with-filter") @@-- exprL xf) @@ (wordL(tagText "with") @@-- exprL xh) + | Expr.Op (TOp.TryFinally _, [_], [Expr.Lambda (_, _, _, [_], x1, _, _);Expr.Lambda (_, _, _, [_], x2, _, _)], _) -> (wordL (tagText "try") @@-- exprL x1) @@ (wordL(tagText "finally") @@-- exprL x2) | Expr.Op (TOp.Bytes _, _, _, _) -> wordL(tagText "bytes++") + | Expr.Op (TOp.UInt16s _, _, _, _) -> wordL(tagText "uint16++") | Expr.Op (TOp.RefAddrGet _, _tyargs, _args, _) -> wordL(tagText "GetRefLVal...") | Expr.Op (TOp.TraitCall _, _tyargs, _args, _) -> wordL(tagText "traitcall...") | Expr.Op (TOp.ExnFieldGet _, _tyargs, _args, _) -> wordL(tagText "TOp.ExnFieldGet...") | Expr.Op (TOp.ExnFieldSet _, _tyargs, _args, _) -> wordL(tagText "TOp.ExnFieldSet...") - | Expr.Op (TOp.TryFinally _, _tyargs, _args, _) -> wordL(tagText "TOp.TryFinally...") - | Expr.Op (TOp.TryWith _, _tyargs, _args, _) -> wordL(tagText "TOp.TryWith...") + | Expr.Op (TOp.TryFinally _, _tyargs, args, _) -> wordL(tagText ("unexpected-try-finally")) ---- aboveListL (List.map atomL args) + | Expr.Op (TOp.TryWith _, _tyargs, args, _) -> wordL(tagText ("unexpected-try-with")) ---- aboveListL (List.map atomL args) | Expr.Op (TOp.Goto l, _tys, args, _) -> wordL(tagText ("Expr.Goto " + string l)) ^^ bracketL (commaListL (List.map atomL args)) | Expr.Op (TOp.Label l, _tys, args, _) -> wordL(tagText ("Expr.Label " + string l)) ^^ bracketL (commaListL (List.map atomL args)) | Expr.Op (_, _tys, args, _) -> wordL(tagText "Expr.Op ...") ^^ bracketL (commaListL (List.map atomL args)) | Expr.Quote (a, _, _, _, _) -> leftL(tagText "<@") ^^ atomL a ^^ rightL(tagText "@>") + | Expr.Obj (_lambdaId, ty, basev, ccall, overrides, iimpls, _) -> (leftL (tagText "{") @@-- ((wordL(tagText "new ") ++ typeL ty) @@-- aboveListL [exprL ccall - optionL valAtBindL basev - aboveListL (List.map (tmethodL g) overrides) - aboveListL (List.map (iimplL g) iimpls)])) + match basev with + | None -> () + | Some b -> valAtBindL b + yield! List.map tmethodL overrides + yield! List.map iimplL iimpls])) @@ rightL (tagText "}") | Expr.WitnessArg _ -> wordL (tagText "") + | Expr.StaticOptimization (_tcs, csx, x, _) -> (wordL(tagText "opt") @@- (exprL x)) @@-- (wordL(tagText "|") ^^ exprL csx --- (wordL(tagText "when...") )) // For tracking ranges through expr rewrites - if layoutRanges.Value then - leftL(tagText "{") ^^ (rangeL expr.Range ^^ rightL(tagText ":")) ++ lay ^^ rightL(tagText "}") + if layoutRanges then + aboveListL [ + leftL(tagText "//") ^^ rangeL expr.Range + lay + ] else lay - and implFilesL g implFiles = - aboveListL (List.map (implFileL g) implFiles) - - and appL g flayout tys args = + and appL flayout tys args = let z = flayout let z = if isNil tys then z else z ^^ instL typeL tys - let z = if isNil args then z else z --- spaceListL (List.map (atomL g) args) + let z = if isNil args then z else z --- spaceListL (List.map atomL args) z - and implFileL g (CheckedImplFile (signature=implFileTy; contents=implFileContents)) = - aboveListL [(wordL(tagText "top implementation ")) @@-- mexprL g implFileTy implFileContents] - - and mexprL g mtyp defs = - mdefL g defs @@- (wordL(tagText ":") @@- entityTypeL g mtyp) - - and mdefsL g defs = - wordL(tagText "Module Defs") @@-- aboveListL(List.map (mdefL g) defs) - - and mdefL g x = - match x with - | TMDefRec(_, _, tycons, mbinds, _) -> aboveListL ((tycons |> List.map (tyconL g)) @ (mbinds |> List.map (mbindL g))) - | TMDefLet(bind, _) -> letL g bind emptyL - | TMDefDo(e, _) -> exprL g e - | TMDefOpens _ -> wordL (tagText "open ... ") - | TMDefs defs -> mdefsL g defs - - and mbindL g x = - match x with - | ModuleOrNamespaceBinding.Binding bind -> letL g bind emptyL - | ModuleOrNamespaceBinding.Module(mspec, rhs) -> - (wordL (tagText (if mspec.IsNamespace then "namespace" else "module")) ^^ (wordL (tagText mspec.DemangledModuleOrNamespaceName) |> stampL mspec.Stamp)) @@-- mdefL g rhs - - and entityTypeL g (mtyp: ModuleOrNamespaceType) = - aboveListL [qlistL typeOfValL mtyp.AllValsAndMembers - qlistL (tyconL g) mtyp.AllEntities] - - and entityL g (ms: ModuleOrNamespace) = - let header = wordL(tagText "module") ^^ (wordL (tagText ms.DemangledModuleOrNamespaceName) |> stampL ms.Stamp) ^^ wordL(tagText ":") - let footer = wordL(tagText "end") - let body = entityTypeL g ms.ModuleOrNamespaceType - (header @@-- body) @@ footer - - and ccuL g (ccu: CcuThunk) = entityL g ccu.Contents - - and decisionTreeL g x = + and decisionTreeL x = match x with | TDBind (bind, body) -> - let bind = wordL(tagText "let") ^^ bindingL g bind - (bind @@ decisionTreeL g body) + let bind = wordL(tagText "let") ^^ bindingL bind + (bind @@ decisionTreeL body) | TDSuccess (args, n) -> - wordL(tagText "Success") ^^ leftL(tagText "T") ^^ intL n ^^ tupleL (args |> List.map (exprL g)) + wordL(tagText "Success") ^^ leftL(tagText "T") ^^ intL n ^^ tupleL (args |> List.map (exprL)) | TDSwitch (test, dcases, dflt, _) -> - (wordL(tagText "Switch") --- exprL g test) @@-- - (aboveListL (List.map (dcaseL g) dcases) @@ + (wordL(tagText "Switch") --- exprL test) @@-- + (aboveListL (List.map dcaseL dcases) @@ match dflt with | None -> emptyL - | Some dtree -> wordL(tagText "dflt:") --- decisionTreeL g dtree) + | Some dtree -> wordL(tagText "dflt:") --- decisionTreeL dtree) - and dcaseL g (TCase (test, dtree)) = (dtestL g test ^^ wordL(tagText "//")) --- decisionTreeL g dtree + and dcaseL (TCase (test, dtree)) = + (dtestL test ^^ wordL(tagText "//")) --- decisionTreeL dtree - and dtestL g x = + and dtestL x = match x with | DecisionTreeTest.UnionCase (c, tinst) -> wordL(tagText "is") ^^ unionCaseRefL c ^^ instL typeL tinst | DecisionTreeTest.ArrayLength (n, ty) -> wordL(tagText "length") ^^ intL n ^^ typeL ty | DecisionTreeTest.Const c -> wordL(tagText "is") ^^ constL c | DecisionTreeTest.IsNull -> wordL(tagText "isnull") | DecisionTreeTest.IsInst (_, ty) -> wordL(tagText "isinst") ^^ typeL ty - | DecisionTreeTest.ActivePatternCase (exp, _, _, _, _, _) -> wordL(tagText "query") ^^ exprL g exp + | DecisionTreeTest.ActivePatternCase (exp, _, _, _, _, _) -> wordL(tagText "query") ^^ exprL exp | DecisionTreeTest.Error _ -> wordL (tagText "error recovery") - and targetL g i (TTarget (argvs, body, _)) = - leftL(tagText "T") ^^ intL i ^^ tupleL (flatValsL argvs) ^^ rightL(tagText ":") --- exprL g body + and targetL i (TTarget (argvs, body, _)) = + leftL(tagText "T") ^^ intL i ^^ tupleL (flatValsL argvs) ^^ rightL(tagText ":") --- exprL body and flatValsL vs = vs |> List.map valL - and tmethodL g (TObjExprMethod(TSlotSig(nm, _, _, _, _, _), _, tps, vs, e, _)) = - ((wordL(tagText "TObjExprMethod") --- (wordL (tagText nm)) ^^ wordL(tagText "=")) -- - (angleBracketListL (List.map typarL tps) ^^ rightL(tagText ".")) --- - (tupleL (List.map (List.map (valAtBindL g) >> tupleL) vs) ^^ rightL(tagText "."))) + and tmethodL (TObjExprMethod(TSlotSig(nm, _, _, _, _, _), _, tps, vs, e, _)) = + (wordL(tagText "member") ^^ (wordL (tagText nm)) ^^ layoutTyparDecls tps ^^ tupleL (List.map (List.map valAtBindL >> tupleL) vs) ^^ rightL(tagText "=")) @@-- - (atomL g e) + exprL e + + and iimplL (ty, tmeths) = wordL(tagText "impl") ^^ aboveListL (typeL ty :: List.map tmethodL tmeths) + + let rec tyconL (tycon: Tycon) = + + let lhsL = wordL (tagText (match tycon.TypeOrMeasureKind with TyparKind.Measure -> "[] type" | TyparKind.Type -> "type")) ^^ wordL (tagText tycon.DisplayName) ^^ layoutTyparDecls tycon.TyparsNoRange + let lhsL = lhsL --- layoutAttribs tycon.Attribs + let memberLs = + let adhoc = + tycon.MembersOfFSharpTyconSorted + |> List.filter (fun v -> not v.IsDispatchSlot) + |> List.filter (fun v -> not v.Deref.IsClassConstructor) + // Don't print individual methods forming interface implementations - these are currently never exported + |> List.filter (fun v -> isNil (Option.get v.MemberInfo).ImplementedSlotSigs) + let iimpls = + match tycon.TypeReprInfo with + | TFSharpObjectRepr r when (match r.fsobjmodel_kind with TFSharpInterface -> true | _ -> false) -> [] + | _ -> tycon.ImmediateInterfacesOfFSharpTycon + let iimpls = iimpls |> List.filter (fun (_, compgen, _) -> not compgen) + // if TFSharpInterface, the iimpls should be printed as inherited interfaces + if isNil adhoc && isNil iimpls then + emptyL + else + let iimplsLs = iimpls |> List.map (fun (ty, _, _) -> wordL(tagText "interface") --- typeL ty) + let adhocLs = adhoc |> List.map (fun vref -> valAtBindL vref.Deref) + (wordL(tagText "with") @@-- aboveListL (iimplsLs @ adhocLs)) @@ wordL(tagText "end") + let reprL = + match tycon.TypeReprInfo with +#if !NO_TYPEPROVIDERS + | TProvidedTypeRepr _ + | TProvidedNamespaceRepr _ +#endif + | TNoRepr -> + match tycon.TypeAbbrev with + | None -> lhsL @@-- memberLs + | Some a -> (lhsL ^^ wordL(tagText "=")) --- (typeL a @@ memberLs) + | a -> + let rhsL = tyconReprL (a, tycon) @@ memberLs + (lhsL ^^ wordL(tagText "=")) @@-- rhsL + reprL + + and entityL (entity: Entity) = + if entity.IsModuleOrNamespace then + moduleOrNamespaceL entity + else + tyconL entity - and iimplL g (ty, tmeths) = wordL(tagText "impl") ^^ aboveListL (typeL ty :: List.map (tmethodL g) tmeths) + and mexprL mtyp defs = + let resL = mdefL defs + let resL = if layoutTypes then resL @@- (wordL(tagText ":") @@- moduleOrNamespaceTypeL mtyp) else resL + resL + + and mdefsL defs = + wordL(tagText "Module Defs") @@-- aboveListL(List.map mdefL defs) + + and mdefL x = + match x with + | TMDefRec(_, _, tycons, mbinds, _) -> aboveListL ((tycons |> List.map tyconL) @ (mbinds |> List.map mbindL)) + | TMDefLet(bind, _) -> letL bind emptyL + | TMDefDo(e, _) -> exprL e + | TMDefOpens _ -> wordL (tagText "open ... ") + | TMDefs defs -> mdefsL defs + + and mbindL x = + match x with + | ModuleOrNamespaceBinding.Binding bind -> letL bind emptyL + | ModuleOrNamespaceBinding.Module(mspec, rhs) -> + let titleL = wordL (tagText (if mspec.IsNamespace then "namespace" else "module")) ^^ (wordL (tagText mspec.DemangledModuleOrNamespaceName) |> stampL mspec.Stamp) + titleL @@-- mdefL rhs + + and moduleOrNamespaceTypeL (mtyp: ModuleOrNamespaceType) = + aboveListL [qlistL typeOfValL mtyp.AllValsAndMembers + qlistL tyconL mtyp.AllEntities] + + and moduleOrNamespaceL (ms: ModuleOrNamespace) = + let header = wordL(tagText "module") ^^ (wordL (tagText ms.DemangledModuleOrNamespaceName) |> stampL ms.Stamp) ^^ wordL(tagText ":") + let footer = wordL(tagText "end") + let body = moduleOrNamespaceTypeL ms.ModuleOrNamespaceType + (header @@-- body) @@ footer + + let rec implFilesL implFiles = + aboveListL (List.map implFileL implFiles) + + and implFileL (CheckedImplFile (signature=implFileTy; contents=implFileContents)) = + aboveListL [(wordL(tagText "top implementation ")) @@-- mexprL implFileTy implFileContents] + + and ccuL (ccu: CcuThunk) = + entityL ccu.Contents let showType x = showL (typeL x) - let showExpr g x = showL (exprL g x) + let showExpr x = showL (exprL x) let traitL x = auxTraitL SimplifyTypes.typeSimplificationInfo0 x @@ -4408,10 +4489,10 @@ let wrapModuleOrNamespaceType id cpath mtyp = let wrapModuleOrNamespaceTypeInNamespace id cpath mtyp = let mspec = wrapModuleOrNamespaceType id cpath mtyp - Construct.NewModuleOrNamespaceType Namespace [ mspec ] [], mspec + Construct.NewModuleOrNamespaceType (Namespace false) [ mspec ] [], mspec -let wrapModuleOrNamespaceContentsInNamespace (id: Ident) cpath mexpr = - let mspec = wrapModuleOrNamespaceType id cpath (Construct.NewEmptyModuleOrNamespaceType Namespace) +let wrapModuleOrNamespaceContentsInNamespace isModule (id: Ident) (cpath: CompilationPath) mexpr = + let mspec = wrapModuleOrNamespaceType id cpath (Construct.NewEmptyModuleOrNamespaceType (Namespace (not isModule))) TMDefRec (false, [], [], [ModuleOrNamespaceBinding.Module(mspec, mexpr)], id.idRange) //-------------------------------------------------------------------------- @@ -4871,7 +4952,7 @@ and accFreeInTest (opts: FreeVarOptions) discrim acc = | DecisionTreeTest.ArrayLength(_, ty) -> accFreeVarsInTy opts ty acc | DecisionTreeTest.Const _ | DecisionTreeTest.IsNull -> acc - | DecisionTreeTest.IsInst (srcty, tgty) -> accFreeVarsInTy opts srcty (accFreeVarsInTy opts tgty acc) + | DecisionTreeTest.IsInst (srcTy, tgtTy) -> accFreeVarsInTy opts srcTy (accFreeVarsInTy opts tgtTy acc) | DecisionTreeTest.ActivePatternCase (exp, tys, _, activePatIdentity, _, _) -> accFreeInExpr opts exp (accFreeVarsInTys opts tys @@ -5279,7 +5360,8 @@ let InferArityOfExpr g allowTypeDirectedDetupling ty partialArgAttribsL retAttri (ids, attribs) ||> List.map2 (fun id attribs -> { Name = id; Attribs = attribs }: ArgReprInfo )) let retInfo: ArgReprInfo = { Attribs = retAttribs; Name = None } - ValReprInfo (ValReprInfo.InferTyparInfo tps, curriedArgInfos, retInfo) + let info = ValReprInfo (ValReprInfo.InferTyparInfo tps, curriedArgInfos, retInfo) + if ValReprInfo.IsEmpty info then ValReprInfo.emptyValData else info let InferArityOfExprBinding g allowTypeDirectedDetupling (v: Val) expr = match v.ValReprInfo with @@ -5466,11 +5548,11 @@ and remapValReprInfo ctxt tmenv (ValReprInfo(tpNames, arginfosl, retInfo)) = and remapValData ctxt tmenv (d: ValData) = let ty = d.val_type - let topValInfo = d.ValReprInfo + let valReprInfo = d.ValReprInfo let tyR = ty |> remapPossibleForallTyImpl ctxt tmenv let declaringEntityR = d.DeclaringEntity |> remapParentRef tmenv let reprInfoR = d.ValReprInfo |> Option.map (remapValReprInfo ctxt tmenv) - let memberInfoR = d.MemberInfo |> Option.map (remapMemberInfo ctxt d.val_range topValInfo ty tyR tmenv) + let memberInfoR = d.MemberInfo |> Option.map (remapMemberInfo ctxt d.val_range valReprInfo ty tyR tmenv) let attribsR = d.Attribs |> remapAttribs ctxt tmenv { d with val_type = tyR @@ -5745,7 +5827,7 @@ and remapDecisionTree ctxt compgen tmenv x = | DecisionTreeTest.UnionCase (uc, tinst) -> DecisionTreeTest.UnionCase(remapUnionCaseRef tmenv.tyconRefRemap uc, remapTypes tmenv tinst) | DecisionTreeTest.ArrayLength (n, ty) -> DecisionTreeTest.ArrayLength(n, remapType tmenv ty) | DecisionTreeTest.Const _ -> test - | DecisionTreeTest.IsInst (srcty, tgty) -> DecisionTreeTest.IsInst (remapType tmenv srcty, remapType tmenv tgty) + | DecisionTreeTest.IsInst (srcTy, tgtTy) -> DecisionTreeTest.IsInst (remapType tmenv srcTy, remapType tmenv tgtTy) | DecisionTreeTest.IsNull -> DecisionTreeTest.IsNull | DecisionTreeTest.ActivePatternCase _ -> failwith "DecisionTreeTest.ActivePatternCase should only be used during pattern match compilation" | DecisionTreeTest.Error(m) -> DecisionTreeTest.Error(m) @@ -5855,12 +5937,12 @@ and remapTyconExnInfo ctxt tmenv inp = | TExnFresh x -> TExnFresh (remapRecdFields ctxt tmenv x) | TExnAsmRepr _ | TExnNone -> inp -and remapMemberInfo ctxt m topValInfo ty tyR tmenv x = +and remapMemberInfo ctxt m valReprInfo ty tyR tmenv x = // The slotsig in the ImplementedSlotSigs is w.r.t. the type variables in the value's type. // REVIEW: this is a bit gross. It would be nice if the slotsig was standalone - assert (Option.isSome topValInfo) - let tpsorig, _, _, _ = GetMemberTypeInFSharpForm ctxt.g x.MemberFlags (Option.get topValInfo) ty m - let tps, _, _, _ = GetMemberTypeInFSharpForm ctxt.g x.MemberFlags (Option.get topValInfo) tyR m + assert (Option.isSome valReprInfo) + let tpsorig, _, _, _ = GetMemberTypeInFSharpForm ctxt.g x.MemberFlags (Option.get valReprInfo) ty m + let tps, _, _, _ = GetMemberTypeInFSharpForm ctxt.g x.MemberFlags (Option.get valReprInfo) tyR m let renaming, _ = mkTyparToTyparRenaming tpsorig tps let tmenv = { tmenv with tpinst = tmenv.tpinst @ renaming } { x with @@ -5872,18 +5954,18 @@ and copyAndRemapAndBindModTy ctxt compgen tmenv mty = let tycons = allEntitiesOfModuleOrNamespaceTy mty let vs = allValsOfModuleOrNamespaceTy mty let _, _, tmenvinner = copyAndRemapAndBindTyconsAndVals ctxt compgen tmenv tycons vs - remapModTy ctxt compgen tmenvinner mty, tmenvinner + remapModTy compgen tmenvinner mty, tmenvinner -and remapModTy ctxt _compgen tmenv mty = - mapImmediateValsAndTycons (renameTycon ctxt.g tmenv) (renameVal tmenv) mty +and remapModTy _compgen tmenv mty = + mapImmediateValsAndTycons (renameTycon tmenv) (renameVal tmenv) mty -and renameTycon g tyenv x = +and renameTycon tyenv x = let tcref = try let res = tyenv.tyconRefRemap[mkLocalTyconRef x] res with :? KeyNotFoundException -> - errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL g x), x.Range)) + errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL x), x.Range)) mkLocalTyconRef x tcref.Deref @@ -5919,17 +6001,18 @@ and copyAndRemapAndBindTyconsAndVals ctxt compgen tmenv tycons vs = mkLocalValRef v vref.Deref - let lookupTycon g tycon = + let lookupTycon tycon = let tcref = try let res = tmenvinner.tyconRefRemap[mkLocalTyconRef tycon] res with :? KeyNotFoundException -> - errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL g tycon), tycon.Range)) + errorR(InternalError("couldn't remap internal tycon " + showL(DebugPrint.tyconL tycon), tycon.Range)) mkLocalTyconRef tycon tcref.Deref + (tycons, tyconsR) ||> List.iter2 (fun tcd tcdR -> - let lookupTycon tycon = lookupTycon ctxt.g tycon + let lookupTycon tycon = lookupTycon tycon let tpsR, tmenvinner2 = tmenvCopyRemapAndBindTypars (remapAttribs ctxt tmenvinner) tmenvinner (tcd.entity_typars.Force(tcd.entity_range)) tcdR.entity_typars <- LazyWithContext.NotLazy tpsR tcdR.entity_attribs <- tcd.entity_attribs |> remapAttribs ctxt tmenvinner2 @@ -6009,7 +6092,7 @@ and remapAndRenameModDef ctxt compgen tmenv mdef = | TMDefRec(isRec, opens, tycons, mbinds, m) -> // Abstract (virtual) vslots in the tycons at TMDefRec nodes are binders. They also need to be copied and renamed. let opensR = remapOpenDeclarations tmenv opens - let tyconsR = tycons |> List.map (renameTycon ctxt.g tmenv) + let tyconsR = tycons |> List.map (renameTycon tmenv) let mbindsR = mbinds |> List.map (remapAndRenameModBind ctxt compgen tmenv) TMDefRec(isRec, opensR, tyconsR, mbindsR, m) | TMDefLet(bind, m) -> @@ -6033,7 +6116,7 @@ and remapAndRenameModBind ctxt compgen tmenv x = let bind2 = remapAndRenameBind ctxt compgen tmenv bind v2 ModuleOrNamespaceBinding.Binding bind2 | ModuleOrNamespaceBinding.Module(mspec, def) -> - let mspec = renameTycon ctxt.g tmenv mspec + let mspec = renameTycon tmenv mspec let def = remapAndRenameModDef ctxt compgen tmenv def ModuleOrNamespaceBinding.Module(mspec, def) @@ -7842,7 +7925,7 @@ let mkCompilerGeneratedAttr (g: TcGlobals) n = mkILCustomAttribute (tref_CompilationMappingAttr g, [mkILNonGenericValueTy (tref_SourceConstructFlags g)], [ILAttribElem.Int32 n], []) //-------------------------------------------------------------------------- -// tupled lambda --> method/function with a given topValInfo specification. +// tupled lambda --> method/function with a given valReprInfo specification. // // AdjustArityOfLambdaBody: "(vs, body)" represents a lambda "fun (vs) -> body". The // aim is to produce a "static method" represented by a pair @@ -8026,9 +8109,9 @@ let MakeArgsForTopArgs _g m argTysl tpenv = | Some id -> id.idText fst (mkCompGenLocal m nm ty))) -let AdjustValForExpectedArity g m (vref: ValRef) flags topValInfo = +let AdjustValForExpectedArity g m (vref: ValRef) flags valReprInfo = - let tps, argTysl, retTy, _ = GetTopValTypeInFSharpForm g topValInfo vref.Type m + let tps, argTysl, retTy, _ = GetTopValTypeInFSharpForm g valReprInfo vref.Type m let tpsR = copyTypars tps let tyargsR = List.map mkTyparTy tpsR let tpenv = bindTypars tps tyargsR emptyTyparInst @@ -8515,8 +8598,8 @@ let rec typeEnc g (gtpsType, gtpsMethod) ty = else sprintf "System.Tuple%s"(tyargsEnc g (gtpsType, gtpsMethod) tys) - | TType_fun (f, x, _) -> - "Microsoft.FSharp.Core.FSharpFunc" + tyargsEnc g (gtpsType, gtpsMethod) [f;x] + | TType_fun (domainTy, rangeTy, _) -> + "Microsoft.FSharp.Core.FSharpFunc" + tyargsEnc g (gtpsType, gtpsMethod) [domainTy; rangeTy] | TType_var (typar, _) -> typarEnc g (gtpsType, gtpsMethod) typar @@ -8787,22 +8870,22 @@ let canUseUnboxFast g m ty = // // No sequence point is generated for this expression form as this function is only // used for compiler-generated code. -let mkIsInstConditional g m tgty vinputExpr v e2 e3 = +let mkIsInstConditional g m tgtTy vinputExpr v e2 e3 = - if canUseTypeTestFast g tgty && isRefTy g tgty then + if canUseTypeTestFast g tgtTy && isRefTy g tgtTy then let mbuilder = MatchBuilder(DebugPointAtBinding.NoneAtInvisible, m) let tg2 = mbuilder.AddResultTarget(e2) let tg3 = mbuilder.AddResultTarget(e3) let dtree = TDSwitch(exprForVal m v, [TCase(DecisionTreeTest.IsNull, tg3)], Some tg2, m) let expr = mbuilder.Close(dtree, m, tyOfExpr g e2) - mkCompGenLet m v (mkIsInst tgty vinputExpr m) expr + mkCompGenLet m v (mkIsInst tgtTy vinputExpr m) expr else let mbuilder = MatchBuilder(DebugPointAtBinding.NoneAtInvisible, m) - let tg2 = TDSuccess([mkCallUnbox g m tgty vinputExpr], mbuilder.AddTarget(TTarget([v], e2, None))) + let tg2 = TDSuccess([mkCallUnbox g m tgtTy vinputExpr], mbuilder.AddTarget(TTarget([v], e2, None))) let tg3 = mbuilder.AddResultTarget(e3) - let dtree = TDSwitch(vinputExpr, [TCase(DecisionTreeTest.IsInst(tyOfExpr g vinputExpr, tgty), tg2)], Some tg3, m) + let dtree = TDSwitch(vinputExpr, [TCase(DecisionTreeTest.IsInst(tyOfExpr g vinputExpr, tgtTy), tg2)], Some tg3, m) let expr = mbuilder.Close(dtree, m, tyOfExpr g e2) expr @@ -9543,13 +9626,13 @@ let EvalLiteralExprOrAttribArg g x = // below is a little ugly. let GetTypeOfIntrinsicMemberInCompiledForm g (vref: ValRef) = assert (not vref.IsExtensionMember) - let membInfo, topValInfo = checkMemberValRef vref + let membInfo, valReprInfo = checkMemberValRef vref let tps, cxs, argInfos, retTy, retInfo = GetTypeOfMemberInMemberForm g vref let argInfos = // Check if the thing is really an instance member compiled as a static member // If so, the object argument counts as a normal argument in the compiled form if membInfo.MemberFlags.IsInstance && not (ValRefIsCompiledAsInstanceMember g vref) then - let _, origArgInfos, _, _ = GetTopValTypeInFSharpForm g topValInfo vref.Type vref.Range + let _, origArgInfos, _, _ = GetTopValTypeInFSharpForm g valReprInfo vref.Type vref.Range match origArgInfos with | [] -> errorR(InternalError("value does not have a valid member type", vref.Range)) @@ -9822,7 +9905,7 @@ let CombineCcuContentFragments m l = /// same namespace, making new module specs as we go. let rec CombineModuleOrNamespaceTypes path m (mty1: ModuleOrNamespaceType) (mty2: ModuleOrNamespaceType) = match mty1.ModuleOrNamespaceKind, mty2.ModuleOrNamespaceKind with - | Namespace, Namespace -> + | Namespace _, Namespace _ -> let kind = mty1.ModuleOrNamespaceKind let tab1 = mty1.AllEntitiesByLogicalMangledName let tab2 = mty2.AllEntitiesByLogicalMangledName @@ -9840,7 +9923,7 @@ let CombineCcuContentFragments m l = ModuleOrNamespaceType(kind, vals, QueueList.ofList entities) - | Namespace, _ | _, Namespace -> + | Namespace _, _ | _, Namespace _ -> error(Error(FSComp.SR.tastNamespaceAndModuleWithSameNameInAssembly(textOfPath path), m)) | _-> @@ -10032,7 +10115,7 @@ let (|ResumableCodeInvoke|_|) g expr = let ComputeUseMethodImpl g (v: Val) = v.ImplementedSlotSigs |> List.exists (fun slotsig -> - let oty = slotsig.ImplementedType + let oty = slotsig.DeclaringType let otcref = tcrefOfAppTy g oty let tcref = v.MemberApparentEntity diff --git a/src/Compiler/TypedTree/TypedTreeOps.fsi b/src/Compiler/TypedTree/TypedTreeOps.fsi index 9530e3c0662..5d27bff7fbc 100755 --- a/src/Compiler/TypedTree/TypedTreeOps.fsi +++ b/src/Compiler/TypedTree/TypedTreeOps.fsi @@ -845,7 +845,7 @@ val isDimensionless: TcGlobals -> TType -> bool // TType modifications and comparisons //--------------------------------------------------------------------------- -val stripMeasuresFromTType: TcGlobals -> TType -> TType +val stripMeasuresFromTy: TcGlobals -> TType -> TType //------------------------------------------------------------------------- // Equivalence of types (up to substitution of type variables in the left-hand type) @@ -1284,7 +1284,11 @@ val mkRepackageRemapping: SignatureRepackageInfo -> Remap /// Wrap one module or namespace implementation in a 'namespace N' outer wrapper val wrapModuleOrNamespaceContentsInNamespace: - Ident -> CompilationPath -> ModuleOrNamespaceContents -> ModuleOrNamespaceContents + isModule: bool -> + id: Ident -> + cpath: CompilationPath -> + mexpr: ModuleOrNamespaceContents -> + ModuleOrNamespaceContents /// Wrap one module or namespace definition in a 'namespace N' outer wrapper val wrapModuleOrNamespaceTypeInNamespace: @@ -1399,14 +1403,23 @@ val JoinTyparStaticReq: TyparStaticReq -> TyparStaticReq -> TyparStaticReq /// Layout for internal compiler debugging purposes module DebugPrint = + /// A global flag indicating whether debug output should include ValReprInfo + val mutable layoutValReprInfo: bool + + /// A global flag indicating whether debug output should include stamps of Val and Entity + val mutable layoutStamps: bool + /// A global flag indicating whether debug output should include ranges - val layoutRanges: bool ref + val mutable layoutRanges: bool + + /// A global flag indicating whether debug output should include type information + val mutable layoutTypes: bool /// Convert a type to a string for debugging purposes val showType: TType -> string /// Convert an expression to a string for debugging purposes - val showExpr: TcGlobals -> Expr -> string + val showExpr: Expr -> string /// Debug layout for a reference to a value val valRefL: ValRef -> Layout @@ -1415,7 +1428,7 @@ module DebugPrint = val unionCaseRefL: UnionCaseRef -> Layout /// Debug layout for an value definition at its binding site - val valAtBindL: TcGlobals -> Val -> Layout + val valAtBindL: Val -> Layout /// Debug layout for an integer val intL: int -> Layout @@ -1441,32 +1454,26 @@ module DebugPrint = /// Debug layout for a method slot signature val slotSigL: SlotSig -> Layout - /// Debug layout for the type signature of a module or namespace definition - val entityTypeL: TcGlobals -> ModuleOrNamespaceType -> Layout - /// Debug layout for a module or namespace definition - val entityL: TcGlobals -> ModuleOrNamespace -> Layout - - /// Debug layout for the type of a value - val typeOfValL: Val -> Layout + val entityL: ModuleOrNamespace -> Layout /// Debug layout for a binding of an expression to a value - val bindingL: TcGlobals -> Binding -> Layout + val bindingL: Binding -> Layout /// Debug layout for an expression - val exprL: TcGlobals -> Expr -> Layout + val exprL: Expr -> Layout /// Debug layout for a type definition - val tyconL: TcGlobals -> Tycon -> Layout + val tyconL: Tycon -> Layout /// Debug layout for a decision tree - val decisionTreeL: TcGlobals -> DecisionTree -> Layout + val decisionTreeL: DecisionTree -> Layout /// Debug layout for an implementation file - val implFileL: TcGlobals -> CheckedImplFile -> Layout + val implFileL: CheckedImplFile -> Layout /// Debug layout for a list of implementation files - val implFilesL: TcGlobals -> CheckedImplFile list -> Layout + val implFilesL: CheckedImplFile list -> Layout /// Debug layout for class and record fields val recdFieldRefL: RecdFieldRef -> Layout @@ -1658,6 +1665,9 @@ val underlyingTypeOfEnumTy: TcGlobals -> TType -> TType /// If the input type is an enum type, then convert to its underlying type, otherwise return the input type val normalizeEnumTy: TcGlobals -> TType -> TType +/// Determine if TyconRef is to a struct type +val isStructTyconRef: TyconRef -> bool + /// Determine if a type is a struct type val isStructTy: TcGlobals -> TType -> bool diff --git a/src/Compiler/TypedTree/TypedTreePickle.fs b/src/Compiler/TypedTree/TypedTreePickle.fs index 00e9ae570f1..57c557d2b8a 100644 --- a/src/Compiler/TypedTree/TypedTreePickle.fs +++ b/src/Compiler/TypedTree/TypedTreePickle.fs @@ -1575,7 +1575,7 @@ let p_measure_one = p_byte 4 // Pickle a unit-of-measure variable or constructor let p_measure_varcon unt st = match unt with - | Measure.Con tcref -> p_measure_con tcref st + | Measure.Const tcref -> p_measure_con tcref st | Measure.Var v -> p_measure_var v st | _ -> pfailwith st "p_measure_varcon: expected measure variable or constructor" @@ -1604,7 +1604,7 @@ let rec p_measure_power unt q st = let rec p_normalized_measure unt st = let unt = stripUnitEqnsAux false unt match unt with - | Measure.Con tcref -> p_measure_con tcref st + | Measure.Const tcref -> p_measure_con tcref st | Measure.Inv x -> p_byte 1 st; p_normalized_measure x st | Measure.Prod(x1, x2) -> p_byte 2 st; p_normalized_measure x1 st; p_normalized_measure x2 st | Measure.Var v -> p_measure_var v st @@ -1625,7 +1625,7 @@ let u_rational st = let rec u_measure_expr st = let tag = u_byte st match tag with - | 0 -> let a = u_tcref st in Measure.Con a + | 0 -> let a = u_tcref st in Measure.Const a | 1 -> let a = u_measure_expr st in Measure.Inv a | 2 -> let a, b = u_tup2 u_measure_expr u_measure_expr st in Measure.Prod (a, b) | 3 -> let a = u_tpref st in Measure.Var a @@ -1855,7 +1855,7 @@ let p_istype x st = match x with | FSharpModuleWithSuffix -> p_byte 0 st | ModuleOrType -> p_byte 1 st - | Namespace -> p_byte 2 st + | Namespace _ -> p_byte 2 st let p_cpath (CompPath(a, b)) st = p_tup2 p_ILScopeRef (p_list (p_tup2 p_string p_istype)) (a, b) st @@ -1867,7 +1867,7 @@ let u_istype st = match tag with | 0 -> FSharpModuleWithSuffix | 1 -> ModuleOrType - | 2 -> Namespace + | 2 -> Namespace true | _ -> ufailwith st "u_istype" let u_cpath st = let a, b = u_tup2 u_ILScopeRef (u_list (u_tup2 u_string u_istype)) st in (CompPath(a, b)) @@ -2353,6 +2353,7 @@ and u_ValData st = val_other_range = (match x1a with None -> None | Some(_, b) -> Some(b, true)) val_defn = None val_repr_info = x10 + val_repr_info_for_display = None val_const = x14 val_access = x13 val_xmldoc = defaultArg x15 XmlDoc.Empty @@ -2436,7 +2437,7 @@ and p_dtree_discrim x st = | DecisionTreeTest.UnionCase (ucref, tinst) -> p_byte 0 st; p_tup2 p_ucref p_tys (ucref, tinst) st | DecisionTreeTest.Const c -> p_byte 1 st; p_const c st | DecisionTreeTest.IsNull -> p_byte 2 st - | DecisionTreeTest.IsInst (srcty, tgty) -> p_byte 3 st; p_ty srcty st; p_ty tgty st + | DecisionTreeTest.IsInst (srcTy, tgtTy) -> p_byte 3 st; p_ty srcTy st; p_ty tgtTy st | DecisionTreeTest.ArrayLength (n, ty) -> p_byte 4 st; p_tup2 p_int p_ty (n, ty) st | DecisionTreeTest.ActivePatternCase _ -> pfailwith st "DecisionTreeTest.ActivePatternCase: only used during pattern match compilation" | DecisionTreeTest.Error _ -> pfailwith st "DecisionTreeTest.Error: only used during pattern match compilation" diff --git a/src/Compiler/Utilities/FileSystem.fs b/src/Compiler/Utilities/FileSystem.fs index 465adeac51d..bdd64e87b69 100644 --- a/src/Compiler/Utilities/FileSystem.fs +++ b/src/Compiler/Utilities/FileSystem.fs @@ -127,7 +127,8 @@ type ByteArrayMemory(bytes: byte[], offset, length) = ByteArrayMemory(Array.empty, 0, 0) :> ByteMemory override _.CopyTo stream = - if length > 0 then stream.Write(bytes, offset, length) + if length > 0 then + stream.Write(bytes, offset, length) override _.Copy(srcOffset, dest, destOffset, count) = checkCount count @@ -412,7 +413,8 @@ module internal FileSystemUtils = let checkSuffix (path: string) (suffix: string) = path.EndsWithOrdinalIgnoreCase(suffix) let hasExtensionWithValidate (validate: bool) (s: string) = - if validate then (checkPathForIllegalChars s) + if validate then + (checkPathForIllegalChars s) let sLen = s.Length @@ -437,7 +439,8 @@ module internal FileSystemUtils = Path.GetFileName(path) let fileNameWithoutExtensionWithValidate (validate: bool) path = - if validate then checkPathForIllegalChars path + if validate then + checkPathForIllegalChars path Path.GetFileNameWithoutExtension(path) @@ -563,7 +566,8 @@ type DefaultFileSystem() as this = let stream = new MemoryMappedStream(mmf, length) - if not stream.CanRead then invalidOp "Cannot read file" + if not stream.CanRead then + invalidOp "Cannot read file" stream :> Stream @@ -881,7 +885,8 @@ type internal ByteStream = } member b.ReadByte() = - if b.pos >= b.max then failwith "end of stream" + if b.pos >= b.max then + failwith "end of stream" let res = b.bytes[b.pos] b.pos <- b.pos + 1 @@ -948,7 +953,8 @@ type internal ByteBuffer = Bytes.blit old 0 buf.bbArray 0 buf.bbCurrent - if buf.useArrayPool then ArrayPool.Shared.Return old + if buf.useArrayPool then + ArrayPool.Shared.Return old member buf.AsMemory() = buf.CheckDisposed() diff --git a/src/Compiler/Utilities/HashMultiMap.fs b/src/Compiler/Utilities/HashMultiMap.fs index cb750676fe3..b88af5d77eb 100644 --- a/src/Compiler/Utilities/HashMultiMap.fs +++ b/src/Compiler/Utilities/HashMultiMap.fs @@ -170,7 +170,8 @@ type internal HashMultiMap<'Key, 'Value>(size: int, comparer: IEqualityComparer< member s.Remove(x) = match s.TryFind x.Key with | Some v -> - if Unchecked.equals v x.Value then s.Remove(x.Key) + if Unchecked.equals v x.Value then + s.Remove(x.Key) true | _ -> false diff --git a/src/Compiler/Utilities/ImmutableArray.fs b/src/Compiler/Utilities/ImmutableArray.fs index 5311efa5e0c..985799856c0 100644 --- a/src/Compiler/Utilities/ImmutableArray.fs +++ b/src/Compiler/Utilities/ImmutableArray.fs @@ -18,7 +18,8 @@ module ImmutableArray = | 0 -> ImmutableArray.Empty | 1 -> ImmutableArray.Create(f 0) | n -> - if n < 0 then invalidArg "n" "Below zero." + if n < 0 then + invalidArg "n" "Below zero." let builder = ImmutableArray.CreateBuilder(n) @@ -180,7 +181,8 @@ module ImmutableArray = let builder = ImmutableArray.CreateBuilder(arr.Length) for i = 0 to arr.Length - 1 do - if predicate arr[i] then builder.Add(arr[i]) + if predicate arr[i] then + builder.Add(arr[i]) builder.Capacity <- builder.Count builder.MoveToImmutable() @@ -199,7 +201,8 @@ module ImmutableArray = for i = 0 to arr.Length - 1 do let result = chooser arr[i] - if result.IsSome then builder.Add(result.Value) + if result.IsSome then + builder.Add(result.Value) builder.Capacity <- builder.Count builder.MoveToImmutable() diff --git a/src/Compiler/Utilities/ResizeArray.fs b/src/Compiler/Utilities/ResizeArray.fs index e96c775f972..cd6e405129c 100644 --- a/src/Compiler/Utilities/ResizeArray.fs +++ b/src/Compiler/Utilities/ResizeArray.fs @@ -26,7 +26,8 @@ module internal ResizeArray = if start2 < 0 then invalidArg "start2" "index must be positive" - if len < 0 then invalidArg "len" "length must be positive" + if len < 0 then + invalidArg "len" "length must be positive" if start1 + len > length arr1 then invalidArg "start1" "(start1+len) out of range" @@ -52,7 +53,8 @@ module internal ResizeArray = if start < 0 then invalidArg "start" "index must be positive" - if len < 0 then invalidArg "len" "length must be positive" + if len < 0 then + invalidArg "len" "length must be positive" if start + len > length arr then invalidArg "len" "length must be positive" @@ -63,7 +65,8 @@ module internal ResizeArray = if start < 0 then invalidArg "start" "index must be positive" - if len < 0 then invalidArg "len" "length must be positive" + if len < 0 then + invalidArg "len" "length must be positive" if start + len > length arr then invalidArg "len" "length must be positive" @@ -203,7 +206,9 @@ module internal ResizeArray = for i = 0 to length arr - 1 do let x = arr[i] - if f x then res.Add(x) + + if f x then + res.Add(x) res diff --git a/src/Compiler/Utilities/illib.fs b/src/Compiler/Utilities/illib.fs index b5e0a2d5218..3c1172aec7d 100644 --- a/src/Compiler/Utilities/illib.fs +++ b/src/Compiler/Utilities/illib.fs @@ -10,6 +10,9 @@ open System.IO open System.Threading open System.Threading.Tasks open System.Runtime.CompilerServices +#if !USE_SHIPPED_FSCORE +open FSharp.Core.CompilerServices.StateMachineHelpers +#endif [] module internal PervasiveAutoOpens = @@ -196,7 +199,8 @@ module Array = let mutable i = 0 while eq && i < len do - if not (inp[i] === res[i]) then eq <- false + if not (inp[i] === res[i]) then + eq <- false i <- i + 1 @@ -885,51 +889,27 @@ type ValueOrCancelled<'TResult> = /// A cancellable computation is passed may be cancelled via a CancellationToken, which is propagated implicitly. /// If cancellation occurs, it is propagated as data rather than by raising an OperationCanceledException. [] -type Cancellable<'TResult> = Cancellable of (CancellationToken -> ValueOrCancelled<'TResult>) +type Cancellable<'T> = Cancellable of (CancellationToken -> ValueOrCancelled<'T>) module Cancellable = /// Run a cancellable computation using the given cancellation token - let run (ct: CancellationToken) (Cancellable oper) = + let inline run (ct: CancellationToken) (Cancellable oper) = if ct.IsCancellationRequested then ValueOrCancelled.Cancelled(OperationCanceledException ct) else oper ct - /// Bind the result of a cancellable computation - let inline bind f comp1 = - Cancellable(fun ct -> - match run ct comp1 with - | ValueOrCancelled.Value v1 -> run ct (f v1) - | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1) - - /// Map the result of a cancellable computation - let inline map f oper = - Cancellable(fun ct -> - match run ct oper with - | ValueOrCancelled.Value res -> ValueOrCancelled.Value(f res) - | ValueOrCancelled.Cancelled err -> ValueOrCancelled.Cancelled err) - - /// Return a simple value as the result of a cancellable computation - let inline ret x = - Cancellable(fun _ -> ValueOrCancelled.Value x) - - /// Fold a cancellable computation along a sequence of inputs let fold f acc seq = Cancellable(fun ct -> - (ValueOrCancelled.Value acc, seq) - ||> Seq.fold (fun acc x -> - match acc with - | ValueOrCancelled.Value accv -> run ct (f accv x) - | res -> res)) + let mutable acc = ValueOrCancelled.Value acc - /// Iterate a cancellable computation over a collection - let inline each f seq = - fold (fun acc x -> f x |> map (fun y -> (y :: acc))) [] seq |> map List.rev + for x in seq do + match acc with + | ValueOrCancelled.Value accv -> acc <- run ct (f accv x) + | ValueOrCancelled.Cancelled _ -> () - /// Delay a cancellable computation - let inline delay (f: unit -> Cancellable<'T>) = - Cancellable(fun ct -> let (Cancellable g) = f () in g ct) + acc) /// Run the computation in a mode where it may not be cancelled. The computation never results in a /// ValueOrCancelled.Cancelled. @@ -960,61 +940,118 @@ module Cancellable = let canceled () = Cancellable(fun ct -> ValueOrCancelled.Cancelled(OperationCanceledException ct)) - /// Catch exceptions in a computation - let inline catch comp = - let (Cancellable f) = comp +type CancellableBuilder() = + member inline _.Delay([] f) = Cancellable(fun ct -> - try - match f ct with - | ValueOrCancelled.Value res -> ValueOrCancelled.Value(Choice1Of2 res) - | ValueOrCancelled.Cancelled exn -> ValueOrCancelled.Cancelled exn - with err -> - ValueOrCancelled.Value(Choice2Of2 err)) - - /// Implement try/finally for a cancellable computation - let inline tryFinally comp compensation = - catch comp - |> bind (fun res -> - compensation () - - match res with - | Choice1Of2 r -> ret r - | Choice2Of2 err -> raise err) - - /// Implement try/with for a cancellable computation - let inline tryWith comp handler = - catch comp - |> bind (fun res -> - match res with - | Choice1Of2 r -> ret r - | Choice2Of2 err -> handler err) + let (Cancellable g) = f () + g ct) -type CancellableBuilder() = + member inline _.Bind(comp, [] k) = + Cancellable(fun ct -> +#if !USE_SHIPPED_FSCORE + __debugPoint "" +#endif - member inline _.BindReturn(comp, k) = Cancellable.map k comp + match Cancellable.run ct comp with + | ValueOrCancelled.Value v1 -> Cancellable.run ct (k v1) + | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1) - member inline _.Bind(comp, k) = Cancellable.bind k comp + member inline _.BindReturn(comp, [] k) = + Cancellable(fun ct -> +#if !USE_SHIPPED_FSCORE + __debugPoint "" +#endif - member inline _.Return v = Cancellable.ret v + match Cancellable.run ct comp with + | ValueOrCancelled.Value v1 -> ValueOrCancelled.Value(k v1) + | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1) - member inline _.ReturnFrom(v: Cancellable<'T>) = v + member inline _.Combine(comp1, comp2) = + Cancellable(fun ct -> +#if !USE_SHIPPED_FSCORE + __debugPoint "" +#endif - member inline _.Combine(e1, e2) = e1 |> Cancellable.bind (fun () -> e2) + match Cancellable.run ct comp1 with + | ValueOrCancelled.Value () -> Cancellable.run ct comp2 + | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1) - member inline _.For(es, f) = es |> Cancellable.each f + member inline _.TryWith(comp, [] handler) = + Cancellable(fun ct -> +#if !USE_SHIPPED_FSCORE + __debugPoint "" +#endif - member inline _.TryWith(comp, handler) = Cancellable.tryWith comp handler + let compRes = + try + match Cancellable.run ct comp with + | ValueOrCancelled.Value res -> ValueOrCancelled.Value(Choice1Of2 res) + | ValueOrCancelled.Cancelled exn -> ValueOrCancelled.Cancelled exn + with err -> + ValueOrCancelled.Value(Choice2Of2 err) + + match compRes with + | ValueOrCancelled.Value res -> + match res with + | Choice1Of2 r -> ValueOrCancelled.Value r + | Choice2Of2 err -> Cancellable.run ct (handler err) + | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1) - member inline _.Using(resource, comp) = - Cancellable.tryFinally (comp resource) (fun () -> (resource :> IDisposable).Dispose()) + member inline _.Using(resource, [] comp) = + Cancellable(fun ct -> +#if !USE_SHIPPED_FSCORE + __debugPoint "" +#endif + let body = comp resource - member inline _.TryFinally(comp, compensation) = - Cancellable.tryFinally comp compensation + let compRes = + try + match Cancellable.run ct body with + | ValueOrCancelled.Value res -> ValueOrCancelled.Value(Choice1Of2 res) + | ValueOrCancelled.Cancelled exn -> ValueOrCancelled.Cancelled exn + with err -> + ValueOrCancelled.Value(Choice2Of2 err) + + match compRes with + | ValueOrCancelled.Value res -> + (resource :> IDisposable).Dispose() + + match res with + | Choice1Of2 r -> ValueOrCancelled.Value r + | Choice2Of2 err -> raise err + | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1) - member inline _.Delay f = Cancellable.delay f + member inline _.TryFinally(comp, [] compensation) = + Cancellable(fun ct -> +#if !USE_SHIPPED_FSCORE + __debugPoint "" +#endif + + let compRes = + try + match Cancellable.run ct comp with + | ValueOrCancelled.Value res -> ValueOrCancelled.Value(Choice1Of2 res) + | ValueOrCancelled.Cancelled exn -> ValueOrCancelled.Cancelled exn + with err -> + ValueOrCancelled.Value(Choice2Of2 err) + + match compRes with + | ValueOrCancelled.Value res -> + compensation () + + match res with + | Choice1Of2 r -> ValueOrCancelled.Value r + | Choice2Of2 err -> raise err + | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1) + + member inline _.Return v = + Cancellable(fun _ -> ValueOrCancelled.Value v) + + member inline _.ReturnFrom(v: Cancellable<'T>) = v - member inline _.Zero() = Cancellable.ret () + member inline _.Zero() = + Cancellable(fun _ -> ValueOrCancelled.Value()) [] module CancellableAutoOpens = @@ -1046,9 +1083,11 @@ type MemoizationTable<'T, 'U>(compute: 'T -> 'U, keyComparer: IEqualityComparer< let table = new ConcurrentDictionary<'T, 'U>(keyComparer) member t.Apply x = - if (match canMemoize with - | None -> true - | Some f -> f x) then + if + (match canMemoize with + | None -> true + | Some f -> f x) + then match table.TryGetValue x with | true, res -> res | _ -> diff --git a/src/Compiler/Utilities/illib.fsi b/src/Compiler/Utilities/illib.fsi index f2518c2cfb3..8ea3cb9727b 100644 --- a/src/Compiler/Utilities/illib.fsi +++ b/src/Compiler/Utilities/illib.fsi @@ -369,80 +369,53 @@ type internal ValueOrCancelled<'TResult> = | Value of result: 'TResult | Cancelled of ``exception``: OperationCanceledException -/// Represents a synchronous cancellable computation with explicit representation of a cancelled result. +/// Represents a synchronous, cold-start, cancellable computation with explicit representation of a cancelled result. /// -/// A cancellable computation is passed may be cancelled via a CancellationToken, which is propagated implicitly. +/// A cancellable computation may be cancelled via a CancellationToken, which is propagated implicitly. /// If cancellation occurs, it is propagated as data rather than by raising an OperationCanceledException. [] -type internal Cancellable<'TResult> = Cancellable of (CancellationToken -> ValueOrCancelled<'TResult>) +type internal Cancellable<'T> = Cancellable of (CancellationToken -> ValueOrCancelled<'T>) module internal Cancellable = /// Run a cancellable computation using the given cancellation token - val run: ct: CancellationToken -> Cancellable<'a> -> ValueOrCancelled<'a> + val inline run: ct: CancellationToken -> Cancellable<'T> -> ValueOrCancelled<'T> - /// Bind the result of a cancellable computation - val inline bind: f: ('a -> Cancellable<'b>) -> comp1: Cancellable<'a> -> Cancellable<'b> - - /// Map the result of a cancellable computation - val inline map: f: ('a -> 'b) -> oper: Cancellable<'a> -> Cancellable<'b> - - /// Return a simple value as the result of a cancellable computation - val inline ret: x: 'a -> Cancellable<'a> - - /// Fold a cancellable computation along a sequence of inputs - val fold: f: ('a -> 'b -> Cancellable<'a>) -> acc: 'a -> seq: seq<'b> -> Cancellable<'a> - - /// Iterate a cancellable computation over a collection - val inline each: f: ('a -> Cancellable<'b>) -> seq: seq<'a> -> Cancellable<'b list> - - /// Delay a cancellable computation - val inline delay: f: (unit -> Cancellable<'T>) -> Cancellable<'T> + val fold: f: ('State -> 'T -> Cancellable<'State>) -> acc: 'State -> seq: seq<'T> -> Cancellable<'State> /// Run the computation in a mode where it may not be cancelled. The computation never results in a /// ValueOrCancelled.Cancelled. - val runWithoutCancellation: comp: Cancellable<'a> -> 'a + val runWithoutCancellation: comp: Cancellable<'T> -> 'T /// Bind the cancellation token associated with the computation val token: unit -> Cancellable - /// Represents a canceled computation - val canceled: unit -> Cancellable<'a> - - /// Implement try/finally for a cancellable computation - val inline catch: comp: Cancellable<'a> -> Cancellable> - - /// Implement try/finally for a cancellable computation - val inline tryFinally: comp: Cancellable<'a> -> compensation: (unit -> unit) -> Cancellable<'a> - - /// Implement try/with for a cancellable computation - val inline tryWith: comp: Cancellable<'a> -> handler: (exn -> Cancellable<'a>) -> Cancellable<'a> - - val toAsync: Cancellable<'a> -> Async<'a> + val toAsync: Cancellable<'T> -> Async<'T> type internal CancellableBuilder = new: unit -> CancellableBuilder - member inline BindReturn: comp: Cancellable<'T> * k: ('T -> 'U) -> Cancellable<'U> - - member inline Bind: comp: Cancellable<'T> * k: ('T -> Cancellable<'U>) -> Cancellable<'U> + member inline BindReturn: comp: Cancellable<'T> * [] k: ('T -> 'U) -> Cancellable<'U> - member inline Combine: e1: Cancellable * e2: Cancellable<'T> -> Cancellable<'T> + member inline Bind: comp: Cancellable<'T> * [] k: ('T -> Cancellable<'U>) -> Cancellable<'U> - member inline Delay: f: (unit -> Cancellable<'T>) -> Cancellable<'T> + member inline Combine: comp1: Cancellable * comp2: Cancellable<'T> -> Cancellable<'T> - member inline For: es: seq<'T> * f: ('T -> Cancellable<'U>) -> Cancellable<'U list> + member inline Delay: [] f: (unit -> Cancellable<'T>) -> Cancellable<'T> member inline Return: v: 'T -> Cancellable<'T> member inline ReturnFrom: v: Cancellable<'T> -> Cancellable<'T> - member inline TryFinally: comp: Cancellable<'T> * compensation: (unit -> unit) -> Cancellable<'T> + member inline TryFinally: comp: Cancellable<'T> * [] compensation: (unit -> unit) -> Cancellable<'T> - member inline TryWith: comp: Cancellable<'T> * handler: (exn -> Cancellable<'T>) -> Cancellable<'T> + member inline TryWith: + comp: Cancellable<'T> * [] handler: (exn -> Cancellable<'T>) -> Cancellable<'T> - member inline Using: resource: 'c * comp: ('c -> Cancellable<'T>) -> Cancellable<'T> when 'c :> IDisposable + member inline Using: + resource: 'Resource * [] comp: ('Resource -> Cancellable<'T>) -> Cancellable<'T> + when 'Resource :> IDisposable member inline Zero: unit -> Cancellable diff --git a/src/Compiler/Utilities/range.fs b/src/Compiler/Utilities/range.fs index 035a5de80f4..bbd6a9f0673 100755 --- a/src/Compiler/Utilities/range.fs +++ b/src/Compiler/Utilities/range.fs @@ -343,9 +343,11 @@ type Range(code1: int64, code2: int64) = member m.DebugCode = let name = m.FileName - if name = unknownFileName - || name = startupFileName - || name = commandLineArgsFileName then + if + name = unknownFileName + || name = startupFileName + || name = commandLineArgsFileName + then name else @@ -460,20 +462,26 @@ module Range = else // If all identical then return m1. This preserves NotedSourceConstruct when no merging takes place - if m1.Code1 = m2.Code1 && m1.Code2 = m2.Code2 then + if + m1.Code1 = m2.Code1 && m1.Code2 = m2.Code2 + then m1 else let start = - if (m1.StartLine > m2.StartLine - || (m1.StartLine = m2.StartLine && m1.StartColumn > m2.StartColumn)) then + if + (m1.StartLine > m2.StartLine + || (m1.StartLine = m2.StartLine && m1.StartColumn > m2.StartColumn)) + then m2 else m1 let finish = - if (m1.EndLine > m2.EndLine - || (m1.EndLine = m2.EndLine && m1.EndColumn > m2.EndColumn)) then + if + (m1.EndLine > m2.EndLine + || (m1.EndLine = m2.EndLine && m1.EndColumn > m2.EndColumn)) + then m1 else m2 diff --git a/src/Compiler/Utilities/sformat.fs b/src/Compiler/Utilities/sformat.fs index e9ff2aecd26..42b13e28ff9 100644 --- a/src/Compiler/Utilities/sformat.fs +++ b/src/Compiler/Utilities/sformat.fs @@ -232,6 +232,8 @@ module TaggedText = let keywordGet = tagKeyword "get" let bar = tagPunctuation "|" let keywordStruct = tagKeyword "struct" + let keywordClass = tagKeyword "class" + let keywordInterface = tagKeyword "interface" let keywordInherit = tagKeyword "inherit" let keywordEnd = tagKeyword "end" let keywordBegin = tagKeyword "begin" @@ -630,7 +632,8 @@ module Display = Breaks(next + 1, outer, stack) let popBreak (Breaks (next, outer, stack)) = - if next = 0 then raise (Failure "popBreak: underflow") + if next = 0 then + raise (Failure "popBreak: underflow") let topBroke = stack[next - 1] < 0 @@ -1310,12 +1313,14 @@ module Display = let possibleKeyValueL v = let tyv = v.GetType() - if word = "map" - && (match v with - | null -> false - | _ -> true) - && tyv.IsGenericType - && tyv.GetGenericTypeDefinition() = typedefof> then + if + word = "map" + && (match v with + | null -> false + | _ -> true) + && tyv.IsGenericType + && tyv.GetGenericTypeDefinition() = typedefof> + then nestedObjL depthLim Precedence.BracketIfTuple @@ -1527,8 +1532,10 @@ module Display = "-infinity" elif Double.IsPositiveInfinity(d) then "infinity" - elif opts.FloatingPointFormat[0] = 'g' - && String.forall (fun c -> Char.IsDigit(c) || c = '-') s then + elif + opts.FloatingPointFormat[0] = 'g' + && String.forall (fun c -> Char.IsDigit(c) || c = '-') s + then s + ".0" else s @@ -1543,11 +1550,13 @@ module Display = "-infinity" elif Single.IsPositiveInfinity(d) then "infinity" - elif opts.FloatingPointFormat.Length >= 1 - && opts.FloatingPointFormat[0] = 'g' - && float32 (Int32.MinValue) < d - && d < float32 (Int32.MaxValue) - && float32 (int32 (d)) = d then + elif + opts.FloatingPointFormat.Length >= 1 + && opts.FloatingPointFormat[0] = 'g' + && float32 (Int32.MinValue) < d + && d < float32 (Int32.MaxValue) + && float32 (int32 (d)) = d + then (Convert.ToInt32 d).ToString(opts.FormatProvider) + ".0" else d.ToString(opts.FloatingPointFormat, opts.FormatProvider)) diff --git a/src/Compiler/Utilities/sformat.fsi b/src/Compiler/Utilities/sformat.fsi index 41f57bc700f..72afa8361d3 100644 --- a/src/Compiler/Utilities/sformat.fsi +++ b/src/Compiler/Utilities/sformat.fsi @@ -188,6 +188,8 @@ module internal TaggedText = val internal keywordGet: TaggedText val internal bar: TaggedText val internal keywordStruct: TaggedText + val internal keywordClass: TaggedText + val internal keywordInterface: TaggedText val internal keywordInherit: TaggedText val internal keywordBegin: TaggedText val internal keywordEnd: TaggedText diff --git a/src/Compiler/pars.fsy b/src/Compiler/pars.fsy index b44dd35ecac..2238c89041b 100644 --- a/src/Compiler/pars.fsy +++ b/src/Compiler/pars.fsy @@ -79,17 +79,10 @@ let addAttribs attrs p = SynPat.Attrib(p, attrs, p.Range) let parse_error_rich = Some (fun (ctxt: ParseErrorContext<_>) -> errorR(SyntaxError(box ctxt, ctxt.ParseState.LexBuffer.LexemeRange))) -let reportParseErrorAt m s = errorR(Error(s, m)) - let unionRangeWithPos (r:range) p = let r2 = mkRange r.FileName p p unionRanges r r2 -let raiseParseErrorAt m s = - reportParseErrorAt m s; - // This initiates error recovery - raise RecoverableParseError - /// Report a good error at the end of file, e.g. for non-terminated strings let checkEndOfFileError t = match t with @@ -148,15 +141,15 @@ type BindingSet = BindingSetPreAttrs of range * bool * bool * (SynAttributes -> let mkClassMemberLocalBindings(isStatic, initialRangeOpt, attrs, vis, BindingSetPreAttrs(_, isRec, isUse, declsPreAttrs, bindingSetRange)) = let ignoredFreeAttrs, decls = declsPreAttrs attrs vis - let wholeRange = + let mWhole = match initialRangeOpt with | None -> bindingSetRange | Some m -> unionRanges m bindingSetRange // decls could have a leading attribute |> fun m -> (m, decls) ||> unionRangeWithListBy (fun (SynBinding(range = m)) -> m) - if not (isNil ignoredFreeAttrs) then warning(Error(FSComp.SR.parsAttributesIgnored(), wholeRange)); - if isUse then errorR(Error(FSComp.SR.parsUseBindingsIllegalInImplicitClassConstructors(), wholeRange)) - SynMemberDefn.LetBindings (decls, isStatic, isRec, wholeRange) + if not (isNil ignoredFreeAttrs) then warning(Error(FSComp.SR.parsAttributesIgnored(), mWhole)); + if isUse then errorR(Error(FSComp.SR.parsUseBindingsIllegalInImplicitClassConstructors(), mWhole)) + SynMemberDefn.LetBindings (decls, isStatic, isRec, mWhole) let mkLocalBindings (mWhole, BindingSetPreAttrs(_, isRec, isUse, declsPreAttrs, _), mIn, body: SynExpr) = let ignoredFreeAttrs, decls = declsPreAttrs [] None @@ -837,12 +830,12 @@ moduleSpfn: _xmlDoc.MarkAsInvalid() let attrs = $1 @ cas let xmlDoc = grabXmlDoc(parseState, $1, 1) - let mTc = + let mDefn = (d3, attrs) ||> unionRangeWithListBy (fun (a: SynAttributeList) -> a.Range) |> unionRanges range |> unionRangeWithXmlDoc xmlDoc - let tc = (SynTypeDefnSig(SynComponentInfo(attrs, a, cs, b, xmlDoc, d, d2, d3), equalsRange, typeRepr, withKeyword, members, mTc)) - let m = (mTc, $5) ||> unionRangeWithListBy (fun (a: SynTypeDefnSig) -> a.Range) |> unionRanges (rhs parseState 3) + let tc = SynTypeDefnSig(SynComponentInfo(attrs, a, cs, b, xmlDoc, d, d2, d3), equalsRange, typeRepr, withKeyword, members, mDefn) + let m = (mDefn, $5) ||> unionRangeWithListBy (fun (a: SynTypeDefnSig) -> a.Range) |> unionRanges (rhs parseState 3) SynModuleSigDecl.Types (tc :: $5, m) } | opt_attributes opt_declVisibility exconSpfn @@ -851,8 +844,8 @@ moduleSpfn: let xmlDoc = grabXmlDoc(parseState, $1, 1) let mDefnReprWithAttributes = (d2, $1) ||> unionRangeWithListBy (fun a -> a.Range) |> unionRangeWithXmlDoc xmlDoc let mWhole = (mDefnReprWithAttributes, members) ||> unionRangeWithListBy (fun (m: SynMemberSig) -> m.Range) - let ec = SynExceptionSig(SynExceptionDefnRepr($1@cas, a, b, xmlDoc, d, mDefnReprWithAttributes), withKeyword, members, mWhole) - SynModuleSigDecl.Exception(ec, mWhole) } + let synExnDefn = SynExceptionSig(SynExceptionDefnRepr($1@cas, a, b, xmlDoc, d, mDefnReprWithAttributes), withKeyword, members, mWhole) + SynModuleSigDecl.Exception(synExnDefn, mWhole) } | openDecl { SynModuleSigDecl.Open($1, (rhs parseState 1)) } @@ -860,24 +853,32 @@ moduleSpfn: valSpfn: | opt_attributes opt_declVisibility VAL opt_attributes opt_inline opt_mutable opt_access nameop opt_explicitValTyparDecls COLON topTypeWithTypeConstraints optLiteralValueSpfn { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) - let attr1, attr2, isInline, isMutable, vis2, id, doc, explicitValTyparDecls, (ty, arity), konst = ($1), ($4), ($5), ($6), ($7), ($8), grabXmlDoc(parseState, $1, 1), ($9), ($11), ($12) + let attr1, attr2, isInline, isMutable, vis2, id, doc, explicitValTyparDecls, (ty, arity), (mEquals, konst: SynExpr option) = ($1), ($4), ($5), ($6), ($7), ($8), grabXmlDoc(parseState, $1, 1), ($9), ($11), ($12) if not (isNil attr2) then errorR(Deprecated(FSComp.SR.parsAttributesMustComeBeforeVal(), rhs parseState 4)) - let m = rhs2 parseState 1 11 |> unionRangeWithXmlDoc doc + let m = + rhs2 parseState 1 11 + |> unionRangeWithXmlDoc doc + |> fun m -> + match konst with + | None -> m + | Some e -> unionRanges m e.Range let mVal = rhs parseState 3 - let valSpfn = SynValSig((attr1@attr2), id, explicitValTyparDecls, ty, arity, isInline, isMutable, doc, vis2, konst, m, { ValKeyword = Some mVal; WithKeyword = None }) + let valSpfn = SynValSig((attr1@attr2), id, explicitValTyparDecls, ty, arity, isInline, isMutable, doc, vis2, konst, m, { ValKeyword = Some mVal; WithKeyword = None; EqualsRange = mEquals }) SynModuleSigDecl.Val(valSpfn, m) } /* The optional literal value on a literal specification in a signature */ optLiteralValueSpfn: | /* EMPTY */ - { None } + { None, None } | EQUALS declExpr - { Some($2) } + { let mEquals = rhs parseState 1 + Some(mEquals), Some($2) } | EQUALS OBLOCKBEGIN declExpr oblockend opt_ODECLEND - { Some($3) } + { let mEquals = rhs parseState 1 + Some(mEquals), Some($3) } /* A block of definitions in a module in a signature file */ @@ -900,7 +901,8 @@ tyconSpfnList: | AND tyconSpfn tyconSpfnList { let xmlDoc = grabXmlDoc(parseState, [], 1) let tyconSpfn = - let (SynTypeDefnSig(SynComponentInfo (a, typars, c, lid, _xmlDoc, fixity, vis, rangeOfLid) as componentInfo, equalsRange, typeRepr, withKeyword, members, range)) = $2 + let (SynTypeDefnSig(componentInfo, equalsRange, typeRepr, withKeyword, members, range)) = $2 + let (SynComponentInfo(a, typars, c, lid, _xmlDoc, fixity, vis, mLongId)) = componentInfo if xmlDoc.IsEmpty then if _xmlDoc.IsEmpty then $2 else let range = unionRangeWithXmlDoc _xmlDoc range @@ -909,7 +911,8 @@ tyconSpfnList: else _xmlDoc.MarkAsInvalid() let range = unionRangeWithXmlDoc xmlDoc range - SynTypeDefnSig(SynComponentInfo (a, typars, c, lid, xmlDoc, fixity, vis, rangeOfLid), equalsRange, typeRepr, withKeyword, members, range) + let componentInfo = SynComponentInfo (a, typars, c, lid, xmlDoc, fixity, vis, mLongId) + SynTypeDefnSig(componentInfo, equalsRange, typeRepr, withKeyword, members, range) tyconSpfn :: $3 } | @@ -919,9 +922,9 @@ tyconSpfnList: /* A type definition in a signature */ tyconSpfn: | typeNameInfo EQUALS tyconSpfnRhsBlock - { let lhsm = rhs parseState 1 + { let mLhs = rhs parseState 1 let mEquals = rhs parseState 2 - $3 lhsm $1 (Some mEquals) } + $3 mLhs $1 (Some mEquals) } | typeNameInfo opt_classSpfn { let mWithKwd, members = $2 let (SynComponentInfo(range=range)) = $1 @@ -948,22 +951,22 @@ tyconSpfnRhsBlock: /* representation. */ | OBLOCKBEGIN tyconSpfnRhs opt_OBLOCKSEP classSpfnMembers opt_classSpfn oblockend opt_classSpfn { let m = lhs parseState - (fun lhsm nameInfo mEquals -> + (fun mLhs nameInfo mEquals -> let members = $4 @ (snd $5) - $2 lhsm nameInfo mEquals (checkForMultipleAugmentations m members (snd $7))) } + $2 mLhs nameInfo mEquals (checkForMultipleAugmentations m members (snd $7))) } | tyconSpfnRhs opt_classSpfn { let m = lhs parseState - (fun lhsm nameInfo mEquals -> + (fun mLhs nameInfo mEquals -> let _, members = $2 - $1 lhsm nameInfo mEquals members) } + $1 mLhs nameInfo mEquals members) } /* The right-hand-side of a type definition in a signature */ tyconSpfnRhs: | tyconDefnOrSpfnSimpleRepr - { (fun lhsm nameInfo mEquals augmentation -> - let declRange = unionRanges lhsm $1.Range + { (fun mLhs nameInfo mEquals augmentation -> + let declRange = unionRanges mLhs $1.Range let mWhole = (declRange, augmentation) ||> unionRangeWithListBy (fun (mem: SynMemberSig) -> mem.Range) SynTypeDefnSig(nameInfo, mEquals, SynTypeDefnSigRepr.Simple ($1, $1.Range), None, augmentation, mWhole)) } @@ -1059,19 +1062,23 @@ classSpfnMembersAtLeastOne: classMemberSpfn: | opt_attributes opt_declVisibility memberSpecFlags opt_inline opt_access nameop opt_explicitValTyparDecls COLON topTypeWithTypeConstraints classMemberSpfnGetSet optLiteralValueSpfn { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) - let isInline, doc, vis2, id, explicitValTyparDecls, (ty, arity), optLiteralValue = $4, grabXmlDoc(parseState, $1, 1), $5, $6, $7, $9, $11 + let isInline, doc, vis2, id, explicitValTyparDecls, (ty, arity), (mEquals, optLiteralValue) = $4, grabXmlDoc(parseState, $1, 1), $5, $6, $7, $9, $11 let mWith, getSetRangeOpt, getSet = $10 let getSetAdjuster arity = match arity, getSet with SynValInfo([], _), SynMemberKind.Member -> SynMemberKind.PropertyGet | _ -> getSet - let wholeRange = + let mWhole = let m = rhs parseState 3 match getSetRangeOpt with | None -> unionRanges m ty.Range | Some m2 -> unionRanges m m2 |> fun m -> (m, $1) ||> unionRangeWithListBy (fun (a: SynAttributeList) -> a.Range) |> unionRangeWithXmlDoc doc - let valSpfn = SynValSig($1, id, explicitValTyparDecls, ty, arity, isInline, false, doc, vis2, optLiteralValue, wholeRange, { ValKeyword = None; WithKeyword = mWith }) + |> fun m -> + match optLiteralValue with + | None -> m + | Some e -> unionRanges m e.Range + let valSpfn = SynValSig($1, id, explicitValTyparDecls, ty, arity, isInline, false, doc, vis2, optLiteralValue, mWhole, { ValKeyword = None; WithKeyword = mWith; EqualsRange = mEquals }) let _, flags = $3 - SynMemberSig.Member(valSpfn, flags (getSetAdjuster arity), wholeRange) } + SynMemberSig.Member(valSpfn, flags (getSetAdjuster arity), mWhole) } | opt_attributes opt_declVisibility interfaceMember appType { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) @@ -1082,18 +1089,18 @@ classMemberSpfn: SynMemberSig.Inherit ($4, unionRanges (rhs parseState 3) ($4).Range) } | opt_attributes opt_declVisibility VAL fieldDecl - { let wholeRange = rhs2 parseState 1 4 + { let mWhole = rhs2 parseState 1 4 if Option.isSome $2 then errorR (Error (FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier (), rhs parseState 2)) - let (SynField(_, _, _, _, _, xmlDoc, _, _)) as field = $4 $1 false wholeRange - let wholeRange = unionRangeWithXmlDoc xmlDoc wholeRange - SynMemberSig.ValField (field, wholeRange) } + let (SynField(_, _, _, _, _, xmlDoc, _, _)) as field = $4 $1 false mWhole + let mWhole = unionRangeWithXmlDoc xmlDoc mWhole + SynMemberSig.ValField (field, mWhole) } | opt_attributes opt_declVisibility STATIC VAL fieldDecl - { let wholeRange = rhs2 parseState 1 5 + { let mWhole = rhs2 parseState 1 5 if Option.isSome $2 then errorR (Error (FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier (), rhs parseState 2)) - let (SynField(_, _, _, _, _, xmlDoc, _, _)) as field = $5 $1 true wholeRange - let wholeRange = unionRangeWithXmlDoc xmlDoc wholeRange - SynMemberSig.ValField(field, wholeRange) } + let (SynField(_, _, _, _, _, xmlDoc, _, _)) as field = $5 $1 true mWhole + let mWhole = unionRangeWithXmlDoc xmlDoc mWhole + SynMemberSig.ValField(field, mWhole) } | opt_attributes opt_declVisibility STATIC typeKeyword tyconSpfn { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(), rhs parseState 2)) @@ -1369,9 +1376,9 @@ moduleDefn: let (SynTypeDefn(SynComponentInfo(cas, a, cs, b, _xmlDoc, d, d2, d3), e, f, g, h, trivia)) = $4 _xmlDoc.MarkAsInvalid() let attrs = $1@cas - let mTc = (h, attrs) ||> unionRangeWithListBy (fun (a: SynAttributeList) -> a.Range) |> unionRangeWithXmlDoc xmlDoc + let mDefn = (h, attrs) ||> unionRangeWithListBy (fun (a: SynAttributeList) -> a.Range) |> unionRangeWithXmlDoc xmlDoc let mType = rhs parseState 3 - let tc = (SynTypeDefn(SynComponentInfo(attrs, a, cs, b, xmlDoc, d, d2, d3), e, f, g, mTc, { trivia with TypeKeyword = Some mType })) + let tc = SynTypeDefn(SynComponentInfo(attrs, a, cs, b, xmlDoc, d, d2, d3), e, f, g, mDefn, { trivia with TypeKeyword = Some mType }) let types = tc :: $5 [ SynModuleDecl.Types(types, (rhs parseState 3, types) ||> unionRangeWithListBy (fun t -> t.Range) ) ] } @@ -1382,8 +1389,8 @@ moduleDefn: let xmlDoc = grabXmlDoc(parseState, $1, 1) let defnReprRange = (d2, $1) ||> unionRangeWithListBy (fun a -> a.Range) |> unionRangeWithXmlDoc xmlDoc let mWhole = (f, $1) ||> unionRangeWithListBy (fun a -> a.Range) |> unionRangeWithXmlDoc xmlDoc - let ec = (SynExceptionDefn(SynExceptionDefnRepr($1@cas, a, b, xmlDoc, d, defnReprRange), withKeyword, e, mWhole)) - [ SynModuleDecl.Exception(ec, mWhole) ] } + let synExnDefn = SynExceptionDefn(SynExceptionDefnRepr($1@cas, a, b, xmlDoc, d, defnReprRange), withKeyword, e, mWhole) + [ SynModuleDecl.Exception(synExnDefn, mWhole) ] } /* 'module' definitions */ | opt_attributes opt_declVisibility moduleIntro EQUALS namedModuleDefnBlock @@ -1609,7 +1616,8 @@ tyconDefnList: | AND tyconDefn tyconDefnList { let xmlDoc = grabXmlDoc(parseState, [], 1) let tyconDefn = - let (SynTypeDefn(SynComponentInfo (a, typars, c, lid, _xmlDoc, fixity, vis, rangeOfLid) as componentInfo, typeRepr, members, implicitConstructor, range, trivia)) = $2 + let (SynTypeDefn(componentInfo, typeRepr, members, implicitConstructor, range, trivia)) = $2 + let (SynComponentInfo(a, typars, c, lid, _xmlDoc, fixity, vis, mLongId)) = componentInfo if xmlDoc.IsEmpty then if _xmlDoc.IsEmpty then $2 else let range = unionRangeWithXmlDoc _xmlDoc range @@ -1618,7 +1626,8 @@ tyconDefnList: else _xmlDoc.MarkAsInvalid() let range = unionRangeWithXmlDoc xmlDoc range - SynTypeDefn(SynComponentInfo (a, typars, c, lid, xmlDoc, fixity, vis, rangeOfLid), typeRepr, members, implicitConstructor, range, trivia) + let componentInfo = SynComponentInfo (a, typars, c, lid, xmlDoc, fixity, vis, mLongId) + SynTypeDefn(componentInfo, typeRepr, members, implicitConstructor, range, trivia) tyconDefn :: $3 } | { [] } @@ -1860,198 +1869,8 @@ memberCore: { let mWith, (classDefnMemberGetSetElements, mAnd) = $4 let mWhole = (rhs parseState 2, classDefnMemberGetSetElements) ||> unionRangeWithListBy (fun (_, _, _, _, _, _, m2) -> m2) let propertyNameBindingPat, _ = $2 - let optPropertyType = $3 - let isMutable = false - (fun visNoLongerUsed memFlagsBuilder attrs rangeStart -> - let mutable hasGet = false - let mutable hasSet = false - let xmlDoc = grabXmlDocAtRangeStart(parseState, attrs, rangeStart) - - let tryMkSynMemberDefnMember - (withPropertyKeyword: PropertyKeyword option) - (optInline, (optAttrs: SynAttributeList list), (bindingPat, mBindLhs), optReturnType, mEquals, expr, mExpr) - = - let optInline = $1 || optInline - // optional attributes are only applied to getters and setters - // the "top level" attrs will be applied to both - let optAttrs = - optAttrs |> List.map (fun attrList -> - { attrList with Attributes = attrList.Attributes |> List.map (fun a -> { a with AppliesToGetterAndSetter = true } ) }) - - let attrs = attrs @ optAttrs - - let trivia: SynBindingTrivia = { LetKeyword = None; EqualsRange = mEquals } - let binding = mkSynBinding (xmlDoc, bindingPat) (visNoLongerUsed, optInline, isMutable, mBindLhs, DebugPointAtBinding.NoneAtInvisible, optReturnType, expr, mExpr, [], attrs, Some (memFlagsBuilder SynMemberKind.Member), trivia) - let (SynBinding (vis, _, isInline, _, attrs, doc, valSynData, pv, _, _, mBindLhs, spBind, _)) = binding - let memberKind = - let getset = - let rec go p = - match p with - | SynPat.LongIdent (longDotId=SynLongIdent([id], _, _)) -> id.idText - | SynPat.Named (SynIdent(nm, _), _, _, _) | SynPat.As (_, SynPat.Named (SynIdent(nm, _), _, _, _), _) -> nm.idText - | SynPat.Typed (p, _, _) -> go p - | SynPat.Attrib (p, _, _) -> go p - | _ -> raiseParseErrorAt mBindLhs (FSComp.SR.parsInvalidDeclarationSyntax()) - go pv - if getset = "get" then - if hasGet then - reportParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired()) - None - else - hasGet <- true - Some SynMemberKind.PropertyGet - else if getset = "set" then - if hasSet then - reportParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired()) - None - else - hasSet <- true - Some SynMemberKind.PropertySet - else - raiseParseErrorAt mBindLhs (FSComp.SR.parsGetAndOrSetRequired()) - - match memberKind with - | None -> None - | Some memberKind -> - - // REVIEW: It's hard not to ignore the optPropertyType type annotation for 'set' properties. To apply it, - // we should apply it to the last argument, but at this point we've already pushed the patterns that - // make up the arguments onto the RHS. So we just always give a warning. - - begin match optPropertyType with - | Some _ -> errorR(Error(FSComp.SR.parsTypeAnnotationsOnGetSet(), mBindLhs)) - | None -> () - end - - let optReturnType = - match (memberKind, optReturnType) with - | SynMemberKind.PropertySet, _ -> optReturnType - | _, None -> optPropertyType - | _ -> optReturnType - - // REDO with the correct member kind - let trivia: SynBindingTrivia = { LetKeyword = None; EqualsRange = mEquals } - let binding = mkSynBinding (PreXmlDoc.Empty, bindingPat) (vis, isInline, isMutable, mBindLhs, DebugPointAtBinding.NoneAtInvisible, optReturnType, expr, mExpr, [], attrs, Some(memFlagsBuilder memberKind), trivia) - - let (SynBinding (vis, _, isInline, _, attrs, doc, valSynData, pv, rhsRetInfo, rhsExpr, mBindLhs, spBind, trivia)) = binding - let mWholeBindLhs = (mBindLhs, attrs) ||> unionRangeWithListBy (fun (a: SynAttributeList) -> a.Range) - - let (SynValData(_, valSynInfo, _)) = valSynData - - // Setters have all arguments tupled in their internal TAST form, though they don't appear to be - // tupled from the syntax - let memFlags : SynMemberFlags = memFlagsBuilder memberKind - - let valSynInfo = - let adjustValueArg valueArg = - match valueArg with - | [_] -> valueArg - | _ -> SynInfo.unnamedTopArg - - match memberKind, valSynInfo, memFlags.IsInstance with - | SynMemberKind.PropertyGet, SynValInfo ([], _ret), false - | SynMemberKind.PropertyGet, SynValInfo ([_], _ret), true -> - raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsGetterMustHaveAtLeastOneArgument()) - - | SynMemberKind.PropertyGet, SynValInfo (thisArg :: indexOrUnitArgs :: rest, ret), true -> - if not rest.IsEmpty then - reportParseErrorAt mWholeBindLhs (FSComp.SR.parsGetterAtMostOneArgument ()) - SynValInfo ([thisArg; indexOrUnitArgs], ret) - - | SynMemberKind.PropertyGet, SynValInfo (indexOrUnitArgs :: rest, ret), false -> - if not rest.IsEmpty then - reportParseErrorAt mWholeBindLhs (FSComp.SR.parsGetterAtMostOneArgument ()) - SynValInfo ([indexOrUnitArgs], ret) - - | SynMemberKind.PropertySet, SynValInfo ([thisArg;valueArg], ret), true -> - SynValInfo ([thisArg; adjustValueArg valueArg], ret) - - | SynMemberKind.PropertySet, SynValInfo (thisArg :: indexArgs :: valueArg :: rest, ret), true -> - if not rest.IsEmpty then - reportParseErrorAt mWholeBindLhs (FSComp.SR.parsSetterAtMostTwoArguments ()) - SynValInfo ([thisArg; indexArgs @ adjustValueArg valueArg], ret) - - | SynMemberKind.PropertySet, SynValInfo ([valueArg], ret), false -> - SynValInfo ([adjustValueArg valueArg], ret) - - | SynMemberKind.PropertySet, SynValInfo (indexArgs :: valueArg :: rest, ret), _ -> - if not rest.IsEmpty then - reportParseErrorAt mWholeBindLhs (FSComp.SR.parsSetterAtMostTwoArguments ()) - SynValInfo ([indexArgs @ adjustValueArg valueArg], ret) - - | _ -> - // should be unreachable, cover just in case - raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsInvalidProperty ()) - - let valSynData = SynValData(Some(memFlags), valSynInfo, None) - - // Fold together the information from the first lambda pattern and the get/set binding - // This uses the 'this' variable from the first and the patterns for the get/set binding, - // replacing the get/set identifier. A little gross. - - let bindingPatAdjusted, xmlDocAdjusted = - - let trivia: SynBindingTrivia = { LetKeyword = None; EqualsRange = mEquals } - let bindingOuter = mkSynBinding (xmlDoc, propertyNameBindingPat) (vis, optInline, isMutable, mWholeBindLhs, spBind, optReturnType, expr, mExpr, [], attrs, Some(memFlagsBuilder SynMemberKind.Member), trivia) - - let (SynBinding (_, _, _, _, _, doc2, _, bindingPatOuter, _, _, _, _, _)) = bindingOuter - - let lidOuter, lidVisOuter = - match bindingPatOuter with - | SynPat.LongIdent (lid, _, None, None, SynArgPats.Pats [], lidVisOuter, m) -> lid, lidVisOuter - | SynPat.Named (SynIdent(id, _), _, visOuter, m) | SynPat.As(_, SynPat.Named (SynIdent(id, _), _, visOuter, m), _) -> SynLongIdent([id], [], [None]), visOuter - | p -> raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsInvalidDeclarationSyntax()) - - // Merge the visibility from the outer point with the inner point, e.g. - // member this.Size with get () = m_size - - let mergeLidVisOuter lidVisInner = - match lidVisInner, lidVisOuter with - | None, None -> None - | Some lidVisInner, None | None, Some lidVisInner -> Some lidVisInner - | Some _, Some _ -> - errorR(Error(FSComp.SR.parsMultipleAccessibilitiesForGetSet(), mWholeBindLhs)) - lidVisInner - - // Replace the "get" or the "set" with the right name - let rec go p = - match p with - | SynPat.LongIdent (longDotId=SynLongIdent([id], _, _); typarDecls=tyargs; argPats=SynArgPats.Pats args; accessibility=lidVisInner; range=m) -> - // Setters have all arguments tupled in their internal form, though they don't - // appear to be tupled from the syntax. Somewhat unfortunate - let args = - if id.idText = "set" then - match args with - | [SynPat.Paren(SynPat.Tuple (false, indexPats, _), indexPatRange);valuePat] when id.idText = "set" -> - [SynPat.Tuple(false, indexPats@[valuePat], unionRanges indexPatRange valuePat.Range)] - | [indexPat;valuePat] -> - [SynPat.Tuple(false, args, unionRanges indexPat.Range valuePat.Range)] - | [valuePat] -> - [valuePat] - | _ -> - raiseParseErrorAt m (FSComp.SR.parsSetSyntax()) - else - args - SynPat.LongIdent (lidOuter, withPropertyKeyword, Some(id), tyargs, SynArgPats.Pats args, mergeLidVisOuter lidVisInner, m) - | SynPat.Named (_, _, lidVisInner, m) - | SynPat.As (_, SynPat.Named (_, _, lidVisInner, m), _) -> SynPat.LongIdent (lidOuter, None, None, None, SynArgPats.Pats [], mergeLidVisOuter lidVisInner, m) - | SynPat.Typed (p, ty, m) -> SynPat.Typed(go p, ty, m) - | SynPat.Attrib (p, attribs, m) -> SynPat.Attrib(go p, attribs, m) - | SynPat.Wild(m) -> SynPat.Wild(m) - | _ -> raiseParseErrorAt mWholeBindLhs (FSComp.SR.parsInvalidDeclarationSyntax()) - - go pv, PreXmlDoc.Merge doc2 doc - - let binding = SynBinding (vis, SynBindingKind.Normal, isInline, isMutable, attrs, xmlDocAdjusted, valSynData, bindingPatAdjusted, rhsRetInfo, rhsExpr, mWholeBindLhs, spBind, trivia) - let memberRange = unionRanges rangeStart mWhole |> unionRangeWithXmlDoc xmlDocAdjusted - Some (SynMemberDefn.Member (binding, memberRange)) - - // Iterate over 1 or 2 'get'/'set' entries - match classDefnMemberGetSetElements with - | [ h ] -> List.choose id [ tryMkSynMemberDefnMember (Some (PropertyKeyword.With mWith)) h ] - | [ g ; s ] -> List.choose id [ tryMkSynMemberDefnMember (Some (PropertyKeyword.With mWith)) g ; tryMkSynMemberDefnMember (Option.map PropertyKeyword.And mAnd) s ] - | _ -> []) - } + let optPropertyType = $3 + mkSynMemberDefnGetSet parseState $1 mWith classDefnMemberGetSetElements mAnd mWhole propertyNameBindingPat optPropertyType } abstractMemberFlags: @@ -2095,15 +1914,15 @@ classDefnMember: let isInline, doc, id, explicitValTyparDecls = $4, grabXmlDoc(parseState, $1, 1), $5, $6 let mWith, getSetRangeOpt, getSet = $9 let getSetAdjuster arity = match arity, getSet with SynValInfo([], _), SynMemberKind.Member -> SynMemberKind.PropertyGet | _ -> getSet - let wholeRange = + let mWhole = let m = rhs parseState 1 match getSetRangeOpt with | None -> unionRanges m ty.Range | Some m2 -> unionRanges m m2 |> unionRangeWithXmlDoc doc - if Option.isSome $2 then errorR(Error(FSComp.SR.parsAccessibilityModsIllegalForAbstract(), wholeRange)) - let valSpfn = SynValSig($1, id, explicitValTyparDecls, ty, arity, isInline, false, doc, None, None, wholeRange, { ValKeyword = None; WithKeyword = mWith }) - [ SynMemberDefn.AbstractSlot(valSpfn, AbstractMemberFlags $3 (getSetAdjuster arity), wholeRange) ] } + if Option.isSome $2 then errorR(Error(FSComp.SR.parsAccessibilityModsIllegalForAbstract(), mWhole)) + let valSpfn = SynValSig($1, id, explicitValTyparDecls, ty, arity, isInline, false, doc, None, None, mWhole, { ValKeyword = None; WithKeyword = mWith; EqualsRange = None }) + [ SynMemberDefn.AbstractSlot(valSpfn, AbstractMemberFlags $3 (getSetAdjuster arity), mWhole) ] } | opt_attributes opt_declVisibility inheritsDefn { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalOnInherit(), rhs parseState 1)) @@ -2135,7 +1954,7 @@ classDefnMember: let expr = $7 let valSynData = SynValData (Some (CtorMemberFlags SynMemberFlagsTrivia.Zero), SynValInfo([SynInfo.InferSynArgInfoFromPat $4], SynInfo.unnamedRetVal), $5) let vis = $2 - let declPat = SynPat.LongIdent (SynLongIdent([mkSynId (rhs parseState 3) "new"], [], [None]), None, None, Some noInferredTypars, SynArgPats.Pats [$4], vis, rhs parseState 3) + let declPat = SynPat.LongIdent (SynLongIdent([mkSynId (rhs parseState 3) "new"], [], [None]), None, Some noInferredTypars, SynArgPats.Pats [$4], vis, rhs parseState 3) // Check that 'SynPatForConstructorDecl' matches this correctly assert (match declPat with SynPatForConstructorDecl _ -> true | _ -> false) let synBindingTrivia: SynBindingTrivia = { LetKeyword = None; EqualsRange = Some mEquals } @@ -2183,13 +2002,13 @@ atomicPatternLongIdent: raiseParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnexpectedSymbolDot()) let underscore = ident("_", rhs parseState 1) - let dotm = rhs parseState 2 - None, prependIdentInLongIdentWithTrivia (SynIdent(underscore, None)) dotm $3 } + let mDot = rhs parseState 2 + None, prependIdentInLongIdentWithTrivia (SynIdent(underscore, None)) mDot $3 } | GLOBAL DOT pathOp { let globalIdent = ident(MangledGlobalName, rhs parseState 1) - let dotm = rhs parseState 2 - None, prependIdentInLongIdentWithTrivia (SynIdent(globalIdent, None)) dotm $3 } + let mDot = rhs parseState 2 + None, prependIdentInLongIdentWithTrivia (SynIdent(globalIdent, None)) mDot $3 } | pathOp { (None, $1) } @@ -2199,8 +2018,8 @@ atomicPatternLongIdent: raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsUnexpectedSymbolDot()) let underscore = ident("_", rhs parseState 2) - let dotm = rhs parseState 3 - Some($1), prependIdentInLongIdentWithTrivia (SynIdent(underscore, None)) dotm $4 } + let mDot = rhs parseState 3 + Some($1), prependIdentInLongIdentWithTrivia (SynIdent(underscore, None)) mDot $4 } | access pathOp { (Some($1), $2) } @@ -2216,13 +2035,16 @@ opt_access: access: | PRIVATE - { SynAccess.Private } + { let m = rhs parseState 1 + SynAccess.Private m } | PUBLIC - { SynAccess.Public } + { let m = rhs parseState 1 + SynAccess.Public m } | INTERNAL - { SynAccess.Internal } + { let m = rhs parseState 1 + SynAccess.Internal m } /* only valid on 'NEW' */ opt_declVisibility: @@ -2366,7 +2188,7 @@ tyconDefnOrSpfnSimpleRepr: /* A union type definition */ | opt_attributes opt_declVisibility unionTypeRepr { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(), rhs parseState 1)) - let rangesOf3 = $3 |> List.map (function |Choice1Of2(ec)->ec.Range | Choice2Of2(uc)->uc.Range) + let rangesOf3 = $3 |> List.map (function Choice1Of2 ec -> ec.Range | Choice2Of2 uc -> uc.Range) let mWhole = (rhs2 parseState 1 2, rangesOf3) ||> List.fold unionRanges if $3 |> List.exists (function Choice1Of2 _ -> true | _ -> false) then ( if Option.isSome $2 then errorR(Error(FSComp.SR.parsEnumTypesCannotHaveVisibilityDeclarations(), rhs parseState 2)); @@ -2389,12 +2211,12 @@ tyconDefnOrSpfnSimpleRepr: /* An inline-assembly type definition, for FSharp.Core library only */ | opt_attributes opt_declVisibility LPAREN HASH string HASH rparen { if not (isNil $1) then errorR(Error(FSComp.SR.parsAttributesIllegalHere(), rhs parseState 1)) - let lhsm = lhs parseState - if parseState.LexBuffer.ReportLibraryOnlyFeatures then libraryOnlyError lhsm + let mLhs = lhs parseState + if parseState.LexBuffer.ReportLibraryOnlyFeatures then libraryOnlyError mLhs if Option.isSome $2 then errorR(Error(FSComp.SR.parsInlineAssemblyCannotHaveVisibilityDeclarations(), rhs parseState 2)) let s, _ = $5 let ilType = ParseAssemblyCodeType s parseState.LexBuffer.ReportLibraryOnlyFeatures parseState.LexBuffer.LanguageVersion (rhs parseState 5) - SynTypeDefnSimpleRepr.LibraryOnlyILAssembly (box ilType, lhsm) } + SynTypeDefnSimpleRepr.LibraryOnlyILAssembly (box ilType, mLhs) } /* The core of a record type definition */ @@ -2695,8 +2517,8 @@ unionCaseReprElements: unionCaseReprElement: | ident COLON appType { let xmlDoc = grabXmlDoc(parseState, [], 1) - let wholeRange = rhs2 parseState 1 3 |> unionRangeWithXmlDoc xmlDoc - mkSynNamedField ($1, $3, xmlDoc, wholeRange) } + let mWhole = rhs2 parseState 1 3 |> unionRangeWithXmlDoc xmlDoc + mkSynNamedField ($1, $3, xmlDoc, mWhole) } | appType { let xmlDoc = grabXmlDoc(parseState, [], 1) @@ -2721,19 +2543,19 @@ recdFieldDeclList: /* A field declaration in a record type */ recdFieldDecl: | opt_attributes fieldDecl - { let wholeRange = rhs2 parseState 1 2 - let fld = $2 $1 false wholeRange - let (SynField (a, b, c, d, e, xmlDoc, vis, wholeRange)) = fld + { let mWhole = rhs2 parseState 1 2 + let fld = $2 $1 false mWhole + let (SynField (a, b, c, d, e, xmlDoc, vis, mWhole)) = fld if Option.isSome vis then errorR (Error (FSComp.SR.parsRecordFieldsCannotHaveVisibilityDeclarations (), rhs parseState 2)) - let wholeRange = unionRangeWithXmlDoc xmlDoc wholeRange - SynField (a, b, c, d, e, xmlDoc, None, wholeRange) } + let mWhole = unionRangeWithXmlDoc xmlDoc mWhole + SynField (a, b, c, d, e, xmlDoc, None, mWhole) } /* Part of a field or val declaration in a record type or object type */ fieldDecl: | opt_mutable opt_access ident COLON typ - { fun attrs stat wholeRange -> - let xmlDoc = grabXmlDocAtRangeStart(parseState, attrs, wholeRange) - SynField(attrs, stat, Some $3, $5, $1, xmlDoc, $2, wholeRange) } + { fun attrs stat mWhole -> + let xmlDoc = grabXmlDocAtRangeStart(parseState, attrs, mWhole) + SynField(attrs, stat, Some $3, $5, $1, xmlDoc, $2, mWhole) } /* An exception definition */ exconDefn: @@ -2898,7 +2720,7 @@ cPrototype: SynExpr.Const (SynConst.String("extern was not given a DllImport attribute", SynStringKind.Regular, rhs parseState 8), rhs parseState 8), mRhs) (fun attrs _ -> - let bindingPat = SynPat.LongIdent (SynLongIdent([nm], [], [None]), None, None, Some noInferredTypars, SynArgPats.Pats [SynPat.Tuple(false, args, argsm)], vis, nmm) + let bindingPat = SynPat.LongIdent (SynLongIdent([nm], [], [None]), None, Some noInferredTypars, SynArgPats.Pats [SynPat.Tuple(false, args, argsm)], vis, nmm) let mWholeBindLhs = (mBindLhs, attrs) ||> unionRangeWithListBy (fun (a: SynAttributeList) -> a.Range) let xmlDoc = grabXmlDoc(parseState, attrs, 1) let binding = @@ -3270,7 +3092,7 @@ headBindingPattern: SynPat.Or($1, $3, rhs2 parseState 1 3, { BarRange = mBar }) } | headBindingPattern COLON_COLON headBindingPattern - { SynPat.LongIdent (SynLongIdent(mkSynCaseName (rhs parseState 2) opNameCons, [], [ Some (IdentTrivia.OriginalNotation "::") ]), None, None, None, SynArgPats.Pats [SynPat.Tuple (false, [$1;$3], rhs2 parseState 1 3)], None, lhs parseState) } + { SynPat.LongIdent (SynLongIdent(mkSynCaseName (rhs parseState 2) opNameCons, [], [ Some (IdentTrivia.OriginalNotation "::") ]), None, None, SynArgPats.Pats [SynPat.Tuple (false, [$1;$3], rhs2 parseState 1 3)], None, lhs parseState) } | tuplePatternElements %prec pat_tuple { SynPat.Tuple(false, List.rev $1, lhs parseState) } @@ -3310,43 +3132,43 @@ namePatPair: constrPattern: | atomicPatternLongIdent explicitValTyparDecls { let vis, lid = $1 - SynPat.LongIdent (lid, None, None, Some $2, SynArgPats.Pats [], vis, lhs parseState) } + SynPat.LongIdent (lid, None, Some $2, SynArgPats.Pats [], vis, lhs parseState) } | atomicPatternLongIdent explicitValTyparDecls atomicPatsOrNamePatPairs %prec pat_app { let vis, lid = $1 let args, argsM = $3 let m = unionRanges (rhs2 parseState 1 2) argsM - SynPat.LongIdent (lid, None, None, Some $2, args, vis, m) } + SynPat.LongIdent (lid, None, Some $2, args, vis, m) } | atomicPatternLongIdent explicitValTyparDecls HIGH_PRECEDENCE_PAREN_APP atomicPatsOrNamePatPairs { let vis, lid = $1 let args, argsM = $4 let m = unionRanges (rhs2 parseState 1 2) argsM - SynPat.LongIdent (lid, None, None, Some $2, args, vis, m) } + SynPat.LongIdent (lid, None, Some $2, args, vis, m) } | atomicPatternLongIdent explicitValTyparDecls HIGH_PRECEDENCE_BRACK_APP atomicPatsOrNamePatPairs { let vis, lid = $1 let args, argsM = $4 let m = unionRanges (rhs2 parseState 1 2) argsM - SynPat.LongIdent (lid, None, None, Some $2, args, vis, m) } + SynPat.LongIdent (lid, None, Some $2, args, vis, m) } | atomicPatternLongIdent atomicPatsOrNamePatPairs %prec pat_app { let vis, lid = $1 let args, argsM = $2 let m = unionRanges (rhs parseState 1) argsM - SynPat.LongIdent (lid, None, None, None, args, vis, m) } + SynPat.LongIdent (lid, None, None, args, vis, m) } | atomicPatternLongIdent HIGH_PRECEDENCE_PAREN_APP atomicPatsOrNamePatPairs { let vis, lid = $1 let args, argsM = $3 let m = unionRanges (rhs parseState 1) argsM - SynPat.LongIdent (lid, None, None, None, args, vis, m) } + SynPat.LongIdent (lid, None, None, args, vis, m) } | atomicPatternLongIdent HIGH_PRECEDENCE_BRACK_APP atomicPatsOrNamePatPairs { let vis, lid = $1 let args, argsM = $3 let m = unionRanges (rhs parseState 1) argsM - SynPat.LongIdent (lid, None, None, None, args, vis, m) } + SynPat.LongIdent (lid, None, None, args, vis, m) } | COLON_QMARK atomTypeOrAnonRecdType %prec pat_isinst { SynPat.IsInst($2, lhs parseState) } @@ -3504,15 +3326,15 @@ parenPattern: { SynPat.Ands(List.rev $1, rhs2 parseState 1 3) } | parenPattern COLON typeWithTypeConstraints %prec paren_pat_colon - { let lhsm = lhs parseState - SynPat.Typed($1, $3, lhsm) } + { let mLhs = lhs parseState + SynPat.Typed($1, $3, mLhs) } | attributes parenPattern %prec paren_pat_attribs - { let lhsm = lhs parseState - SynPat.Attrib($2, $1, lhsm) } + { let mLhs = lhs parseState + SynPat.Attrib($2, $1, mLhs) } | parenPattern COLON_COLON parenPattern - { SynPat.LongIdent (SynLongIdent(mkSynCaseName (rhs parseState 2) opNameCons, [], [ Some (IdentTrivia.OriginalNotation "::") ]), None, None, None, SynArgPats.Pats [ SynPat.Tuple (false, [$1;$3], rhs2 parseState 1 3) ], None, lhs parseState) } + { SynPat.LongIdent (SynLongIdent(mkSynCaseName (rhs parseState 2) opNameCons, [], [ Some (IdentTrivia.OriginalNotation "::") ]), None, None, SynArgPats.Pats [ SynPat.Tuple (false, [$1;$3], rhs2 parseState 1 3) ], None, lhs parseState) } | constrPattern { $1 } @@ -4013,6 +3835,13 @@ declExpr: | tupleExpr %prec expr_tuple { let exprs, commas = $1 + let exprs, commas = + // Nested non-struct tuple is only possible during error recovery, + // in other situations there are intermediate nodes. + match exprs with + | SynExpr.Tuple(false, _, _, _) :: _ -> normalizeTupleExpr exprs commas + | _ -> exprs, commas + SynExpr.Tuple (false, List.rev exprs, List.rev commas, (commas.Head, exprs) ||> unionRangeWithListBy (fun e -> e.Range) ) } | declExpr JOIN_IN declExpr @@ -4165,18 +3994,18 @@ declExpr: | declExpr DOT_DOT declExpr { let wholem = rhs2 parseState 1 3 - let opm = rhs parseState 2 - SynExpr.IndexRange(Some $1, opm, Some $3, rhs parseState 1, rhs parseState 3, wholem) } + let mOperator = rhs parseState 2 + SynExpr.IndexRange(Some $1, mOperator, Some $3, rhs parseState 1, rhs parseState 3, wholem) } | declExpr DOT_DOT %prec open_range_expr { let wholem = rhs2 parseState 1 2 - let opm = rhs parseState 2 - SynExpr.IndexRange(Some $1, opm, None, rhs parseState 1, opm, wholem) } + let mOperator = rhs parseState 2 + SynExpr.IndexRange(Some $1, mOperator, None, rhs parseState 1, mOperator, wholem) } | DOT_DOT declExpr %prec open_range_expr { let wholem = rhs2 parseState 1 2 - let opm = rhs parseState 1 - SynExpr.IndexRange(None, opm, Some $2, opm, rhs parseState 2, wholem) } + let mOperator = rhs parseState 1 + SynExpr.IndexRange(None, mOperator, Some $2, mOperator, rhs parseState 2, wholem) } | STAR { let m = rhs parseState 1 @@ -4351,23 +4180,34 @@ ifExprElifs: | ELIF declExpr recover { None, Some (exprFromParseError $2) } -tupleExpr: - | tupleExpr COMMA declExpr - { let exprs, commas = $1 in ($3 :: exprs), ((rhs parseState 2) :: commas) } +tupleExpr: + | tupleExpr COMMA declExpr + { let exprs, commas = $1 + $3 :: exprs, (rhs parseState 2 :: commas) } | tupleExpr COMMA ends_coming_soon_or_recover - { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsExpectedExpressionAfterToken()) - let exprs, commas = $1 - let zeroWidthAtNextToken = (rhs parseState 3).StartRange - ((arbExpr("tupleExpr1", zeroWidthAtNextToken)) :: exprs), (rhs parseState 2) :: commas } + { let commaRange = rhs parseState 2 + if not $3 then reportParseErrorAt commaRange (FSComp.SR.parsExpectedExpressionAfterToken ()) + let exprs, commas = $1 + arbExpr ("tupleExpr1", commaRange.EndRange) :: exprs, commaRange :: commas } | declExpr COMMA ends_coming_soon_or_recover - { if not $3 then reportParseErrorAt (rhs parseState 2) (FSComp.SR.parsExpectedExpressionAfterToken()) - let zeroWidthAtNextToken = (rhs parseState 3).StartRange - ((arbExpr("tupleExpr2", zeroWidthAtNextToken)) :: [$1]), [rhs parseState 2] } + { let commaRange = rhs parseState 2 + if not $3 then reportParseErrorAt commaRange (FSComp.SR.parsExpectedExpressionAfterToken ()) + [arbExpr ("tupleExpr2", commaRange.EndRange); $1], [commaRange] } + + | declExpr COMMA declExpr + { [$3; $1], [rhs parseState 2] } + + | COMMA declExpr + { let commaRange = rhs parseState 1 + reportParseErrorAt commaRange (FSComp.SR.parsExpectingExpressionInTuple ()) + [$2; arbExpr ("tupleExpr3", commaRange.StartRange)], [commaRange] } - | declExpr COMMA declExpr - { [$3 ; $1], [rhs parseState 2] } + | COMMA ends_coming_soon_or_recover + { let commaRange = rhs parseState 1 + if not $2 then reportParseErrorAt commaRange (FSComp.SR.parsExpectedExpressionAfterToken ()) + [arbExpr ("tupleExpr4", commaRange.EndRange); arbExpr ("tupleExpr5", commaRange.StartRange)], [commaRange] } minusExpr: | MINUS minusExpr %prec expr_prefix_plus_minus @@ -4515,61 +4355,61 @@ atomicExpr: atomicExprQualification: | identOrOp { let idm = rhs parseState 1 - (fun e lhsm dotm -> mkSynDot dotm lhsm e $1) } + (fun e mLhs mDot -> mkSynDot mDot mLhs e $1) } | GLOBAL - { (fun e lhsm dotm -> + { (fun e mLhs mDot -> reportParseErrorAt (rhs parseState 3) (FSComp.SR.nrGlobalUsedOnlyAsFirstName()) - let fixedLhsm = mkRange lhsm.FileName lhsm.Start dotm.End // previous lhsm is wrong after 'recover' - mkSynDotMissing dotm fixedLhsm e) } + let fixedLhsm = mkRange mLhs.FileName mLhs.Start mDot.End // previous mLhs is wrong after 'recover' + mkSynDotMissing mDot fixedLhsm e) } | /* empty */ - { (fun e lhsm dotm -> - reportParseErrorAt dotm (FSComp.SR.parsMissingQualificationAfterDot()) - let fixedLhsm = mkRange lhsm.FileName lhsm.Start dotm.End // previous lhsm is wrong after 'recover' - mkSynDotMissing dotm fixedLhsm e) } + { (fun e mLhs mDot -> + reportParseErrorAt mDot (FSComp.SR.parsMissingQualificationAfterDot()) + let fixedLhsm = mkRange mLhs.FileName mLhs.Start mDot.End // previous mLhs is wrong after 'recover' + mkSynDotMissing mDot fixedLhsm e) } | recover - { (fun e lhsm dotm -> - reportParseErrorAt dotm (FSComp.SR.parsMissingQualificationAfterDot()) - let fixedLhsm = mkRange lhsm.FileName lhsm.Start dotm.End // previous lhsm is wrong after 'recover' + { (fun e mLhs mDot -> + reportParseErrorAt mDot (FSComp.SR.parsMissingQualificationAfterDot()) + let fixedLhsm = mkRange mLhs.FileName mLhs.Start mDot.End // previous mLhs is wrong after 'recover' // Include 'e' in the returned expression but throw it away SynExpr.DiscardAfterMissingQualificationAfterDot (e, fixedLhsm)) } | LPAREN COLON_COLON rparen DOT INT32 - { (fun e lhsm dotm -> + { (fun e mLhs mDot -> if parseState.LexBuffer.ReportLibraryOnlyFeatures then libraryOnlyError(lhs parseState) - SynExpr.LibraryOnlyUnionCaseFieldGet (e, mkSynCaseName lhsm opNameCons, (fst $5), lhsm)) } + SynExpr.LibraryOnlyUnionCaseFieldGet (e, mkSynCaseName mLhs opNameCons, (fst $5), mLhs)) } | LPAREN typedSequentialExpr rparen { let lpr = rhs parseState 1 let rpr = rhs parseState 3 - (fun e lhsm dotm -> + (fun e mLhs mDot -> // Check for expr.( * ) // Note that "*" is parsed as an expression (it is allowed in "foo.[3,*]") match $2 with - | SynExpr.IndexRange (None, opm, None, _m1, _m2, _) -> - mkSynDot dotm lhsm e (SynIdent(ident(CompileOpName "*", opm), Some(IdentTrivia.OriginalNotationWithParen(lpr, "*", rpr)))) + | SynExpr.IndexRange (None, mOperator, None, _m1, _m2, _) -> + mkSynDot mDot mLhs e (SynIdent(ident(CompileOpName "*", mOperator), Some(IdentTrivia.OriginalNotationWithParen(lpr, "*", rpr)))) | _ -> if parseState.LexBuffer.SupportsFeature LanguageFeature.MLCompatRevisions then mlCompatError (FSComp.SR.mlCompatMultiPrefixTyparsNoLongerSupported()) (lhs parseState) else mlCompatWarning (FSComp.SR.parsParenFormIsForML()) (lhs parseState) - mkSynDotParenGet lhsm dotm e $2) } + mkSynDotParenGet mLhs mDot e $2) } | LBRACK typedSequentialExpr RBRACK - { (fun e lhsm dotm -> mkSynDotBrackGet lhsm dotm e $2) } + { (fun e mLhs mDot -> mkSynDotBrackGet mLhs mDot e $2) } | LBRACK typedSequentialExpr recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracket()) - (fun e lhsm dotm -> exprFromParseError (mkSynDotBrackGet lhsm dotm e $2)) } + (fun e mLhs mDot -> exprFromParseError (mkSynDotBrackGet mLhs mDot e $2)) } | LBRACK error RBRACK { let mArg = rhs2 parseState 1 3 - (fun e lhsm dotm -> mkSynDotBrackGet lhsm dotm e (arbExpr("indexerExpr1", mArg))) } + (fun e mLhs mDot -> mkSynDotBrackGet mLhs mDot e (arbExpr("indexerExpr1", mArg))) } | LBRACK recover { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedBracket()) let mArg = (rhs parseState 1).EndRange - (fun e lhsm dotm -> exprFromParseError (mkSynDotBrackGet lhsm dotm e (arbExpr("indexerExpr2", mArg)))) } + (fun e mLhs mDot -> exprFromParseError (mkSynDotBrackGet mLhs mDot e (arbExpr("indexerExpr2", mArg)))) } /* the start of atomicExprAfterType must not overlap with the valid postfix tokens of the type syntax, e.g. new List(...) */ atomicExprAfterType: @@ -4663,8 +4503,8 @@ parenExpr: | LPAREN parenExprBody ends_other_than_rparen_coming_soon_or_recover { if not $3 then reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let lhsm = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).End - SynExpr.Paren (exprFromParseError ($2 lhsm), rhs parseState 1, None, lhsm) } + let mLhs = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).End + SynExpr.Paren (exprFromParseError ($2 mLhs), rhs parseState 1, None, mLhs) } | LPAREN error rparen { // silent recovery @@ -4672,18 +4512,18 @@ parenExpr: | LPAREN TYPE_COMING_SOON { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let lhsm = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).Start - arbExpr("parenExpr2tcs", lhsm) } + let mLhs = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).Start + arbExpr("parenExpr2tcs", mLhs) } | LPAREN MODULE_COMING_SOON { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let lhsm = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).Start - arbExpr("parenExpr2mcs", lhsm) } + let mLhs = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).Start + arbExpr("parenExpr2mcs", mLhs) } | LPAREN RBRACE_COMING_SOON { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let lhsm = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).Start - arbExpr("parenExpr2rbcs", lhsm) } + let mLhs = unionRangeWithPos (rhs parseState 1) (rhs parseState 2).Start + arbExpr("parenExpr2rbcs", mLhs) } | LPAREN OBLOCKEND_COMING_SOON { let lparenRange = (rhs parseState 1) @@ -4698,8 +4538,8 @@ parenExpr: // to extend all the way over the "recover", to the end of the file if necessary // // let mLeftParen = rhs parseState 1 - //let lhsm = if $2 then unionRangeWithPos mLeftParen (rhs parseState 2).Start else mLeftParen - //arbExpr("parenExpr2", lhsm) } + //let mLhs = if $2 then unionRangeWithPos mLeftParen (rhs parseState 2).Start else mLeftParen + //arbExpr("parenExpr2", mLhs) } parenExprBody: | staticallyKnownHeadTypars COLON LPAREN classMemberSpfn rparen typedSequentialExpr @@ -4760,21 +4600,21 @@ braceExprBody: listExprElements: | sequentialExpr - { (fun lhsm -> SynExpr.ArrayOrListComputed (false, $1, lhsm)) } + { (fun mLhs -> SynExpr.ArrayOrListComputed (false, $1, mLhs)) } | - { (fun lhsm -> SynExpr.ArrayOrList (false, [ ], lhsm)) } + { (fun mLhs -> SynExpr.ArrayOrList (false, [ ], mLhs)) } arrayExprElements: | sequentialExpr - { (fun lhsm -> SynExpr.ArrayOrListComputed (true, $1, lhsm)) } + { (fun mLhs -> SynExpr.ArrayOrListComputed (true, $1, mLhs)) } | - { (fun lhsm -> SynExpr.ArrayOrList (true, [ ], lhsm)) } + { (fun mLhs -> SynExpr.ArrayOrList (true, [ ], mLhs)) } computationExpr: | sequentialExpr - { $1.Range, (fun lhsm -> SynExpr.ComputationExpr (false, $1, lhsm)) } + { $1.Range, (fun mLhs -> SynExpr.ComputationExpr (false, $1, mLhs)) } arrowThenExprR: | RARROW typedSequentialExprBlockR @@ -5026,7 +4866,7 @@ objExprBindings: let memberDefns = $2 |> (List.choose (function - | SynMemberDefn.Member _ as memberDefn -> Some memberDefn + | (SynMemberDefn.Member _ | SynMemberDefn.GetSetMember _ ) as memberDefn -> Some memberDefn | SynMemberDefn.AutoProperty(range = m) -> errorR(Error(FSComp.SR.parsIllegalMemberVarInObjectImplementation(), m)); None | x -> errorR(Error(FSComp.SR.parsMemberIllegalInObjectImplementation(), x.Range)); None)) mWithKwd, [], memberDefns } @@ -5175,8 +5015,9 @@ opt_topReturnTypeWithTypeConstraints: topType: | topTupleType RARROW topType { let dty, dmdata= $1 - let rty, (SynValInfo(dmdatas, rmdata)) = $3 - SynType.Fun(dty, rty, lhs parseState), (SynValInfo(dmdata :: dmdatas, rmdata)) } + let rty, (SynValInfo(dmdatas, rmdata)) = $3 + let mArrow = rhs parseState 2 + SynType.Fun(dty, rty, lhs parseState, { ArrowRange = mArrow }), (SynValInfo(dmdata :: dmdatas, rmdata)) } | topTupleType { let ty, rmdata = $1 in ty, (SynValInfo([], (match rmdata with [md] -> md | _ -> SynInfo.unnamedRetVal))) } @@ -5222,7 +5063,8 @@ topAppType: /* See the F# specification "Lexical analysis of type applications and type parameter definitions" */ typ: | tupleType RARROW typ - { SynType.Fun($1, $3, lhs parseState) } + { let mArrow = rhs parseState 2 + SynType.Fun($1, $3, lhs parseState, { ArrowRange = mArrow }) } | tupleType %prec prec_typ_prefix { $1 } @@ -5781,27 +5623,7 @@ identExpr: | opName { let m = lhs parseState let ident, trivia = $1 - let mLparen, mRparen, trivia = - match trivia with - | IdentTrivia.OriginalNotation text -> - let mLparen = mkFileIndexRange m.FileIndex m.Start (mkPos m.StartLine (m.StartColumn + 1)) - let mRparen = mkFileIndexRange m.FileIndex (mkPos m.EndLine (m.EndColumn - 1)) m.End - mLparen, mRparen, Some trivia - | IdentTrivia.OriginalNotationWithParen(lpr, text, rpr) -> - lpr, rpr, Some(IdentTrivia.OriginalNotation(text)) - | IdentTrivia.HasParenthesis(lpr, rpr) -> - lpr, rpr, None - - match trivia with - | None -> - SynExpr.Paren(SynExpr.Ident(ident), mLparen, Some mRparen, m) - | Some trivia -> - SynExpr.Paren( - SynExpr.LongIdent(false, SynLongIdent([ident], [], [Some trivia]), None, m), - mLparen, - Some mRparen, - m - ) } + SynExpr.LongIdent(false, SynLongIdent([ident], [], [Some trivia]), None, m) } topSeparator: | SEMICOLON { } diff --git a/src/Compiler/xlf/FSComp.txt.cs.xlf b/src/Compiler/xlf/FSComp.txt.cs.xlf index 93162f272df..4ce11383beb 100644 --- a/src/Compiler/xlf/FSComp.txt.cs.xlf +++ b/src/Compiler/xlf/FSComp.txt.cs.xlf @@ -192,6 +192,11 @@ rozhraní s vícenásobným obecným vytvářením instancí + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions Revize kompatibility ML @@ -437,6 +442,11 @@ Vytiskněte odvozená rozhraní všech kompilovaných souborů do přidružených souborů podpisu. + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Neočekávaný token v definici typu. Za typem {0} se očekává =. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' Tento přístup člena je nejednoznačný. Při vytváření objektu použijte závorky, např. (new SomeType(args)).MemberName' @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Toto není platný číselný literál. Mezi platné číselné literály patří 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Toto není platný číselný literál. Mezi platné číselné literály patří 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.de.xlf b/src/Compiler/xlf/FSComp.txt.de.xlf index d01803b388f..e1c9e9842db 100644 --- a/src/Compiler/xlf/FSComp.txt.de.xlf +++ b/src/Compiler/xlf/FSComp.txt.de.xlf @@ -192,6 +192,11 @@ Schnittstellen mit mehrfacher generischer Instanziierung + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions ML-Kompatibilitätsrevisionen @@ -437,6 +442,11 @@ Drucken der abgeleiteten Schnittstellen aller Dateien an zugehörige Signaturdateien + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Unerwartetes Token in Typdefinition. Nach Typ "{0}" wurde "=" erwartet. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' Dieser Memberzugriff ist mehrdeutig. Setzen Sie Klammern um die Objekterstellung, z. B. "(new SomeType(args)). MemberName“ @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Dies ist kein gültiges numerisches Literal. Unter anderem sind die folgenden numerischen Literale gültig: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Dies ist kein gültiges numerisches Literal. Unter anderem sind die folgenden numerischen Literale gültig: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.es.xlf b/src/Compiler/xlf/FSComp.txt.es.xlf index 3549568633f..dbbe206f0ef 100644 --- a/src/Compiler/xlf/FSComp.txt.es.xlf +++ b/src/Compiler/xlf/FSComp.txt.es.xlf @@ -192,6 +192,11 @@ interfaces con creación de instancias genéricas múltiples + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions Revisiones de compatibilidad de ML @@ -437,6 +442,11 @@ Imprimir las interfaces deducidas de todos los archivos de compilación en los archivos de signatura asociados + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Token inesperado en la definición de tipo. Se esperaba "=" después del tipo "{0}". + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' Este acceso de miembro es ambiguo. Use paréntesis alrededor de la creación del objeto, por ejemplo, '(nuevo AlgúnTipo(args)).NombreMiembro' @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Este literal numérico no es válido. Entre los literales numéricos válidos se incluyen 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal) y 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Este literal numérico no es válido. Entre los literales numéricos válidos se incluyen 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal) y 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.fr.xlf b/src/Compiler/xlf/FSComp.txt.fr.xlf index 4272c571acd..6a4a9beb0c6 100644 --- a/src/Compiler/xlf/FSComp.txt.fr.xlf +++ b/src/Compiler/xlf/FSComp.txt.fr.xlf @@ -192,6 +192,11 @@ interfaces avec plusieurs instanciations génériques + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions Réviseurs de compatibilité ML @@ -437,6 +442,11 @@ Imprimer les interfaces inférées de tous les fichiers de compilation sur les fichiers de signature associés + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Jeton inattendu dans la définition de type. Signe '=' attendu après le type '{0}'. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' L’accès à ce membre est ambigu. Utilisez des parenthèses autour de la création de l’objet, par exemple' (New SomeType (args)). MemberName @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Littéral numérique non valide. Littéraux numériques valides : 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Littéral numérique non valide. Littéraux numériques valides : 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.it.xlf b/src/Compiler/xlf/FSComp.txt.it.xlf index 31dd4d5e3c7..3d66319c8d4 100644 --- a/src/Compiler/xlf/FSComp.txt.it.xlf +++ b/src/Compiler/xlf/FSComp.txt.it.xlf @@ -192,6 +192,11 @@ interfacce con più creazioni di istanze generiche + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions Revisioni della compatibilità di Ml @@ -437,6 +442,11 @@ Stampare le interfacce derivate di tutti i file di compilazione nei file di firma associati + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Token imprevisto nella definizione del tipo. Dopo il tipo '{0}' è previsto '='. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' L'accesso ai membri è ambiguo. Utilizzare le parentesi intorno alla creazione oggetto, ad esempio “(New SomeType (args)). MemberName” @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Questo non è un valore letterale numerico valido. I valori letterali numerici validi includono 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Questo non è un valore letterale numerico valido. I valori letterali numerici validi includono 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.ja.xlf b/src/Compiler/xlf/FSComp.txt.ja.xlf index 4b434db82c9..a9f3581be46 100644 --- a/src/Compiler/xlf/FSComp.txt.ja.xlf +++ b/src/Compiler/xlf/FSComp.txt.ja.xlf @@ -192,6 +192,11 @@ 複数のジェネリックのインスタンス化を含むインターフェイス + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions ML 互換性のリビジョン @@ -437,6 +442,11 @@ すべてのコンパイル ファイルの推定されたインターフェイスを関連する署名ファイルに印刷します + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ 型定義に予期しないトークンがあります。型 '{0}' の後には '=' が必要です。 + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' このメンバーへのアクセスはあいまいです。オブジェクト作成の前後にはかっこを使用してください。例: '(new SomeType(args)).MemberName' @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - これは有効な数値リテラルではありません。有効な数値リテラルの例には、1、0x1、0o1、0b1、1l (int)、1u (uint32)、1L (int64)、1UL (uint64)、1s (int16)、1y (sbyte)、1uy (byte)、1.0 (float)、1.0f (float32)、1.0m (decimal)、1I (BigInteger) などがあります。 + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + これは有効な数値リテラルではありません。有効な数値リテラルの例には、1、0x1、0o1、0b1、1l (int)、1u (uint32)、1L (int64)、1UL (uint64)、1s (int16)、1y (sbyte)、1uy (byte)、1.0 (float)、1.0f (float32)、1.0m (decimal)、1I (BigInteger) などがあります。 diff --git a/src/Compiler/xlf/FSComp.txt.ko.xlf b/src/Compiler/xlf/FSComp.txt.ko.xlf index 780ef6fce0d..6426bf3310d 100644 --- a/src/Compiler/xlf/FSComp.txt.ko.xlf +++ b/src/Compiler/xlf/FSComp.txt.ko.xlf @@ -192,6 +192,11 @@ 여러 제네릭 인스턴스화가 포함된 인터페이스 + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions ML 호환성 개정 @@ -437,6 +442,11 @@ 모든 컴파일 파일의 유추된 인터페이스를 관련 서명 파일로 인쇄합니다. + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ 형식 정의에 예기치 않은 토큰이 있습니다. '{0}' 형식 뒤에 '='가 필요합니다. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' 이 구성원 액세스가 모호합니다. 개체 생성 주위에 괄호를 사용하세요. 예: '(새로운 SomeType(인수)).MemberName' @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - 유효한 숫자 리터럴이 아닙니다. 유효한 숫자 리터럴로는 1, 0x1, 0o1, 0b1, 1l(int), 1u(uint32), 1L(int64), 1UL(uint64), 1s(int16), 1y(sbyte), 1uy(byte), 1.0(float), 1.0f(float32), 1.0m(decimal), 1I(BigInteger) 등이 있습니다. + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + 유효한 숫자 리터럴이 아닙니다. 유효한 숫자 리터럴로는 1, 0x1, 0o1, 0b1, 1l(int), 1u(uint32), 1L(int64), 1UL(uint64), 1s(int16), 1y(sbyte), 1uy(byte), 1.0(float), 1.0f(float32), 1.0m(decimal), 1I(BigInteger) 등이 있습니다. diff --git a/src/Compiler/xlf/FSComp.txt.pl.xlf b/src/Compiler/xlf/FSComp.txt.pl.xlf index ebb2f8b9a66..afdfacc751b 100644 --- a/src/Compiler/xlf/FSComp.txt.pl.xlf +++ b/src/Compiler/xlf/FSComp.txt.pl.xlf @@ -192,6 +192,11 @@ interfejsy z wieloma ogólnymi wystąpieniami + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions Poprawki dotyczące zgodności Machine Learning @@ -437,6 +442,11 @@ Drukowanie wywnioskowanych interfejsów wszystkich plików kompilacji do skojarzonych plików sygnatur + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Nieoczekiwany token w definicji typu. Oczekiwano znaku „=” po typie „{0}”. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' Dostęp tego elementu członkowskiego jest niejednoznaczny. W celu utworzenia obiektu użyj nawiasów, na przykład „(nowy SomeType(args)).MemberName” @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Jest to nieprawidłowy literał liczbowy. Do prawidłowych literałów liczbowych należą: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Jest to nieprawidłowy literał liczbowy. Do prawidłowych literałów liczbowych należą: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.pt-BR.xlf b/src/Compiler/xlf/FSComp.txt.pt-BR.xlf index 0f505fdbd50..74ab3d8218a 100644 --- a/src/Compiler/xlf/FSComp.txt.pt-BR.xlf +++ b/src/Compiler/xlf/FSComp.txt.pt-BR.xlf @@ -192,6 +192,11 @@ interfaces com várias instanciações genéricas + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions Revisões de compatibilidade de ML @@ -437,6 +442,11 @@ Imprimir as interfaces inferidas de todos os arquivos de compilação para os arquivos de assinatura associados + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Token inesperado na definição de tipo. Esperava-se '=' após o tipo '{0}'. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' Este acesso de membro é ambíguo. Use parênteses em torno da criação do objeto, por exemplo, '(new SomeType(args)).MemberName''. @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Este não é um literal numérico válido. Literais numéricos válidos incluem 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Este não é um literal numérico válido. Literais numéricos válidos incluem 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.ru.xlf b/src/Compiler/xlf/FSComp.txt.ru.xlf index 524ca67e6a2..27beda90f17 100644 --- a/src/Compiler/xlf/FSComp.txt.ru.xlf +++ b/src/Compiler/xlf/FSComp.txt.ru.xlf @@ -192,6 +192,11 @@ интерфейсы с множественным универсальным созданием экземпляра + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions Редакции совместимости ML @@ -437,6 +442,11 @@ Печать определяемых интерфейсов всех файлов компиляции в связанные файлы подписей + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Неожиданный токен в определении типа. После типа "{0}" ожидается "=". + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' Неоднозначный доступ к этому элементу. Заключите операцию создания объекта в круглые скобки, например (new Объект(аргументы)).Элемент @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Это не является допустимым числовым литералом. Допустимые числовые литералы: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Это не является допустимым числовым литералом. Допустимые числовые литералы: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.tr.xlf b/src/Compiler/xlf/FSComp.txt.tr.xlf index 6b48aa4e978..caf719f7123 100644 --- a/src/Compiler/xlf/FSComp.txt.tr.xlf +++ b/src/Compiler/xlf/FSComp.txt.tr.xlf @@ -192,6 +192,11 @@ birden çok genel örnek oluşturma içeren arabirimler + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions ML uyumluluk düzeltmeleri @@ -437,6 +442,11 @@ Tüm derleme dosyalarının çıkarsanan arabirimlerini ilişkili imza dosyalarına yazdır + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ Tür tanımında beklenmeyen belirteç var. '{0}' türünden sonra '=' bekleniyordu. + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' Bu üye erişimi belirsiz. Lütfen nesne oluşturma etrafında parantez kullanın, örneğin '(yeni SomeType (args)).MemberName’ @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Bu geçerli bir sayısal sabit değer değil. Geçerli sayısal sabit değerler şunları içerir: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + Bu geçerli bir sayısal sabit değer değil. Geçerli sayısal sabit değerler şunları içerir: 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). diff --git a/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf b/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf index 6a8b22ce3ba..9c35bdaf5ce 100644 --- a/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf +++ b/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf @@ -192,6 +192,11 @@ 具有多个泛型实例化的接口 + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions ML 兼容性修订 @@ -437,6 +442,11 @@ 将所有编译文件的推断接口打印到关联的签名文件 + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ 类型定义中出现意外标记。类型“{0}”后应为 "="。 + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' 此成员访问权限不明确。请在对象创建周围使用括号,例如 “(new SomeType(args)).MemberName” @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - 这不是有效的数字文本。有效的数字文本包括 1、0x1、0o1、0b1、1l (int)、1u (uint32)、1L (int64)、1UL (uint64)、1s (int16)、1y (sbyte)、1uy (byte)、1.0 (float)、1.0f (float32)、1.0m (decimal)、1I (BigInteger)。 + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + 这不是有效的数字文本。有效的数字文本包括 1、0x1、0o1、0b1、1l (int)、1u (uint32)、1L (int64)、1UL (uint64)、1s (int16)、1y (sbyte)、1uy (byte)、1.0 (float)、1.0f (float32)、1.0m (decimal)、1I (BigInteger)。 diff --git a/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf b/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf index 6f59f4ce7bf..175dfc3d236 100644 --- a/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf +++ b/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf @@ -192,6 +192,11 @@ 具有多個泛型具現化的介面 + + Allow lowercase DU when RequireQualifiedAccess attribute + Allow lowercase DU when RequireQualifiedAccess attribute + + ML compatibility revisions ML 相容性修訂 @@ -437,6 +442,11 @@ 將所有編譯檔案的推斷介面列印至相關聯的簽章檔案 + + Clear the package manager results cache + Clear the package manager results cache + + Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. Invalid use of emitting a reference assembly, do not use '--staticlink', or '--refonly' and '--refout' together. @@ -522,6 +532,11 @@ 型別定義中出現非預期的權杖。類型 '{0}' 之後應該要有 '='。 + + Expecting expression + Expecting expression + + This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName' 此成員存取不明確。請在物件建立前後加上括弧,例如「(new SomeType(args)).MemberName」 @@ -5828,8 +5843,8 @@ - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - 這不是有效的數值常值。有效的數值常值包括 1、0x1、0o1、0b1、1l (int)、1u (uint32)、1L (int64)、1UL (uint64)、1s (int16)、1y (sbyte)、1uy (byte)、1.0 (float)、1.0f (float32)、1.0m (decimal)、1I (BigInteger)。 + This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint). + 這不是有效的數值常值。有效的數值常值包括 1、0x1、0o1、0b1、1l (int)、1u (uint32)、1L (int64)、1UL (uint64)、1s (int16)、1y (sbyte)、1uy (byte)、1.0 (float)、1.0f (float32)、1.0m (decimal)、1I (BigInteger)。 diff --git a/src/Compiler/xlf/FSStrings.cs.xlf b/src/Compiler/xlf/FSStrings.cs.xlf index 924659eb22a..849a9018ef5 100644 --- a/src/Compiler/xlf/FSStrings.cs.xlf +++ b/src/Compiler/xlf/FSStrings.cs.xlf @@ -7,6 +7,11 @@ Nejméně jedna informační zpráva v načteném souboru\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' symbol ..^ diff --git a/src/Compiler/xlf/FSStrings.de.xlf b/src/Compiler/xlf/FSStrings.de.xlf index 9462806409e..79176e0e2f1 100644 --- a/src/Compiler/xlf/FSStrings.de.xlf +++ b/src/Compiler/xlf/FSStrings.de.xlf @@ -7,6 +7,11 @@ Mindestens eine Informationsmeldung in der geladenen Datei.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' Symbol "..^" diff --git a/src/Compiler/xlf/FSStrings.es.xlf b/src/Compiler/xlf/FSStrings.es.xlf index b4b8b4531e4..8b09a7c5903 100644 --- a/src/Compiler/xlf/FSStrings.es.xlf +++ b/src/Compiler/xlf/FSStrings.es.xlf @@ -7,6 +7,11 @@ Uno o más mensajes informativos en el archivo cargado.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' símbolo "..^" diff --git a/src/Compiler/xlf/FSStrings.fr.xlf b/src/Compiler/xlf/FSStrings.fr.xlf index 53e4eb6cff4..f88d8e7182b 100644 --- a/src/Compiler/xlf/FSStrings.fr.xlf +++ b/src/Compiler/xlf/FSStrings.fr.xlf @@ -7,6 +7,11 @@ Un ou plusieurs messages d’information dans le fichier chargé.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' symbole '..^' diff --git a/src/Compiler/xlf/FSStrings.it.xlf b/src/Compiler/xlf/FSStrings.it.xlf index d8cf6e9c21e..e46a3cb54d6 100644 --- a/src/Compiler/xlf/FSStrings.it.xlf +++ b/src/Compiler/xlf/FSStrings.it.xlf @@ -7,6 +7,11 @@ Uno o più messaggi informativi nel file caricato.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' simbolo '..^' diff --git a/src/Compiler/xlf/FSStrings.ja.xlf b/src/Compiler/xlf/FSStrings.ja.xlf index ad32096733b..b0a149427b1 100644 --- a/src/Compiler/xlf/FSStrings.ja.xlf +++ b/src/Compiler/xlf/FSStrings.ja.xlf @@ -7,6 +7,11 @@ 読み込まれたファイル内の 1 つ以上の情報メッセージ。\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' シンボル '..^' diff --git a/src/Compiler/xlf/FSStrings.ko.xlf b/src/Compiler/xlf/FSStrings.ko.xlf index 8e112d8d28c..da9ee85444d 100644 --- a/src/Compiler/xlf/FSStrings.ko.xlf +++ b/src/Compiler/xlf/FSStrings.ko.xlf @@ -7,6 +7,11 @@ 로드된 파일에 하나 이상의 정보 메시지가 있습니다.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' 기호 '..^' diff --git a/src/Compiler/xlf/FSStrings.pl.xlf b/src/Compiler/xlf/FSStrings.pl.xlf index fe6c8536f87..f89d330d272 100644 --- a/src/Compiler/xlf/FSStrings.pl.xlf +++ b/src/Compiler/xlf/FSStrings.pl.xlf @@ -7,6 +7,11 @@ Jeden lub więcej komunikatów informacyjnych w załadowanym pliku.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' symbol „..^” diff --git a/src/Compiler/xlf/FSStrings.pt-BR.xlf b/src/Compiler/xlf/FSStrings.pt-BR.xlf index 8dc8c546ffc..a6f597c97aa 100644 --- a/src/Compiler/xlf/FSStrings.pt-BR.xlf +++ b/src/Compiler/xlf/FSStrings.pt-BR.xlf @@ -7,6 +7,11 @@ Uma ou mais mensagens informativas no arquivo carregado.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' símbolo '..^' diff --git a/src/Compiler/xlf/FSStrings.ru.xlf b/src/Compiler/xlf/FSStrings.ru.xlf index 6979fe42d9f..310b7437a2e 100644 --- a/src/Compiler/xlf/FSStrings.ru.xlf +++ b/src/Compiler/xlf/FSStrings.ru.xlf @@ -7,6 +7,11 @@ Одно или несколько информационных сообщений в загруженном файле.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' символ "..^" diff --git a/src/Compiler/xlf/FSStrings.tr.xlf b/src/Compiler/xlf/FSStrings.tr.xlf index 54328fdea3f..c5cbc423360 100644 --- a/src/Compiler/xlf/FSStrings.tr.xlf +++ b/src/Compiler/xlf/FSStrings.tr.xlf @@ -7,6 +7,11 @@ Yüklenen dosyada bir veya daha fazla bilgi mesajı.\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' '..^' sembolü diff --git a/src/Compiler/xlf/FSStrings.zh-Hans.xlf b/src/Compiler/xlf/FSStrings.zh-Hans.xlf index 95130a6391f..be3604df4bf 100644 --- a/src/Compiler/xlf/FSStrings.zh-Hans.xlf +++ b/src/Compiler/xlf/FSStrings.zh-Hans.xlf @@ -7,6 +7,11 @@ 加载文件 .\n 中有一条或多条信息性消息 + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' 符号 "..^" diff --git a/src/Compiler/xlf/FSStrings.zh-Hant.xlf b/src/Compiler/xlf/FSStrings.zh-Hant.xlf index 5ff1442b5c3..67e6c25370e 100644 --- a/src/Compiler/xlf/FSStrings.zh-Hant.xlf +++ b/src/Compiler/xlf/FSStrings.zh-Hant.xlf @@ -7,6 +7,11 @@ 已載入檔案中的一或多個資訊訊息。\n + + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute + + symbol '..^' 符號 '..^' diff --git a/src/Directory.Build.props b/src/Directory.Build.props index ba0693c81e5..5950a28ad0f 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -15,6 +15,7 @@ true false $(ArtifactsPackagesDir)\$(Configuration) + false diff --git a/src/FSharp.Build/FSharp.Build.fsproj b/src/FSharp.Build/FSharp.Build.fsproj index f293b92a05f..ce010764b62 100644 --- a/src/FSharp.Build/FSharp.Build.fsproj +++ b/src/FSharp.Build/FSharp.Build.fsproj @@ -58,10 +58,10 @@ The FSharp.Build built here may be loaded directly into a shipped Visual Studio, to that end, we cannot rely on new API's just being added to FSharp.Core. --> - + - + diff --git a/src/FSharp.Build/FSharpEmbedResXSource.fs b/src/FSharp.Build/FSharpEmbedResXSource.fs index 59a3930059d..4b34660b2a8 100644 --- a/src/FSharp.Build/FSharpEmbedResXSource.fs +++ b/src/FSharp.Build/FSharpEmbedResXSource.fs @@ -24,15 +24,15 @@ type FSharpEmbedResXSource() = namespace {0} open System.Reflection +open System.Globalization module internal {1} = type private C (_dummy:System.Int32) = class end - let mutable Culture = System.Globalization.CultureInfo.CurrentUICulture let ResourceManager = new System.Resources.ResourceManager(""{2}"", C(0).GetType().GetTypeInfo().Assembly) - let GetString(name:System.String) : System.String = ResourceManager.GetString(name, Culture)" + let GetString(name:System.String) : System.String = ResourceManager.GetString(name, CultureInfo.CurrentUICulture)" let boilerplateGetObject = - " let GetObject(name:System.String) : System.Object = ResourceManager.GetObject(name, Culture)" + " let GetObject(name:System.String) : System.Object = ResourceManager.GetObject(name, CultureInfo.CurrentUICulture)" let generateSource (resx: string) (fullModuleName: string) (generateLegacy: bool) (generateLiteral: bool) = try @@ -41,9 +41,11 @@ module internal {1} = let sourcePath = Path.Combine(_outputPath, justFileName + ".fs") // simple up-to-date check - if File.Exists(resx) - && File.Exists(sourcePath) - && File.GetLastWriteTimeUtc(resx) <= File.GetLastWriteTimeUtc(sourcePath) then + if + File.Exists(resx) + && File.Exists(sourcePath) + && File.GetLastWriteTimeUtc(resx) <= File.GetLastWriteTimeUtc(sourcePath) + then printMessage (sprintf "Skipping generation: '%s' since it is up-to-date." sourcePath) Some(sourcePath) else diff --git a/src/FSharp.Build/Fsc.fs b/src/FSharp.Build/Fsc.fs index 26221519380..909354e83e7 100644 --- a/src/FSharp.Build/Fsc.fs +++ b/src/FSharp.Build/Fsc.fs @@ -45,6 +45,7 @@ type public Fsc() as this = let mutable optimize: bool = true let mutable otherFlags: string MaybeNull = null let mutable outputAssembly: string MaybeNull = null + let mutable outputRefAssembly: string MaybeNull = null let mutable pathMap: string MaybeNull = null let mutable pdbFile: string MaybeNull = null let mutable platform: string MaybeNull = null @@ -54,6 +55,7 @@ type public Fsc() as this = let mutable provideCommandLineArgs: bool = false let mutable references: ITaskItem[] = [||] let mutable referencePath: string MaybeNull = null + let mutable refOnly: bool = false let mutable resources: ITaskItem[] = [||] let mutable skipCompilerExecution: bool = false let mutable sources: ITaskItem[] = [||] @@ -328,6 +330,12 @@ type public Fsc() as this = builder.AppendFileNamesIfNotNull(sources, " ") capturedFilenames <- builder.CapturedFilenames() + // Ref assemblies + builder.AppendSwitchIfNotNull("--refout:", outputRefAssembly) + + if refOnly then + builder.AppendSwitch("--refonly") + builder // --baseaddress @@ -450,6 +458,11 @@ type public Fsc() as this = with get () = outputAssembly and set (s) = outputAssembly <- s + // --refout : Name the output ref file + member _.OutputRefAssembly + with get () = outputRefAssembly + and set (s) = outputRefAssembly <- s + // --pathmap : Paths to rewrite when producing deterministic builds member _.PathMap with get () = pathMap @@ -497,6 +510,11 @@ type public Fsc() as this = with get () = referencePath and set (s) = referencePath <- s + // --refonly + member _.RefOnly + with get () = refOnly + and set (b) = refOnly <- b + // --resource : Embed the specified managed resources (.resource). // Produce .resource files from .resx files using resgen.exe or resxc.exe. member _.Resources diff --git a/src/FSharp.Build/Microsoft.FSharp.Targets b/src/FSharp.Build/Microsoft.FSharp.Targets index 229e3bbbc7f..18c05c83c0e 100644 --- a/src/FSharp.Build/Microsoft.FSharp.Targets +++ b/src/FSharp.Build/Microsoft.FSharp.Targets @@ -69,7 +69,7 @@ this file. $(Fsc_NetFramework_ToolPath) $(Fsc_NetFramework_AnyCpu_ToolExe) - $(Fsc_NetFramework_X86_ToolExe) + $(Fsc_NetFramework_PlatformSpecific_ToolExe) @@ -264,6 +264,7 @@ this file. $(LoadSource)" Outputs="@(DocFileItem); @(IntermediateAssembly); + @(IntermediateRefAssembly); @(_DebugSymbolsIntermediatePath); $(NonExistentFile); @(CustomAdditionalCompileOutputs)" @@ -338,6 +339,7 @@ this file. ReflectionFree="$(ReflectionFree)" OtherFlags="$(FscOtherFlags)" OutputAssembly="@(IntermediateAssembly)" + OutputRefAssembly="@(IntermediateRefAssembly)" PathMap="$(PathMap)" PdbFile="$(PdbFile)" Platform="$(PlatformTarget)" @@ -347,6 +349,7 @@ this file. PublicSign="$(PublicSign)" References="@(ReferencePath)" ReferencePath="$(ReferencePath)" + RefOnly="$(ProduceOnlyReferenceAssembly)" Resources="@(ActualEmbeddedResources)" SkipCompilerExecution="$(SkipCompilerExecution)" SourceLink="$(SourceLink)" @@ -391,48 +394,6 @@ this file. ============================================================ --> - - - - - - - - - - - - - - - - - - - - diff --git a/src/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj b/src/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj index cb5aaaf5029..e8561e03080 100644 --- a/src/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj +++ b/src/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj @@ -12,6 +12,7 @@ + diff --git a/src/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj b/src/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj index 8241f891960..b2c7d204445 100644 --- a/src/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj +++ b/src/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj @@ -11,6 +11,7 @@ + diff --git a/src/FSharp.Core/FSharp.Core.fsproj b/src/FSharp.Core/FSharp.Core.fsproj index c5fc82dfebd..0bf44a3d125 100644 --- a/src/FSharp.Core/FSharp.Core.fsproj +++ b/src/FSharp.Core/FSharp.Core.fsproj @@ -10,27 +10,21 @@ $(NoWarn);1204 true $(DefineConstants);FSHARP_CORE - BUILDING_WITH_LKG;$(DefineConstants) $(OtherFlags) --warnon:3218 - - $(OtherFlags) --warnon:1182 - - $(OtherFlags) --warnon:3390 - - $(OtherFlags) --warnon:3520 $(OtherFlags) --warnon:1182 $(OtherFlags) --warnon:3390 + + $(OtherFlags) --warnon:3520 $(OtherFlags) --nowarn:57 + $(OtherFlags) --nowarn:3511 - $(OtherFlags) --nowarn:3511 --nowarn:3513 + $(OtherFlags) --nowarn:3513 $(OtherFlags) --compiling-fslib --compiling-fslib-40 --maxerrors:100 --extraoptimizationloops:1 - - preview true true diff --git a/src/FSharp.Core/Linq.fs b/src/FSharp.Core/Linq.fs index 5b383f2c3d2..7093d0c72d4 100644 --- a/src/FSharp.Core/Linq.fs +++ b/src/FSharp.Core/Linq.fs @@ -593,11 +593,11 @@ module LeafExpressionConverter = | NullableConstruction arg -> Expression.Convert(ConvExprToLinqInContext env arg, x.Type) |> asExpr | _ -> Expression.New(ctorInfo, ConvExprsToLinq env args) |> asExpr - | Patterns.NewDelegate(dty, vs, b) -> + | Patterns.NewDelegate(delegateTy, vs, b) -> let vsP = List.map ConvVarToLinq vs let env = {env with varEnv = List.foldBack2 (fun (v:Var) vP -> Map.add v (vP |> asExpr)) vs vsP env.varEnv } let bodyP = ConvExprToLinqInContext env b - Expression.Lambda(dty, bodyP, vsP) |> asExpr + Expression.Lambda(delegateTy, bodyP, vsP) |> asExpr | Patterns.NewTuple args -> let tupTy = diff --git a/src/FSharp.Core/QueryExtensions.fs b/src/FSharp.Core/QueryExtensions.fs index f9d0ffd72fb..220618ae563 100644 --- a/src/FSharp.Core/QueryExtensions.fs +++ b/src/FSharp.Core/QueryExtensions.fs @@ -212,7 +212,7 @@ module internal Adapters = type ConversionDescription = | TupleConv of ConversionDescription list | RecordConv of Type * ConversionDescription list - | GroupingConv (* origKeyType: *) of Type (* origElemType: *) * Type * ConversionDescription + | GroupingConv (* origKeyType: *) of Type (* origElemType: *) * Type * ConversionDescription | SeqConv of ConversionDescription | NoConv diff --git a/src/FSharp.Core/array.fs b/src/FSharp.Core/array.fs index 1dff8103bda..8c2fa8470fa 100644 --- a/src/FSharp.Core/array.fs +++ b/src/FSharp.Core/array.fs @@ -17,7 +17,8 @@ open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators module Array = let inline checkNonNull argName arg = - if isNull arg then nullArg argName + if isNull arg then + nullArg argName let inline indexNotFound () = raise (KeyNotFoundException(SR.GetString(SR.keyNotFoundAlt))) @@ -1601,7 +1602,9 @@ module Array = for i = 1 to array.Length - 1 do let curr = array.[i] - if curr < acc then acc <- curr + + if curr < acc then + acc <- curr acc @@ -1636,7 +1639,9 @@ module Array = for i = 1 to array.Length - 1 do let curr = array.[i] - if curr > acc then acc <- curr + + if curr > acc then + acc <- curr acc diff --git a/src/FSharp.Core/async.fs b/src/FSharp.Core/async.fs index 46cd93a84ee..e907040c94c 100644 --- a/src/FSharp.Core/async.fs +++ b/src/FSharp.Core/async.fs @@ -412,7 +412,8 @@ type AsyncActivation<'T>(contents: AsyncActivationContents<'T>) = ok <- true res finally - if not ok then ctxt.OnExceptionRaised() + if not ok then + ctxt.OnExceptionRaised() member ctxt.PostWithTrampoline (syncCtxt: SynchronizationContext) (f: unit -> AsyncReturn) = let holder = contents.aux.trampolineHolder @@ -486,7 +487,8 @@ module AsyncPrimitives = result <- userCode arg ok <- true finally - if not ok then ctxt.OnExceptionRaised() + if not ok then + ctxt.OnExceptionRaised() if ok then AsyncActivation<'T>.HijackCheckThenCall ctxt ctxt.cont result @@ -508,7 +510,8 @@ module AsyncPrimitives = result <- part2 result1 ok <- true finally - if not ok then ctxt.OnExceptionRaised() + if not ok then + ctxt.OnExceptionRaised() if ok then Invoke result ctxt @@ -525,7 +528,8 @@ module AsyncPrimitives = res <- userCode result1 ok <- true finally - if not ok then ctxt.OnExceptionRaised() + if not ok then + ctxt.OnExceptionRaised() if ok then res.Invoke ctxt else fake () @@ -543,7 +547,8 @@ module AsyncPrimitives = resOpt <- filterFunction (edi.GetAssociatedSourceException()) ok <- true finally - if not ok then ctxt.OnExceptionRaised() + if not ok then + ctxt.OnExceptionRaised() if ok then match resOpt with @@ -990,7 +995,9 @@ module AsyncPrimitives = else // In this case the ResultCell has already been disposed, e.g. due to a timeout. // The result is dropped on the floor. - if disposed then + if + disposed + then [] else result <- Some res diff --git a/src/FSharp.Core/eventmodule.fs b/src/FSharp.Core/eventmodule.fs index cd9dc68a76d..fc3c2eabd64 100644 --- a/src/FSharp.Core/eventmodule.fs +++ b/src/FSharp.Core/eventmodule.fs @@ -22,7 +22,11 @@ module Event = [] let filter predicate (sourceEvent: IEvent<'Delegate, 'T>) = let ev = new Event<_>() - sourceEvent.Add(fun x -> if predicate x then ev.Trigger x) + + sourceEvent.Add(fun x -> + if predicate x then + ev.Trigger x) + ev.Publish [] diff --git a/src/FSharp.Core/fslib-extra-pervasives.fs b/src/FSharp.Core/fslib-extra-pervasives.fs index c78b71e48e0..90304bd36dc 100644 --- a/src/FSharp.Core/fslib-extra-pervasives.fs +++ b/src/FSharp.Core/fslib-extra-pervasives.fs @@ -373,11 +373,9 @@ module ExtraTopLevelOperators = [] [] [] -#if !BUILDING_WITH_LKG && !BUILD_FROM_SOURCE [] [] [] -#endif [] [] do () diff --git a/src/FSharp.Core/list.fs b/src/FSharp.Core/list.fs index fbf8089610d..e0dff3d7adb 100644 --- a/src/FSharp.Core/list.fs +++ b/src/FSharp.Core/list.fs @@ -15,7 +15,8 @@ open System.Collections.Generic module List = let inline checkNonNull argName arg = - if isNull arg then nullArg argName + if isNull arg then + nullArg argName let inline indexNotFound () = raise (KeyNotFoundException(SR.GetString(SR.keyNotFoundAlt))) @@ -742,7 +743,8 @@ module List = let mutable acc = h for x in t do - if x > acc then acc <- x + if x > acc then + acc <- x acc @@ -771,7 +773,8 @@ module List = let mutable acc = h for x in t do - if x < acc then acc <- x + if x < acc then + acc <- x acc @@ -910,7 +913,9 @@ module List = match curr with | [] -> invalidArg "index" "index must be within bounds of the list" | h :: t -> - if i < index then coll.Add(h) //items before index we keep + if i < index then + coll.Add(h) //items before index we keep + curr <- t i <- i + 1 diff --git a/src/FSharp.Core/map.fs b/src/FSharp.Core/map.fs index 0d510239f32..9fad005450e 100644 --- a/src/FSharp.Core/map.fs +++ b/src/FSharp.Core/map.fs @@ -1040,7 +1040,8 @@ and KeyCollection<'Key, 'Value when 'Key: comparison>(parent: Map<'Key, 'Value>) parent.ContainsKey x member _.CopyTo(arr, index) = - if isNull arr then nullArg "arr" + if isNull arr then + nullArg "arr" if index < 0 then invalidArg "index" "index must be positive" @@ -1090,7 +1091,8 @@ and ValueCollection<'Key, 'Value when 'Key: comparison>(parent: Map<'Key, 'Value parent.Exists(fun _ value -> Unchecked.equals value x) member _.CopyTo(arr, index) = - if isNull arr then nullArg "arr" + if isNull arr then + nullArg "arr" if index < 0 then invalidArg "index" "index must be positive" diff --git a/src/FSharp.Core/observable.fs b/src/FSharp.Core/observable.fs index d1bcd160313..eb34c62c850 100644 --- a/src/FSharp.Core/observable.fs +++ b/src/FSharp.Core/observable.fs @@ -12,11 +12,12 @@ open Microsoft.FSharp.Control module Observable = let inline protect f succeed fail = - match (try - Choice1Of2(f ()) - with e -> - Choice2Of2 e) - with + match + (try + Choice1Of2(f ()) + with e -> + Choice2Of2 e) + with | Choice1Of2 x -> (succeed x) | Choice2Of2 e -> (fail e) @@ -34,7 +35,8 @@ module Observable = interface IObserver<'T> with member x.OnNext value = - if not stopped then x.Next value + if not stopped then + x.Next value member x.OnError e = if not stopped then @@ -166,7 +168,8 @@ module Observable = source1.Subscribe { new IObserver<'T> with member x.OnNext(v) = - if not stopped then observer.OnNext v + if not stopped then + observer.OnNext v member x.OnError(e) = if not stopped then @@ -186,7 +189,8 @@ module Observable = source2.Subscribe { new IObserver<'T> with member x.OnNext(v) = - if not stopped then observer.OnNext v + if not stopped then + observer.OnNext v member x.OnError(e) = if not stopped then diff --git a/src/FSharp.Core/prim-types.fs b/src/FSharp.Core/prim-types.fs index 4f7486c8fe5..40b4941045b 100644 --- a/src/FSharp.Core/prim-types.fs +++ b/src/FSharp.Core/prim-types.fs @@ -472,9 +472,9 @@ namespace Microsoft.FSharp.Core let inline floatEq (x:float) (y:float) = (# "ceq" x y : bool #) let inline float32Eq (x:float32) (y:float32) = (# "ceq" x y : bool #) let inline charEq (x:char) (y:char) = (# "ceq" x y : bool #) - let inline intOrder (x:int) (y:int) = if (# "clt" x y : bool #) then (0-1) else (# "cgt" x y : int #) - let inline int64Order (x:int64) (y:int64) = if (# "clt" x y : bool #) then (0-1) else (# "cgt" x y : int #) - let inline byteOrder (x:byte) (y:byte) = if (# "clt" x y : bool #) then (0-1) else (# "cgt" x y : int #) + let inline intOrder (x:int) (y:int) = (# "cgt" x y : int #) - (# "clt" x y : int #) + let inline int64Order (x:int64) (y:int64) = (# "cgt" x y : int #) - (# "clt" x y : int #) + let inline byteOrder (x:byte) (y:byte) = (# "cgt" x y: int #) - (# "clt" x y: int #) let inline byteEq (x:byte) (y:byte) = (# "ceq" x y : bool #) let inline int64 (x:int) = (# "conv.i8" x : int64 #) let inline int32 (x:int64) = (# "conv.i4" x : int32 #) @@ -914,10 +914,10 @@ namespace Microsoft.FSharp.Core x.CompareTo(yobj) | (:? nativeint as x),(:? nativeint as y) -> - if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) + (# "cgt" x y : int #) - (# "clt" x y : int #) | (:? unativeint as x),(:? unativeint as y) -> - if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) + (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) | _,(:? IStructuralComparable as yc) -> let res = yc.CompareTo(xobj,comp) @@ -1059,17 +1059,25 @@ namespace Microsoft.FSharp.Core // let inline GenericComparisonWithComparerFast<'T> (comp:IComparer) (x:'T) (y:'T) : int = GenericComparisonWithComparerIntrinsic comp x y - when 'T : bool = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : sbyte = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : int16 = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : int32 = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : int64 = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : nativeint = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : byte = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : uint16 = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : uint32 = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : uint64 = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : unativeint = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) + + when 'T : bool = + // bool is already 1 for True or 0 for False + // x - y gives: + // compare true false -> 1 - 0 -> 1 + // compare false true -> 0 - 1 -> -1 + // compare true true -> 1 - 1 -> 0 + // compare false false -> 0 - 0 -> 0 + (# "" x : int #) - (# "" y : int #) + when 'T : sbyte = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : int16 = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : int32 = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : int64 = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : nativeint = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : byte = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : uint16 = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : uint32 = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : uint64 = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : unativeint = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) // Note, these bail out to GenericComparisonWithComparerIntrinsic if called with NaN values, because clt and cgt and ceq all return "false" for that case. when 'T : float = if (# "clt" x y : bool #) then (-1) elif (# "cgt" x y : bool #) then (1) @@ -1079,7 +1087,7 @@ namespace Microsoft.FSharp.Core elif (# "cgt" x y : bool #) then (1) elif (# "ceq" x y : bool #) then (0) else GenericComparisonWithComparerIntrinsic comp x y - when 'T : char = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) + when 'T : char = (# "cgt" x y : int #) - (# "clt" x y : int #) when 'T : string = // NOTE: we don't have to null check here because System.String.CompareOrdinal // gives reliable results on null values. @@ -1137,17 +1145,25 @@ namespace Microsoft.FSharp.Core /// for known cases. let inline GenericComparisonFast<'T> (x:'T) (y:'T) : int = GenericComparisonIntrinsic x y - when 'T : bool = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : sbyte = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : int16 = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : int32 = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : int64 = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : nativeint = if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - when 'T : byte = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : uint16 = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : uint32 = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : uint64 = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) - when 'T : unativeint = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) + + when 'T : bool = + // bool is already 1 for True or 0 for False + // x - y gives: + // compare true false -> 1 - 0 -> 1 + // compare false true -> 0 - 1 -> -1 + // compare true true -> 1 - 1 -> 0 + // compare false false -> 0 - 0 -> 0 + (# "" x : int #) - (# "" y : int #) + when 'T : sbyte = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : int16 = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : int32 = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : int64 = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : nativeint = (# "cgt" x y : int #) - (# "clt" x y : int #) + when 'T : byte = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : uint16 = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : uint32 = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : uint64 = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) + when 'T : unativeint = (# "cgt.un" x y : int #) - (# "clt.un" x y : int #) when 'T : float = if (# "clt" x y : bool #) then (-1) elif (# "cgt" x y : bool #) then (1) elif (# "ceq" x y : bool #) then (0) @@ -1158,7 +1174,7 @@ namespace Microsoft.FSharp.Core elif (# "ceq" x y : bool #) then (0) elif (# "ceq" y y : bool #) then (-1) else (# "ceq" x x : int #) - when 'T : char = if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) + when 'T : char = (# "cgt" x y : int #) - (# "clt" x y : int #) when 'T : string = // NOTE: we don't have to null check here because System.String.CompareOrdinal // gives reliable results on null values. @@ -4771,17 +4787,24 @@ namespace Microsoft.FSharp.Core [] let inline compare (e1: ^T) (e2: ^T) : int = (if e1 < e2 then -1 elif e1 > e2 then 1 else 0) - when ^T : bool = if (# "clt" e1 e2 : bool #) then (-1) else (# "cgt" e1 e2 : int #) - when ^T : sbyte = if (# "clt" e1 e2 : bool #) then (-1) else (# "cgt" e1 e2 : int #) - when ^T : int16 = if (# "clt" e1 e2 : bool #) then (-1) else (# "cgt" e1 e2 : int #) - when ^T : int32 = if (# "clt" e1 e2 : bool #) then (-1) else (# "cgt" e1 e2 : int #) - when ^T : int64 = if (# "clt" e1 e2 : bool #) then (-1) else (# "cgt" e1 e2 : int #) - when ^T : nativeint = if (# "clt" e1 e2 : bool #) then (-1) else (# "cgt" e1 e2 : int #) - when ^T : byte = if (# "clt.un" e1 e2 : bool #) then (-1) else (# "cgt.un" e1 e2 : int #) - when ^T : uint16 = if (# "clt.un" e1 e2 : bool #) then (-1) else (# "cgt.un" e1 e2 : int #) - when ^T : uint32 = if (# "clt.un" e1 e2 : bool #) then (-1) else (# "cgt.un" e1 e2 : int #) - when ^T : uint64 = if (# "clt.un" e1 e2 : bool #) then (-1) else (# "cgt.un" e1 e2 : int #) - when ^T : unativeint = if (# "clt.un" e1 e2 : bool #) then (-1) else (# "cgt.un" e1 e2 : int #) + when ^T : bool = + // bool is already 1 for true or 0 for false + // e1 - e2 gives: + // compare true false -> 1 - 0 -> 1 + // compare false true -> 0 - 1 -> -1 + // compare true true -> 1 - 1 -> 0 + // compare false false -> 0 - 0 -> 0 + (# "" e1 : int #) - (# "" e2 : int #) + when ^T : sbyte = (# "cgt" e1 e2 : int #) - (# "clt" e1 e2 : int #) + when ^T : int16 = (# "cgt" e1 e2 : int #) - (# "clt" e1 e2 : int #) + when ^T : int32 = (# "cgt" e1 e2 : int #) - (# "clt" e1 e2 : int #) + when ^T : int64 = (# "cgt" e1 e2 : int #) - (# "clt" e1 e2 : int #) + when ^T : nativeint = (# "cgt" e1 e2 : int #) - (# "clt" e1 e2 : int #) + when ^T : byte = (# "cgt.un" e1 e2 : int #) - (# "clt.un" e1 e2 : int #) + when ^T : uint16 = (# "cgt.un" e1 e2 : int #) - (# "clt.un" e1 e2 : int #) + when ^T : uint32 = (# "cgt.un" e1 e2 : int #) - (# "clt.un" e1 e2 : int #) + when ^T : uint64 = (# "cgt.un" e1 e2 : int #) - (# "clt.un" e1 e2 : int #) + when ^T : unativeint = (# "cgt.un" e1 e2 : int #) - (# "clt.un" e1 e2 : int #) when ^T : float = if (# "clt" e1 e2 : bool #) then (-1) elif (# "cgt" e1 e2 : bool #) then (1) elif (# "ceq" e1 e2 : bool #) then (0) @@ -4792,7 +4815,7 @@ namespace Microsoft.FSharp.Core elif (# "ceq" e1 e2 : bool #) then (0) elif (# "ceq" e2 e2 : bool #) then (-1) else (# "ceq" e1 e1 : int #) - when ^T : char = if (# "clt.un" e1 e2 : bool #) then (-1) else (# "cgt.un" e1 e2 : int #) + when ^T : char = (# "cgt" e1 e2 : int #) - (# "clt" e1 e2 : int #) when ^T : string = // NOTE: we don't have to null check here because String.CompareOrdinal // gives reliable results on null values. @@ -4833,8 +4856,7 @@ namespace Microsoft.FSharp.Core [] [] [] // assembly is fully transparent -#if CROSS_PLATFORM_COMPILER -#else +#if !CROSS_PLATFORM_COMPILER [] // v4 transparency; soon to be the default, but not yet #endif do () diff --git a/src/FSharp.Core/prim-types.fsi b/src/FSharp.Core/prim-types.fsi index af9b1c1e5a3..70ee63e0c2d 100644 --- a/src/FSharp.Core/prim-types.fsi +++ b/src/FSharp.Core/prim-types.fsi @@ -1027,7 +1027,7 @@ namespace Microsoft.FSharp.Core /// Basic Types with Units of Measure [] type byte<[] 'Measure> = byte - + /// The type of 16-bit unsigned integer numbers, annotated with a unit of measure. /// The unit of measure is erased in compiled code and when values of this type /// are analyzed using reflection. The type is representationally equivalent to @@ -1036,7 +1036,7 @@ namespace Microsoft.FSharp.Core /// Basic Types with Units of Measure [] type uint16<[] 'Measure> = uint16 - + /// The type of 64-bit unsigned integer numbers, annotated with a unit of measure. /// The unit of measure is erased in compiled code and when values of this type /// are analyzed using reflection. The type is representationally equivalent to @@ -1045,7 +1045,7 @@ namespace Microsoft.FSharp.Core /// Basic Types with Units of Measure [] type uint64<[] 'Measure> = uint64 - + /// The type of machine-sized unsigned integer numbers, annotated with a unit of measure. /// The unit of measure is erased in compiled code and when values of this type /// are analyzed using reflection. The type is representationally equivalent to @@ -1054,7 +1054,7 @@ namespace Microsoft.FSharp.Core /// Basic Types with Units of Measure [] type unativeint<[] 'Measure> = unativeint - + /// The type of double-precision floating point numbers, annotated with a unit of measure. /// The unit of measure is erased in compiled code and when values of this type /// are analyzed using reflection. The type is representationally equivalent to diff --git a/src/FSharp.Core/printf.fsi b/src/FSharp.Core/printf.fsi index 0171baecad6..dc9d8b9a629 100644 --- a/src/FSharp.Core/printf.fsi +++ b/src/FSharp.Core/printf.fsi @@ -35,8 +35,10 @@ type PrintfFormat<'Printer, 'State, 'Residue, 'Result> = /// The raw text of the format string. member Value: string + /// The captures associated with an interpolated string. member Captures: obj[] + /// The capture types associated with an interpolated string. member CaptureTypes: System.Type[] /// Type of a formatting expression. diff --git a/src/FSharp.Core/quotations.fs b/src/FSharp.Core/quotations.fs index a309d9c1816..44c625de5f5 100644 --- a/src/FSharp.Core/quotations.fs +++ b/src/FSharp.Core/quotations.fs @@ -1408,11 +1408,11 @@ module Patterns = | Unique of 'T | Ambiguous of 'R - let typeEquals (s: Type) (t: Type) = - s.Equals t + let typeEquals (ty1: Type) (ty2: Type) = + ty1.Equals ty2 - let typesEqual (ss: Type list) (tt: Type list) = - (ss.Length = tt.Length) && List.forall2 typeEquals ss tt + let typesEqual (tys1: Type list) (tys2: Type list) = + (tys1.Length = tys2.Length) && List.forall2 typeEquals tys1 tys2 let instFormal (typarEnv: Type[]) (ty: Instantiable<'T>) = ty (fun i -> typarEnv.[i]) @@ -1469,9 +1469,11 @@ module Patterns = else // If a known-number-of-arguments-including-object-argument has been given then check that - if (match knownArgCount with - | ValueNone -> false - | ValueSome n -> n <> (if methInfo.IsStatic then 0 else 1) + nargTs) then + if + (match knownArgCount with + | ValueNone -> false + | ValueSome n -> n <> (if methInfo.IsStatic then 0 else 1) + nargTs) + then false else diff --git a/src/FSharp.Core/reflect.fs b/src/FSharp.Core/reflect.fs index 4bc089765fb..76dbb87c490 100644 --- a/src/FSharp.Core/reflect.fs +++ b/src/FSharp.Core/reflect.fs @@ -1172,10 +1172,12 @@ type FSharpType = // No assembly passed therefore just get framework local version of Tuple let asm = typeof.Assembly - if types - |> Array.exists (function - | null -> true - | _ -> false) then + if + types + |> Array.exists (function + | null -> true + | _ -> false) + then invalidArg "types" (SR.GetString(SR.nullsNotAllowedInArray)) mkTupleType false asm types @@ -1183,10 +1185,12 @@ type FSharpType = static member MakeTupleType(asm: Assembly, types: Type[]) = checkNonNull "types" types - if types - |> Array.exists (function - | null -> true - | _ -> false) then + if + types + |> Array.exists (function + | null -> true + | _ -> false) + then invalidArg "types" (SR.GetString(SR.nullsNotAllowedInArray)) mkTupleType false asm types @@ -1194,10 +1198,12 @@ type FSharpType = static member MakeStructTupleType(asm: Assembly, types: Type[]) = checkNonNull "types" types - if types - |> Array.exists (function - | null -> true - | _ -> false) then + if + types + |> Array.exists (function + | null -> true + | _ -> false) + then invalidArg "types" (SR.GetString(SR.nullsNotAllowedInArray)) mkTupleType true asm types diff --git a/src/FSharp.Core/result.fs b/src/FSharp.Core/result.fs index 1f82740fa5f..a6e954b73af 100644 --- a/src/FSharp.Core/result.fs +++ b/src/FSharp.Core/result.fs @@ -22,3 +22,99 @@ module Result = match result with | Error e -> Error e | Ok x -> binder x + + [] + let inline isOk result = + match result with + | Ok _ -> true + | Error _ -> false + + [] + let inline isError result = + match result with + | Ok _ -> false + | Error _ -> true + + [] + let defaultValue value result = + match result with + | Error _ -> value + | Ok v -> v + + [] + let defaultWith defThunk result = + match result with + | Error _ -> defThunk () + | Ok v -> v + + [] + let count result = + match result with + | Error _ -> 0 + | Ok _ -> 1 + + [] + let fold<'T, 'Error, 'State> folder (state: 'State) (result: Result<'T, 'Error>) = + match result with + | Error _ -> state + | Ok x -> folder state x + + [] + let foldBack<'T, 'Error, 'State> folder (result: Result<'T, 'Error>) (state: 'State) = + match result with + | Error _ -> state + | Ok x -> folder x state + + [] + let exists predicate result = + match result with + | Error _ -> false + | Ok x -> predicate x + + [] + let forall predicate result = + match result with + | Error _ -> true + | Ok x -> predicate x + + [] + let inline contains value result = + match result with + | Error _ -> false + | Ok v -> v = value + + [] + let iter action result = + match result with + | Error _ -> () + | Ok x -> action x + + [] + let toArray result = + match result with + | Error _ -> [||] + | Ok x -> [| x |] + + [] + let toList result = + match result with + | Error _ -> [] + | Ok x -> [ x ] + + [] + let toSeq result = + match result with + | Error _ -> [] + | Ok x -> [ x ] + + [] + let toOption result = + match result with + | Error _ -> None + | Ok x -> Some x + + [] + let toValueOption result = + match result with + | Error _ -> ValueNone + | Ok x -> ValueSome x diff --git a/src/FSharp.Core/result.fsi b/src/FSharp.Core/result.fsi index 1429642a8a5..9c8fb7bbd5a 100644 --- a/src/FSharp.Core/result.fsi +++ b/src/FSharp.Core/result.fsi @@ -2,7 +2,7 @@ namespace Microsoft.FSharp.Core -open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators +open Microsoft.FSharp.Collections /// Contains operations for working with values of type . /// @@ -68,3 +68,247 @@ module Result = /// [] val bind: binder: ('T -> Result<'U, 'TError>) -> result: Result<'T, 'TError> -> Result<'U, 'TError> + + /// Returns true if the result is Ok. + /// The input result. + /// + /// True if the result is OK. + /// + /// + /// + /// Ok 42 |> Result.isOk // evaluates to true + /// Error 42 |> Result.isOk // evaluates to false + /// + /// + [] + val inline isOk: result: Result<'T, 'Error> -> bool + + /// Returns true if the result is Error. + /// + /// The input result. + /// + /// True if the result is Error. + /// + /// + /// + /// Ok 42 |> Result.isError // evaluates to false + /// Error 42 |> Result.isError // evaluates to true + /// + /// + [] + val inline isError: result: Result<'T, 'Error> -> bool + + /// Gets the value of the result if the result is Ok, otherwise returns the specified default value. + /// + /// The specified default value. + /// The input result. + /// + /// The result if the result is Ok, else the default value. + /// + /// + /// + /// Result.defaultValue 2 (Error 3) // evaluates to 2 + /// Result.defaultValue 2 (Ok 1) // evaluates to 1 + /// + /// + [] + val defaultValue: value: 'T -> result: Result<'T, 'Error> -> 'T + + /// Gets the value of the result if the result is Ok, otherwise evaluates and returns the result. + /// + /// A thunk that provides a default value when evaluated. + /// The input result. + /// + /// The result if the result is Ok, else the result of evaluating . + /// is not evaluated unless is Error. + /// + /// + /// + /// Ok 1 |> Result.defaultWith (fun () -> 99) // evaluates to 1 + /// Error 2 |> Result.defaultWith (fun () -> 99) // evaluates to 99 + /// + /// + [] + val defaultWith: defThunk: (unit -> 'T) -> result: Result<'T, 'Error> -> 'T + + /// count inp evaluates to match inp with Error _ -> 0 | Ok _ -> 1. + /// + /// The input result. + /// + /// A zero if the result is Error, a one otherwise. + /// + /// + /// + /// Error 99 |> Result.count // evaluates to 0 + /// Ok 99 |> Result.count // evaluates to 1 + /// + /// + [] + val count: result: Result<'T, 'Error> -> int + + /// fold f s inp evaluates to match inp with Error _ -> s | Ok x -> f s x. + /// + /// A function to update the state data when given a value from an result. + /// The initial state. + /// The input result. + /// + /// The original state if the result is Error, otherwise it returns the updated state with the folder + /// and the result value. + /// + /// + /// + /// (0, Error 2) ||> Result.fold (fun accum x -> accum + x * 2) // evaluates to 0 + /// (0, Ok 1) ||> Result.fold (fun accum x -> accum + x * 2) // evaluates to 2 + /// (10, Ok 1) ||> Result.fold (fun accum x -> accum + x * 2) // evaluates to 12 + /// + /// + [] + val fold<'T, 'Error, 'State> : + folder: ('State -> 'T -> 'State) -> state: 'State -> result: Result<'T, 'Error> -> 'State + + /// fold f inp s evaluates to match inp with Error _ -> s | Ok x -> f x s. + /// + /// A function to update the state data when given a value from an result. + /// The input result. + /// The initial state. + /// + /// The original state if the result is Error, otherwise it returns the updated state with the folder + /// and the result value. + /// + /// + /// + /// (Error 2, 0) ||> Result.foldBack (fun x accum -> accum + x * 2) // evaluates to 0 + /// (Ok 1, 0) ||> Result.foldBack (fun x accum -> accum + x * 2) // evaluates to 2 + /// (Ok 1, 10) ||> Result.foldBack (fun x accum -> accum + x * 2) // evaluates to 12 + /// + /// + [] + val foldBack<'T, 'Error, 'State> : + folder: ('T -> 'State -> 'State) -> result: Result<'T, 'Error> -> state: 'State -> 'State + + /// exists p inp evaluates to match inp with Error _ -> false | Ok x -> p x. + /// + /// A function that evaluates to a boolean when given a value from the result type. + /// The input result. + /// + /// False if the result is Error, otherwise it returns the result of applying the predicate + /// to the result value. + /// + /// + /// + /// Error 6 |> Result.exists (fun x -> x >= 5) // evaluates to false + /// Ok 42 |> Result.exists (fun x -> x >= 5) // evaluates to true + /// Ok 4 |> Result.exists (fun x -> x >= 5) // evaluates to false + /// + /// + [] + val exists: predicate: ('T -> bool) -> result: Result<'T, 'Error> -> bool + + /// forall p inp evaluates to match inp with Error _ -> true | Ok x -> p x. + /// + /// A function that evaluates to a boolean when given a value from the result type. + /// The input result. + /// + /// True if the result is Error, otherwise it returns the result of applying the predicate + /// to the result value. + /// + /// + /// + /// Error 1 |> Result.forall (fun x -> x >= 5) // evaluates to true + /// Ok 42 |> Result.forall (fun x -> x >= 5) // evaluates to true + /// Ok 4 |> Result.forall (fun x -> x >= 5) // evaluates to false + /// + /// + [] + val forall: predicate: ('T -> bool) -> result: Result<'T, 'Error> -> bool + + /// Evaluates to true if is Ok and its value is equal to . + /// + /// The value to test for equality. + /// The input result. + /// + /// True if the result is Ok and contains a value equal to , otherwise false. + /// + /// + /// + /// (99, Error 99) ||> Result.contains // evaluates to false + /// (99, Ok 99) ||> Result.contains // evaluates to true + /// (99, Ok 100) ||> Result.contains // evaluates to false + /// + /// + [] + val inline contains: value: 'T -> result: Result<'T, 'Error> -> bool when 'T: equality + + /// iter f inp executes match inp with Error _ -> () | Ok x -> f x. + /// + /// A function to apply to the result value. + /// The input result. + /// + /// + /// + /// Error "Hello world" |> Result.iter (printfn "%s") // does nothing + /// Ok "Hello world" |> Result.iter (printfn "%s") // prints "Hello world" + /// + /// + [] + val iter: action: ('T -> unit) -> result: Result<'T, 'Error> -> unit + + /// Convert the result to an array of length 0 or 1. + /// + /// The input result. + /// + /// The result array. + /// + /// + /// + /// Error 42 |> Result.toArray // evaluates to [||] + /// Ok 42 |> Result.toArray // evaluates to [| 42 |] + /// + /// + [] + val toArray: result: Result<'T, 'Error> -> 'T[] + + /// Convert the result to a list of length 0 or 1. + /// + /// The input result. + /// + /// The result list. + /// + /// + /// + /// Error 42 |> Result.toList // evaluates to [] + /// Ok 42 |> Result.toList // evaluates to [ 42 ] + /// + /// + [] + val toList: result: Result<'T, 'Error> -> List<'T> + + /// Convert the result to an Option value. + /// + /// The input result. + /// + /// The option value. + /// + /// + /// + /// Error 42 |> Result.toOption // evaluates to None + /// Ok 42 |> Result.toOption // evaluates to Some 42 + /// + /// + [] + val toOption: result: Result<'T, 'Error> -> Option<'T> + + /// Convert the result to an Option value. + /// + /// The input result. + /// + /// The result value. + /// + /// + /// + /// Error 42 |> Result.toOption // evaluates to ValueNone + /// Ok 42 |> Result.toOption // evaluates to ValueSome 42 + /// + /// + [] + val toValueOption: result: Result<'T, 'Error> -> ValueOption<'T> diff --git a/src/FSharp.Core/resumable.fs b/src/FSharp.Core/resumable.fs index ee762d3bf17..7e79af69aee 100644 --- a/src/FSharp.Core/resumable.fs +++ b/src/FSharp.Core/resumable.fs @@ -9,7 +9,6 @@ #nowarn "51" namespace Microsoft.FSharp.Core.CompilerServices -#if !BUILDING_WITH_LKG && !BUILD_FROM_SOURCE open System open System.Runtime.CompilerServices open Microsoft.FSharp.Core @@ -444,5 +443,3 @@ module ResumableCode = //-- RESUMABLE CODE END else YieldDynamic(&sm)) - -#endif diff --git a/src/FSharp.Core/resumable.fsi b/src/FSharp.Core/resumable.fsi index d7c82027279..3cd295f71e4 100644 --- a/src/FSharp.Core/resumable.fsi +++ b/src/FSharp.Core/resumable.fsi @@ -2,7 +2,6 @@ namespace Microsoft.FSharp.Core.CompilerServices -#if !BUILDING_WITH_LKG && !BUILD_FROM_SOURCE open Microsoft.FSharp.Collections open Microsoft.FSharp.Core open System @@ -66,7 +65,6 @@ and ResumptionFunc<'Data> = delegate of byref> -> b type ResumableCode<'Data, 'T> = delegate of byref> -> bool /// Contains functions for composing resumable code blocks -[] [] module ResumableCode = @@ -125,7 +123,6 @@ type SetStateMachineMethodImpl<'Data> = delegate of byref = delegate of byref> -> 'Result /// Contains compiler intrinsics related to the definition of state machines. -[] module StateMachineHelpers = /// @@ -231,5 +228,3 @@ type NoEagerConstraintApplicationAttribute = /// Creates an instance of the attribute /// NoEagerConstraintApplicationAttribute new : unit -> NoEagerConstraintApplicationAttribute - -#endif diff --git a/src/FSharp.Core/seq.fs b/src/FSharp.Core/seq.fs index b04ecfa3ec8..18d89ce07f7 100644 --- a/src/FSharp.Core/seq.fs +++ b/src/FSharp.Core/seq.fs @@ -214,7 +214,9 @@ module Internal = member _.Current = box (get ()) member _.MoveNext() = - if not started then started <- true + if not started then + started <- true + curr <- None while (curr.IsNone && e.MoveNext()) do @@ -244,7 +246,9 @@ module Internal = member _.MoveNext() = let rec next () = - if not started then started <- true + if not started then + started <- true + e.MoveNext() && (f e.Current || next ()) next () @@ -304,7 +308,8 @@ module Internal = current <- (Unchecked.defaultof<_>) // cache node unprimed, initialised on demand. let getCurrent () = - if index = unstarted then notStarted () + if index = unstarted then + notStarted () if index = completed then alreadyFinished () @@ -507,7 +512,8 @@ module Internal = interface System.IDisposable with member _.Dispose() = - if not finished then disposeG g + if not finished then + disposeG g // Internal type, used to optimize Enumerator/Generator chains type LazyGeneratorWrappingEnumerator<'T>(e: IEnumerator<'T>) = @@ -791,7 +797,9 @@ module Seq = while (Option.isNone res && e.MoveNext()) do let c = e.Current - if predicate c then res <- Some c + + if predicate c then + res <- Some c res @@ -1316,7 +1324,8 @@ module Seq = let hashSet = HashSet<'T>(HashIdentity.Structural<'T>) for v in source do - if hashSet.Add v then yield v + if hashSet.Add v then + yield v } [] @@ -1484,7 +1493,9 @@ module Seq = while e.MoveNext() do let curr = e.Current - if curr < acc then acc <- curr + + if curr < acc then + acc <- curr acc @@ -1522,7 +1533,9 @@ module Seq = while e.MoveNext() do let curr = e.Current - if curr > acc then acc <- curr + + if curr > acc then + acc <- curr acc @@ -1593,8 +1606,10 @@ module Seq = let mutable ok = false while e.MoveNext() do - if (latest <- e.Current - (ok || not (predicate latest))) then + if + (latest <- e.Current + (ok || not (predicate latest))) + then ok <- true yield latest } @@ -1741,11 +1756,15 @@ module Seq = if e.MoveNext() then let cached = HashSet(itemsToExclude, HashIdentity.Structural) let next = e.Current - if cached.Add next then yield next + + if cached.Add next then + yield next while e.MoveNext() do let next = e.Current - if cached.Add next then yield next + + if cached.Add next then + yield next } [] @@ -1794,7 +1813,9 @@ module Seq = let mutable i = 0 for item in source do - if i <> index then yield item + if i <> index then + yield item + i <- i + 1 if i <= index then @@ -1848,11 +1869,14 @@ module Seq = let mutable i = 0 for item in source do - if i = index then yield value + if i = index then + yield value + yield item i <- i + 1 - if i = index then yield value + if i = index then + yield value if i < index then invalidArg "index" "index must be within bounds of the array" @@ -1867,11 +1891,14 @@ module Seq = let mutable i = 0 for item in source do - if i = index then yield! values + if i = index then + yield! values + yield item i <- i + 1 - if i = index then yield! values // support inserting at the end + if i = index then + yield! values // support inserting at the end if i < index then invalidArg "index" "index must be within bounds of the array" diff --git a/src/FSharp.Core/set.fsi b/src/FSharp.Core/set.fsi index 45056191d24..b1c51c87afb 100644 --- a/src/FSharp.Core/set.fsi +++ b/src/FSharp.Core/set.fsi @@ -71,7 +71,7 @@ type Set<[] 'T when 'T: comparison> = /// /// /// let set = Set.empty.Add(1).Add(1).Add(2) - /// printfn $"The new set is: {set}" + /// printfn $"The set has {set.Count} elements" /// /// The sample evaluates to the following output: The set has 3 elements /// diff --git a/src/FSharp.Core/tasks.fs b/src/FSharp.Core/tasks.fs index a4a0e22b575..a52cae27310 100644 --- a/src/FSharp.Core/tasks.fs +++ b/src/FSharp.Core/tasks.fs @@ -13,7 +13,6 @@ namespace Microsoft.FSharp.Control -#if !BUILDING_WITH_LKG && !BUILD_FROM_SOURCE open System open System.Runtime.CompilerServices open System.Threading @@ -464,5 +463,3 @@ module MediumPriority = member inline this.ReturnFrom(computation: Async<'T>) : TaskCode<'T, 'T> = this.ReturnFrom(Async.StartAsTask computation) - -#endif diff --git a/src/FSharp.Core/tasks.fsi b/src/FSharp.Core/tasks.fsi index b32cd287316..1374895ed1f 100644 --- a/src/FSharp.Core/tasks.fsi +++ b/src/FSharp.Core/tasks.fsi @@ -4,7 +4,6 @@ namespace Microsoft.FSharp.Control - #if !BUILDING_WITH_LKG && !BUILD_FROM_SOURCE open System open System.Runtime.CompilerServices open System.Threading.Tasks @@ -286,4 +285,3 @@ namespace Microsoft.FSharp.Control.TaskBuilderExtensions task: Task<'TResult1> * continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>) -> bool -#endif diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs index 24ad0c02f38..311888a6a65 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.ProjectFile.fs @@ -13,103 +13,12 @@ type PackageReference = Script: string } -// Resolved assembly information -type internal Resolution = - { - NugetPackageId: string - NugetPackageVersion: string - PackageRoot: string - FullPath: string - AssetType: string - IsNotImplementationReference: string - InitializeSourcePath: string - NativePath: string - } - module internal ProjectFile = let fsxExt = ".fsx" let csxExt = ".csx" - let findLoadsFromResolutions (resolutions: Resolution[]) = - resolutions - |> Array.filter (fun r -> - not ( - String.IsNullOrEmpty(r.NugetPackageId) - || String.IsNullOrEmpty(r.InitializeSourcePath) - ) - && File.Exists(r.InitializeSourcePath)) - |> Array.map (fun r -> r.InitializeSourcePath) - |> Array.distinct - - let findReferencesFromResolutions (resolutions: Resolution array) = - - let equals (s1: string) (s2: string) = - String.Compare(s1, s2, StringComparison.InvariantCultureIgnoreCase) = 0 - - resolutions - |> Array.filter (fun r -> - not (String.IsNullOrEmpty(r.NugetPackageId) || String.IsNullOrEmpty(r.FullPath)) - && not (equals r.IsNotImplementationReference "true") - && File.Exists(r.FullPath) - && equals r.AssetType "runtime") - |> Array.map (fun r -> r.FullPath) - |> Array.distinct - - let findIncludesFromResolutions (resolutions: Resolution[]) = - let managedRoots = - resolutions - |> Array.filter (fun r -> - not (String.IsNullOrEmpty(r.NugetPackageId) || String.IsNullOrEmpty(r.PackageRoot)) - && Directory.Exists(r.PackageRoot)) - |> Array.map (fun r -> r.PackageRoot) - - let nativeRoots = - resolutions - |> Array.filter (fun r -> not (String.IsNullOrEmpty(r.NugetPackageId) || String.IsNullOrEmpty(r.NativePath))) - |> Array.map (fun r -> - if Directory.Exists(r.NativePath) then - Some r.NativePath - elif File.Exists(r.NativePath) then - Some(Path.GetDirectoryName(r.NativePath).Replace('\\', '/')) - else - None) - |> Array.filter (fun r -> r.IsSome) - |> Array.map (fun r -> r.Value) - - Array.concat [| managedRoots; nativeRoots |] |> Array.distinct - - let getResolutionsFromFile resolutionsFile = - - let lines = - try - File - .ReadAllText(resolutionsFile) - .Split([| '\r'; '\n' |], StringSplitOptions.None) - |> Array.filter (fun line -> not (String.IsNullOrEmpty(line))) - with _ -> - [||] - - [| - for line in lines do - let fields = line.Split(',') - - if fields.Length < 8 then - raise (InvalidOperationException(sprintf "Internal error - Invalid resolutions file format '%s'" line)) - else - { - NugetPackageId = fields[0] - NugetPackageVersion = fields[1] - PackageRoot = fields[2] - FullPath = fields[3] - AssetType = fields[4] - IsNotImplementationReference = fields[5] - InitializeSourcePath = fields[6] - NativePath = fields[7] - } - |] - let makeScriptFromReferences (references: string seq) poundRprefix = let expandReferences = references diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs index faa0c126948..8a1b526837a 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs @@ -5,6 +5,7 @@ open System open System.Diagnostics open System.IO open System.Reflection +open System.Security.Cryptography open FSDependencyManager open Internal.Utilities.FSharpEnvironment @@ -12,6 +13,19 @@ open Internal.Utilities.FSharpEnvironment type DependencyManagerAttribute() = inherit Attribute() +// Resolved assembly information +type Resolution = + { + NugetPackageId: string + NugetPackageVersion: string + PackageRoot: string + FullPath: string + AssetType: string + IsNotImplementationReference: string + InitializeSourcePath: string + NativePath: string + } + /// The result of building the package resolution files. type PackageBuildResolutionResult = { @@ -20,10 +34,93 @@ type PackageBuildResolutionResult = stdOut: string array stdErr: string array resolutionsFile: string option + resolutions: Resolution[] + references: string list + loads: string list + includes: string list } module internal Utilities = + let verifyFilesExist files = + files |> List.tryFind (fun f -> not (File.Exists(f))) |> Option.isNone + + let findLoadsFromResolutions (resolutions: Resolution[]) = + resolutions + |> Array.filter (fun r -> + not ( + String.IsNullOrEmpty(r.NugetPackageId) + || String.IsNullOrEmpty(r.InitializeSourcePath) + ) + && File.Exists(r.InitializeSourcePath)) + |> Array.map (fun r -> r.InitializeSourcePath) + |> Array.distinct + + let findReferencesFromResolutions (resolutions: Resolution array) = + let equals (s1: string) (s2: string) = + String.Compare(s1, s2, StringComparison.InvariantCultureIgnoreCase) = 0 + + resolutions + |> Array.filter (fun r -> + not (String.IsNullOrEmpty(r.NugetPackageId) || String.IsNullOrEmpty(r.FullPath)) + && not (equals r.IsNotImplementationReference "true") + && File.Exists(r.FullPath) + && equals r.AssetType "runtime") + |> Array.map (fun r -> r.FullPath) + |> Array.distinct + + let findIncludesFromResolutions (resolutions: Resolution[]) = + let managedRoots = + resolutions + |> Array.filter (fun r -> + not (String.IsNullOrEmpty(r.NugetPackageId) || String.IsNullOrEmpty(r.PackageRoot)) + && Directory.Exists(r.PackageRoot)) + |> Array.map (fun r -> r.PackageRoot) + + let nativeRoots = + resolutions + |> Array.filter (fun r -> not (String.IsNullOrEmpty(r.NugetPackageId) || String.IsNullOrEmpty(r.NativePath))) + |> Array.map (fun r -> + if Directory.Exists(r.NativePath) then + Some r.NativePath + elif File.Exists(r.NativePath) then + Some(Path.GetDirectoryName(r.NativePath).Replace('\\', '/')) + else + None) + |> Array.filter (fun r -> r.IsSome) + |> Array.map (fun r -> r.Value) + + Array.concat [| managedRoots; nativeRoots |] |> Array.distinct + + let getResolutionsFromFile resolutionsFile = + let lines = + try + File + .ReadAllText(resolutionsFile) + .Split([| '\r'; '\n' |], StringSplitOptions.None) + |> Array.filter (fun line -> not (String.IsNullOrEmpty(line))) + with _ -> + [||] + + [| + for line in lines do + let fields = line.Split(',') + + if fields.Length < 8 then + raise (InvalidOperationException(sprintf "Internal error - Invalid resolutions file format '%s'" line)) + else + { + NugetPackageId = fields[0] + NugetPackageVersion = fields[1] + PackageRoot = fields[2] + FullPath = fields[3] + AssetType = fields[4] + IsNotImplementationReference = fields[5] + InitializeSourcePath = fields[6] + NativePath = fields[7] + } + |] + /// Return a string array delimited by commas /// Note that a quoted string is not going to be mangled into pieces. let trimChars = [| ' '; '\t'; '\''; '\"' |] @@ -160,11 +257,15 @@ module internal Utilities = let outputFile = projectPath + ".resolvedReferences.paths" - let resolutionsFile = + let resolutionsFile, resolutions, references, loads, includes = if success && File.Exists(outputFile) then - Some outputFile + let resolutions = getResolutionsFromFile outputFile + let references = (findReferencesFromResolutions resolutions) |> Array.toList + let loads = (findLoadsFromResolutions resolutions) |> Array.toList + let includes = (findIncludesFromResolutions resolutions) |> Array.toList + (Some outputFile), resolutions, references, loads, includes else - None + None, [||], List.empty, List.empty, List.empty { success = success @@ -172,6 +273,10 @@ module internal Utilities = stdOut = stdOut stdErr = stdErr resolutionsFile = resolutionsFile + resolutions = resolutions + references = references + loads = loads + includes = includes } let generateSourcesFromNugetConfigs scriptDirectory workingDir timeout = @@ -198,11 +303,14 @@ module internal Utilities = seq { if success then for source in stdOut do - // String returned by dotnet nuget list source --format short - // is formatted similar to: + // String returned by `dotnet nuget list source --format short` is formatted similar to: // E https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json - // So strip off the flags - let pos = source.IndexOf(" ") + // Use enabled feeds only (see NuGet.Commands.ListSourceRunner.Run) and strip off the flags. + if source.Length > 0 && source.[0] = 'E' then + let pos = source.IndexOf(" ") - if pos >= 0 then yield ("i", source.Substring(pos).Trim()) + if pos >= 0 then + "i", source.Substring(pos).Trim() } + + let computeSha256HashOfBytes (bytes: byte[]) : byte[] = SHA256.Create().ComputeHash(bytes) diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs index e5f8cd95704..294cf2df55d 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs @@ -6,6 +6,7 @@ open System open System.Collections.Concurrent open System.Diagnostics open System.IO +open System.Text open FSharp.DependencyManager.Nuget open FSharp.DependencyManager.Nuget.Utilities open FSharp.DependencyManager.Nuget.ProjectFile @@ -197,6 +198,57 @@ module FSharpDependencyManager = |> List.distinct |> (fun l -> l, binLogPath, timeout) + let computeHashForResolutionInputs + ( + scriptExt: string, + directiveLines: (string * string) seq, + targetFrameworkMoniker: string, + runtimeIdentifier: string + ) : string option = + + let packageReferences, _, _ = + directiveLines |> List.ofSeq |> parsePackageDirective scriptExt + + 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 = _ + } = + p + + not (String.IsNullOrWhiteSpace(package)) + && (not (String.IsNullOrWhiteSpace(ver)) && ver.Contains("*")) + + packageReferences |> List.tryFind hasWildCardVersion |> Option.isSome + + if referencesHaveWildCardVersion then + // We have wildcard references so no caching can apply + None + else + let packageReferenceText = + packageReferences + |> List.map formatPackageReference + |> Seq.concat + |> Seq.distinct + |> Seq.toArray + |> Seq.sort + |> Seq.fold (fun acc s -> acc + s) "" + + let value = + $"""Tfm={targetFrameworkMoniker}:Rid={runtimeIdentifier}:PackageReferences={packageReferenceText}:Ext={match scriptExt with + | ".csx" -> csxExt + | _ -> fsxExt}""" + + Some( + computeSha256HashOfBytes (Encoding.Unicode.GetBytes(value)) + |> Array.fold (fun acc byte -> acc + $"%02x{byte}") "" + ) + /// The results of ResolveDependencies type ResolveDependenciesResult ( @@ -237,45 +289,48 @@ type ResolveDependenciesResult member _.Roots = roots [] -type FSharpDependencyManager(outputDirectory: string option) = +type FSharpDependencyManager(outputDirectory: string option, useResultsCache: bool) = let key = "nuget" let name = "MsBuild Nuget DependencyManager" let generatedScripts = ConcurrentDictionary() - let workingDirectory = + let projectDirectory, cacheDirectory = + let createDirectory directory = + lazy + try + if not (Directory.Exists(directory)) then + Directory.CreateDirectory(directory) |> ignore + + directory + with _ -> + directory + // Calculate the working directory for dependency management // if a path wasn't supplied to the dependency manager then use the temporary directory as the root // if a path was supplied if it was rooted then use the rooted path as the root // if the path wasn't supplied or not rooted use the temp directory as the root. - let directory = - let path = - Path.Combine(Process.GetCurrentProcess().Id.ToString() + "--" + Guid.NewGuid().ToString()) + let specialDir = + Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile), ".packagemanagement", "nuget") - match outputDirectory with - | None -> Path.Combine(Path.GetTempPath(), path) - | Some v -> - if Path.IsPathRooted(v) then - Path.Combine(v, path) - else - Path.Combine(Path.GetTempPath(), path) + let path = + Path.Combine(Process.GetCurrentProcess().Id.ToString() + "--" + Guid.NewGuid().ToString()) - lazy - try - if not (Directory.Exists(directory)) then - Directory.CreateDirectory(directory) |> ignore + let root = + match outputDirectory with + | Some v when Path.IsPathRooted(v) -> v + | Some v -> Path.Combine(specialDir, v) + | _ -> specialDir - directory - with _ -> - directory + createDirectory (Path.Combine(root, "Projects", path)), createDirectory (Path.Combine(root, "Cache")) let deleteScripts () = try #if !DEBUG - if workingDirectory.IsValueCreated then - if Directory.Exists(workingDirectory.Value) then - Directory.Delete(workingDirectory.Value, true) + if projectDirectory.IsValueCreated then + if Directory.Exists(projectDirectory.Value) then + Directory.Delete(projectDirectory.Value, true) #else () #endif @@ -315,7 +370,7 @@ type FSharpDependencyManager(outputDirectory: string option) = let packageReferenceText = String.Join(Environment.NewLine, packageReferenceLines) - let projectPath = Path.Combine(workingDirectory.Value, "Project.fsproj") + let projectPath = Path.Combine(projectDirectory.Value, "Project.fsproj") let generateAndBuildProjectArtifacts = let writeFile path body = @@ -339,8 +394,43 @@ type FSharpDependencyManager(outputDirectory: string option) = generateAndBuildProjectArtifacts + let tryGetResultsForResolutionHash hash (projectDirectory: Lazy) : PackageBuildResolutionResult option = + match hash with + | Some hash when useResultsCache = true -> + let resolutionsFile = + Path.Combine(cacheDirectory.Value, (hash + ".resolvedReferences.paths")) + + if File.Exists(resolutionsFile) then + let resolutions, references, loads, includes = + let resolutions = getResolutionsFromFile resolutionsFile + let references = (findReferencesFromResolutions resolutions) |> Array.toList + let loads = (findLoadsFromResolutions resolutions) |> Array.toList + let includes = (findIncludesFromResolutions resolutions) |> Array.toList + resolutions, references, loads, includes + + if verifyFilesExist (references) then + Some + { + success = true + projectPath = Path.Combine(projectDirectory.Value, "Project.fsproj") + stdOut = [||] + stdErr = [||] + resolutionsFile = Some resolutionsFile + resolutions = resolutions + references = references + loads = loads + includes = includes + } + else + None + else + None + | _ -> None + do AppDomain.CurrentDomain.ProcessExit |> Event.add (fun _ -> deleteScripts ()) + new(outputDirectory: string option) = FSharpDependencyManager(outputDirectory, true) + member _.Name = name member _.Key = key @@ -357,6 +447,10 @@ type FSharpDependencyManager(outputDirectory: string option) = (SR.highestVersion ()) |] + member _.ClearResultsCache() = + Directory.Delete(cacheDirectory.Value, true) + Directory.CreateDirectory(cacheDirectory.Value) |> ignore + member _.ResolveDependencies ( scriptDirectory: string, @@ -376,34 +470,49 @@ type FSharpDependencyManager(outputDirectory: string option) = let generateAndBuildProjectArtifacts = let configIncludes = - generateSourcesFromNugetConfigs scriptDirectory workingDirectory.Value timeout + generateSourcesFromNugetConfigs scriptDirectory projectDirectory.Value timeout let directiveLines = Seq.append packageManagerTextLines configIncludes - let resolutionResult = - prepareDependencyResolutionFiles (scriptExt, directiveLines, targetFrameworkMoniker, runtimeIdentifier, timeout) + let resolutionHash = + FSharpDependencyManager.computeHashForResolutionInputs ( + scriptExt, + directiveLines, + targetFrameworkMoniker, + runtimeIdentifier + ) + + let fromCache, resolutionResult = + match tryGetResultsForResolutionHash resolutionHash projectDirectory with + | Some resolutionResult -> true, resolutionResult + | None -> + false, prepareDependencyResolutionFiles (scriptExt, directiveLines, targetFrameworkMoniker, runtimeIdentifier, timeout) match resolutionResult.resolutionsFile with | Some file -> - let resolutions = getResolutionsFromFile file - let references = (findReferencesFromResolutions resolutions) |> Array.toSeq + let generatedScriptPath = + match resolutionHash with + | Some hash -> Path.Combine(cacheDirectory.Value, hash) + scriptExt + | None -> resolutionResult.projectPath + scriptExt + + // We have succeeded to gather information -- generate script and copy the results to the cache + if not (fromCache) then + let generatedScriptBody = + makeScriptFromReferences resolutionResult.references poundRprefix - let scripts = - let generatedScriptPath = resolutionResult.projectPath + scriptExt - let generatedScriptBody = makeScriptFromReferences references poundRprefix emitFile generatedScriptPath generatedScriptBody - let loads = (findLoadsFromResolutions resolutions) |> Array.toList - List.concat [ [ generatedScriptPath ]; loads ] |> List.toSeq - let includes = (findIncludesFromResolutions resolutions) |> Array.toSeq + match resolutionHash with + | Some hash -> File.Copy(file, Path.Combine(cacheDirectory.Value, hash + ".resolvedReferences.paths"), true) + | None -> () ResolveDependenciesResult( resolutionResult.success, resolutionResult.stdOut, resolutionResult.stdErr, - references, - scripts, - includes + resolutionResult.references, + Seq.concat [ [ generatedScriptPath ]; resolutionResult.loads ], + resolutionResult.includes ) | None -> diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fsi b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fsi index 5344b5fe6aa..56d037274af 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fsi +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fsi @@ -45,6 +45,7 @@ type ResolveDependenciesResult = [] type FSharpDependencyManager = + new: outputDirectory: string option * useResultsCache: bool -> FSharpDependencyManager new: outputDirectory: string option -> FSharpDependencyManager member Name: string @@ -53,6 +54,8 @@ type FSharpDependencyManager = member HelpMessages: string[] + member ClearResultsCache: unit -> unit + member ResolveDependencies: scriptDirectory: string * scriptName: string * diff --git a/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.csproj b/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.csproj index eaeac80f362..a16bc1310ee 100644 --- a/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.csproj +++ b/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.csproj @@ -11,6 +11,13 @@ true + + $(NuGetPackageRoot)microsoft.dotnet.arcade.sdk\$(ArcadeSdkVersion)\ + <_BuildReleasePackagesTargets>$(ArcadeSdkDir)tools\BuildReleasePackages.targets + + + + @@ -19,6 +26,36 @@ - + + + + + + + + TargetFrameworks=netstandard2.1;netstandard2.0 + + + TargetFrameworks=netstandard2.0 + + + TargetFrameworks=netstandard2.0 + + + TargetFrameworks=netstandard2.0 + + + TargetFrameworks=netstandard2.0 + + + + + + + + + diff --git a/src/Microsoft.FSharp.Compiler/Program.cs b/src/Microsoft.FSharp.Compiler/Program.cs index c52f1037882..0be8ed50b0e 100644 --- a/src/Microsoft.FSharp.Compiler/Program.cs +++ b/src/Microsoft.FSharp.Compiler/Program.cs @@ -1,2 +1,2 @@ -// See https://aka.ms/new-console-template for more information +// See https://aka.ms/new-console-template for more information return 0; \ No newline at end of file diff --git a/src/fsc/App.config b/src/fsc/App.config index 9ff4d9b9f78..eb256128200 100644 --- a/src/fsc/App.config +++ b/src/fsc/App.config @@ -1,6 +1,7 @@ + diff --git a/src/fsc/fsc.fsproj b/src/fsc/fsc.targets similarity index 58% rename from src/fsc/fsc.fsproj rename to src/fsc/fsc.targets index 4db15591cfc..9e4e4e48067 100644 --- a/src/fsc/fsc.fsproj +++ b/src/fsc/fsc.targets @@ -1,12 +1,17 @@ - + Exe - $(ProtoTargetFramework) - net472;net6.0 - net6.0 + + $(NoWarn);NU1505 + $(NoWarn);44 $(NoWarn);75 true @@ -15,25 +20,19 @@ false - - x86 - - - - fscmain.fs - - + + {{FSCoreVersion}} $(FSCoreVersion) - - - - + + + + diff --git a/src/fsc/fscAnyCpuProject/fscAnyCpu.fsproj b/src/fsc/fscAnyCpuProject/fscAnyCpu.fsproj new file mode 100644 index 00000000000..9b0de73dd99 --- /dev/null +++ b/src/fsc/fscAnyCpuProject/fscAnyCpu.fsproj @@ -0,0 +1,14 @@ + + + + + + net472 + anycpu + .exe + true + + + + + diff --git a/src/fsc/fscArm64Project/fscArm64.fsproj b/src/fsc/fscArm64Project/fscArm64.fsproj new file mode 100644 index 00000000000..d430a022213 --- /dev/null +++ b/src/fsc/fscArm64Project/fscArm64.fsproj @@ -0,0 +1,14 @@ + + + + + + net472 + arm64 + .exe + true + + + + + diff --git a/src/fsc/fscProject/fsc.fsproj b/src/fsc/fscProject/fsc.fsproj new file mode 100644 index 00000000000..03fbcd56d51 --- /dev/null +++ b/src/fsc/fscProject/fsc.fsproj @@ -0,0 +1,14 @@ + + + + + + $(ProtoTargetFramework) + net472;net6.0 + net6.0 + x86 + + + + + diff --git a/src/fsc/fscmain.fs b/src/fsc/fscmain.fs index e29f07e8b20..ebdf21af60d 100644 --- a/src/fsc/fscmain.fs +++ b/src/fsc/fscmain.fs @@ -26,8 +26,10 @@ let main (argv) = let compilerName = // the 64 bit desktop version of the compiler is name fscAnyCpu.exe, all others are fsc.exe - if Environment.Is64BitProcess - && typeof.Assembly.GetName().Name <> "System.Private.CoreLib" then + if + Environment.Is64BitProcess + && typeof.Assembly.GetName().Name <> "System.Private.CoreLib" + then "fscAnyCpu.exe" else "fsc.exe" @@ -104,7 +106,7 @@ let main (argv) = CompileFromCommandLineArguments( ctok, argv, - legacyReferenceResolver (*bannerAlreadyPrinted*) , + legacyReferenceResolver, false, ReduceMemoryFlag.No, CopyFSharpCoreFlag.Yes, diff --git a/src/fscAnyCpu/App.config b/src/fscAnyCpu/App.config deleted file mode 100644 index eb256128200..00000000000 --- a/src/fscAnyCpu/App.config +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/fscAnyCpu/Directory.Build.props b/src/fscAnyCpu/Directory.Build.props deleted file mode 100644 index 7cd41381b5d..00000000000 --- a/src/fscAnyCpu/Directory.Build.props +++ /dev/null @@ -1,9 +0,0 @@ - - - - true - - - - - diff --git a/src/fscAnyCpu/fscAnyCpu.fsproj b/src/fscAnyCpu/fscAnyCpu.fsproj deleted file mode 100644 index 1c090556a48..00000000000 --- a/src/fscAnyCpu/fscAnyCpu.fsproj +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - Exe - net472 - AnyCPU - .exe - $(NoWarn);44;45;55;62;75;1204 - true - true - true - - - - - fscmain.fs - - - {{FSCoreVersion}} - $(FSCoreVersion) - - - - - - - - - - - - - - - - - - - - - diff --git a/src/fsi/App.config b/src/fsi/App.config index 18af8b871fd..0978bc125a4 100644 --- a/src/fsi/App.config +++ b/src/fsi/App.config @@ -1,6 +1,7 @@ + diff --git a/src/fsi/console.fs b/src/fsi/console.fs index 05f242990b2..b64849394d3 100644 --- a/src/fsi/console.fs +++ b/src/fsi/console.fs @@ -247,8 +247,10 @@ type internal ReadLineConsole() = checkLeftEdge false let writeChar (c) = - if Console.CursorTop = Console.BufferHeight - 1 - && Console.CursorLeft = Console.BufferWidth - 1 then + if + Console.CursorTop = Console.BufferHeight - 1 + && Console.CursorLeft = Console.BufferWidth - 1 + then //printf "bottom right!\n" anchor <- { anchor with top = (anchor).top - 1 } @@ -278,7 +280,8 @@ type internal ReadLineConsole() = let mutable position = -1 for i = 0 to input.Length - 1 do - if (i = curr) then position <- output.Length + if (i = curr) then + position <- output.Length let c = input.Chars(i) @@ -287,7 +290,8 @@ type internal ReadLineConsole() = else output.Append(c) |> ignore - if (curr = input.Length) then position <- output.Length + if (curr = input.Length) then + position <- output.Length // render the current text, computing a new value for "rendered" let old_rendered = rendered @@ -419,7 +423,8 @@ type internal ReadLineConsole() = if (line = "\x1A") then null else - if (line.Length > 0) then history.AddLast(line) + if (line.Length > 0) then + history.AddLast(line) line diff --git a/src/fsi/fsi.fsproj b/src/fsi/fsi.targets similarity index 76% rename from src/fsi/fsi.fsproj rename to src/fsi/fsi.targets index 3deb73708db..ce90d34c3cc 100644 --- a/src/fsi/fsi.fsproj +++ b/src/fsi/fsi.targets @@ -1,30 +1,33 @@ - + - + Exe - $(ProtoTargetFramework) - net472;net6.0 - net6.0 + + $(NoWarn);NU1505 $(NoWarn);44 true $(OtherFlags) --warnon:1182 - fsi.res + $(MSBuildThisFileDirectory)fsi.res true true false - x86 $(DefineConstants);FSI_SHADOW_COPY_REFERENCES;FSI_SERVER - - - + + + {{FSCoreVersion}} $(FSCoreVersion) @@ -58,4 +61,4 @@ - + \ No newline at end of file diff --git a/src/fsi/fsiAnyCpuProject/fsiAnyCpu.fsproj b/src/fsi/fsiAnyCpuProject/fsiAnyCpu.fsproj new file mode 100644 index 00000000000..9f71fce7692 --- /dev/null +++ b/src/fsi/fsiAnyCpuProject/fsiAnyCpu.fsproj @@ -0,0 +1,15 @@ + + + + + + net472 + anycpu + .exe + true + $(DefineConstants);FSI_SHADOW_COPY_REFERENCES;FSI_SERVER + + + + + diff --git a/src/fsi/fsiArm64Project/fsiArm64.fsproj b/src/fsi/fsiArm64Project/fsiArm64.fsproj new file mode 100644 index 00000000000..4d46d947ddf --- /dev/null +++ b/src/fsi/fsiArm64Project/fsiArm64.fsproj @@ -0,0 +1,15 @@ + + + + + + net472 + arm64 + .exe + true + $(DefineConstants);FSI_SHADOW_COPY_REFERENCES;FSI_SERVER + + + + + diff --git a/src/fsi/fsiProject/fsi.fsproj b/src/fsi/fsiProject/fsi.fsproj new file mode 100644 index 00000000000..b027f97e2b9 --- /dev/null +++ b/src/fsi/fsiProject/fsi.fsproj @@ -0,0 +1,14 @@ + + + + + + $(ProtoTargetFramework) + net472;net6.0 + net6.0 + x86 + + + + + diff --git a/src/fsi/fsimain.fs b/src/fsi/fsimain.fs index b94a152c171..ae6513f00cc 100644 --- a/src/fsi/fsimain.fs +++ b/src/fsi/fsimain.fs @@ -411,8 +411,10 @@ let MainMain argv = || x = "/shadowcopyreferences+" || x = "--shadowcopyreferences+") - if AppDomain.CurrentDomain.IsDefaultAppDomain() - && argv |> Array.exists isShadowCopy then + if + AppDomain.CurrentDomain.IsDefaultAppDomain() + && argv |> Array.exists isShadowCopy + then let setupInformation = AppDomain.CurrentDomain.SetupInformation setupInformation.ShadowCopyFiles <- "true" let helper = AppDomain.CreateDomain("FSI_Domain", null, setupInformation) diff --git a/src/fsiAnyCpu/App.config b/src/fsiAnyCpu/App.config deleted file mode 100644 index 0978bc125a4..00000000000 --- a/src/fsiAnyCpu/App.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/src/fsiAnyCpu/Directory.Build.props b/src/fsiAnyCpu/Directory.Build.props deleted file mode 100644 index 7cd41381b5d..00000000000 --- a/src/fsiAnyCpu/Directory.Build.props +++ /dev/null @@ -1,9 +0,0 @@ - - - - true - - - - - diff --git a/src/fsiAnyCpu/fsiAnyCpu.fsproj b/src/fsiAnyCpu/fsiAnyCpu.fsproj deleted file mode 100644 index a4d99dbceb5..00000000000 --- a/src/fsiAnyCpu/fsiAnyCpu.fsproj +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - Exe - net472 - AnyCPU - .exe - $(NoWarn);44 - true - $(OtherFlags) --warnon:1182 - ..\fsi\fsi.res - true - true - - - - $(DefineConstants);FSI_SHADOW_COPY_REFERENCES;FSI_SERVER - - - - - - - {{FSCoreVersion}} - $(FSCoreVersion) - - - - - - - - - - - - - - - - - - - - diff --git a/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs b/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs index 9387ec6fe3b..b3953588a22 100644 --- a/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs +++ b/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs @@ -5340,7 +5340,7 @@ namespace ProviderImplementation.ProvidedTypes.AssemblyReader fst, simpleIndexCompare gpidx, isSorted ILTableNames.GenericParamConstraint, - (snd >> seekReadTypeDefOrRef numtypars AsObject (*ok*) [| |])) + (snd >> seekReadTypeDefOrRef numtypars AsObject [| |])) and seekReadTypeDefAsType boxity (ginst:ILTypes) idx = cacheTypeDefAsType seekReadTypeDefAsTypeUncached (TypeDefAsTypIdx (boxity,ginst,idx)) diff --git a/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs b/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs index ad3c87c24fc..efca9112737 100644 --- a/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs +++ b/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs @@ -48,7 +48,7 @@ type SourceRoot = /// these tests are ported from https://github.com/dotnet/roslyn/blob/093ea477717001c58be6231cf2a793f4245cbf72/src/Compilers/Core/MSBuildTaskTests/MapSourceRootTests.cs /// Same scenarios, slightly different setup/teardown -[] +[] type MapSourceRootsTests() = let assertNoErrors (t: MapSourceRoots) = diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/DelegateDefinition.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/DelegateDefinition.fs new file mode 100644 index 00000000000..df0857b3f28 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/DelegateDefinition.fs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.ComponentTests.Conformance.DelegateTypes + +open Xunit +open FSharp.Test.Compiler + +module DelegateDefinition = + + [] + let ``Delegate definition with primary constructor and argument.`` () = + FSharp + """ +namespace FSharpTest + type T(x: int) = + delegate of int -> int + """ + |> compile + |> shouldFail + |> withErrorCode 552 + |> withErrorMessage "Only class types may take value arguments" + + [] + let ``Delegate definition with primary constructor no argument.`` () = + FSharp + """ +namespace FSharpTest + type T() = + delegate of int -> int + """ + |> compile + |> shouldFail + |> withErrorCode 552 + |> withErrorMessage "Only class types may take value arguments" + + [] + let ``Delegate definition`` () = + FSharp + """ +namespace FSharpTest + type T = + delegate of int -> int + """ + |> compile + |> shouldSucceed diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/invalid_delegate_definition.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/invalid_delegate_definition.fs new file mode 100644 index 00000000000..dd55759ff61 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/invalid_delegate_definition.fs @@ -0,0 +1,5 @@ +type T(x: int) = + delegate of int -> int + +type T() = + delegate of int -> int \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/invalid_delegate_definition.fs.err.bsl b/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/invalid_delegate_definition.fs.err.bsl new file mode 100644 index 00000000000..c804d430211 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/DelegateTypes/invalid_delegate_definition.fs.err.bsl @@ -0,0 +1,3 @@ +invalid_delegate_definition.fs (1,6)-(1,15) Only class types may take value arguments +invalid_delegate_definition.fs (4,6)-(1,9) Only class types may take value arguments + diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/E_LowercaseWhenRequireQualifiedAccess.fsx b/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/E_LowercaseWhenRequireQualifiedAccess.fsx new file mode 100644 index 00000000000..a7e7a928e36 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/E_LowercaseWhenRequireQualifiedAccess.fsx @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + + + + +type DU1 = | ``not.allowed`` + +type DU2 = ``not.allowed`` + +[] +type DU3 = | ``not.allowed`` + +[] +type DU4 = ``not.allowed`` + +type DU5 = | a + +type DU6 = a + +type du1 = du1 of string + +type du2 = | du2 of string \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/LowercaseWhenRequireQualifiedAccess.fsx b/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/LowercaseWhenRequireQualifiedAccess.fsx new file mode 100644 index 00000000000..e9080c19964 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/LowercaseWhenRequireQualifiedAccess.fsx @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + + + + +[] +type DU1 = + | a + | b + | c + +[] +type DU2 = + | a of int + | B of string + | C + +[] +type DU3 = | a + +[] +type DU4 = a + +[] +type du1 = du1 of string + +[] +type du2 = | du2 of string + +let a = DU1.a +let b = du2.du2 +let c = DU2.a(1) +let d = du2.du2("du2") +let e = du1.du1("du1") + +let f du1 = + match du1 with + | DU1.a -> () + | DU1.b -> () + | DU1.c -> () + +f DU1.c + + diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/UnionTypes.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/UnionTypes.fs index 1e27322bfbd..39f4fac3804 100644 --- a/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/UnionTypes.fs +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/UnionTypes/UnionTypes.fs @@ -509,6 +509,64 @@ module UnionTypes = |> verifyCompileAndRun |> shouldSucceed + //SOURCE=LowercaseWhenRequireQualifiedAccess.fsx # LowercaseWhenRequireQualifiedAccess.fsx + [] + let ``LowercaseWhenRequireQualifiedAccess_fs in langversion 6`` compilation = + compilation + |> withLangVersion60 + |> verifyCompile + |> shouldFail + + //SOURCE=LowercaseWhenRequireQualifiedAccess.fsx # LowercaseWhenRequireQualifiedAccess.fsx + [] + let ``LowercaseWhenRequireQualifiedAccess_fs in preview`` compilation = + compilation + |> withLangVersionPreview + |> verifyCompileAndRun + |> shouldSucceed + + //SOURCE=E_LowercaseWhenRequireQualifiedAccess.fsx # E_LowercaseWhenRequireQualifiedAccess.fsx + [] + let ``E_LowercaseWhenRequireQualifiedAccess_fs in preview`` compilation = + compilation + |> withLangVersionPreview + |> verifyCompile + |> shouldFail + |> withDiagnostics [ + (Error 883, Line 6, Col 14, Line 6, Col 29, "Invalid namespace, module, type or union case name"); + (Error 53, Line 6, Col 14, Line 6, Col 29, "Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute"); + (Error 883, Line 8, Col 12, Line 8, Col 27, "Invalid namespace, module, type or union case name"); + (Error 53, Line 8, Col 12, Line 8, Col 27, "Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute"); + (Error 883, Line 11, Col 14, Line 11, Col 29, "Invalid namespace, module, type or union case name"); + (Error 883, Line 14, Col 12, Line 14, Col 27, "Invalid namespace, module, type or union case name"); + (Error 53, Line 16, Col 14, Line 16, Col 15, "Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute"); + (Error 53, Line 18, Col 12, Line 18, Col 13, "Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute"); + (Error 53, Line 20, Col 12, Line 20, Col 15, "Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute"); + (Error 53, Line 22, Col 14, Line 22, Col 17, "Lowercase discriminated union cases are only allowed when using RequireQualifiedAccess attribute") + ] + + //SOURCE=E_LowercaseWhenRequireQualifiedAccess.fsx # E_LowercaseWhenRequireQualifiedAccess.fsx + [] + let ``E_LowercaseWhenRequireQualifiedAccess_fs in langversion 6`` compilation = + compilation + |> withLangVersion60 + |> verifyCompile + |> shouldFail + |> withDiagnostics [ + (Error 883, Line 6, Col 14, Line 6, Col 29, "Invalid namespace, module, type or union case name"); + (Error 53, Line 6, Col 14, Line 6, Col 29, "Discriminated union cases and exception labels must be uppercase identifiers"); + (Error 883, Line 8, Col 12, Line 8, Col 27, "Invalid namespace, module, type or union case name"); + (Error 53, Line 8, Col 12, Line 8, Col 27, "Discriminated union cases and exception labels must be uppercase identifiers"); + (Error 883, Line 11, Col 14, Line 11, Col 29, "Invalid namespace, module, type or union case name"); + (Error 53, Line 11, Col 14, Line 11, Col 29, "Discriminated union cases and exception labels must be uppercase identifiers"); + (Error 883, Line 14, Col 12, Line 14, Col 27, "Invalid namespace, module, type or union case name"); + (Error 53, Line 14, Col 12, Line 14, Col 27, "Discriminated union cases and exception labels must be uppercase identifiers"); + (Error 53, Line 16, Col 14, Line 16, Col 15, "Discriminated union cases and exception labels must be uppercase identifiers"); + (Error 53, Line 18, Col 12, Line 18, Col 13, "Discriminated union cases and exception labels must be uppercase identifiers"); + (Error 53, Line 20, Col 12, Line 20, Col 15, "Discriminated union cases and exception labels must be uppercase identifiers"); + (Error 53, Line 22, Col 14, Line 22, Col 17, "Discriminated union cases and exception labels must be uppercase identifiers") + ] + //SOURCE=W_GenericFunctionValuedStaticProp02.fs SCFLAGS="--test:ErrorRanges --warnaserror-" # W_GenericFunctionValuedStaticProp02.fs [] let ``W_GenericFunctionValuedStaticProp02_fs`` compilation = diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare01.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare01.fsx.il.bsl index 810ce530eb7..6f2e871ca38 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare01.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare01.fsx.il.bsl @@ -28,22 +28,22 @@ } .mresource public FSharpSignatureData.Compare01 { - // Offset: 0x00000000 Length: 0x00000258 + // Offset: 0x00000000 Length: 0x00000248 // WARNING: managed resource file FSharpSignatureData.Compare01 created } .mresource public FSharpOptimizationData.Compare01 { - // Offset: 0x00000260 Length: 0x000000B2 + // Offset: 0x00000250 Length: 0x000000B2 // WARNING: managed resource file FSharpOptimizationData.Compare01 created } .module Compare01.exe -// MVID: {624F9D3B-7932-7F19-A745-03833B9D4F62} +// MVID: {629EFC18-7932-7F19-A745-038318FC9E62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03860000 +// Image base: 0x006A0000 // =============== CLASS MEMBERS DECLARATION =================== @@ -58,42 +58,29 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static void f4() cil managed { - // Code size 36 (0x24) + // Code size 23 (0x17) .maxstack 4 .locals init (int32 V_0, - int32 V_1, - int32 V_2) + int32 V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: nop IL_0003: nop IL_0004: ldc.i4.0 IL_0005: stloc.1 - IL_0006: br.s IL_001b - - IL_0008: ldc.i4.1 - IL_0009: ldc.i4.1 - IL_000a: cgt - IL_000c: stloc.2 - IL_000d: ldloc.2 - IL_000e: brfalse.s IL_0014 - - IL_0010: ldloc.2 - IL_0011: nop - IL_0012: br.s IL_0016 - - IL_0014: ldc.i4.m1 - IL_0015: nop - IL_0016: stloc.0 - IL_0017: ldloc.1 - IL_0018: ldc.i4.1 - IL_0019: add - IL_001a: stloc.1 - IL_001b: ldloc.1 - IL_001c: ldc.i4 0x989681 - IL_0021: blt.s IL_0008 - - IL_0023: ret + IL_0006: br.s IL_000e + + IL_0008: ldc.i4.m1 + IL_0009: stloc.0 + IL_000a: ldloc.1 + IL_000b: ldc.i4.1 + IL_000c: add + IL_000d: stloc.1 + IL_000e: ldloc.1 + IL_000f: ldc.i4 0x989681 + IL_0014: blt.s IL_0008 + + IL_0016: ret } // end of method CompareMicroPerfAndCodeGenerationTests::f4 } // end of class CompareMicroPerfAndCodeGenerationTests @@ -117,4 +104,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare01_fsx\Compare01.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare01_fsx\Compare01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare02.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare02.fsx.il.bsl index 6cfb4dc6a92..1389e074b5b 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare02.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare02.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,91 +21,66 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Compare02 { - // Offset: 0x00000000 Length: 0x0000025F + // Offset: 0x00000000 Length: 0x0000024F // WARNING: managed resource file FSharpSignatureData.Compare02 created } .mresource public FSharpOptimizationData.Compare02 { - // Offset: 0x00000268 Length: 0x000000B9 + // Offset: 0x00000258 Length: 0x000000B9 // WARNING: managed resource file FSharpOptimizationData.Compare02 created } .module Compare02.exe -// MVID: {624F9D3B-7915-7F19-A745-03833B9D4F62} +// MVID: {629F023F-DFF8-1315-A745-03833F029F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03E40000 +// Image base: 0x00000285F4090000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Compare02 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public CompareMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static void f4_triple() cil managed { - // Code size 48 (0x30) + // Code size 23 (0x17) .maxstack 4 .locals init (int32 V_0, - int32 V_1, - int32 V_2, - int32 V_3) + int32 V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: nop IL_0003: nop IL_0004: ldc.i4.0 IL_0005: stloc.1 - IL_0006: br.s IL_0027 - - IL_0008: ldc.i4.1 - IL_0009: ldc.i4.1 - IL_000a: cgt - IL_000c: stloc.2 - IL_000d: ldloc.2 - IL_000e: brfalse.s IL_0014 - - IL_0010: ldloc.2 - IL_0011: nop - IL_0012: br.s IL_0022 - - IL_0014: ldc.i4.2 - IL_0015: ldc.i4.2 - IL_0016: cgt - IL_0018: stloc.3 - IL_0019: ldloc.3 - IL_001a: brfalse.s IL_0020 - - IL_001c: ldloc.3 - IL_001d: nop - IL_001e: br.s IL_0022 - - IL_0020: ldc.i4.m1 - IL_0021: nop - IL_0022: stloc.0 - IL_0023: ldloc.1 - IL_0024: ldc.i4.1 - IL_0025: add - IL_0026: stloc.1 - IL_0027: ldloc.1 - IL_0028: ldc.i4 0x989681 - IL_002d: blt.s IL_0008 - - IL_002f: ret + IL_0006: br.s IL_000e + + IL_0008: ldc.i4.m1 + IL_0009: stloc.0 + IL_000a: ldloc.1 + IL_000b: ldc.i4.1 + IL_000c: add + IL_000d: stloc.1 + IL_000e: ldloc.1 + IL_000f: ldc.i4 0x989681 + IL_0014: blt.s IL_0008 + + IL_0016: ret } // end of method CompareMicroPerfAndCodeGenerationTests::f4_triple } // end of class CompareMicroPerfAndCodeGenerationTests @@ -113,7 +88,7 @@ } // end of class Compare02 .class private abstract auto ansi sealed ''.$Compare02$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -129,4 +104,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare02_fsx\Compare02.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Compare02_fsx\Compare02.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.net472.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.net472.bsl index cc3ed8aeffb..207653403ea 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.net472.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.net472.bsl @@ -33,22 +33,22 @@ } .mresource public FSharpSignatureData.Compare03 { - // Offset: 0x00000000 Length: 0x0000026A + // Offset: 0x00000000 Length: 0x0000025A // WARNING: managed resource file FSharpSignatureData.Compare03 created } .mresource public FSharpOptimizationData.Compare03 { - // Offset: 0x00000270 Length: 0x000000B9 + // Offset: 0x00000260 Length: 0x000000B9 // WARNING: managed resource file FSharpOptimizationData.Compare03 created } .module Compare03.exe -// MVID: {624F9E44-79F4-7F19-A745-0383449E4F62} +// MVID: {629F0A77-79F4-7F19-A745-0383770A9F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03180000 +// Image base: 0x03150000 // =============== CLASS MEMBERS DECLARATION =================== @@ -63,70 +63,33 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 f4_tuple4() cil managed { - // Code size 78 (0x4e) + // Code size 38 (0x26) .maxstack 4 .locals init (int32 V_0, - int32 V_1, - int32 V_2, - int32 V_3, - int32 V_4) + int32 V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: nop IL_0003: nop IL_0004: ldc.i4.0 IL_0005: stloc.1 - IL_0006: br.s IL_0044 - - IL_0008: ldc.i4.1 - IL_0009: ldc.i4.1 - IL_000a: cgt - IL_000c: stloc.2 - IL_000d: ldloc.2 - IL_000e: brfalse.s IL_0014 - - IL_0010: ldloc.2 - IL_0011: nop - IL_0012: br.s IL_003f - - IL_0014: ldc.i4.2 - IL_0015: ldc.i4.2 - IL_0016: cgt - IL_0018: stloc.3 - IL_0019: ldloc.3 - IL_001a: brfalse.s IL_0020 - - IL_001c: ldloc.3 - IL_001d: nop - IL_001e: br.s IL_003f - - IL_0020: ldc.i4.4 - IL_0021: ldc.i4.4 - IL_0022: cgt - IL_0024: stloc.s V_4 - IL_0026: ldloc.s V_4 - IL_0028: brfalse.s IL_002f - - IL_002a: ldloc.s V_4 - IL_002c: nop - IL_002d: br.s IL_003f - - IL_002f: ldstr "five" - IL_0034: ldstr "5" - IL_0039: call int32 [netstandard]System.String::CompareOrdinal(string, + IL_0006: br.s IL_001c + + IL_0008: ldstr "five" + IL_000d: ldstr "5" + IL_0012: call int32 [netstandard]System.String::CompareOrdinal(string, string) - IL_003e: nop - IL_003f: stloc.0 - IL_0040: ldloc.1 - IL_0041: ldc.i4.1 - IL_0042: add - IL_0043: stloc.1 - IL_0044: ldloc.1 - IL_0045: ldc.i4 0x989681 - IL_004a: blt.s IL_0008 - - IL_004c: ldloc.0 - IL_004d: ret + IL_0017: stloc.0 + IL_0018: ldloc.1 + IL_0019: ldc.i4.1 + IL_001a: add + IL_001b: stloc.1 + IL_001c: ldloc.1 + IL_001d: ldc.i4 0x989681 + IL_0022: blt.s IL_0008 + + IL_0024: ldloc.0 + IL_0025: ret } // end of method CompareMicroPerfAndCodeGenerationTests::f4_tuple4 } // end of class CompareMicroPerfAndCodeGenerationTests @@ -150,4 +113,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare03_fsx\Compare03.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare03_fsx\Compare03.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.netcore.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.netcore.bsl index ddbde9afeb9..6a102e3cdeb 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.netcore.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare03.fsx.il.netcore.bsl @@ -33,22 +33,22 @@ } .mresource public FSharpSignatureData.Compare03 { - // Offset: 0x00000000 Length: 0x0000026A + // Offset: 0x00000000 Length: 0x0000025A // WARNING: managed resource file FSharpSignatureData.Compare03 created } .mresource public FSharpOptimizationData.Compare03 { - // Offset: 0x00000270 Length: 0x000000B9 + // Offset: 0x00000260 Length: 0x000000B9 // WARNING: managed resource file FSharpOptimizationData.Compare03 created } .module Compare03.exe -// MVID: {624F9DB5-C542-34BD-A745-0383B59D4F62} +// MVID: {629F023F-32CA-B31A-A745-03833F029F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x000001540B310000 +// Image base: 0x000002145FFA0000 // =============== CLASS MEMBERS DECLARATION =================== @@ -63,70 +63,33 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 f4_tuple4() cil managed { - // Code size 78 (0x4e) + // Code size 38 (0x26) .maxstack 4 .locals init (int32 V_0, - int32 V_1, - int32 V_2, - int32 V_3, - int32 V_4) + int32 V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: nop IL_0003: nop IL_0004: ldc.i4.0 IL_0005: stloc.1 - IL_0006: br.s IL_0044 - - IL_0008: ldc.i4.1 - IL_0009: ldc.i4.1 - IL_000a: cgt - IL_000c: stloc.2 - IL_000d: ldloc.2 - IL_000e: brfalse.s IL_0014 - - IL_0010: ldloc.2 - IL_0011: nop - IL_0012: br.s IL_003f - - IL_0014: ldc.i4.2 - IL_0015: ldc.i4.2 - IL_0016: cgt - IL_0018: stloc.3 - IL_0019: ldloc.3 - IL_001a: brfalse.s IL_0020 - - IL_001c: ldloc.3 - IL_001d: nop - IL_001e: br.s IL_003f - - IL_0020: ldc.i4.4 - IL_0021: ldc.i4.4 - IL_0022: cgt - IL_0024: stloc.s V_4 - IL_0026: ldloc.s V_4 - IL_0028: brfalse.s IL_002f - - IL_002a: ldloc.s V_4 - IL_002c: nop - IL_002d: br.s IL_003f - - IL_002f: ldstr "five" - IL_0034: ldstr "5" - IL_0039: call int32 [netstandard]System.String::CompareOrdinal(string, + IL_0006: br.s IL_001c + + IL_0008: ldstr "five" + IL_000d: ldstr "5" + IL_0012: call int32 [netstandard]System.String::CompareOrdinal(string, string) - IL_003e: nop - IL_003f: stloc.0 - IL_0040: ldloc.1 - IL_0041: ldc.i4.1 - IL_0042: add - IL_0043: stloc.1 - IL_0044: ldloc.1 - IL_0045: ldc.i4 0x989681 - IL_004a: blt.s IL_0008 - - IL_004c: ldloc.0 - IL_004d: ret + IL_0017: stloc.0 + IL_0018: ldloc.1 + IL_0019: ldc.i4.1 + IL_001a: add + IL_001b: stloc.1 + IL_001c: ldloc.1 + IL_001d: ldc.i4 0x989681 + IL_0022: blt.s IL_0008 + + IL_0024: ldloc.0 + IL_0025: ret } // end of method CompareMicroPerfAndCodeGenerationTests::f4_tuple4 } // end of class CompareMicroPerfAndCodeGenerationTests @@ -150,4 +113,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Compare03_fsx\Compare03.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Compare03_fsx\Compare03.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.net472.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.net472.bsl index a2b428d42d0..e7e3c876c00 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.net472.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.net472.bsl @@ -33,22 +33,22 @@ } .mresource public FSharpSignatureData.Compare04 { - // Offset: 0x00000000 Length: 0x0000026E + // Offset: 0x00000000 Length: 0x0000025A // WARNING: managed resource file FSharpSignatureData.Compare04 created } .mresource public FSharpOptimizationData.Compare04 { - // Offset: 0x00000278 Length: 0x000000B9 + // Offset: 0x00000260 Length: 0x000000B9 // WARNING: managed resource file FSharpOptimizationData.Compare04 created } .module Compare04.exe -// MVID: {624FC1D8-79CF-7F19-A745-0383D8C14F62} +// MVID: {629F0A77-79CF-7F19-A745-0383770A9F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03B30000 +// Image base: 0x029E0000 // =============== CLASS MEMBERS DECLARATION =================== @@ -63,112 +63,76 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 f4_tuple5() cil managed { - // Code size 210 (0xd2) + // Code size 159 (0x9f) .maxstack 5 .locals init (int32 V_0, int32 V_1, - int32 V_2, - int32 V_3, - int32 V_4, - int32 V_5) + int32 V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: nop IL_0003: nop IL_0004: ldc.i4.0 IL_0005: stloc.1 - IL_0006: br IL_00c5 - - IL_000b: ldc.i4.1 - IL_000c: ldc.i4.1 - IL_000d: cgt - IL_000f: stloc.2 - IL_0010: ldloc.2 - IL_0011: brfalse.s IL_001a - - IL_0013: ldloc.2 - IL_0014: nop - IL_0015: br IL_00c0 - - IL_001a: ldc.i4.2 - IL_001b: ldc.i4.2 - IL_001c: cgt - IL_001e: stloc.3 - IL_001f: ldloc.3 - IL_0020: brfalse.s IL_0029 - - IL_0022: ldloc.3 - IL_0023: nop - IL_0024: br IL_00c0 - - IL_0029: ldc.i4.4 - IL_002a: ldc.i4.4 - IL_002b: cgt - IL_002d: stloc.s V_4 - IL_002f: ldloc.s V_4 - IL_0031: brfalse.s IL_003b - - IL_0033: ldloc.s V_4 - IL_0035: nop - IL_0036: br IL_00c0 - - IL_003b: ldstr "5" - IL_0040: ldstr "5" - IL_0045: call int32 [netstandard]System.String::CompareOrdinal(string, + IL_0006: br IL_0092 + + IL_000b: ldstr "5" + IL_0010: ldstr "5" + IL_0015: call int32 [netstandard]System.String::CompareOrdinal(string, string) - IL_004a: stloc.s V_5 - IL_004c: ldloc.s V_5 - IL_004e: brfalse.s IL_0055 - - IL_0050: ldloc.s V_5 - IL_0052: nop - IL_0053: br.s IL_00c0 - - IL_0055: ldc.r8 6.0999999999999996 - IL_005e: ldc.r8 7.0999999999999996 - IL_0067: clt - IL_0069: brfalse.s IL_006f - - IL_006b: ldc.i4.m1 - IL_006c: nop - IL_006d: br.s IL_00c0 - - IL_006f: ldc.r8 6.0999999999999996 - IL_0078: ldc.r8 7.0999999999999996 - IL_0081: cgt - IL_0083: brfalse.s IL_0089 - - IL_0085: ldc.i4.1 - IL_0086: nop - IL_0087: br.s IL_00c0 - - IL_0089: ldc.r8 6.0999999999999996 - IL_0092: ldc.r8 7.0999999999999996 - IL_009b: ceq - IL_009d: brfalse.s IL_00a3 - - IL_009f: ldc.i4.0 - IL_00a0: nop - IL_00a1: br.s IL_00c0 - - IL_00a3: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_00a8: ldc.r8 6.0999999999999996 - IL_00b1: ldc.r8 7.0999999999999996 - IL_00ba: call int32 [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericComparisonWithComparerIntrinsic(class [mscorlib]System.Collections.IComparer, + IL_001a: stloc.2 + IL_001b: ldloc.2 + IL_001c: brfalse.s IL_0022 + + IL_001e: ldloc.2 + IL_001f: nop + IL_0020: br.s IL_008d + + IL_0022: ldc.r8 6.0999999999999996 + IL_002b: ldc.r8 7.0999999999999996 + IL_0034: clt + IL_0036: brfalse.s IL_003c + + IL_0038: ldc.i4.m1 + IL_0039: nop + IL_003a: br.s IL_008d + + IL_003c: ldc.r8 6.0999999999999996 + IL_0045: ldc.r8 7.0999999999999996 + IL_004e: cgt + IL_0050: brfalse.s IL_0056 + + IL_0052: ldc.i4.1 + IL_0053: nop + IL_0054: br.s IL_008d + + IL_0056: ldc.r8 6.0999999999999996 + IL_005f: ldc.r8 7.0999999999999996 + IL_0068: ceq + IL_006a: brfalse.s IL_0070 + + IL_006c: ldc.i4.0 + IL_006d: nop + IL_006e: br.s IL_008d + + IL_0070: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0075: ldc.r8 6.0999999999999996 + IL_007e: ldc.r8 7.0999999999999996 + IL_0087: call int32 [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericComparisonWithComparerIntrinsic(class [mscorlib]System.Collections.IComparer, !!0, !!0) - IL_00bf: nop - IL_00c0: stloc.0 - IL_00c1: ldloc.1 - IL_00c2: ldc.i4.1 - IL_00c3: add - IL_00c4: stloc.1 - IL_00c5: ldloc.1 - IL_00c6: ldc.i4 0x989681 - IL_00cb: blt IL_000b - - IL_00d0: ldloc.0 - IL_00d1: ret + IL_008c: nop + IL_008d: stloc.0 + IL_008e: ldloc.1 + IL_008f: ldc.i4.1 + IL_0090: add + IL_0091: stloc.1 + IL_0092: ldloc.1 + IL_0093: ldc.i4 0x989681 + IL_0098: blt IL_000b + + IL_009d: ldloc.0 + IL_009e: ret } // end of method CompareMicroPerfAndCodeGenerationTests::f4_tuple5 } // end of class CompareMicroPerfAndCodeGenerationTests @@ -192,4 +156,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\GenericComparison\Compare04_fsx\Compare04.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare04_fsx\Compare04.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.netcore.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.netcore.bsl index 8f3b478c26b..ce923e6340e 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.netcore.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare04.fsx.il.netcore.bsl @@ -33,22 +33,22 @@ } .mresource public FSharpSignatureData.Compare04 { - // Offset: 0x00000000 Length: 0x0000026E + // Offset: 0x00000000 Length: 0x0000025A // WARNING: managed resource file FSharpSignatureData.Compare04 created } .mresource public FSharpOptimizationData.Compare04 { - // Offset: 0x00000278 Length: 0x000000B9 + // Offset: 0x00000260 Length: 0x000000B9 // WARNING: managed resource file FSharpOptimizationData.Compare04 created } .module Compare04.exe -// MVID: {624FC26D-B3E3-57E7-A745-03836DC24F62} +// MVID: {629F023F-7AE0-AE2A-A745-03833F029F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x000001F437780000 +// Image base: 0x000001BE779D0000 // =============== CLASS MEMBERS DECLARATION =================== @@ -63,112 +63,76 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 f4_tuple5() cil managed { - // Code size 210 (0xd2) + // Code size 159 (0x9f) .maxstack 5 .locals init (int32 V_0, int32 V_1, - int32 V_2, - int32 V_3, - int32 V_4, - int32 V_5) + int32 V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: nop IL_0003: nop IL_0004: ldc.i4.0 IL_0005: stloc.1 - IL_0006: br IL_00c5 - - IL_000b: ldc.i4.1 - IL_000c: ldc.i4.1 - IL_000d: cgt - IL_000f: stloc.2 - IL_0010: ldloc.2 - IL_0011: brfalse.s IL_001a - - IL_0013: ldloc.2 - IL_0014: nop - IL_0015: br IL_00c0 - - IL_001a: ldc.i4.2 - IL_001b: ldc.i4.2 - IL_001c: cgt - IL_001e: stloc.3 - IL_001f: ldloc.3 - IL_0020: brfalse.s IL_0029 - - IL_0022: ldloc.3 - IL_0023: nop - IL_0024: br IL_00c0 - - IL_0029: ldc.i4.4 - IL_002a: ldc.i4.4 - IL_002b: cgt - IL_002d: stloc.s V_4 - IL_002f: ldloc.s V_4 - IL_0031: brfalse.s IL_003b - - IL_0033: ldloc.s V_4 - IL_0035: nop - IL_0036: br IL_00c0 - - IL_003b: ldstr "5" - IL_0040: ldstr "5" - IL_0045: call int32 [netstandard]System.String::CompareOrdinal(string, + IL_0006: br IL_0092 + + IL_000b: ldstr "5" + IL_0010: ldstr "5" + IL_0015: call int32 [netstandard]System.String::CompareOrdinal(string, string) - IL_004a: stloc.s V_5 - IL_004c: ldloc.s V_5 - IL_004e: brfalse.s IL_0055 - - IL_0050: ldloc.s V_5 - IL_0052: nop - IL_0053: br.s IL_00c0 - - IL_0055: ldc.r8 6.0999999999999996 - IL_005e: ldc.r8 7.0999999999999996 - IL_0067: clt - IL_0069: brfalse.s IL_006f - - IL_006b: ldc.i4.m1 - IL_006c: nop - IL_006d: br.s IL_00c0 - - IL_006f: ldc.r8 6.0999999999999996 - IL_0078: ldc.r8 7.0999999999999996 - IL_0081: cgt - IL_0083: brfalse.s IL_0089 - - IL_0085: ldc.i4.1 - IL_0086: nop - IL_0087: br.s IL_00c0 - - IL_0089: ldc.r8 6.0999999999999996 - IL_0092: ldc.r8 7.0999999999999996 - IL_009b: ceq - IL_009d: brfalse.s IL_00a3 - - IL_009f: ldc.i4.0 - IL_00a0: nop - IL_00a1: br.s IL_00c0 - - IL_00a3: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_00a8: ldc.r8 6.0999999999999996 - IL_00b1: ldc.r8 7.0999999999999996 - IL_00ba: call int32 [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericComparisonWithComparerIntrinsic(class [System.Runtime]System.Collections.IComparer, + IL_001a: stloc.2 + IL_001b: ldloc.2 + IL_001c: brfalse.s IL_0022 + + IL_001e: ldloc.2 + IL_001f: nop + IL_0020: br.s IL_008d + + IL_0022: ldc.r8 6.0999999999999996 + IL_002b: ldc.r8 7.0999999999999996 + IL_0034: clt + IL_0036: brfalse.s IL_003c + + IL_0038: ldc.i4.m1 + IL_0039: nop + IL_003a: br.s IL_008d + + IL_003c: ldc.r8 6.0999999999999996 + IL_0045: ldc.r8 7.0999999999999996 + IL_004e: cgt + IL_0050: brfalse.s IL_0056 + + IL_0052: ldc.i4.1 + IL_0053: nop + IL_0054: br.s IL_008d + + IL_0056: ldc.r8 6.0999999999999996 + IL_005f: ldc.r8 7.0999999999999996 + IL_0068: ceq + IL_006a: brfalse.s IL_0070 + + IL_006c: ldc.i4.0 + IL_006d: nop + IL_006e: br.s IL_008d + + IL_0070: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0075: ldc.r8 6.0999999999999996 + IL_007e: ldc.r8 7.0999999999999996 + IL_0087: call int32 [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericComparisonWithComparerIntrinsic(class [System.Runtime]System.Collections.IComparer, !!0, !!0) - IL_00bf: nop - IL_00c0: stloc.0 - IL_00c1: ldloc.1 - IL_00c2: ldc.i4.1 - IL_00c3: add - IL_00c4: stloc.1 - IL_00c5: ldloc.1 - IL_00c6: ldc.i4 0x989681 - IL_00cb: blt IL_000b - - IL_00d0: ldloc.0 - IL_00d1: ret + IL_008c: nop + IL_008d: stloc.0 + IL_008e: ldloc.1 + IL_008f: ldc.i4.1 + IL_0090: add + IL_0091: stloc.1 + IL_0092: ldloc.1 + IL_0093: ldc.i4 0x989681 + IL_0098: blt IL_000b + + IL_009d: ldloc.0 + IL_009e: ret } // end of method CompareMicroPerfAndCodeGenerationTests::f4_tuple5 } // end of class CompareMicroPerfAndCodeGenerationTests @@ -192,4 +156,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\GenericComparison\Compare04_fsx\Compare04.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Compare04_fsx\Compare04.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare05.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare05.fsx.il.bsl index eb2f59b56de..7f3f99eda4e 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare05.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare05.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Compare05 { - // Offset: 0x00000000 Length: 0x00000713 + // Offset: 0x00000000 Length: 0x00000709 // WARNING: managed resource file FSharpSignatureData.Compare05 created } .mresource public FSharpOptimizationData.Compare05 { - // Offset: 0x00000718 Length: 0x000003BA + // Offset: 0x00000710 Length: 0x000003C6 // WARNING: managed resource file FSharpOptimizationData.Compare05 created } .module Compare05.exe -// MVID: {624F9D3B-79AE-7F19-A745-03833B9D4F62} +// MVID: {628F4C90-6B90-06FF-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x00E80000 +// Image base: 0x0000023405D00000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Compare05 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public CompareMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Key - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Compare05/CompareMicroPerfAndCodeGenerationTests/Key NewKey(int32 item1, int32 item2) cil managed @@ -94,12 +94,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item1 @@ -112,8 +112,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -124,8 +124,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,8 +136,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -149,8 +149,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -164,7 +164,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -178,20 +178,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Compare05/CompareMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 110 (0x6e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 105 (0x69) + .maxstack 5 .locals init (class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_0, class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0067 + IL_0001: brfalse.s IL_0062 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0065 + IL_0004: brfalse.s IL_0060 IL_0006: ldarg.0 IL_0007: pop @@ -199,7 +199,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item1 @@ -209,68 +209,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.3 - IL_0046: ldloc.0 - IL_0047: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.1 - IL_004f: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: brfalse.s IL_006c + IL_003b: ret - IL_006a: ldc.i4.m1 - IL_006b: ret + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.3 + IL_0042: ldloc.0 + IL_0043: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.1 + IL_004b: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: brfalse.s IL_0067 + + IL_0065: ldc.i4.m1 + IL_0066: ret - IL_006c: ldc.i4.0 - IL_006d: ret + IL_0067: ldc.i4.0 + IL_0068: ret } // end of method Key::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -282,11 +274,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 115 (0x73) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 110 (0x6e) + .maxstack 5 .locals init (class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_0, class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_1, class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_2, @@ -297,11 +289,11 @@ IL_0001: unbox.any Compare05/CompareMicroPerfAndCodeGenerationTests/Key IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0067 + IL_0008: brfalse.s IL_0062 IL_000a: ldarg.1 IL_000b: unbox.any Compare05/CompareMicroPerfAndCodeGenerationTests/Key - IL_0010: brfalse.s IL_0065 + IL_0010: brfalse.s IL_0060 IL_0012: ldarg.0 IL_0013: pop @@ -317,67 +309,59 @@ IL_0026: stloc.s V_5 IL_0028: ldloc.s V_4 IL_002a: ldloc.s V_5 - IL_002c: bge.s IL_0032 - - IL_002e: ldc.i4.m1 - IL_002f: nop - IL_0030: br.s IL_0039 + IL_002c: cgt + IL_002e: ldloc.s V_4 + IL_0030: ldloc.s V_5 + IL_0032: clt + IL_0034: sub + IL_0035: stloc.3 + IL_0036: ldloc.3 + IL_0037: ldc.i4.0 + IL_0038: bge.s IL_003c - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: nop - IL_0039: stloc.3 IL_003a: ldloc.3 - IL_003b: ldc.i4.0 - IL_003c: bge.s IL_0040 + IL_003b: ret - IL_003e: ldloc.3 - IL_003f: ret + IL_003c: ldloc.3 + IL_003d: ldc.i4.0 + IL_003e: ble.s IL_0042 IL_0040: ldloc.3 - IL_0041: ldc.i4.0 - IL_0042: ble.s IL_0046 - - IL_0044: ldloc.3 - IL_0045: ret - - IL_0046: ldloc.1 - IL_0047: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.2 - IL_004f: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: unbox.any Compare05/CompareMicroPerfAndCodeGenerationTests/Key - IL_006d: brfalse.s IL_0071 + IL_0041: ret + + IL_0042: ldloc.1 + IL_0043: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.2 + IL_004b: ldfld int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: unbox.any Compare05/CompareMicroPerfAndCodeGenerationTests/Key + IL_0068: brfalse.s IL_006c - IL_006f: ldc.i4.m1 - IL_0070: ret + IL_006a: ldc.i4.m1 + IL_006b: ret - IL_0071: ldc.i4.0 - IL_0072: ret + IL_006c: ldc.i4.0 + IL_006d: ret } // end of method Key::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 57 (0x39) .maxstack 7 .locals init (int32 V_0, @@ -429,20 +413,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Key::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 60 (0x3c) .maxstack 4 .locals init (class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_0, @@ -493,7 +477,7 @@ .method public hidebysig virtual final instance bool Equals(class Compare05/CompareMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_0, @@ -540,7 +524,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Compare05/CompareMicroPerfAndCodeGenerationTests/Key V_0) @@ -561,9 +545,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::get_Tag() } // end of property Key::Tag .property instance int32 Item1() @@ -571,8 +555,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::get_Item1() } // end of property Key::Item1 .property instance int32 Item2() @@ -580,8 +564,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Compare05/CompareMicroPerfAndCodeGenerationTests/Key::get_Item2() } // end of property Key::Item2 } // end of class Key @@ -631,7 +615,7 @@ } // end of class Compare05 .class private abstract auto ansi sealed ''.$Compare05$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -647,4 +631,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare05_fsx\Compare05.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Compare05_fsx\Compare05.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare06.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare06.fsx.il.bsl index 1de6ccd40fd..30f333f36c8 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare06.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare06.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,54 +21,54 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Compare06 { - // Offset: 0x00000000 Length: 0x00000706 + // Offset: 0x00000000 Length: 0x000006FC // WARNING: managed resource file FSharpSignatureData.Compare06 created } .mresource public FSharpOptimizationData.Compare06 { - // Offset: 0x00000710 Length: 0x000003BC + // Offset: 0x00000700 Length: 0x000003C8 // WARNING: managed resource file FSharpOptimizationData.Compare06 created } .module Compare06.exe -// MVID: {624F9D3B-7991-7F19-A745-03833B9D4F62} +// MVID: {628F4C90-FEB0-939C-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03080000 +// Image base: 0x000001E44D5F0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Compare06 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public CompareMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto ansi serializable sealed nested public KeyR - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 02 00 00 00 00 00 ) .field assembly int32 key1@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field assembly int32 key2@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance int32 get_key1() cil managed { @@ -96,7 +96,7 @@ // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -109,7 +109,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -123,20 +123,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 92 (0x5c) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 87 (0x57) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0055 + IL_0001: brfalse.s IL_0050 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0053 + IL_0004: brfalse.s IL_004e - IL_0006: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0006: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_000b: stloc.1 IL_000c: ldarg.0 IL_000d: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -146,68 +146,60 @@ IL_0019: stloc.3 IL_001a: ldloc.2 IL_001b: ldloc.3 - IL_001c: bge.s IL_0022 - - IL_001e: ldc.i4.m1 - IL_001f: nop - IL_0020: br.s IL_0027 + IL_001c: cgt + IL_001e: ldloc.2 + IL_001f: ldloc.3 + IL_0020: clt + IL_0022: sub + IL_0023: stloc.0 + IL_0024: ldloc.0 + IL_0025: ldc.i4.0 + IL_0026: bge.s IL_002a - IL_0022: ldloc.2 - IL_0023: ldloc.3 - IL_0024: cgt - IL_0026: nop - IL_0027: stloc.0 IL_0028: ldloc.0 - IL_0029: ldc.i4.0 - IL_002a: bge.s IL_002e + IL_0029: ret - IL_002c: ldloc.0 - IL_002d: ret + IL_002a: ldloc.0 + IL_002b: ldc.i4.0 + IL_002c: ble.s IL_0030 IL_002e: ldloc.0 - IL_002f: ldc.i4.0 - IL_0030: ble.s IL_0034 - - IL_0032: ldloc.0 - IL_0033: ret - - IL_0034: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0039: stloc.1 - IL_003a: ldarg.0 - IL_003b: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0040: stloc.2 - IL_0041: ldarg.1 - IL_0042: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0047: stloc.3 + IL_002f: ret + + IL_0030: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0035: stloc.1 + IL_0036: ldarg.0 + IL_0037: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_003c: stloc.2 + IL_003d: ldarg.1 + IL_003e: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_0043: stloc.3 + IL_0044: ldloc.2 + IL_0045: ldloc.3 + IL_0046: cgt IL_0048: ldloc.2 IL_0049: ldloc.3 - IL_004a: bge.s IL_004e - - IL_004c: ldc.i4.m1 + IL_004a: clt + IL_004c: sub IL_004d: ret - IL_004e: ldloc.2 - IL_004f: ldloc.3 - IL_0050: cgt - IL_0052: ret - - IL_0053: ldc.i4.1 - IL_0054: ret + IL_004e: ldc.i4.1 + IL_004f: ret - IL_0055: ldarg.1 - IL_0056: brfalse.s IL_005a + IL_0050: ldarg.1 + IL_0051: brfalse.s IL_0055 - IL_0058: ldc.i4.m1 - IL_0059: ret + IL_0053: ldc.i4.m1 + IL_0054: ret - IL_005a: ldc.i4.0 - IL_005b: ret + IL_0055: ldc.i4.0 + IL_0056: ret } // end of method KeyR::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -219,11 +211,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 97 (0x61) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 92 (0x5c) + .maxstack 5 .locals init (class Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR V_0, int32 V_1, int32 V_2, @@ -232,11 +224,11 @@ IL_0001: unbox.any Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0055 + IL_0008: brfalse.s IL_0050 IL_000a: ldarg.1 IL_000b: unbox.any Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR - IL_0010: brfalse.s IL_0053 + IL_0010: brfalse.s IL_004e IL_0012: ldarg.0 IL_0013: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -246,67 +238,59 @@ IL_001f: stloc.3 IL_0020: ldloc.2 IL_0021: ldloc.3 - IL_0022: bge.s IL_0028 - - IL_0024: ldc.i4.m1 - IL_0025: nop - IL_0026: br.s IL_002d + IL_0022: cgt + IL_0024: ldloc.2 + IL_0025: ldloc.3 + IL_0026: clt + IL_0028: sub + IL_0029: stloc.1 + IL_002a: ldloc.1 + IL_002b: ldc.i4.0 + IL_002c: bge.s IL_0030 - IL_0028: ldloc.2 - IL_0029: ldloc.3 - IL_002a: cgt - IL_002c: nop - IL_002d: stloc.1 IL_002e: ldloc.1 - IL_002f: ldc.i4.0 - IL_0030: bge.s IL_0034 + IL_002f: ret - IL_0032: ldloc.1 - IL_0033: ret + IL_0030: ldloc.1 + IL_0031: ldc.i4.0 + IL_0032: ble.s IL_0036 IL_0034: ldloc.1 - IL_0035: ldc.i4.0 - IL_0036: ble.s IL_003a - - IL_0038: ldloc.1 - IL_0039: ret - - IL_003a: ldarg.0 - IL_003b: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0040: stloc.2 - IL_0041: ldloc.0 - IL_0042: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0047: stloc.3 + IL_0035: ret + + IL_0036: ldarg.0 + IL_0037: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_003c: stloc.2 + IL_003d: ldloc.0 + IL_003e: ldfld int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_0043: stloc.3 + IL_0044: ldloc.2 + IL_0045: ldloc.3 + IL_0046: cgt IL_0048: ldloc.2 IL_0049: ldloc.3 - IL_004a: bge.s IL_004e - - IL_004c: ldc.i4.m1 + IL_004a: clt + IL_004c: sub IL_004d: ret - IL_004e: ldloc.2 - IL_004f: ldloc.3 - IL_0050: cgt - IL_0052: ret - - IL_0053: ldc.i4.1 - IL_0054: ret + IL_004e: ldc.i4.1 + IL_004f: ret - IL_0055: ldarg.1 - IL_0056: unbox.any Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR - IL_005b: brfalse.s IL_005f + IL_0050: ldarg.1 + IL_0051: unbox.any Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR + IL_0056: brfalse.s IL_005a - IL_005d: ldc.i4.m1 - IL_005e: ret + IL_0058: ldc.i4.m1 + IL_0059: ret - IL_005f: ldc.i4.0 - IL_0060: ret + IL_005a: ldc.i4.0 + IL_005b: ret } // end of method KeyR::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 51 (0x33) .maxstack 7 .locals init (int32 V_0) @@ -351,20 +335,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method KeyR::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 54 (0x36) .maxstack 4 .locals init (class Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR V_0) @@ -407,7 +391,7 @@ .method public hidebysig virtual final instance bool Equals(class Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 47 (0x2f) .maxstack 8 IL_0000: ldarg.0 @@ -446,7 +430,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Compare06/CompareMicroPerfAndCodeGenerationTests/KeyR V_0) @@ -523,7 +507,7 @@ } // end of class Compare06 .class private abstract auto ansi sealed ''.$Compare06$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -539,4 +523,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare06_fsx\Compare06.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Compare06_fsx\Compare06.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare10.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare10.fsx.il.bsl index 8acdd8d684b..4029fde7bb9 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare10.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Compare10.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Compare10 { - // Offset: 0x00000000 Length: 0x00000ACB + // Offset: 0x00000000 Length: 0x00000AC1 // WARNING: managed resource file FSharpSignatureData.Compare10 created } .mresource public FSharpOptimizationData.Compare10 { - // Offset: 0x00000AD0 Length: 0x0000058E + // Offset: 0x00000AC8 Length: 0x0000059A // WARNING: managed resource file FSharpOptimizationData.Compare10 created } .module Compare10.exe -// MVID: {624F9D3B-7953-9DDE-A745-03833B9D4F62} +// MVID: {628F4C90-2093-2BBE-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x04DD0000 +// Image base: 0x00000206CE490000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Compare10 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public CompareMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Key - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Compare10/CompareMicroPerfAndCodeGenerationTests/Key NewKey(int32 item1, int32 item2) cil managed @@ -94,12 +94,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item1 @@ -112,8 +112,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -124,8 +124,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,8 +136,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -149,8 +149,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -164,7 +164,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -178,20 +178,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Compare10/CompareMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 110 (0x6e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 105 (0x69) + .maxstack 5 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_0, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0067 + IL_0001: brfalse.s IL_0062 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0065 + IL_0004: brfalse.s IL_0060 IL_0006: ldarg.0 IL_0007: pop @@ -199,7 +199,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item1 @@ -209,68 +209,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.3 - IL_0046: ldloc.0 - IL_0047: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.1 - IL_004f: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret + IL_003b: ret - IL_0065: ldc.i4.1 + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.3 + IL_0042: ldloc.0 + IL_0043: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.1 + IL_004b: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: brfalse.s IL_0067 + + IL_0065: ldc.i4.m1 IL_0066: ret - IL_0067: ldarg.1 - IL_0068: brfalse.s IL_006c - - IL_006a: ldc.i4.m1 - IL_006b: ret - - IL_006c: ldc.i4.0 - IL_006d: ret + IL_0067: ldc.i4.0 + IL_0068: ret } // end of method Key::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -282,11 +274,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 115 (0x73) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 110 (0x6e) + .maxstack 5 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_0, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_1, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_2, @@ -297,11 +289,11 @@ IL_0001: unbox.any Compare10/CompareMicroPerfAndCodeGenerationTests/Key IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0067 + IL_0008: brfalse.s IL_0062 IL_000a: ldarg.1 IL_000b: unbox.any Compare10/CompareMicroPerfAndCodeGenerationTests/Key - IL_0010: brfalse.s IL_0065 + IL_0010: brfalse.s IL_0060 IL_0012: ldarg.0 IL_0013: pop @@ -317,67 +309,59 @@ IL_0026: stloc.s V_5 IL_0028: ldloc.s V_4 IL_002a: ldloc.s V_5 - IL_002c: bge.s IL_0032 - - IL_002e: ldc.i4.m1 - IL_002f: nop - IL_0030: br.s IL_0039 + IL_002c: cgt + IL_002e: ldloc.s V_4 + IL_0030: ldloc.s V_5 + IL_0032: clt + IL_0034: sub + IL_0035: stloc.3 + IL_0036: ldloc.3 + IL_0037: ldc.i4.0 + IL_0038: bge.s IL_003c - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: nop - IL_0039: stloc.3 IL_003a: ldloc.3 - IL_003b: ldc.i4.0 - IL_003c: bge.s IL_0040 + IL_003b: ret - IL_003e: ldloc.3 - IL_003f: ret + IL_003c: ldloc.3 + IL_003d: ldc.i4.0 + IL_003e: ble.s IL_0042 IL_0040: ldloc.3 - IL_0041: ldc.i4.0 - IL_0042: ble.s IL_0046 - - IL_0044: ldloc.3 - IL_0045: ret - - IL_0046: ldloc.1 - IL_0047: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.2 - IL_004f: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: unbox.any Compare10/CompareMicroPerfAndCodeGenerationTests/Key - IL_006d: brfalse.s IL_0071 + IL_0041: ret + + IL_0042: ldloc.1 + IL_0043: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.2 + IL_004b: ldfld int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: unbox.any Compare10/CompareMicroPerfAndCodeGenerationTests/Key + IL_0068: brfalse.s IL_006c - IL_006f: ldc.i4.m1 - IL_0070: ret + IL_006a: ldc.i4.m1 + IL_006b: ret - IL_0071: ldc.i4.0 - IL_0072: ret + IL_006c: ldc.i4.0 + IL_006d: ret } // end of method Key::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 57 (0x39) .maxstack 7 .locals init (int32 V_0, @@ -429,20 +413,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Key::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 60 (0x3c) .maxstack 4 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_0, @@ -493,7 +477,7 @@ .method public hidebysig virtual final instance bool Equals(class Compare10/CompareMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_0, @@ -540,7 +524,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_0) @@ -561,9 +545,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::get_Tag() } // end of property Key::Tag .property instance int32 Item1() @@ -571,8 +555,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::get_Item1() } // end of property Key::Item1 .property instance int32 Item2() @@ -580,34 +564,34 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::get_Item2() } // end of property Key::Item2 } // end of class Key .class auto autochar serializable sealed nested public beforefieldinit KeyWithInnerKeys - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly class Compare10/CompareMicroPerfAndCodeGenerationTests/Key item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .field assembly initonly class [mscorlib]System.Tuple`2 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .field assembly initonly class [System.Runtime]System.Tuple`2 item2 + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys NewKeyWithInnerKeys(class Compare10/CompareMicroPerfAndCodeGenerationTests/Key item1, - class [mscorlib]System.Tuple`2 item2) cil managed + class [System.Runtime]System.Tuple`2 item2) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32) = ( 01 00 08 00 00 00 00 00 00 00 00 00 ) @@ -616,34 +600,34 @@ IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj instance void Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::.ctor(class Compare10/CompareMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0007: ret } // end of method KeyWithInnerKeys::NewKeyWithInnerKeys .method assembly specialname rtspecialname instance void .ctor(class Compare10/CompareMicroPerfAndCodeGenerationTests/Key item1, - class [mscorlib]System.Tuple`2 item2) cil managed + class [System.Runtime]System.Tuple`2 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Compare10/CompareMicroPerfAndCodeGenerationTests/Key Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 IL_000d: ldarg.0 IL_000e: ldarg.2 - IL_000f: stfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_000f: stfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0014: ret } // end of method KeyWithInnerKeys::.ctor .method public hidebysig instance class Compare10/CompareMicroPerfAndCodeGenerationTests/Key get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -651,23 +635,23 @@ IL_0006: ret } // end of method KeyWithInnerKeys::get_Item1 - .method public hidebysig instance class [mscorlib]System.Tuple`2 + .method public hidebysig instance class [System.Runtime]System.Tuple`2 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0001: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0006: ret } // end of method KeyWithInnerKeys::get_Item2 .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -679,8 +663,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -694,7 +678,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -708,17 +692,17 @@ .method public hidebysig virtual final instance int32 CompareTo(class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 160 (0xa0) .maxstack 5 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_4, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_5, - class [mscorlib]System.Tuple`2 V_6, - class [mscorlib]System.Tuple`2 V_7, + class [System.Runtime]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_7, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_8, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_9, int32 V_10) @@ -734,7 +718,7 @@ IL_000f: stloc.0 IL_0010: ldarg.1 IL_0011: stloc.1 - IL_0012: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0012: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0017: stloc.3 IL_0018: ldloc.0 IL_0019: ldfld class Compare10/CompareMicroPerfAndCodeGenerationTests/Key Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 @@ -746,7 +730,7 @@ IL_002a: ldloc.s V_5 IL_002c: ldloc.3 IL_002d: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0032: stloc.2 IL_0033: ldloc.2 IL_0034: ldc.i4.0 @@ -762,31 +746,31 @@ IL_003d: ldloc.2 IL_003e: ret - IL_003f: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_003f: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0044: stloc.3 IL_0045: ldloc.0 - IL_0046: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0046: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_004b: stloc.s V_6 IL_004d: ldloc.1 - IL_004e: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_004e: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0053: stloc.s V_7 IL_0055: ldloc.s V_6 - IL_0057: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0057: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_005c: stloc.s V_4 IL_005e: ldloc.s V_6 - IL_0060: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0060: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0065: stloc.s V_5 IL_0067: ldloc.s V_7 - IL_0069: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0069: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_006e: stloc.s V_8 IL_0070: ldloc.s V_7 - IL_0072: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0072: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0077: stloc.s V_9 IL_0079: ldloc.s V_4 IL_007b: ldloc.s V_8 IL_007d: ldloc.3 IL_007e: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0083: stloc.s V_10 IL_0085: ldloc.s V_10 IL_0087: brfalse.s IL_008c @@ -798,7 +782,7 @@ IL_008e: ldloc.s V_9 IL_0090: ldloc.3 IL_0091: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0096: ret IL_0097: ldc.i4.1 @@ -817,7 +801,7 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -829,9 +813,9 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 165 (0xa5) .maxstack 5 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -840,8 +824,8 @@ int32 V_3, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_4, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_5, - class [mscorlib]System.Tuple`2 V_6, - class [mscorlib]System.Tuple`2 V_7, + class [System.Runtime]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_7, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_8, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_9, int32 V_10) @@ -871,7 +855,7 @@ IL_0030: ldloc.s V_5 IL_0032: ldarg.2 IL_0033: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0038: stloc.3 IL_0039: ldloc.3 IL_003a: ldc.i4.0 @@ -888,28 +872,28 @@ IL_0044: ret IL_0045: ldloc.1 - IL_0046: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0046: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_004b: stloc.s V_6 IL_004d: ldloc.2 - IL_004e: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_004e: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0053: stloc.s V_7 IL_0055: ldloc.s V_6 - IL_0057: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0057: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_005c: stloc.s V_4 IL_005e: ldloc.s V_6 - IL_0060: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0060: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0065: stloc.s V_5 IL_0067: ldloc.s V_7 - IL_0069: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0069: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_006e: stloc.s V_8 IL_0070: ldloc.s V_7 - IL_0072: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0072: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0077: stloc.s V_9 IL_0079: ldloc.s V_4 IL_007b: ldloc.s V_8 IL_007d: ldarg.2 IL_007e: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0083: stloc.s V_10 IL_0085: ldloc.s V_10 IL_0087: brfalse.s IL_008c @@ -921,7 +905,7 @@ IL_008e: ldloc.s V_9 IL_0090: ldarg.2 IL_0091: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0096: ret IL_0097: ldc.i4.1 @@ -939,14 +923,14 @@ } // end of method KeyWithInnerKeys::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 104 (0x68) .maxstack 7 .locals init (int32 V_0, class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_1, - class [mscorlib]System.Tuple`2 V_2, + class [System.Runtime]System.Tuple`2 V_2, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_3, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_4, int32 V_5) @@ -963,17 +947,17 @@ IL_000a: stloc.0 IL_000b: ldc.i4 0x9e3779b9 IL_0010: ldloc.1 - IL_0011: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0011: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0016: stloc.2 IL_0017: ldloc.2 - IL_0018: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0018: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_001d: stloc.3 IL_001e: ldloc.2 - IL_001f: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_001f: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0024: stloc.s V_4 IL_0026: ldloc.3 IL_0027: ldarg.1 - IL_0028: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0028: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_002d: stloc.s V_5 IL_002f: ldloc.s V_5 IL_0031: ldc.i4.5 @@ -982,7 +966,7 @@ IL_0035: add IL_0036: ldloc.s V_4 IL_0038: ldarg.1 - IL_0039: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0039: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_003e: xor IL_003f: ldloc.0 IL_0040: ldc.i4.6 @@ -998,7 +982,7 @@ IL_004e: ldloc.1 IL_004f: ldfld class Compare10/CompareMicroPerfAndCodeGenerationTests/Key Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 IL_0054: ldarg.1 - IL_0055: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0055: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_005a: ldloc.0 IL_005b: ldc.i4.6 IL_005c: shl @@ -1019,20 +1003,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method KeyWithInnerKeys::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 135 (0x87) .maxstack 5 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -1040,8 +1024,8 @@ class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_2, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_3, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_4, - class [mscorlib]System.Tuple`2 V_5, - class [mscorlib]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_5, + class [System.Runtime]System.Tuple`2 V_6, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_7, class Compare10/CompareMicroPerfAndCodeGenerationTests/Key V_8) IL_0000: ldarg.0 @@ -1069,39 +1053,39 @@ IL_0026: ldloc.s V_4 IL_0028: ldarg.2 IL_0029: callvirt instance bool Compare10/CompareMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_002e: brfalse.s IL_007b IL_0030: ldloc.1 - IL_0031: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0031: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0036: stloc.s V_5 IL_0038: ldloc.2 - IL_0039: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0039: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_003e: stloc.s V_6 IL_0040: ldloc.s V_5 - IL_0042: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0042: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_0047: stloc.3 IL_0048: ldloc.s V_5 - IL_004a: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_004a: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_004f: stloc.s V_4 IL_0051: ldloc.s V_6 - IL_0053: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0053: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_0058: stloc.s V_7 IL_005a: ldloc.s V_6 - IL_005c: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_005c: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0061: stloc.s V_8 IL_0063: ldloc.3 IL_0064: ldloc.s V_7 IL_0066: ldarg.2 IL_0067: callvirt instance bool Compare10/CompareMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_006c: brfalse.s IL_0079 IL_006e: ldloc.s V_4 IL_0070: ldloc.s V_8 IL_0072: ldarg.2 IL_0073: callvirt instance bool Compare10/CompareMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_0078: ret IL_0079: ldc.i4.0 @@ -1124,7 +1108,7 @@ .method public hidebysig virtual final instance bool Equals(class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 63 (0x3f) .maxstack 4 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -1149,12 +1133,12 @@ IL_001d: brfalse.s IL_0033 IL_001f: ldloc.0 - IL_0020: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0020: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0025: ldloc.1 - IL_0026: ldfld class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0026: ldfld class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_002b: tail. - IL_002d: call bool [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericEqualityERIntrinsic>(!!0, - !!0) + IL_002d: call bool [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericEqualityERIntrinsic>(!!0, + !!0) IL_0032: ret IL_0033: ldc.i4.0 @@ -1174,7 +1158,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 4 .locals init (class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0) @@ -1196,9 +1180,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Tag() } // end of property KeyWithInnerKeys::Tag .property instance class Compare10/CompareMicroPerfAndCodeGenerationTests/Key @@ -1207,19 +1191,19 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance class Compare10/CompareMicroPerfAndCodeGenerationTests/Key Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item1() } // end of property KeyWithInnerKeys::Item1 - .property instance class [mscorlib]System.Tuple`2 + .property instance class [System.Runtime]System.Tuple`2 Item2() { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .get instance class [mscorlib]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item2() + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .get instance class [System.Runtime]System.Tuple`2 Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item2() } // end of property KeyWithInnerKeys::Item2 } // end of class KeyWithInnerKeys @@ -1245,10 +1229,10 @@ IL_0011: ldc.i4.2 IL_0012: call class Compare10/CompareMicroPerfAndCodeGenerationTests/Key Compare10/CompareMicroPerfAndCodeGenerationTests/Key::NewKey(int32, int32) - IL_0017: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_0017: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_001c: call class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::NewKeyWithInnerKeys(class Compare10/CompareMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0021: stloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 @@ -1262,10 +1246,10 @@ IL_0031: ldc.i4.3 IL_0032: call class Compare10/CompareMicroPerfAndCodeGenerationTests/Key Compare10/CompareMicroPerfAndCodeGenerationTests/Key::NewKey(int32, int32) - IL_0037: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_0037: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_003c: call class Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys Compare10/CompareMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::NewKeyWithInnerKeys(class Compare10/CompareMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0041: stloc.2 IL_0042: ldc.i4.0 IL_0043: stloc.3 @@ -1291,7 +1275,7 @@ } // end of class Compare10 .class private abstract auto ansi sealed ''.$Compare10$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -1307,4 +1291,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Compare10_fsx\Compare10.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Compare10_fsx\Compare10.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals04.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals04.fsx.il.bsl index d35456fbd2d..f8409177e22 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals04.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals04.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Equals04 { - // Offset: 0x00000000 Length: 0x0000070E + // Offset: 0x00000000 Length: 0x00000704 // WARNING: managed resource file FSharpSignatureData.Equals04 created } .mresource public FSharpOptimizationData.Equals04 { - // Offset: 0x00000718 Length: 0x000003B7 + // Offset: 0x00000708 Length: 0x000003C3 // WARNING: managed resource file FSharpOptimizationData.Equals04 created } .module Equals04.exe -// MVID: {624F9D3B-EB3D-4EE8-A745-03833B9D4F62} +// MVID: {628F4C90-417C-5CA8-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x00E10000 +// Image base: 0x000002876A530000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Equals04 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public EqualsMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Key - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key NewKey(int32 item1, int32 item2) cil managed @@ -94,12 +94,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item1 @@ -112,8 +112,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -124,8 +124,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,8 +136,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -149,8 +149,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -164,7 +164,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -178,20 +178,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 110 (0x6e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 105 (0x69) + .maxstack 5 .locals init (class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_0, class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0067 + IL_0001: brfalse.s IL_0062 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0065 + IL_0004: brfalse.s IL_0060 IL_0006: ldarg.0 IL_0007: pop @@ -199,7 +199,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item1 @@ -209,68 +209,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.3 - IL_0046: ldloc.0 - IL_0047: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.1 - IL_004f: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: brfalse.s IL_006c + IL_003b: ret - IL_006a: ldc.i4.m1 - IL_006b: ret + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.3 + IL_0042: ldloc.0 + IL_0043: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.1 + IL_004b: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: brfalse.s IL_0067 + + IL_0065: ldc.i4.m1 + IL_0066: ret - IL_006c: ldc.i4.0 - IL_006d: ret + IL_0067: ldc.i4.0 + IL_0068: ret } // end of method Key::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -282,11 +274,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 115 (0x73) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 110 (0x6e) + .maxstack 5 .locals init (class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_0, class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_1, class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_2, @@ -297,11 +289,11 @@ IL_0001: unbox.any Equals04/EqualsMicroPerfAndCodeGenerationTests/Key IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0067 + IL_0008: brfalse.s IL_0062 IL_000a: ldarg.1 IL_000b: unbox.any Equals04/EqualsMicroPerfAndCodeGenerationTests/Key - IL_0010: brfalse.s IL_0065 + IL_0010: brfalse.s IL_0060 IL_0012: ldarg.0 IL_0013: pop @@ -317,67 +309,59 @@ IL_0026: stloc.s V_5 IL_0028: ldloc.s V_4 IL_002a: ldloc.s V_5 - IL_002c: bge.s IL_0032 - - IL_002e: ldc.i4.m1 - IL_002f: nop - IL_0030: br.s IL_0039 + IL_002c: cgt + IL_002e: ldloc.s V_4 + IL_0030: ldloc.s V_5 + IL_0032: clt + IL_0034: sub + IL_0035: stloc.3 + IL_0036: ldloc.3 + IL_0037: ldc.i4.0 + IL_0038: bge.s IL_003c - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: nop - IL_0039: stloc.3 IL_003a: ldloc.3 - IL_003b: ldc.i4.0 - IL_003c: bge.s IL_0040 + IL_003b: ret - IL_003e: ldloc.3 - IL_003f: ret + IL_003c: ldloc.3 + IL_003d: ldc.i4.0 + IL_003e: ble.s IL_0042 IL_0040: ldloc.3 - IL_0041: ldc.i4.0 - IL_0042: ble.s IL_0046 - - IL_0044: ldloc.3 - IL_0045: ret - - IL_0046: ldloc.1 - IL_0047: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.2 - IL_004f: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: unbox.any Equals04/EqualsMicroPerfAndCodeGenerationTests/Key - IL_006d: brfalse.s IL_0071 + IL_0041: ret + + IL_0042: ldloc.1 + IL_0043: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.2 + IL_004b: ldfld int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: unbox.any Equals04/EqualsMicroPerfAndCodeGenerationTests/Key + IL_0068: brfalse.s IL_006c - IL_006f: ldc.i4.m1 - IL_0070: ret + IL_006a: ldc.i4.m1 + IL_006b: ret - IL_0071: ldc.i4.0 - IL_0072: ret + IL_006c: ldc.i4.0 + IL_006d: ret } // end of method Key::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 57 (0x39) .maxstack 7 .locals init (int32 V_0, @@ -429,20 +413,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Key::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 60 (0x3c) .maxstack 4 .locals init (class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_0, @@ -493,7 +477,7 @@ .method public hidebysig virtual final instance bool Equals(class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_0, @@ -540,7 +524,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Equals04/EqualsMicroPerfAndCodeGenerationTests/Key V_0) @@ -561,9 +545,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::get_Tag() } // end of property Key::Tag .property instance int32 Item1() @@ -571,8 +555,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::get_Item1() } // end of property Key::Item1 .property instance int32 Item2() @@ -580,8 +564,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::get_Item2() } // end of property Key::Item2 } // end of class Key @@ -612,9 +596,9 @@ IL_0016: ldloc.1 IL_0017: ldloc.2 - IL_0018: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0018: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() IL_001d: callvirt instance bool Equals04/EqualsMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_0022: stloc.0 IL_0023: ldloc.3 IL_0024: ldc.i4.1 @@ -633,7 +617,7 @@ } // end of class Equals04 .class private abstract auto ansi sealed ''.$Equals04$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -649,4 +633,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Equals04_fsx\Equals04.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Equals04_fsx\Equals04.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals05.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals05.fsx.il.bsl index a47fd919542..78d4df8f587 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals05.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals05.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,54 +21,54 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Equals05 { - // Offset: 0x00000000 Length: 0x00000701 + // Offset: 0x00000000 Length: 0x000006F7 // WARNING: managed resource file FSharpSignatureData.Equals05 created } .mresource public FSharpOptimizationData.Equals05 { - // Offset: 0x00000708 Length: 0x000003B9 + // Offset: 0x00000700 Length: 0x000003C5 // WARNING: managed resource file FSharpOptimizationData.Equals05 created } .module Equals05.exe -// MVID: {624F9D3B-EB3D-46ED-A745-03833B9D4F62} +// MVID: {628F4C90-28FA-85D1-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03C00000 +// Image base: 0x000001B974410000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Equals05 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public EqualsMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto ansi serializable sealed nested public KeyR - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 02 00 00 00 00 00 ) .field assembly int32 key1@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field assembly int32 key2@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance int32 get_key1() cil managed { @@ -96,7 +96,7 @@ // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -109,7 +109,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -123,20 +123,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 92 (0x5c) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 87 (0x57) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0055 + IL_0001: brfalse.s IL_0050 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0053 + IL_0004: brfalse.s IL_004e - IL_0006: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0006: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_000b: stloc.1 IL_000c: ldarg.0 IL_000d: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -146,68 +146,60 @@ IL_0019: stloc.3 IL_001a: ldloc.2 IL_001b: ldloc.3 - IL_001c: bge.s IL_0022 - - IL_001e: ldc.i4.m1 - IL_001f: nop - IL_0020: br.s IL_0027 + IL_001c: cgt + IL_001e: ldloc.2 + IL_001f: ldloc.3 + IL_0020: clt + IL_0022: sub + IL_0023: stloc.0 + IL_0024: ldloc.0 + IL_0025: ldc.i4.0 + IL_0026: bge.s IL_002a - IL_0022: ldloc.2 - IL_0023: ldloc.3 - IL_0024: cgt - IL_0026: nop - IL_0027: stloc.0 IL_0028: ldloc.0 - IL_0029: ldc.i4.0 - IL_002a: bge.s IL_002e + IL_0029: ret - IL_002c: ldloc.0 - IL_002d: ret + IL_002a: ldloc.0 + IL_002b: ldc.i4.0 + IL_002c: ble.s IL_0030 IL_002e: ldloc.0 - IL_002f: ldc.i4.0 - IL_0030: ble.s IL_0034 - - IL_0032: ldloc.0 - IL_0033: ret - - IL_0034: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0039: stloc.1 - IL_003a: ldarg.0 - IL_003b: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0040: stloc.2 - IL_0041: ldarg.1 - IL_0042: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0047: stloc.3 + IL_002f: ret + + IL_0030: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0035: stloc.1 + IL_0036: ldarg.0 + IL_0037: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_003c: stloc.2 + IL_003d: ldarg.1 + IL_003e: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_0043: stloc.3 + IL_0044: ldloc.2 + IL_0045: ldloc.3 + IL_0046: cgt IL_0048: ldloc.2 IL_0049: ldloc.3 - IL_004a: bge.s IL_004e - - IL_004c: ldc.i4.m1 + IL_004a: clt + IL_004c: sub IL_004d: ret - IL_004e: ldloc.2 - IL_004f: ldloc.3 - IL_0050: cgt - IL_0052: ret - - IL_0053: ldc.i4.1 - IL_0054: ret + IL_004e: ldc.i4.1 + IL_004f: ret - IL_0055: ldarg.1 - IL_0056: brfalse.s IL_005a + IL_0050: ldarg.1 + IL_0051: brfalse.s IL_0055 - IL_0058: ldc.i4.m1 - IL_0059: ret + IL_0053: ldc.i4.m1 + IL_0054: ret - IL_005a: ldc.i4.0 - IL_005b: ret + IL_0055: ldc.i4.0 + IL_0056: ret } // end of method KeyR::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -219,11 +211,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 97 (0x61) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 92 (0x5c) + .maxstack 5 .locals init (class Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR V_0, int32 V_1, int32 V_2, @@ -232,11 +224,11 @@ IL_0001: unbox.any Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0055 + IL_0008: brfalse.s IL_0050 IL_000a: ldarg.1 IL_000b: unbox.any Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR - IL_0010: brfalse.s IL_0053 + IL_0010: brfalse.s IL_004e IL_0012: ldarg.0 IL_0013: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -246,67 +238,59 @@ IL_001f: stloc.3 IL_0020: ldloc.2 IL_0021: ldloc.3 - IL_0022: bge.s IL_0028 - - IL_0024: ldc.i4.m1 - IL_0025: nop - IL_0026: br.s IL_002d + IL_0022: cgt + IL_0024: ldloc.2 + IL_0025: ldloc.3 + IL_0026: clt + IL_0028: sub + IL_0029: stloc.1 + IL_002a: ldloc.1 + IL_002b: ldc.i4.0 + IL_002c: bge.s IL_0030 - IL_0028: ldloc.2 - IL_0029: ldloc.3 - IL_002a: cgt - IL_002c: nop - IL_002d: stloc.1 IL_002e: ldloc.1 - IL_002f: ldc.i4.0 - IL_0030: bge.s IL_0034 + IL_002f: ret - IL_0032: ldloc.1 - IL_0033: ret + IL_0030: ldloc.1 + IL_0031: ldc.i4.0 + IL_0032: ble.s IL_0036 IL_0034: ldloc.1 - IL_0035: ldc.i4.0 - IL_0036: ble.s IL_003a - - IL_0038: ldloc.1 - IL_0039: ret - - IL_003a: ldarg.0 - IL_003b: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0040: stloc.2 - IL_0041: ldloc.0 - IL_0042: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0047: stloc.3 + IL_0035: ret + + IL_0036: ldarg.0 + IL_0037: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_003c: stloc.2 + IL_003d: ldloc.0 + IL_003e: ldfld int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_0043: stloc.3 + IL_0044: ldloc.2 + IL_0045: ldloc.3 + IL_0046: cgt IL_0048: ldloc.2 IL_0049: ldloc.3 - IL_004a: bge.s IL_004e - - IL_004c: ldc.i4.m1 + IL_004a: clt + IL_004c: sub IL_004d: ret - IL_004e: ldloc.2 - IL_004f: ldloc.3 - IL_0050: cgt - IL_0052: ret - - IL_0053: ldc.i4.1 - IL_0054: ret + IL_004e: ldc.i4.1 + IL_004f: ret - IL_0055: ldarg.1 - IL_0056: unbox.any Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR - IL_005b: brfalse.s IL_005f + IL_0050: ldarg.1 + IL_0051: unbox.any Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR + IL_0056: brfalse.s IL_005a - IL_005d: ldc.i4.m1 - IL_005e: ret + IL_0058: ldc.i4.m1 + IL_0059: ret - IL_005f: ldc.i4.0 - IL_0060: ret + IL_005a: ldc.i4.0 + IL_005b: ret } // end of method KeyR::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 51 (0x33) .maxstack 7 .locals init (int32 V_0) @@ -351,20 +335,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method KeyR::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 54 (0x36) .maxstack 4 .locals init (class Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR V_0) @@ -407,7 +391,7 @@ .method public hidebysig virtual final instance bool Equals(class Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 47 (0x2f) .maxstack 8 IL_0000: ldarg.0 @@ -446,7 +430,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR V_0) @@ -505,9 +489,9 @@ IL_0016: ldloc.1 IL_0017: ldloc.2 - IL_0018: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0018: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() IL_001d: callvirt instance bool Equals05/EqualsMicroPerfAndCodeGenerationTests/KeyR::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_0022: stloc.0 IL_0023: ldloc.3 IL_0024: ldc.i4.1 @@ -525,7 +509,7 @@ } // end of class Equals05 .class private abstract auto ansi sealed ''.$Equals05$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -541,4 +525,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Equals05_fsx\Equals05.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Equals05_fsx\Equals05.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals09.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals09.fsx.il.bsl index 7dc05e76024..a1e2de9fe5d 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals09.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Equals09.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Equals09 { - // Offset: 0x00000000 Length: 0x00000AC6 + // Offset: 0x00000000 Length: 0x00000ABC // WARNING: managed resource file FSharpSignatureData.Equals09 created } .mresource public FSharpOptimizationData.Equals09 { - // Offset: 0x00000AD0 Length: 0x0000058B + // Offset: 0x00000AC0 Length: 0x00000597 // WARNING: managed resource file FSharpOptimizationData.Equals09 created } .module Equals09.exe -// MVID: {624F9D3B-EB3D-C201-A745-03833B9D4F62} +// MVID: {628F4C90-2F86-CEF4-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x035F0000 +// Image base: 0x000001D5AC4C0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Equals09 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public EqualsMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Key - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key NewKey(int32 item1, int32 item2) cil managed @@ -94,12 +94,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item1 @@ -112,8 +112,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -124,8 +124,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,8 +136,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -149,8 +149,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -164,7 +164,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -178,20 +178,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 110 (0x6e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 105 (0x69) + .maxstack 5 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_0, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0067 + IL_0001: brfalse.s IL_0062 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0065 + IL_0004: brfalse.s IL_0060 IL_0006: ldarg.0 IL_0007: pop @@ -199,7 +199,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item1 @@ -209,68 +209,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.3 - IL_0046: ldloc.0 - IL_0047: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.1 - IL_004f: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret + IL_003b: ret - IL_0065: ldc.i4.1 + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.3 + IL_0042: ldloc.0 + IL_0043: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.1 + IL_004b: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: brfalse.s IL_0067 + + IL_0065: ldc.i4.m1 IL_0066: ret - IL_0067: ldarg.1 - IL_0068: brfalse.s IL_006c - - IL_006a: ldc.i4.m1 - IL_006b: ret - - IL_006c: ldc.i4.0 - IL_006d: ret + IL_0067: ldc.i4.0 + IL_0068: ret } // end of method Key::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -282,11 +274,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 115 (0x73) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 110 (0x6e) + .maxstack 5 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_0, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_1, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_2, @@ -297,11 +289,11 @@ IL_0001: unbox.any Equals09/EqualsMicroPerfAndCodeGenerationTests/Key IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0067 + IL_0008: brfalse.s IL_0062 IL_000a: ldarg.1 IL_000b: unbox.any Equals09/EqualsMicroPerfAndCodeGenerationTests/Key - IL_0010: brfalse.s IL_0065 + IL_0010: brfalse.s IL_0060 IL_0012: ldarg.0 IL_0013: pop @@ -317,67 +309,59 @@ IL_0026: stloc.s V_5 IL_0028: ldloc.s V_4 IL_002a: ldloc.s V_5 - IL_002c: bge.s IL_0032 - - IL_002e: ldc.i4.m1 - IL_002f: nop - IL_0030: br.s IL_0039 + IL_002c: cgt + IL_002e: ldloc.s V_4 + IL_0030: ldloc.s V_5 + IL_0032: clt + IL_0034: sub + IL_0035: stloc.3 + IL_0036: ldloc.3 + IL_0037: ldc.i4.0 + IL_0038: bge.s IL_003c - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: nop - IL_0039: stloc.3 IL_003a: ldloc.3 - IL_003b: ldc.i4.0 - IL_003c: bge.s IL_0040 + IL_003b: ret - IL_003e: ldloc.3 - IL_003f: ret + IL_003c: ldloc.3 + IL_003d: ldc.i4.0 + IL_003e: ble.s IL_0042 IL_0040: ldloc.3 - IL_0041: ldc.i4.0 - IL_0042: ble.s IL_0046 - - IL_0044: ldloc.3 - IL_0045: ret - - IL_0046: ldloc.1 - IL_0047: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.2 - IL_004f: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: unbox.any Equals09/EqualsMicroPerfAndCodeGenerationTests/Key - IL_006d: brfalse.s IL_0071 + IL_0041: ret + + IL_0042: ldloc.1 + IL_0043: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.2 + IL_004b: ldfld int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: unbox.any Equals09/EqualsMicroPerfAndCodeGenerationTests/Key + IL_0068: brfalse.s IL_006c - IL_006f: ldc.i4.m1 - IL_0070: ret + IL_006a: ldc.i4.m1 + IL_006b: ret - IL_0071: ldc.i4.0 - IL_0072: ret + IL_006c: ldc.i4.0 + IL_006d: ret } // end of method Key::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 57 (0x39) .maxstack 7 .locals init (int32 V_0, @@ -429,20 +413,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Key::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 60 (0x3c) .maxstack 4 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_0, @@ -493,7 +477,7 @@ .method public hidebysig virtual final instance bool Equals(class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_0, @@ -540,7 +524,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_0) @@ -561,9 +545,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::get_Tag() } // end of property Key::Tag .property instance int32 Item1() @@ -571,8 +555,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::get_Item1() } // end of property Key::Item1 .property instance int32 Item2() @@ -580,34 +564,34 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::get_Item2() } // end of property Key::Item2 } // end of class Key .class auto autochar serializable sealed nested public beforefieldinit KeyWithInnerKeys - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .field assembly initonly class [mscorlib]System.Tuple`2 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .field assembly initonly class [System.Runtime]System.Tuple`2 item2 + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys NewKeyWithInnerKeys(class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key item1, - class [mscorlib]System.Tuple`2 item2) cil managed + class [System.Runtime]System.Tuple`2 item2) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32) = ( 01 00 08 00 00 00 00 00 00 00 00 00 ) @@ -616,34 +600,34 @@ IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj instance void Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::.ctor(class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0007: ret } // end of method KeyWithInnerKeys::NewKeyWithInnerKeys .method assembly specialname rtspecialname instance void .ctor(class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key item1, - class [mscorlib]System.Tuple`2 item2) cil managed + class [System.Runtime]System.Tuple`2 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 IL_000d: ldarg.0 IL_000e: ldarg.2 - IL_000f: stfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_000f: stfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0014: ret } // end of method KeyWithInnerKeys::.ctor .method public hidebysig instance class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -651,23 +635,23 @@ IL_0006: ret } // end of method KeyWithInnerKeys::get_Item1 - .method public hidebysig instance class [mscorlib]System.Tuple`2 + .method public hidebysig instance class [System.Runtime]System.Tuple`2 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0001: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0006: ret } // end of method KeyWithInnerKeys::get_Item2 .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -679,8 +663,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -694,7 +678,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -708,17 +692,17 @@ .method public hidebysig virtual final instance int32 CompareTo(class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 160 (0xa0) .maxstack 5 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_4, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_5, - class [mscorlib]System.Tuple`2 V_6, - class [mscorlib]System.Tuple`2 V_7, + class [System.Runtime]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_7, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_8, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_9, int32 V_10) @@ -734,7 +718,7 @@ IL_000f: stloc.0 IL_0010: ldarg.1 IL_0011: stloc.1 - IL_0012: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0012: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0017: stloc.3 IL_0018: ldloc.0 IL_0019: ldfld class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 @@ -746,7 +730,7 @@ IL_002a: ldloc.s V_5 IL_002c: ldloc.3 IL_002d: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0032: stloc.2 IL_0033: ldloc.2 IL_0034: ldc.i4.0 @@ -762,31 +746,31 @@ IL_003d: ldloc.2 IL_003e: ret - IL_003f: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_003f: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0044: stloc.3 IL_0045: ldloc.0 - IL_0046: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0046: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_004b: stloc.s V_6 IL_004d: ldloc.1 - IL_004e: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_004e: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0053: stloc.s V_7 IL_0055: ldloc.s V_6 - IL_0057: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0057: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_005c: stloc.s V_4 IL_005e: ldloc.s V_6 - IL_0060: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0060: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0065: stloc.s V_5 IL_0067: ldloc.s V_7 - IL_0069: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0069: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_006e: stloc.s V_8 IL_0070: ldloc.s V_7 - IL_0072: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0072: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0077: stloc.s V_9 IL_0079: ldloc.s V_4 IL_007b: ldloc.s V_8 IL_007d: ldloc.3 IL_007e: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0083: stloc.s V_10 IL_0085: ldloc.s V_10 IL_0087: brfalse.s IL_008c @@ -798,7 +782,7 @@ IL_008e: ldloc.s V_9 IL_0090: ldloc.3 IL_0091: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0096: ret IL_0097: ldc.i4.1 @@ -817,7 +801,7 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -829,9 +813,9 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 165 (0xa5) .maxstack 5 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -840,8 +824,8 @@ int32 V_3, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_4, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_5, - class [mscorlib]System.Tuple`2 V_6, - class [mscorlib]System.Tuple`2 V_7, + class [System.Runtime]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_7, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_8, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_9, int32 V_10) @@ -871,7 +855,7 @@ IL_0030: ldloc.s V_5 IL_0032: ldarg.2 IL_0033: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0038: stloc.3 IL_0039: ldloc.3 IL_003a: ldc.i4.0 @@ -888,28 +872,28 @@ IL_0044: ret IL_0045: ldloc.1 - IL_0046: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0046: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_004b: stloc.s V_6 IL_004d: ldloc.2 - IL_004e: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_004e: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0053: stloc.s V_7 IL_0055: ldloc.s V_6 - IL_0057: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0057: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_005c: stloc.s V_4 IL_005e: ldloc.s V_6 - IL_0060: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0060: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0065: stloc.s V_5 IL_0067: ldloc.s V_7 - IL_0069: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0069: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_006e: stloc.s V_8 IL_0070: ldloc.s V_7 - IL_0072: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0072: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0077: stloc.s V_9 IL_0079: ldloc.s V_4 IL_007b: ldloc.s V_8 IL_007d: ldarg.2 IL_007e: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0083: stloc.s V_10 IL_0085: ldloc.s V_10 IL_0087: brfalse.s IL_008c @@ -921,7 +905,7 @@ IL_008e: ldloc.s V_9 IL_0090: ldarg.2 IL_0091: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0096: ret IL_0097: ldc.i4.1 @@ -939,14 +923,14 @@ } // end of method KeyWithInnerKeys::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 104 (0x68) .maxstack 7 .locals init (int32 V_0, class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_1, - class [mscorlib]System.Tuple`2 V_2, + class [System.Runtime]System.Tuple`2 V_2, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_3, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_4, int32 V_5) @@ -963,17 +947,17 @@ IL_000a: stloc.0 IL_000b: ldc.i4 0x9e3779b9 IL_0010: ldloc.1 - IL_0011: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0011: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0016: stloc.2 IL_0017: ldloc.2 - IL_0018: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0018: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_001d: stloc.3 IL_001e: ldloc.2 - IL_001f: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_001f: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0024: stloc.s V_4 IL_0026: ldloc.3 IL_0027: ldarg.1 - IL_0028: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0028: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_002d: stloc.s V_5 IL_002f: ldloc.s V_5 IL_0031: ldc.i4.5 @@ -982,7 +966,7 @@ IL_0035: add IL_0036: ldloc.s V_4 IL_0038: ldarg.1 - IL_0039: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0039: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_003e: xor IL_003f: ldloc.0 IL_0040: ldc.i4.6 @@ -998,7 +982,7 @@ IL_004e: ldloc.1 IL_004f: ldfld class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 IL_0054: ldarg.1 - IL_0055: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0055: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_005a: ldloc.0 IL_005b: ldc.i4.6 IL_005c: shl @@ -1019,20 +1003,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method KeyWithInnerKeys::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 135 (0x87) .maxstack 5 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -1040,8 +1024,8 @@ class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_2, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_3, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_4, - class [mscorlib]System.Tuple`2 V_5, - class [mscorlib]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_5, + class [System.Runtime]System.Tuple`2 V_6, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_7, class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key V_8) IL_0000: ldarg.0 @@ -1069,39 +1053,39 @@ IL_0026: ldloc.s V_4 IL_0028: ldarg.2 IL_0029: callvirt instance bool Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_002e: brfalse.s IL_007b IL_0030: ldloc.1 - IL_0031: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0031: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0036: stloc.s V_5 IL_0038: ldloc.2 - IL_0039: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0039: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_003e: stloc.s V_6 IL_0040: ldloc.s V_5 - IL_0042: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0042: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_0047: stloc.3 IL_0048: ldloc.s V_5 - IL_004a: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_004a: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_004f: stloc.s V_4 IL_0051: ldloc.s V_6 - IL_0053: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0053: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_0058: stloc.s V_7 IL_005a: ldloc.s V_6 - IL_005c: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_005c: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0061: stloc.s V_8 IL_0063: ldloc.3 IL_0064: ldloc.s V_7 IL_0066: ldarg.2 IL_0067: callvirt instance bool Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_006c: brfalse.s IL_0079 IL_006e: ldloc.s V_4 IL_0070: ldloc.s V_8 IL_0072: ldarg.2 IL_0073: callvirt instance bool Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_0078: ret IL_0079: ldc.i4.0 @@ -1124,7 +1108,7 @@ .method public hidebysig virtual final instance bool Equals(class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 63 (0x3f) .maxstack 4 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -1149,12 +1133,12 @@ IL_001d: brfalse.s IL_0033 IL_001f: ldloc.0 - IL_0020: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0020: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0025: ldloc.1 - IL_0026: ldfld class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0026: ldfld class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_002b: tail. - IL_002d: call bool [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericEqualityERIntrinsic>(!!0, - !!0) + IL_002d: call bool [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericEqualityERIntrinsic>(!!0, + !!0) IL_0032: ret IL_0033: ldc.i4.0 @@ -1174,7 +1158,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 4 .locals init (class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0) @@ -1196,9 +1180,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Tag() } // end of property KeyWithInnerKeys::Tag .property instance class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key @@ -1207,19 +1191,19 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item1() } // end of property KeyWithInnerKeys::Item1 - .property instance class [mscorlib]System.Tuple`2 + .property instance class [System.Runtime]System.Tuple`2 Item2() { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .get instance class [mscorlib]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item2() + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .get instance class [System.Runtime]System.Tuple`2 Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item2() } // end of property KeyWithInnerKeys::Item2 } // end of class KeyWithInnerKeys @@ -1245,10 +1229,10 @@ IL_0011: ldc.i4.2 IL_0012: call class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::NewKey(int32, int32) - IL_0017: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_0017: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_001c: call class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::NewKeyWithInnerKeys(class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0021: stloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 @@ -1262,10 +1246,10 @@ IL_0031: ldc.i4.3 IL_0032: call class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key Equals09/EqualsMicroPerfAndCodeGenerationTests/Key::NewKey(int32, int32) - IL_0037: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_0037: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_003c: call class Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::NewKeyWithInnerKeys(class Equals09/EqualsMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0041: stloc.2 IL_0042: ldc.i4.0 IL_0043: stloc.3 @@ -1273,9 +1257,9 @@ IL_0046: ldloc.1 IL_0047: ldloc.2 - IL_0048: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0048: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() IL_004d: callvirt instance bool Equals09/EqualsMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_0052: stloc.0 IL_0053: ldloc.3 IL_0054: ldc.i4.1 @@ -1293,7 +1277,7 @@ } // end of class Equals09 .class private abstract auto ansi sealed ''.$Equals09$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -1309,4 +1293,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Equals09_fsx\Equals09.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Equals09_fsx\Equals09.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash05.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash05.fsx.il.bsl index 8656893b746..9d3644fad7d 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash05.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash05.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Hash05 { - // Offset: 0x00000000 Length: 0x00000704 + // Offset: 0x00000000 Length: 0x000006F9 // WARNING: managed resource file FSharpSignatureData.Hash05 created } .mresource public FSharpOptimizationData.Hash05 { - // Offset: 0x00000708 Length: 0x000003B1 + // Offset: 0x00000700 Length: 0x000003BD // WARNING: managed resource file FSharpOptimizationData.Hash05 created } .module Hash05.exe -// MVID: {624F9D3B-964E-03B5-A745-03833B9D4F62} +// MVID: {628F4C90-4A65-A473-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x00EA0000 +// Image base: 0x00000246CC8A0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Hash05 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public HashMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Key - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Hash05/HashMicroPerfAndCodeGenerationTests/Key NewKey(int32 item1, int32 item2) cil managed @@ -94,12 +94,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item1 @@ -112,8 +112,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -124,8 +124,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,8 +136,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -149,8 +149,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -164,7 +164,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -178,20 +178,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Hash05/HashMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 110 (0x6e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 105 (0x69) + .maxstack 5 .locals init (class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_0, class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0067 + IL_0001: brfalse.s IL_0062 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0065 + IL_0004: brfalse.s IL_0060 IL_0006: ldarg.0 IL_0007: pop @@ -199,7 +199,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item1 @@ -209,68 +209,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.3 - IL_0046: ldloc.0 - IL_0047: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.1 - IL_004f: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: brfalse.s IL_006c + IL_003b: ret - IL_006a: ldc.i4.m1 - IL_006b: ret + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.3 + IL_0042: ldloc.0 + IL_0043: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.1 + IL_004b: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: brfalse.s IL_0067 + + IL_0065: ldc.i4.m1 + IL_0066: ret - IL_006c: ldc.i4.0 - IL_006d: ret + IL_0067: ldc.i4.0 + IL_0068: ret } // end of method Key::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -282,11 +274,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 115 (0x73) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 110 (0x6e) + .maxstack 5 .locals init (class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_0, class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_1, class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_2, @@ -297,11 +289,11 @@ IL_0001: unbox.any Hash05/HashMicroPerfAndCodeGenerationTests/Key IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0067 + IL_0008: brfalse.s IL_0062 IL_000a: ldarg.1 IL_000b: unbox.any Hash05/HashMicroPerfAndCodeGenerationTests/Key - IL_0010: brfalse.s IL_0065 + IL_0010: brfalse.s IL_0060 IL_0012: ldarg.0 IL_0013: pop @@ -317,67 +309,59 @@ IL_0026: stloc.s V_5 IL_0028: ldloc.s V_4 IL_002a: ldloc.s V_5 - IL_002c: bge.s IL_0032 - - IL_002e: ldc.i4.m1 - IL_002f: nop - IL_0030: br.s IL_0039 + IL_002c: cgt + IL_002e: ldloc.s V_4 + IL_0030: ldloc.s V_5 + IL_0032: clt + IL_0034: sub + IL_0035: stloc.3 + IL_0036: ldloc.3 + IL_0037: ldc.i4.0 + IL_0038: bge.s IL_003c - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: nop - IL_0039: stloc.3 IL_003a: ldloc.3 - IL_003b: ldc.i4.0 - IL_003c: bge.s IL_0040 + IL_003b: ret - IL_003e: ldloc.3 - IL_003f: ret + IL_003c: ldloc.3 + IL_003d: ldc.i4.0 + IL_003e: ble.s IL_0042 IL_0040: ldloc.3 - IL_0041: ldc.i4.0 - IL_0042: ble.s IL_0046 - - IL_0044: ldloc.3 - IL_0045: ret - - IL_0046: ldloc.1 - IL_0047: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.2 - IL_004f: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: unbox.any Hash05/HashMicroPerfAndCodeGenerationTests/Key - IL_006d: brfalse.s IL_0071 + IL_0041: ret + + IL_0042: ldloc.1 + IL_0043: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.2 + IL_004b: ldfld int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: unbox.any Hash05/HashMicroPerfAndCodeGenerationTests/Key + IL_0068: brfalse.s IL_006c - IL_006f: ldc.i4.m1 - IL_0070: ret + IL_006a: ldc.i4.m1 + IL_006b: ret - IL_0071: ldc.i4.0 - IL_0072: ret + IL_006c: ldc.i4.0 + IL_006d: ret } // end of method Key::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 57 (0x39) .maxstack 7 .locals init (int32 V_0, @@ -429,20 +413,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Key::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 60 (0x3c) .maxstack 4 .locals init (class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_0, @@ -493,7 +477,7 @@ .method public hidebysig virtual final instance bool Equals(class Hash05/HashMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_0, @@ -540,7 +524,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Hash05/HashMicroPerfAndCodeGenerationTests/Key V_0) @@ -561,9 +545,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::get_Tag() } // end of property Key::Tag .property instance int32 Item1() @@ -571,8 +555,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::get_Item1() } // end of property Key::Item1 .property instance int32 Item2() @@ -580,8 +564,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::get_Item2() } // end of property Key::Item2 } // end of class Key @@ -601,8 +585,8 @@ IL_0006: ldc.i4.2 IL_0007: call class Hash05/HashMicroPerfAndCodeGenerationTests/Key Hash05/HashMicroPerfAndCodeGenerationTests/Key::NewKey(int32, int32) - IL_000c: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityERComparer() - IL_0011: callvirt instance int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_000c: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityERComparer() + IL_0011: callvirt instance int32 Hash05/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_0016: stloc.1 IL_0017: ldloc.0 IL_0018: ldc.i4.1 @@ -620,7 +604,7 @@ } // end of class Hash05 .class private abstract auto ansi sealed ''.$Hash05$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -636,4 +620,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Hash05_fsx\Hash05.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Hash05_fsx\Hash05.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash06.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash06.fsx.il.bsl index 8c9ffc80633..f72d0b9ef6f 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash06.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash06.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Hash06 { - // Offset: 0x00000000 Length: 0x00000705 + // Offset: 0x00000000 Length: 0x000006FA // WARNING: managed resource file FSharpSignatureData.Hash06 created } .mresource public FSharpOptimizationData.Hash06 { - // Offset: 0x00000710 Length: 0x000003B2 + // Offset: 0x00000700 Length: 0x000003BE // WARNING: managed resource file FSharpOptimizationData.Hash06 created } .module Hash06.exe -// MVID: {624F9D3B-964E-045E-A745-03833B9D4F62} +// MVID: {628F4C90-548C-2CC0-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03140000 +// Image base: 0x000001969BEC0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Hash06 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public HashMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Key - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Hash06/HashMicroPerfAndCodeGenerationTests/Key NewKey(int32 item1, int32 item2) cil managed @@ -94,12 +94,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item1 @@ -112,8 +112,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -124,8 +124,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,8 +136,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -149,8 +149,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -164,7 +164,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -178,20 +178,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Hash06/HashMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 110 (0x6e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 105 (0x69) + .maxstack 5 .locals init (class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_0, class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0067 + IL_0001: brfalse.s IL_0062 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0065 + IL_0004: brfalse.s IL_0060 IL_0006: ldarg.0 IL_0007: pop @@ -199,7 +199,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item1 @@ -209,68 +209,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.3 - IL_0046: ldloc.0 - IL_0047: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.1 - IL_004f: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: brfalse.s IL_006c + IL_003b: ret - IL_006a: ldc.i4.m1 - IL_006b: ret + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.3 + IL_0042: ldloc.0 + IL_0043: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.1 + IL_004b: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: brfalse.s IL_0067 + + IL_0065: ldc.i4.m1 + IL_0066: ret - IL_006c: ldc.i4.0 - IL_006d: ret + IL_0067: ldc.i4.0 + IL_0068: ret } // end of method Key::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -282,11 +274,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 115 (0x73) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 110 (0x6e) + .maxstack 5 .locals init (class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_0, class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_1, class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_2, @@ -297,11 +289,11 @@ IL_0001: unbox.any Hash06/HashMicroPerfAndCodeGenerationTests/Key IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0067 + IL_0008: brfalse.s IL_0062 IL_000a: ldarg.1 IL_000b: unbox.any Hash06/HashMicroPerfAndCodeGenerationTests/Key - IL_0010: brfalse.s IL_0065 + IL_0010: brfalse.s IL_0060 IL_0012: ldarg.0 IL_0013: pop @@ -317,67 +309,59 @@ IL_0026: stloc.s V_5 IL_0028: ldloc.s V_4 IL_002a: ldloc.s V_5 - IL_002c: bge.s IL_0032 - - IL_002e: ldc.i4.m1 - IL_002f: nop - IL_0030: br.s IL_0039 + IL_002c: cgt + IL_002e: ldloc.s V_4 + IL_0030: ldloc.s V_5 + IL_0032: clt + IL_0034: sub + IL_0035: stloc.3 + IL_0036: ldloc.3 + IL_0037: ldc.i4.0 + IL_0038: bge.s IL_003c - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: nop - IL_0039: stloc.3 IL_003a: ldloc.3 - IL_003b: ldc.i4.0 - IL_003c: bge.s IL_0040 + IL_003b: ret - IL_003e: ldloc.3 - IL_003f: ret + IL_003c: ldloc.3 + IL_003d: ldc.i4.0 + IL_003e: ble.s IL_0042 IL_0040: ldloc.3 - IL_0041: ldc.i4.0 - IL_0042: ble.s IL_0046 - - IL_0044: ldloc.3 - IL_0045: ret - - IL_0046: ldloc.1 - IL_0047: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.2 - IL_004f: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: unbox.any Hash06/HashMicroPerfAndCodeGenerationTests/Key - IL_006d: brfalse.s IL_0071 + IL_0041: ret + + IL_0042: ldloc.1 + IL_0043: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.2 + IL_004b: ldfld int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: unbox.any Hash06/HashMicroPerfAndCodeGenerationTests/Key + IL_0068: brfalse.s IL_006c - IL_006f: ldc.i4.m1 - IL_0070: ret + IL_006a: ldc.i4.m1 + IL_006b: ret - IL_0071: ldc.i4.0 - IL_0072: ret + IL_006c: ldc.i4.0 + IL_006d: ret } // end of method Key::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 57 (0x39) .maxstack 7 .locals init (int32 V_0, @@ -429,20 +413,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Key::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 60 (0x3c) .maxstack 4 .locals init (class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_0, @@ -493,7 +477,7 @@ .method public hidebysig virtual final instance bool Equals(class Hash06/HashMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_0, @@ -540,7 +524,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Hash06/HashMicroPerfAndCodeGenerationTests/Key V_0) @@ -561,9 +545,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::get_Tag() } // end of property Key::Tag .property instance int32 Item1() @@ -571,8 +555,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::get_Item1() } // end of property Key::Item1 .property instance int32 Item2() @@ -580,8 +564,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Hash06/HashMicroPerfAndCodeGenerationTests/Key::get_Item2() } // end of property Key::Item2 } // end of class Key @@ -601,7 +585,7 @@ IL_0006: ldc.i4.2 IL_0007: call class Hash06/HashMicroPerfAndCodeGenerationTests/Key Hash06/HashMicroPerfAndCodeGenerationTests/Key::NewKey(int32, int32) - IL_000c: callvirt instance int32 [mscorlib]System.Object::GetHashCode() + IL_000c: callvirt instance int32 [System.Runtime]System.Object::GetHashCode() IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: ldc.i4.1 @@ -619,7 +603,7 @@ } // end of class Hash06 .class private abstract auto ansi sealed ''.$Hash06$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -635,4 +619,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Hash06_fsx\Hash06.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Hash06_fsx\Hash06.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash08.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash08.fsx.il.bsl index 71c30b50880..b23967fe77b 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash08.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash08.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,54 +21,54 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Hash08 { - // Offset: 0x00000000 Length: 0x000006F7 + // Offset: 0x00000000 Length: 0x000006EC // WARNING: managed resource file FSharpSignatureData.Hash08 created } .mresource public FSharpOptimizationData.Hash08 { - // Offset: 0x00000700 Length: 0x000003B3 + // Offset: 0x000006F0 Length: 0x000003BF // WARNING: managed resource file FSharpOptimizationData.Hash08 created } .module Hash08.exe -// MVID: {624F9D3B-964E-0318-A745-03833B9D4F62} +// MVID: {628F4C90-DB21-7098-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x04D90000 +// Image base: 0x000001AEC8160000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Hash08 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public HashMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto ansi serializable sealed nested public KeyR - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 02 00 00 00 00 00 ) .field assembly int32 key1@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field assembly int32 key2@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance int32 get_key1() cil managed { @@ -96,7 +96,7 @@ // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -109,7 +109,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -123,20 +123,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Hash08/HashMicroPerfAndCodeGenerationTests/KeyR obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 92 (0x5c) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 87 (0x57) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0055 + IL_0001: brfalse.s IL_0050 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0053 + IL_0004: brfalse.s IL_004e - IL_0006: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0006: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_000b: stloc.1 IL_000c: ldarg.0 IL_000d: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -146,68 +146,60 @@ IL_0019: stloc.3 IL_001a: ldloc.2 IL_001b: ldloc.3 - IL_001c: bge.s IL_0022 - - IL_001e: ldc.i4.m1 - IL_001f: nop - IL_0020: br.s IL_0027 + IL_001c: cgt + IL_001e: ldloc.2 + IL_001f: ldloc.3 + IL_0020: clt + IL_0022: sub + IL_0023: stloc.0 + IL_0024: ldloc.0 + IL_0025: ldc.i4.0 + IL_0026: bge.s IL_002a - IL_0022: ldloc.2 - IL_0023: ldloc.3 - IL_0024: cgt - IL_0026: nop - IL_0027: stloc.0 IL_0028: ldloc.0 - IL_0029: ldc.i4.0 - IL_002a: bge.s IL_002e + IL_0029: ret - IL_002c: ldloc.0 - IL_002d: ret + IL_002a: ldloc.0 + IL_002b: ldc.i4.0 + IL_002c: ble.s IL_0030 IL_002e: ldloc.0 - IL_002f: ldc.i4.0 - IL_0030: ble.s IL_0034 - - IL_0032: ldloc.0 - IL_0033: ret - - IL_0034: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0039: stloc.1 - IL_003a: ldarg.0 - IL_003b: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0040: stloc.2 - IL_0041: ldarg.1 - IL_0042: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0047: stloc.3 + IL_002f: ret + + IL_0030: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0035: stloc.1 + IL_0036: ldarg.0 + IL_0037: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_003c: stloc.2 + IL_003d: ldarg.1 + IL_003e: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_0043: stloc.3 + IL_0044: ldloc.2 + IL_0045: ldloc.3 + IL_0046: cgt IL_0048: ldloc.2 IL_0049: ldloc.3 - IL_004a: bge.s IL_004e - - IL_004c: ldc.i4.m1 + IL_004a: clt + IL_004c: sub IL_004d: ret - IL_004e: ldloc.2 - IL_004f: ldloc.3 - IL_0050: cgt - IL_0052: ret - - IL_0053: ldc.i4.1 - IL_0054: ret + IL_004e: ldc.i4.1 + IL_004f: ret - IL_0055: ldarg.1 - IL_0056: brfalse.s IL_005a + IL_0050: ldarg.1 + IL_0051: brfalse.s IL_0055 - IL_0058: ldc.i4.m1 - IL_0059: ret + IL_0053: ldc.i4.m1 + IL_0054: ret - IL_005a: ldc.i4.0 - IL_005b: ret + IL_0055: ldc.i4.0 + IL_0056: ret } // end of method KeyR::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -219,11 +211,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 97 (0x61) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 92 (0x5c) + .maxstack 5 .locals init (class Hash08/HashMicroPerfAndCodeGenerationTests/KeyR V_0, int32 V_1, int32 V_2, @@ -232,11 +224,11 @@ IL_0001: unbox.any Hash08/HashMicroPerfAndCodeGenerationTests/KeyR IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0055 + IL_0008: brfalse.s IL_0050 IL_000a: ldarg.1 IL_000b: unbox.any Hash08/HashMicroPerfAndCodeGenerationTests/KeyR - IL_0010: brfalse.s IL_0053 + IL_0010: brfalse.s IL_004e IL_0012: ldarg.0 IL_0013: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key1@ @@ -246,67 +238,59 @@ IL_001f: stloc.3 IL_0020: ldloc.2 IL_0021: ldloc.3 - IL_0022: bge.s IL_0028 - - IL_0024: ldc.i4.m1 - IL_0025: nop - IL_0026: br.s IL_002d + IL_0022: cgt + IL_0024: ldloc.2 + IL_0025: ldloc.3 + IL_0026: clt + IL_0028: sub + IL_0029: stloc.1 + IL_002a: ldloc.1 + IL_002b: ldc.i4.0 + IL_002c: bge.s IL_0030 - IL_0028: ldloc.2 - IL_0029: ldloc.3 - IL_002a: cgt - IL_002c: nop - IL_002d: stloc.1 IL_002e: ldloc.1 - IL_002f: ldc.i4.0 - IL_0030: bge.s IL_0034 + IL_002f: ret - IL_0032: ldloc.1 - IL_0033: ret + IL_0030: ldloc.1 + IL_0031: ldc.i4.0 + IL_0032: ble.s IL_0036 IL_0034: ldloc.1 - IL_0035: ldc.i4.0 - IL_0036: ble.s IL_003a - - IL_0038: ldloc.1 - IL_0039: ret - - IL_003a: ldarg.0 - IL_003b: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0040: stloc.2 - IL_0041: ldloc.0 - IL_0042: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ - IL_0047: stloc.3 + IL_0035: ret + + IL_0036: ldarg.0 + IL_0037: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_003c: stloc.2 + IL_003d: ldloc.0 + IL_003e: ldfld int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::key2@ + IL_0043: stloc.3 + IL_0044: ldloc.2 + IL_0045: ldloc.3 + IL_0046: cgt IL_0048: ldloc.2 IL_0049: ldloc.3 - IL_004a: bge.s IL_004e - - IL_004c: ldc.i4.m1 + IL_004a: clt + IL_004c: sub IL_004d: ret - IL_004e: ldloc.2 - IL_004f: ldloc.3 - IL_0050: cgt - IL_0052: ret - - IL_0053: ldc.i4.1 - IL_0054: ret + IL_004e: ldc.i4.1 + IL_004f: ret - IL_0055: ldarg.1 - IL_0056: unbox.any Hash08/HashMicroPerfAndCodeGenerationTests/KeyR - IL_005b: brfalse.s IL_005f + IL_0050: ldarg.1 + IL_0051: unbox.any Hash08/HashMicroPerfAndCodeGenerationTests/KeyR + IL_0056: brfalse.s IL_005a - IL_005d: ldc.i4.m1 - IL_005e: ret + IL_0058: ldc.i4.m1 + IL_0059: ret - IL_005f: ldc.i4.0 - IL_0060: ret + IL_005a: ldc.i4.0 + IL_005b: ret } // end of method KeyR::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 51 (0x33) .maxstack 7 .locals init (int32 V_0) @@ -351,20 +335,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method KeyR::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 54 (0x36) .maxstack 4 .locals init (class Hash08/HashMicroPerfAndCodeGenerationTests/KeyR V_0) @@ -407,7 +391,7 @@ .method public hidebysig virtual final instance bool Equals(class Hash08/HashMicroPerfAndCodeGenerationTests/KeyR obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 47 (0x2f) .maxstack 8 IL_0000: ldarg.0 @@ -446,7 +430,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Hash08/HashMicroPerfAndCodeGenerationTests/KeyR V_0) @@ -494,8 +478,8 @@ IL_0006: ldc.i4.2 IL_0007: newobj instance void Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::.ctor(int32, int32) - IL_000c: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityERComparer() - IL_0011: callvirt instance int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_000c: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityERComparer() + IL_0011: callvirt instance int32 Hash08/HashMicroPerfAndCodeGenerationTests/KeyR::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_0016: stloc.1 IL_0017: ldloc.0 IL_0018: ldc.i4.1 @@ -513,7 +497,7 @@ } // end of class Hash08 .class private abstract auto ansi sealed ''.$Hash08$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -529,4 +513,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Hash08_fsx\Hash08.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Hash08_fsx\Hash08.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash12.fsx.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash12.fsx.il.bsl index 798f52c0f9e..313ec19364b 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash12.fsx.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/GenericComparison/Hash12.fsx.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Hash12 { - // Offset: 0x00000000 Length: 0x00000ABC + // Offset: 0x00000000 Length: 0x00000AB1 // WARNING: managed resource file FSharpSignatureData.Hash12 created } .mresource public FSharpOptimizationData.Hash12 { - // Offset: 0x00000AC0 Length: 0x00000585 + // Offset: 0x00000AB8 Length: 0x00000591 // WARNING: managed resource file FSharpOptimizationData.Hash12 created } .module Hash12.exe -// MVID: {624F9D3B-966D-04DA-A745-03833B9D4F62} +// MVID: {628F4C90-0442-DE17-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03E50000 +// Image base: 0x000001B6BC460000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Hash12 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto ansi sealed nested public HashMicroPerfAndCodeGenerationTests - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Key - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Hash12/HashMicroPerfAndCodeGenerationTests/Key NewKey(int32 item1, int32 item2) cil managed @@ -94,12 +94,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item1 @@ -112,8 +112,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -124,8 +124,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,8 +136,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -149,8 +149,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -164,7 +164,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -178,20 +178,20 @@ .method public hidebysig virtual final instance int32 CompareTo(class Hash12/HashMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 110 (0x6e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 105 (0x69) + .maxstack 5 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_0, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0067 + IL_0001: brfalse.s IL_0062 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0065 + IL_0004: brfalse.s IL_0060 IL_0006: ldarg.0 IL_0007: pop @@ -199,7 +199,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item1 @@ -209,68 +209,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.3 - IL_0046: ldloc.0 - IL_0047: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.1 - IL_004f: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret + IL_003b: ret - IL_0065: ldc.i4.1 + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.3 + IL_0042: ldloc.0 + IL_0043: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.1 + IL_004b: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: brfalse.s IL_0067 + + IL_0065: ldc.i4.m1 IL_0066: ret - IL_0067: ldarg.1 - IL_0068: brfalse.s IL_006c - - IL_006a: ldc.i4.m1 - IL_006b: ret - - IL_006c: ldc.i4.0 - IL_006d: ret + IL_0067: ldc.i4.0 + IL_0068: ret } // end of method Key::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -282,11 +274,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 115 (0x73) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 110 (0x6e) + .maxstack 5 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_0, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_1, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_2, @@ -297,11 +289,11 @@ IL_0001: unbox.any Hash12/HashMicroPerfAndCodeGenerationTests/Key IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0067 + IL_0008: brfalse.s IL_0062 IL_000a: ldarg.1 IL_000b: unbox.any Hash12/HashMicroPerfAndCodeGenerationTests/Key - IL_0010: brfalse.s IL_0065 + IL_0010: brfalse.s IL_0060 IL_0012: ldarg.0 IL_0013: pop @@ -317,67 +309,59 @@ IL_0026: stloc.s V_5 IL_0028: ldloc.s V_4 IL_002a: ldloc.s V_5 - IL_002c: bge.s IL_0032 - - IL_002e: ldc.i4.m1 - IL_002f: nop - IL_0030: br.s IL_0039 + IL_002c: cgt + IL_002e: ldloc.s V_4 + IL_0030: ldloc.s V_5 + IL_0032: clt + IL_0034: sub + IL_0035: stloc.3 + IL_0036: ldloc.3 + IL_0037: ldc.i4.0 + IL_0038: bge.s IL_003c - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: nop - IL_0039: stloc.3 IL_003a: ldloc.3 - IL_003b: ldc.i4.0 - IL_003c: bge.s IL_0040 + IL_003b: ret - IL_003e: ldloc.3 - IL_003f: ret + IL_003c: ldloc.3 + IL_003d: ldc.i4.0 + IL_003e: ble.s IL_0042 IL_0040: ldloc.3 - IL_0041: ldc.i4.0 - IL_0042: ble.s IL_0046 - - IL_0044: ldloc.3 - IL_0045: ret - - IL_0046: ldloc.1 - IL_0047: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_004c: stloc.s V_4 - IL_004e: ldloc.2 - IL_004f: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 - IL_0054: stloc.s V_5 - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: bge.s IL_005e - - IL_005c: ldc.i4.m1 - IL_005d: ret - - IL_005e: ldloc.s V_4 - IL_0060: ldloc.s V_5 - IL_0062: cgt - IL_0064: ret - - IL_0065: ldc.i4.1 - IL_0066: ret - - IL_0067: ldarg.1 - IL_0068: unbox.any Hash12/HashMicroPerfAndCodeGenerationTests/Key - IL_006d: brfalse.s IL_0071 + IL_0041: ret + + IL_0042: ldloc.1 + IL_0043: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0048: stloc.s V_4 + IL_004a: ldloc.2 + IL_004b: ldfld int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::item2 + IL_0050: stloc.s V_5 + IL_0052: ldloc.s V_4 + IL_0054: ldloc.s V_5 + IL_0056: cgt + IL_0058: ldloc.s V_4 + IL_005a: ldloc.s V_5 + IL_005c: clt + IL_005e: sub + IL_005f: ret + + IL_0060: ldc.i4.1 + IL_0061: ret + + IL_0062: ldarg.1 + IL_0063: unbox.any Hash12/HashMicroPerfAndCodeGenerationTests/Key + IL_0068: brfalse.s IL_006c - IL_006f: ldc.i4.m1 - IL_0070: ret + IL_006a: ldc.i4.m1 + IL_006b: ret - IL_0071: ldc.i4.0 - IL_0072: ret + IL_006c: ldc.i4.0 + IL_006d: ret } // end of method Key::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 57 (0x39) .maxstack 7 .locals init (int32 V_0, @@ -429,20 +413,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Key::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 60 (0x3c) .maxstack 4 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_0, @@ -493,7 +477,7 @@ .method public hidebysig virtual final instance bool Equals(class Hash12/HashMicroPerfAndCodeGenerationTests/Key obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_0, @@ -540,7 +524,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_0) @@ -561,9 +545,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::get_Tag() } // end of property Key::Tag .property instance int32 Item1() @@ -571,8 +555,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::get_Item1() } // end of property Key::Item1 .property instance int32 Item2() @@ -580,34 +564,34 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::get_Item2() } // end of property Key::Item2 } // end of class Key .class auto autochar serializable sealed nested public beforefieldinit KeyWithInnerKeys - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly class Hash12/HashMicroPerfAndCodeGenerationTests/Key item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .field assembly initonly class [mscorlib]System.Tuple`2 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .field assembly initonly class [System.Runtime]System.Tuple`2 item2 + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys NewKeyWithInnerKeys(class Hash12/HashMicroPerfAndCodeGenerationTests/Key item1, - class [mscorlib]System.Tuple`2 item2) cil managed + class [System.Runtime]System.Tuple`2 item2) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32) = ( 01 00 08 00 00 00 00 00 00 00 00 00 ) @@ -616,34 +600,34 @@ IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj instance void Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::.ctor(class Hash12/HashMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0007: ret } // end of method KeyWithInnerKeys::NewKeyWithInnerKeys .method assembly specialname rtspecialname instance void .ctor(class Hash12/HashMicroPerfAndCodeGenerationTests/Key item1, - class [mscorlib]System.Tuple`2 item2) cil managed + class [System.Runtime]System.Tuple`2 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Hash12/HashMicroPerfAndCodeGenerationTests/Key Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 IL_000d: ldarg.0 IL_000e: ldarg.2 - IL_000f: stfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_000f: stfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0014: ret } // end of method KeyWithInnerKeys::.ctor .method public hidebysig instance class Hash12/HashMicroPerfAndCodeGenerationTests/Key get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -651,23 +635,23 @@ IL_0006: ret } // end of method KeyWithInnerKeys::get_Item1 - .method public hidebysig instance class [mscorlib]System.Tuple`2 + .method public hidebysig instance class [System.Runtime]System.Tuple`2 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0001: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0006: ret } // end of method KeyWithInnerKeys::get_Item2 .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -679,8 +663,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -694,7 +678,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -708,17 +692,17 @@ .method public hidebysig virtual final instance int32 CompareTo(class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 160 (0xa0) .maxstack 5 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_4, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_5, - class [mscorlib]System.Tuple`2 V_6, - class [mscorlib]System.Tuple`2 V_7, + class [System.Runtime]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_7, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_8, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_9, int32 V_10) @@ -734,7 +718,7 @@ IL_000f: stloc.0 IL_0010: ldarg.1 IL_0011: stloc.1 - IL_0012: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0012: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0017: stloc.3 IL_0018: ldloc.0 IL_0019: ldfld class Hash12/HashMicroPerfAndCodeGenerationTests/Key Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 @@ -746,7 +730,7 @@ IL_002a: ldloc.s V_5 IL_002c: ldloc.3 IL_002d: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0032: stloc.2 IL_0033: ldloc.2 IL_0034: ldc.i4.0 @@ -762,31 +746,31 @@ IL_003d: ldloc.2 IL_003e: ret - IL_003f: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_003f: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0044: stloc.3 IL_0045: ldloc.0 - IL_0046: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0046: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_004b: stloc.s V_6 IL_004d: ldloc.1 - IL_004e: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_004e: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0053: stloc.s V_7 IL_0055: ldloc.s V_6 - IL_0057: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0057: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_005c: stloc.s V_4 IL_005e: ldloc.s V_6 - IL_0060: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0060: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0065: stloc.s V_5 IL_0067: ldloc.s V_7 - IL_0069: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0069: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_006e: stloc.s V_8 IL_0070: ldloc.s V_7 - IL_0072: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0072: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0077: stloc.s V_9 IL_0079: ldloc.s V_4 IL_007b: ldloc.s V_8 IL_007d: ldloc.3 IL_007e: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0083: stloc.s V_10 IL_0085: ldloc.s V_10 IL_0087: brfalse.s IL_008c @@ -798,7 +782,7 @@ IL_008e: ldloc.s V_9 IL_0090: ldloc.3 IL_0091: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0096: ret IL_0097: ldc.i4.1 @@ -817,7 +801,7 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -829,9 +813,9 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 165 (0xa5) .maxstack 5 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -840,8 +824,8 @@ int32 V_3, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_4, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_5, - class [mscorlib]System.Tuple`2 V_6, - class [mscorlib]System.Tuple`2 V_7, + class [System.Runtime]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_7, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_8, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_9, int32 V_10) @@ -871,7 +855,7 @@ IL_0030: ldloc.s V_5 IL_0032: ldarg.2 IL_0033: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0038: stloc.3 IL_0039: ldloc.3 IL_003a: ldc.i4.0 @@ -888,28 +872,28 @@ IL_0044: ret IL_0045: ldloc.1 - IL_0046: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0046: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_004b: stloc.s V_6 IL_004d: ldloc.2 - IL_004e: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_004e: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0053: stloc.s V_7 IL_0055: ldloc.s V_6 - IL_0057: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0057: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_005c: stloc.s V_4 IL_005e: ldloc.s V_6 - IL_0060: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0060: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0065: stloc.s V_5 IL_0067: ldloc.s V_7 - IL_0069: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0069: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_006e: stloc.s V_8 IL_0070: ldloc.s V_7 - IL_0072: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_0072: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0077: stloc.s V_9 IL_0079: ldloc.s V_4 IL_007b: ldloc.s V_8 IL_007d: ldarg.2 IL_007e: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0083: stloc.s V_10 IL_0085: ldloc.s V_10 IL_0087: brfalse.s IL_008c @@ -921,7 +905,7 @@ IL_008e: ldloc.s V_9 IL_0090: ldarg.2 IL_0091: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::CompareTo(object, - class [mscorlib]System.Collections.IComparer) + class [System.Runtime]System.Collections.IComparer) IL_0096: ret IL_0097: ldc.i4.1 @@ -939,14 +923,14 @@ } // end of method KeyWithInnerKeys::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 104 (0x68) .maxstack 7 .locals init (int32 V_0, class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_1, - class [mscorlib]System.Tuple`2 V_2, + class [System.Runtime]System.Tuple`2 V_2, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_3, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_4, int32 V_5) @@ -963,17 +947,17 @@ IL_000a: stloc.0 IL_000b: ldc.i4 0x9e3779b9 IL_0010: ldloc.1 - IL_0011: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0011: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0016: stloc.2 IL_0017: ldloc.2 - IL_0018: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0018: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_001d: stloc.3 IL_001e: ldloc.2 - IL_001f: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_001f: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0024: stloc.s V_4 IL_0026: ldloc.3 IL_0027: ldarg.1 - IL_0028: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0028: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_002d: stloc.s V_5 IL_002f: ldloc.s V_5 IL_0031: ldc.i4.5 @@ -982,7 +966,7 @@ IL_0035: add IL_0036: ldloc.s V_4 IL_0038: ldarg.1 - IL_0039: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0039: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_003e: xor IL_003f: ldloc.0 IL_0040: ldc.i4.6 @@ -998,7 +982,7 @@ IL_004e: ldloc.1 IL_004f: ldfld class Hash12/HashMicroPerfAndCodeGenerationTests/Key Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item1 IL_0054: ldarg.1 - IL_0055: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0055: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/Key::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_005a: ldloc.0 IL_005b: ldc.i4.6 IL_005c: shl @@ -1019,20 +1003,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method KeyWithInnerKeys::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 135 (0x87) .maxstack 5 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -1040,8 +1024,8 @@ class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_2, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_3, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_4, - class [mscorlib]System.Tuple`2 V_5, - class [mscorlib]System.Tuple`2 V_6, + class [System.Runtime]System.Tuple`2 V_5, + class [System.Runtime]System.Tuple`2 V_6, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_7, class Hash12/HashMicroPerfAndCodeGenerationTests/Key V_8) IL_0000: ldarg.0 @@ -1069,39 +1053,39 @@ IL_0026: ldloc.s V_4 IL_0028: ldarg.2 IL_0029: callvirt instance bool Hash12/HashMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_002e: brfalse.s IL_007b IL_0030: ldloc.1 - IL_0031: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0031: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0036: stloc.s V_5 IL_0038: ldloc.2 - IL_0039: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0039: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_003e: stloc.s V_6 IL_0040: ldloc.s V_5 - IL_0042: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0042: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_0047: stloc.3 IL_0048: ldloc.s V_5 - IL_004a: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_004a: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_004f: stloc.s V_4 IL_0051: ldloc.s V_6 - IL_0053: call instance !0 class [mscorlib]System.Tuple`2::get_Item1() + IL_0053: call instance !0 class [System.Runtime]System.Tuple`2::get_Item1() IL_0058: stloc.s V_7 IL_005a: ldloc.s V_6 - IL_005c: call instance !1 class [mscorlib]System.Tuple`2::get_Item2() + IL_005c: call instance !1 class [System.Runtime]System.Tuple`2::get_Item2() IL_0061: stloc.s V_8 IL_0063: ldloc.3 IL_0064: ldloc.s V_7 IL_0066: ldarg.2 IL_0067: callvirt instance bool Hash12/HashMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_006c: brfalse.s IL_0079 IL_006e: ldloc.s V_4 IL_0070: ldloc.s V_8 IL_0072: ldarg.2 IL_0073: callvirt instance bool Hash12/HashMicroPerfAndCodeGenerationTests/Key::Equals(object, - class [mscorlib]System.Collections.IEqualityComparer) + class [System.Runtime]System.Collections.IEqualityComparer) IL_0078: ret IL_0079: ldc.i4.0 @@ -1124,7 +1108,7 @@ .method public hidebysig virtual final instance bool Equals(class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 63 (0x3f) .maxstack 4 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0, @@ -1149,12 +1133,12 @@ IL_001d: brfalse.s IL_0033 IL_001f: ldloc.0 - IL_0020: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0020: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_0025: ldloc.1 - IL_0026: ldfld class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 + IL_0026: ldfld class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::item2 IL_002b: tail. - IL_002d: call bool [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericEqualityERIntrinsic>(!!0, - !!0) + IL_002d: call bool [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/HashCompare::GenericEqualityERIntrinsic>(!!0, + !!0) IL_0032: ret IL_0033: ldc.i4.0 @@ -1174,7 +1158,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 4 .locals init (class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys V_0) @@ -1196,9 +1180,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Tag() } // end of property KeyWithInnerKeys::Tag .property instance class Hash12/HashMicroPerfAndCodeGenerationTests/Key @@ -1207,19 +1191,19 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance class Hash12/HashMicroPerfAndCodeGenerationTests/Key Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item1() } // end of property KeyWithInnerKeys::Item1 - .property instance class [mscorlib]System.Tuple`2 + .property instance class [System.Runtime]System.Tuple`2 Item2() { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .get instance class [mscorlib]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item2() + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .get instance class [System.Runtime]System.Tuple`2 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::get_Item2() } // end of property KeyWithInnerKeys::Item2 } // end of class KeyWithInnerKeys @@ -1243,18 +1227,18 @@ IL_0010: ldc.i4.2 IL_0011: call class Hash12/HashMicroPerfAndCodeGenerationTests/Key Hash12/HashMicroPerfAndCodeGenerationTests/Key::NewKey(int32, int32) - IL_0016: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_0016: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_001b: call class Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::NewKeyWithInnerKeys(class Hash12/HashMicroPerfAndCodeGenerationTests/Key, - class [mscorlib]System.Tuple`2) + class [System.Runtime]System.Tuple`2) IL_0020: stloc.0 IL_0021: ldc.i4.0 IL_0022: stloc.1 IL_0023: br.s IL_0035 IL_0025: ldloc.0 - IL_0026: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityERComparer() - IL_002b: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0026: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityERComparer() + IL_002b: callvirt instance int32 Hash12/HashMicroPerfAndCodeGenerationTests/KeyWithInnerKeys::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_0030: stloc.2 IL_0031: ldloc.1 IL_0032: ldc.i4.1 @@ -1272,7 +1256,7 @@ } // end of class Hash12 .class private abstract auto ansi sealed ''.$Hash12$fsx - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -1288,4 +1272,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\GenericComparison\Hash12_fsx\Hash12.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\GenericComparison\Hash12_fsx\Hash12.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.debug.bsl index 427461bb728..3d7263bd40f 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Match01 { - // Offset: 0x00000000 Length: 0x00000722 + // Offset: 0x00000000 Length: 0x00000718 // WARNING: managed resource file FSharpSignatureData.Match01 created } .mresource public FSharpOptimizationData.Match01 { - // Offset: 0x00000728 Length: 0x000003B7 + // Offset: 0x00000720 Length: 0x000003C3 // WARNING: managed resource file FSharpOptimizationData.Match01 created } .module Match01.exe -// MVID: {624E9975-1470-80B4-A745-038375994E62} +// MVID: {628F4C90-D9D6-6143-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x04BD0000 +// Image base: 0x0000019CC0BB0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Match01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto autochar serializable nested public beforefieldinit Test1 - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .class abstract auto ansi sealed nested public Tags - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field public static literal int32 X11 = int32(0x00000000) .field public static literal int32 X12 = int32(0x00000001) @@ -75,20 +75,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X11 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 31 40 44 65 62 75 67 54 79 70 65 50 72 // +X11@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 31 40 44 65 62 75 67 54 79 70 65 50 72 // +X11@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -103,8 +103,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -117,8 +117,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X11::get_Item() } // end of property X11::Item } // end of class X11 @@ -126,20 +126,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X12 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 32 40 44 65 62 75 67 54 79 70 65 50 72 // +X12@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 32 40 44 65 62 75 67 54 79 70 65 50 72 // +X12@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -154,8 +154,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -168,8 +168,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X12::get_Item() } // end of property X12::Item } // end of class X12 @@ -177,20 +177,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X13 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 33 40 44 65 62 75 67 54 79 70 65 50 72 // +X13@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 33 40 44 65 62 75 67 54 79 70 65 50 72 // +X13@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -205,8 +205,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -219,8 +219,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 02 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X13::get_Item() } // end of property X13::Item } // end of class X13 @@ -228,20 +228,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X14 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 34 40 44 65 62 75 67 54 79 70 65 50 72 // +X14@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 34 40 44 65 62 75 67 54 79 70 65 50 72 // +X14@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -256,8 +256,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -270,28 +270,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 03 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X14::get_Item() } // end of property X14::Item } // end of class X14 .class auto ansi nested assembly beforefieldinit specialname X11@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X11 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X11 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X11 Match01/Test1/X11@DebugTypeProxy::_obj @@ -301,8 +301,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -316,28 +316,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X11@DebugTypeProxy::get_Item() } // end of property X11@DebugTypeProxy::Item } // end of class X11@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname X12@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X12 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X12 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X12 Match01/Test1/X12@DebugTypeProxy::_obj @@ -347,8 +347,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -362,28 +362,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X12@DebugTypeProxy::get_Item() } // end of property X12@DebugTypeProxy::Item } // end of class X12@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname X13@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X13 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X13 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X13 Match01/Test1/X13@DebugTypeProxy::_obj @@ -393,8 +393,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -408,28 +408,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 02 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X13@DebugTypeProxy::get_Item() } // end of property X13@DebugTypeProxy::Item } // end of class X13@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname X14@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X14 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X14 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X14 Match01/Test1/X14@DebugTypeProxy::_obj @@ -439,8 +439,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -454,25 +454,25 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 03 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X14@DebugTypeProxy::get_Item() } // end of property X14@DebugTypeProxy::Item } // end of class X14@DebugTypeProxy .field assembly initonly int32 _tag - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 _tag) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Match01/Test1::_tag @@ -494,8 +494,8 @@ .method public hidebysig instance bool get_IsX11() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -520,8 +520,8 @@ .method public hidebysig instance bool get_IsX12() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -546,8 +546,8 @@ .method public hidebysig instance bool get_IsX13() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -572,8 +572,8 @@ .method public hidebysig instance bool get_IsX14() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -586,8 +586,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -598,8 +598,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -613,7 +613,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -627,57 +627,40 @@ .method public hidebysig virtual final instance int32 CompareTo(class Match01/Test1 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 46 (0x2e) - .maxstack 5 - .locals init (int32 V_0, - int32 V_1) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 24 (0x18) + .maxstack 8 IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0027 + IL_0001: brfalse.s IL_0011 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0025 + IL_0004: brfalse.s IL_000f IL_0006: ldarg.0 - IL_0007: ldfld int32 Match01/Test1::_tag - IL_000c: stloc.0 - IL_000d: ldarg.1 - IL_000e: ldfld int32 Match01/Test1::_tag - IL_0013: stloc.1 - IL_0014: ldloc.0 - IL_0015: ldloc.1 - IL_0016: bne.un.s IL_0021 - - IL_0018: ldarg.0 - IL_0019: ldarg.1 - IL_001a: ldnull - IL_001b: call int32 Match01::CompareTo$cont@4(class Match01/Test1, + IL_0007: ldarg.1 + IL_0008: ldnull + IL_0009: call int32 Match01::CompareTo$cont@4(class Match01/Test1, class Match01/Test1, class [FSharp.Core]Microsoft.FSharp.Core.Unit) - IL_0020: ret - - IL_0021: ldloc.0 - IL_0022: ldloc.1 - IL_0023: sub - IL_0024: ret + IL_000e: ret - IL_0025: ldc.i4.1 - IL_0026: ret + IL_000f: ldc.i4.1 + IL_0010: ret - IL_0027: ldarg.1 - IL_0028: brfalse.s IL_002c + IL_0011: ldarg.1 + IL_0012: brfalse.s IL_0016 - IL_002a: ldc.i4.m1 - IL_002b: ret + IL_0014: ldc.i4.m1 + IL_0015: ret - IL_002c: ldc.i4.0 - IL_002d: ret + IL_0016: ldc.i4.0 + IL_0017: ret } // end of method Test1::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -689,65 +672,48 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 63 (0x3f) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 41 (0x29) .maxstack 5 - .locals init (class Match01/Test1 V_0, - int32 V_1, - int32 V_2) + .locals init (class Match01/Test1 V_0) IL_0000: ldarg.1 IL_0001: unbox.any Match01/Test1 IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0033 + IL_0008: brfalse.s IL_001d IL_000a: ldarg.1 IL_000b: unbox.any Match01/Test1 - IL_0010: brfalse.s IL_0031 + IL_0010: brfalse.s IL_001b IL_0012: ldarg.0 - IL_0013: ldfld int32 Match01/Test1::_tag - IL_0018: stloc.1 - IL_0019: ldloc.0 - IL_001a: ldfld int32 Match01/Test1::_tag - IL_001f: stloc.2 - IL_0020: ldloc.1 - IL_0021: ldloc.2 - IL_0022: bne.un.s IL_002d - - IL_0024: ldarg.0 - IL_0025: ldloc.0 - IL_0026: ldnull - IL_0027: call int32 Match01::'CompareTo$cont@4-1'(class Match01/Test1, + IL_0013: ldloc.0 + IL_0014: ldnull + IL_0015: call int32 Match01::'CompareTo$cont@4-1'(class Match01/Test1, class Match01/Test1, class [FSharp.Core]Microsoft.FSharp.Core.Unit) - IL_002c: ret - - IL_002d: ldloc.1 - IL_002e: ldloc.2 - IL_002f: sub - IL_0030: ret + IL_001a: ret - IL_0031: ldc.i4.1 - IL_0032: ret + IL_001b: ldc.i4.1 + IL_001c: ret - IL_0033: ldarg.1 - IL_0034: unbox.any Match01/Test1 - IL_0039: brfalse.s IL_003d + IL_001d: ldarg.1 + IL_001e: unbox.any Match01/Test1 + IL_0023: brfalse.s IL_0027 - IL_003b: ldc.i4.m1 - IL_003c: ret + IL_0025: ldc.i4.m1 + IL_0026: ret - IL_003d: ldc.i4.0 - IL_003e: ret + IL_0027: ldc.i4.0 + IL_0028: ret } // end of method Test1::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 167 (0xa7) .maxstack 7 .locals init (int32 V_0, @@ -858,20 +824,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Match01/Test1::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Match01/Test1::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Test1::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 209 (0xd1) .maxstack 4 .locals init (class Match01/Test1 V_0, @@ -980,7 +946,7 @@ .method public hidebysig virtual final instance bool Equals(class Match01/Test1 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 200 (0xc8) .maxstack 4 .locals init (int32 V_0, @@ -1085,7 +1051,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Match01/Test1 V_0) @@ -1106,37 +1072,37 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Match01/Test1::get_Tag() } // end of property Test1::Tag .property instance bool IsX11() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX11() } // end of property Test1::IsX11 .property instance bool IsX12() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX12() } // end of property Test1::IsX12 .property instance bool IsX13() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX13() } // end of property Test1::IsX13 .property instance bool IsX14() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX14() } // end of property Test1::IsX14 } // end of class Test1 @@ -1145,251 +1111,261 @@ class Match01/Test1 obj, class [FSharp.Core]Microsoft.FSharp.Core.Unit unitVar) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 231 (0xe7) - .maxstack 4 - .locals init (class Match01/Test1/X11 V_0, - class Match01/Test1/X11 V_1, - class [mscorlib]System.Collections.IComparer V_2, - int32 V_3, - int32 V_4, - class Match01/Test1/X12 V_5, - class Match01/Test1/X12 V_6, - class Match01/Test1/X13 V_7, - class Match01/Test1/X13 V_8, - class Match01/Test1/X14 V_9, - class Match01/Test1/X14 V_10) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 268 (0x10c) + .maxstack 5 + .locals init (int32 V_0, + int32 V_1, + class Match01/Test1/X11 V_2, + class Match01/Test1/X11 V_3, + class [System.Runtime]System.Collections.IComparer V_4, + int32 V_5, + int32 V_6, + class Match01/Test1/X12 V_7, + class Match01/Test1/X12 V_8, + class Match01/Test1/X13 V_9, + class Match01/Test1/X13 V_10, + class Match01/Test1/X14 V_11, + class Match01/Test1/X14 V_12) IL_0000: ldarg.0 - IL_0001: call instance int32 Match01/Test1::get_Tag() - IL_0006: switch ( - IL_001b, - IL_004b, - IL_007f, - IL_00b3) - IL_001b: ldarg.0 - IL_001c: castclass Match01/Test1/X11 - IL_0021: stloc.0 - IL_0022: ldarg.1 - IL_0023: castclass Match01/Test1/X11 - IL_0028: stloc.1 - IL_0029: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_002e: stloc.2 - IL_002f: ldloc.0 - IL_0030: ldfld int32 Match01/Test1/X11::item - IL_0035: stloc.3 - IL_0036: ldloc.1 - IL_0037: ldfld int32 Match01/Test1/X11::item - IL_003c: stloc.s V_4 - IL_003e: ldloc.3 - IL_003f: ldloc.s V_4 - IL_0041: bge.s IL_0045 - - IL_0043: ldc.i4.m1 - IL_0044: ret - - IL_0045: ldloc.3 - IL_0046: ldloc.s V_4 - IL_0048: cgt - IL_004a: ret - - IL_004b: ldarg.0 - IL_004c: castclass Match01/Test1/X12 - IL_0051: stloc.s V_5 - IL_0053: ldarg.1 - IL_0054: castclass Match01/Test1/X12 - IL_0059: stloc.s V_6 - IL_005b: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0060: stloc.2 - IL_0061: ldloc.s V_5 - IL_0063: ldfld int32 Match01/Test1/X12::item - IL_0068: stloc.3 - IL_0069: ldloc.s V_6 - IL_006b: ldfld int32 Match01/Test1/X12::item - IL_0070: stloc.s V_4 - IL_0072: ldloc.3 - IL_0073: ldloc.s V_4 - IL_0075: bge.s IL_0079 - - IL_0077: ldc.i4.m1 - IL_0078: ret - - IL_0079: ldloc.3 - IL_007a: ldloc.s V_4 - IL_007c: cgt - IL_007e: ret - - IL_007f: ldarg.0 - IL_0080: castclass Match01/Test1/X13 - IL_0085: stloc.s V_7 - IL_0087: ldarg.1 - IL_0088: castclass Match01/Test1/X13 - IL_008d: stloc.s V_8 - IL_008f: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0094: stloc.2 - IL_0095: ldloc.s V_7 - IL_0097: ldfld int32 Match01/Test1/X13::item - IL_009c: stloc.3 - IL_009d: ldloc.s V_8 - IL_009f: ldfld int32 Match01/Test1/X13::item - IL_00a4: stloc.s V_4 - IL_00a6: ldloc.3 - IL_00a7: ldloc.s V_4 - IL_00a9: bge.s IL_00ad - - IL_00ab: ldc.i4.m1 - IL_00ac: ret - - IL_00ad: ldloc.3 - IL_00ae: ldloc.s V_4 - IL_00b0: cgt - IL_00b2: ret - - IL_00b3: ldarg.0 - IL_00b4: castclass Match01/Test1/X14 - IL_00b9: stloc.s V_9 - IL_00bb: ldarg.1 - IL_00bc: castclass Match01/Test1/X14 - IL_00c1: stloc.s V_10 - IL_00c3: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_00c8: stloc.2 - IL_00c9: ldloc.s V_9 - IL_00cb: ldfld int32 Match01/Test1/X14::item - IL_00d0: stloc.3 - IL_00d1: ldloc.s V_10 - IL_00d3: ldfld int32 Match01/Test1/X14::item - IL_00d8: stloc.s V_4 - IL_00da: ldloc.3 - IL_00db: ldloc.s V_4 - IL_00dd: bge.s IL_00e1 - - IL_00df: ldc.i4.m1 - IL_00e0: ret - - IL_00e1: ldloc.3 - IL_00e2: ldloc.s V_4 - IL_00e4: cgt - IL_00e6: ret + IL_0001: ldfld int32 Match01/Test1::_tag + IL_0006: stloc.0 + IL_0007: ldarg.1 + IL_0008: ldfld int32 Match01/Test1::_tag + IL_000d: stloc.1 + IL_000e: ldloc.0 + IL_000f: ldloc.1 + IL_0010: bne.un IL_0108 + + IL_0015: ldarg.0 + IL_0016: call instance int32 Match01/Test1::get_Tag() + IL_001b: switch ( + IL_0030, + IL_0063, + IL_009a, + IL_00d1) + IL_0030: ldarg.0 + IL_0031: castclass Match01/Test1/X11 + IL_0036: stloc.2 + IL_0037: ldarg.1 + IL_0038: castclass Match01/Test1/X11 + IL_003d: stloc.3 + IL_003e: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0043: stloc.s V_4 + IL_0045: ldloc.2 + IL_0046: ldfld int32 Match01/Test1/X11::item + IL_004b: stloc.s V_5 + IL_004d: ldloc.3 + IL_004e: ldfld int32 Match01/Test1/X11::item + IL_0053: stloc.s V_6 + IL_0055: ldloc.s V_5 + IL_0057: ldloc.s V_6 + IL_0059: cgt + IL_005b: ldloc.s V_5 + IL_005d: ldloc.s V_6 + IL_005f: clt + IL_0061: sub + IL_0062: ret + + IL_0063: ldarg.0 + IL_0064: castclass Match01/Test1/X12 + IL_0069: stloc.s V_7 + IL_006b: ldarg.1 + IL_006c: castclass Match01/Test1/X12 + IL_0071: stloc.s V_8 + IL_0073: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0078: stloc.s V_4 + IL_007a: ldloc.s V_7 + IL_007c: ldfld int32 Match01/Test1/X12::item + IL_0081: stloc.s V_5 + IL_0083: ldloc.s V_8 + IL_0085: ldfld int32 Match01/Test1/X12::item + IL_008a: stloc.s V_6 + IL_008c: ldloc.s V_5 + IL_008e: ldloc.s V_6 + IL_0090: cgt + IL_0092: ldloc.s V_5 + IL_0094: ldloc.s V_6 + IL_0096: clt + IL_0098: sub + IL_0099: ret + + IL_009a: ldarg.0 + IL_009b: castclass Match01/Test1/X13 + IL_00a0: stloc.s V_9 + IL_00a2: ldarg.1 + IL_00a3: castclass Match01/Test1/X13 + IL_00a8: stloc.s V_10 + IL_00aa: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_00af: stloc.s V_4 + IL_00b1: ldloc.s V_9 + IL_00b3: ldfld int32 Match01/Test1/X13::item + IL_00b8: stloc.s V_5 + IL_00ba: ldloc.s V_10 + IL_00bc: ldfld int32 Match01/Test1/X13::item + IL_00c1: stloc.s V_6 + IL_00c3: ldloc.s V_5 + IL_00c5: ldloc.s V_6 + IL_00c7: cgt + IL_00c9: ldloc.s V_5 + IL_00cb: ldloc.s V_6 + IL_00cd: clt + IL_00cf: sub + IL_00d0: ret + + IL_00d1: ldarg.0 + IL_00d2: castclass Match01/Test1/X14 + IL_00d7: stloc.s V_11 + IL_00d9: ldarg.1 + IL_00da: castclass Match01/Test1/X14 + IL_00df: stloc.s V_12 + IL_00e1: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_00e6: stloc.s V_4 + IL_00e8: ldloc.s V_11 + IL_00ea: ldfld int32 Match01/Test1/X14::item + IL_00ef: stloc.s V_5 + IL_00f1: ldloc.s V_12 + IL_00f3: ldfld int32 Match01/Test1/X14::item + IL_00f8: stloc.s V_6 + IL_00fa: ldloc.s V_5 + IL_00fc: ldloc.s V_6 + IL_00fe: cgt + IL_0100: ldloc.s V_5 + IL_0102: ldloc.s V_6 + IL_0104: clt + IL_0106: sub + IL_0107: ret + + IL_0108: ldloc.0 + IL_0109: ldloc.1 + IL_010a: sub + IL_010b: ret } // end of method Match01::CompareTo$cont@4 .method assembly static int32 'CompareTo$cont@4-1'(class Match01/Test1 this, class Match01/Test1 objTemp, class [FSharp.Core]Microsoft.FSharp.Core.Unit unitVar) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 195 (0xc3) - .maxstack 4 - .locals init (class Match01/Test1/X11 V_0, - class Match01/Test1/X11 V_1, - int32 V_2, - int32 V_3, - class Match01/Test1/X12 V_4, - class Match01/Test1/X12 V_5, - class Match01/Test1/X13 V_6, - class Match01/Test1/X13 V_7, - class Match01/Test1/X14 V_8, - class Match01/Test1/X14 V_9) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 240 (0xf0) + .maxstack 5 + .locals init (int32 V_0, + int32 V_1, + class Match01/Test1/X11 V_2, + class Match01/Test1/X11 V_3, + int32 V_4, + int32 V_5, + class Match01/Test1/X12 V_6, + class Match01/Test1/X12 V_7, + class Match01/Test1/X13 V_8, + class Match01/Test1/X13 V_9, + class Match01/Test1/X14 V_10, + class Match01/Test1/X14 V_11) IL_0000: ldarg.0 - IL_0001: call instance int32 Match01/Test1::get_Tag() - IL_0006: switch ( - IL_001b, - IL_0042, - IL_006d, - IL_0098) - IL_001b: ldarg.0 - IL_001c: castclass Match01/Test1/X11 - IL_0021: stloc.0 - IL_0022: ldarg.1 - IL_0023: castclass Match01/Test1/X11 - IL_0028: stloc.1 - IL_0029: ldloc.0 - IL_002a: ldfld int32 Match01/Test1/X11::item - IL_002f: stloc.2 - IL_0030: ldloc.1 - IL_0031: ldfld int32 Match01/Test1/X11::item - IL_0036: stloc.3 - IL_0037: ldloc.2 - IL_0038: ldloc.3 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.2 - IL_003e: ldloc.3 - IL_003f: cgt - IL_0041: ret - - IL_0042: ldarg.0 - IL_0043: castclass Match01/Test1/X12 - IL_0048: stloc.s V_4 - IL_004a: ldarg.1 - IL_004b: castclass Match01/Test1/X12 - IL_0050: stloc.s V_5 - IL_0052: ldloc.s V_4 - IL_0054: ldfld int32 Match01/Test1/X12::item - IL_0059: stloc.2 - IL_005a: ldloc.s V_5 - IL_005c: ldfld int32 Match01/Test1/X12::item - IL_0061: stloc.3 - IL_0062: ldloc.2 - IL_0063: ldloc.3 - IL_0064: bge.s IL_0068 - - IL_0066: ldc.i4.m1 - IL_0067: ret - - IL_0068: ldloc.2 - IL_0069: ldloc.3 - IL_006a: cgt - IL_006c: ret - - IL_006d: ldarg.0 - IL_006e: castclass Match01/Test1/X13 - IL_0073: stloc.s V_6 - IL_0075: ldarg.1 - IL_0076: castclass Match01/Test1/X13 - IL_007b: stloc.s V_7 - IL_007d: ldloc.s V_6 - IL_007f: ldfld int32 Match01/Test1/X13::item - IL_0084: stloc.2 - IL_0085: ldloc.s V_7 - IL_0087: ldfld int32 Match01/Test1/X13::item - IL_008c: stloc.3 - IL_008d: ldloc.2 - IL_008e: ldloc.3 - IL_008f: bge.s IL_0093 - - IL_0091: ldc.i4.m1 - IL_0092: ret - - IL_0093: ldloc.2 - IL_0094: ldloc.3 - IL_0095: cgt - IL_0097: ret - - IL_0098: ldarg.0 - IL_0099: castclass Match01/Test1/X14 - IL_009e: stloc.s V_8 - IL_00a0: ldarg.1 - IL_00a1: castclass Match01/Test1/X14 - IL_00a6: stloc.s V_9 - IL_00a8: ldloc.s V_8 - IL_00aa: ldfld int32 Match01/Test1/X14::item - IL_00af: stloc.2 - IL_00b0: ldloc.s V_9 - IL_00b2: ldfld int32 Match01/Test1/X14::item - IL_00b7: stloc.3 - IL_00b8: ldloc.2 - IL_00b9: ldloc.3 - IL_00ba: bge.s IL_00be - - IL_00bc: ldc.i4.m1 - IL_00bd: ret - - IL_00be: ldloc.2 - IL_00bf: ldloc.3 - IL_00c0: cgt - IL_00c2: ret + IL_0001: ldfld int32 Match01/Test1::_tag + IL_0006: stloc.0 + IL_0007: ldarg.1 + IL_0008: ldfld int32 Match01/Test1::_tag + IL_000d: stloc.1 + IL_000e: ldloc.0 + IL_000f: ldloc.1 + IL_0010: bne.un IL_00ec + + IL_0015: ldarg.0 + IL_0016: call instance int32 Match01/Test1::get_Tag() + IL_001b: switch ( + IL_0030, + IL_005c, + IL_008c, + IL_00bc) + IL_0030: ldarg.0 + IL_0031: castclass Match01/Test1/X11 + IL_0036: stloc.2 + IL_0037: ldarg.1 + IL_0038: castclass Match01/Test1/X11 + IL_003d: stloc.3 + IL_003e: ldloc.2 + IL_003f: ldfld int32 Match01/Test1/X11::item + IL_0044: stloc.s V_4 + IL_0046: ldloc.3 + IL_0047: ldfld int32 Match01/Test1/X11::item + IL_004c: stloc.s V_5 + IL_004e: ldloc.s V_4 + IL_0050: ldloc.s V_5 + IL_0052: cgt + IL_0054: ldloc.s V_4 + IL_0056: ldloc.s V_5 + IL_0058: clt + IL_005a: sub + IL_005b: ret + + IL_005c: ldarg.0 + IL_005d: castclass Match01/Test1/X12 + IL_0062: stloc.s V_6 + IL_0064: ldarg.1 + IL_0065: castclass Match01/Test1/X12 + IL_006a: stloc.s V_7 + IL_006c: ldloc.s V_6 + IL_006e: ldfld int32 Match01/Test1/X12::item + IL_0073: stloc.s V_4 + IL_0075: ldloc.s V_7 + IL_0077: ldfld int32 Match01/Test1/X12::item + IL_007c: stloc.s V_5 + IL_007e: ldloc.s V_4 + IL_0080: ldloc.s V_5 + IL_0082: cgt + IL_0084: ldloc.s V_4 + IL_0086: ldloc.s V_5 + IL_0088: clt + IL_008a: sub + IL_008b: ret + + IL_008c: ldarg.0 + IL_008d: castclass Match01/Test1/X13 + IL_0092: stloc.s V_8 + IL_0094: ldarg.1 + IL_0095: castclass Match01/Test1/X13 + IL_009a: stloc.s V_9 + IL_009c: ldloc.s V_8 + IL_009e: ldfld int32 Match01/Test1/X13::item + IL_00a3: stloc.s V_4 + IL_00a5: ldloc.s V_9 + IL_00a7: ldfld int32 Match01/Test1/X13::item + IL_00ac: stloc.s V_5 + IL_00ae: ldloc.s V_4 + IL_00b0: ldloc.s V_5 + IL_00b2: cgt + IL_00b4: ldloc.s V_4 + IL_00b6: ldloc.s V_5 + IL_00b8: clt + IL_00ba: sub + IL_00bb: ret + + IL_00bc: ldarg.0 + IL_00bd: castclass Match01/Test1/X14 + IL_00c2: stloc.s V_10 + IL_00c4: ldarg.1 + IL_00c5: castclass Match01/Test1/X14 + IL_00ca: stloc.s V_11 + IL_00cc: ldloc.s V_10 + IL_00ce: ldfld int32 Match01/Test1/X14::item + IL_00d3: stloc.s V_4 + IL_00d5: ldloc.s V_11 + IL_00d7: ldfld int32 Match01/Test1/X14::item + IL_00dc: stloc.s V_5 + IL_00de: ldloc.s V_4 + IL_00e0: ldloc.s V_5 + IL_00e2: cgt + IL_00e4: ldloc.s V_4 + IL_00e6: ldloc.s V_5 + IL_00e8: clt + IL_00ea: sub + IL_00eb: ret + + IL_00ec: ldloc.0 + IL_00ed: ldloc.1 + IL_00ee: sub + IL_00ef: ret } // end of method Match01::'CompareTo$cont@4-1' .method public static int32 select1(class Match01/Test1 x) cil managed @@ -1431,7 +1407,7 @@ } // end of class Match01 .class private abstract auto ansi sealed ''.$Match01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -1447,4 +1423,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\Inlining\Match01_fs\Match01.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\Inlining\Match01_fs\Match01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.release.bsl index 2817e1ffaaf..bea000625f7 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Match01.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Match01 { - // Offset: 0x00000000 Length: 0x00000727 + // Offset: 0x00000000 Length: 0x00000737 // WARNING: managed resource file FSharpSignatureData.Match01 created } .mresource public FSharpOptimizationData.Match01 { - // Offset: 0x00000730 Length: 0x000003B7 + // Offset: 0x00000740 Length: 0x000003C3 // WARNING: managed resource file FSharpOptimizationData.Match01 created } .module Match01.exe -// MVID: {624E95FC-1470-80B4-A745-0383FC954E62} +// MVID: {628FBBC7-8C69-BAB4-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03AA0000 +// Image base: 0x000002362B810000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Match01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto autochar serializable nested public beforefieldinit Test1 - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .class abstract auto ansi sealed nested public Tags - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field public static literal int32 X11 = int32(0x00000000) .field public static literal int32 X12 = int32(0x00000001) @@ -75,20 +75,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X11 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 31 40 44 65 62 75 67 54 79 70 65 50 72 // +X11@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 31 40 44 65 62 75 67 54 79 70 65 50 72 // +X11@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -103,8 +103,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -117,8 +117,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X11::get_Item() } // end of property X11::Item } // end of class X11 @@ -126,20 +126,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X12 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 32 40 44 65 62 75 67 54 79 70 65 50 72 // +X12@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 32 40 44 65 62 75 67 54 79 70 65 50 72 // +X12@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -154,8 +154,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -168,8 +168,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X12::get_Item() } // end of property X12::Item } // end of class X12 @@ -177,20 +177,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X13 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 33 40 44 65 62 75 67 54 79 70 65 50 72 // +X13@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 33 40 44 65 62 75 67 54 79 70 65 50 72 // +X13@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -205,8 +205,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -219,8 +219,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 02 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X13::get_Item() } // end of property X13::Item } // end of class X13 @@ -228,20 +228,20 @@ .class auto ansi serializable nested public beforefieldinit specialname X14 extends Match01/Test1 { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 - 2B 58 31 34 40 44 65 62 75 67 54 79 70 65 50 72 // +X14@DebugTypePr - 6F 78 79 00 00 ) // oxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 20 4D 61 74 63 68 30 31 2B 54 65 73 74 31 // .. Match01+Test1 + 2B 58 31 34 40 44 65 62 75 67 54 79 70 65 50 72 // +X14@DebugTypePr + 6F 78 79 00 00 ) // oxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -256,8 +256,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -270,28 +270,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 03 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X14::get_Item() } // end of property X14::Item } // end of class X14 .class auto ansi nested assembly beforefieldinit specialname X11@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X11 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X11 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X11 Match01/Test1/X11@DebugTypeProxy::_obj @@ -301,8 +301,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -316,28 +316,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X11@DebugTypeProxy::get_Item() } // end of property X11@DebugTypeProxy::Item } // end of class X11@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname X12@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X12 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X12 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X12 Match01/Test1/X12@DebugTypeProxy::_obj @@ -347,8 +347,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -362,28 +362,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X12@DebugTypeProxy::get_Item() } // end of property X12@DebugTypeProxy::Item } // end of class X12@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname X13@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X13 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X13 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X13 Match01/Test1/X13@DebugTypeProxy::_obj @@ -393,8 +393,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -408,28 +408,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 02 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X13@DebugTypeProxy::get_Item() } // end of property X13@DebugTypeProxy::Item } // end of class X13@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname X14@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class Match01/Test1/X14 _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class Match01/Test1/X14 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class Match01/Test1/X14 Match01/Test1/X14@DebugTypeProxy::_obj @@ -439,8 +439,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -454,25 +454,25 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 03 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 Match01/Test1/X14@DebugTypeProxy::get_Item() } // end of property X14@DebugTypeProxy::Item } // end of class X14@DebugTypeProxy .field assembly initonly int32 _tag - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 _tag) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 Match01/Test1::_tag @@ -494,8 +494,8 @@ .method public hidebysig instance bool get_IsX11() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -520,8 +520,8 @@ .method public hidebysig instance bool get_IsX12() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -546,8 +546,8 @@ .method public hidebysig instance bool get_IsX13() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -572,8 +572,8 @@ .method public hidebysig instance bool get_IsX14() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -586,8 +586,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -598,8 +598,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -613,7 +613,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -627,7 +627,7 @@ .method public hidebysig virtual final instance int32 CompareTo(class Match01/Test1 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 @@ -660,7 +660,7 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -672,48 +672,43 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 41 (0x29) - .maxstack 5 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 32 (0x20) + .maxstack 6 .locals init (class Match01/Test1 V_0) IL_0000: ldarg.1 IL_0001: unbox.any Match01/Test1 IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_001d + IL_0008: brfalse.s IL_0014 - IL_000a: ldarg.1 - IL_000b: unbox.any Match01/Test1 - IL_0010: brfalse.s IL_001b - - IL_0012: ldarg.0 - IL_0013: ldloc.0 - IL_0014: ldnull - IL_0015: call int32 Match01::'CompareTo$cont@4-1'(class Match01/Test1, + IL_000a: ldarg.0 + IL_000b: ldarg.1 + IL_000c: ldloc.0 + IL_000d: ldnull + IL_000e: call int32 Match01::'CompareTo$cont@4-1'(class Match01/Test1, + object, class Match01/Test1, class [FSharp.Core]Microsoft.FSharp.Core.Unit) - IL_001a: ret - - IL_001b: ldc.i4.1 - IL_001c: ret + IL_0013: ret - IL_001d: ldarg.1 - IL_001e: unbox.any Match01/Test1 - IL_0023: brfalse.s IL_0027 + IL_0014: ldarg.1 + IL_0015: unbox.any Match01/Test1 + IL_001a: brfalse.s IL_001e - IL_0025: ldc.i4.m1 - IL_0026: ret + IL_001c: ldc.i4.m1 + IL_001d: ret - IL_0027: ldc.i4.0 - IL_0028: ret + IL_001e: ldc.i4.0 + IL_001f: ret } // end of method Test1::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 167 (0xa7) .maxstack 7 .locals init (int32 V_0, @@ -824,20 +819,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 Match01/Test1::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 Match01/Test1::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Test1::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 209 (0xd1) .maxstack 4 .locals init (class Match01/Test1 V_0, @@ -946,7 +941,7 @@ .method public hidebysig virtual final instance bool Equals(class Match01/Test1 obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 200 (0xc8) .maxstack 4 .locals init (int32 V_0, @@ -1051,7 +1046,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class Match01/Test1 V_0) @@ -1072,37 +1067,37 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 Match01/Test1::get_Tag() } // end of property Test1::Tag .property instance bool IsX11() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX11() } // end of property Test1::IsX11 .property instance bool IsX12() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX12() } // end of property Test1::IsX12 .property instance bool IsX13() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX13() } // end of property Test1::IsX13 .property instance bool IsX14() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool Match01/Test1::get_IsX14() } // end of property Test1::IsX14 } // end of class Test1 @@ -1111,14 +1106,14 @@ class Match01/Test1 obj, class [FSharp.Core]Microsoft.FSharp.Core.Unit unitVar) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 272 (0x110) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 268 (0x10c) + .maxstack 5 .locals init (int32 V_0, int32 V_1, class Match01/Test1/X11 V_2, class Match01/Test1/X11 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6, class Match01/Test1/X12 V_7, @@ -1135,22 +1130,22 @@ IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldloc.1 - IL_0010: bne.un IL_010c + IL_0010: bne.un IL_0108 IL_0015: ldarg.0 IL_0016: call instance int32 Match01/Test1::get_Tag() IL_001b: switch ( IL_0030, - IL_0064, - IL_009c, - IL_00d4) + IL_0063, + IL_009a, + IL_00d1) IL_0030: ldarg.0 IL_0031: castclass Match01/Test1/X11 IL_0036: stloc.2 IL_0037: ldarg.1 IL_0038: castclass Match01/Test1/X11 IL_003d: stloc.3 - IL_003e: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_003e: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0043: stloc.s V_4 IL_0045: ldloc.2 IL_0046: ldfld int32 Match01/Test1/X11::item @@ -1160,107 +1155,96 @@ IL_0053: stloc.s V_6 IL_0055: ldloc.s V_5 IL_0057: ldloc.s V_6 - IL_0059: bge.s IL_005d - - IL_005b: ldc.i4.m1 - IL_005c: ret - - IL_005d: ldloc.s V_5 - IL_005f: ldloc.s V_6 - IL_0061: cgt - IL_0063: ret - - IL_0064: ldarg.0 - IL_0065: castclass Match01/Test1/X12 - IL_006a: stloc.s V_7 - IL_006c: ldarg.1 - IL_006d: castclass Match01/Test1/X12 - IL_0072: stloc.s V_8 - IL_0074: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0079: stloc.s V_4 - IL_007b: ldloc.s V_7 - IL_007d: ldfld int32 Match01/Test1/X12::item - IL_0082: stloc.s V_5 - IL_0084: ldloc.s V_8 - IL_0086: ldfld int32 Match01/Test1/X12::item - IL_008b: stloc.s V_6 - IL_008d: ldloc.s V_5 - IL_008f: ldloc.s V_6 - IL_0091: bge.s IL_0095 - - IL_0093: ldc.i4.m1 - IL_0094: ret - - IL_0095: ldloc.s V_5 - IL_0097: ldloc.s V_6 - IL_0099: cgt - IL_009b: ret - - IL_009c: ldarg.0 - IL_009d: castclass Match01/Test1/X13 - IL_00a2: stloc.s V_9 - IL_00a4: ldarg.1 - IL_00a5: castclass Match01/Test1/X13 - IL_00aa: stloc.s V_10 - IL_00ac: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_00b1: stloc.s V_4 - IL_00b3: ldloc.s V_9 - IL_00b5: ldfld int32 Match01/Test1/X13::item - IL_00ba: stloc.s V_5 - IL_00bc: ldloc.s V_10 - IL_00be: ldfld int32 Match01/Test1/X13::item - IL_00c3: stloc.s V_6 - IL_00c5: ldloc.s V_5 - IL_00c7: ldloc.s V_6 - IL_00c9: bge.s IL_00cd - - IL_00cb: ldc.i4.m1 - IL_00cc: ret - - IL_00cd: ldloc.s V_5 - IL_00cf: ldloc.s V_6 - IL_00d1: cgt - IL_00d3: ret - - IL_00d4: ldarg.0 - IL_00d5: castclass Match01/Test1/X14 - IL_00da: stloc.s V_11 - IL_00dc: ldarg.1 - IL_00dd: castclass Match01/Test1/X14 - IL_00e2: stloc.s V_12 - IL_00e4: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_00e9: stloc.s V_4 - IL_00eb: ldloc.s V_11 - IL_00ed: ldfld int32 Match01/Test1/X14::item - IL_00f2: stloc.s V_5 - IL_00f4: ldloc.s V_12 - IL_00f6: ldfld int32 Match01/Test1/X14::item - IL_00fb: stloc.s V_6 - IL_00fd: ldloc.s V_5 - IL_00ff: ldloc.s V_6 - IL_0101: bge.s IL_0105 - - IL_0103: ldc.i4.m1 - IL_0104: ret - - IL_0105: ldloc.s V_5 - IL_0107: ldloc.s V_6 - IL_0109: cgt + IL_0059: cgt + IL_005b: ldloc.s V_5 + IL_005d: ldloc.s V_6 + IL_005f: clt + IL_0061: sub + IL_0062: ret + + IL_0063: ldarg.0 + IL_0064: castclass Match01/Test1/X12 + IL_0069: stloc.s V_7 + IL_006b: ldarg.1 + IL_006c: castclass Match01/Test1/X12 + IL_0071: stloc.s V_8 + IL_0073: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0078: stloc.s V_4 + IL_007a: ldloc.s V_7 + IL_007c: ldfld int32 Match01/Test1/X12::item + IL_0081: stloc.s V_5 + IL_0083: ldloc.s V_8 + IL_0085: ldfld int32 Match01/Test1/X12::item + IL_008a: stloc.s V_6 + IL_008c: ldloc.s V_5 + IL_008e: ldloc.s V_6 + IL_0090: cgt + IL_0092: ldloc.s V_5 + IL_0094: ldloc.s V_6 + IL_0096: clt + IL_0098: sub + IL_0099: ret + + IL_009a: ldarg.0 + IL_009b: castclass Match01/Test1/X13 + IL_00a0: stloc.s V_9 + IL_00a2: ldarg.1 + IL_00a3: castclass Match01/Test1/X13 + IL_00a8: stloc.s V_10 + IL_00aa: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_00af: stloc.s V_4 + IL_00b1: ldloc.s V_9 + IL_00b3: ldfld int32 Match01/Test1/X13::item + IL_00b8: stloc.s V_5 + IL_00ba: ldloc.s V_10 + IL_00bc: ldfld int32 Match01/Test1/X13::item + IL_00c1: stloc.s V_6 + IL_00c3: ldloc.s V_5 + IL_00c5: ldloc.s V_6 + IL_00c7: cgt + IL_00c9: ldloc.s V_5 + IL_00cb: ldloc.s V_6 + IL_00cd: clt + IL_00cf: sub + IL_00d0: ret + + IL_00d1: ldarg.0 + IL_00d2: castclass Match01/Test1/X14 + IL_00d7: stloc.s V_11 + IL_00d9: ldarg.1 + IL_00da: castclass Match01/Test1/X14 + IL_00df: stloc.s V_12 + IL_00e1: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_00e6: stloc.s V_4 + IL_00e8: ldloc.s V_11 + IL_00ea: ldfld int32 Match01/Test1/X14::item + IL_00ef: stloc.s V_5 + IL_00f1: ldloc.s V_12 + IL_00f3: ldfld int32 Match01/Test1/X14::item + IL_00f8: stloc.s V_6 + IL_00fa: ldloc.s V_5 + IL_00fc: ldloc.s V_6 + IL_00fe: cgt + IL_0100: ldloc.s V_5 + IL_0102: ldloc.s V_6 + IL_0104: clt + IL_0106: sub + IL_0107: ret + + IL_0108: ldloc.0 + IL_0109: ldloc.1 + IL_010a: sub IL_010b: ret - - IL_010c: ldloc.0 - IL_010d: ldloc.1 - IL_010e: sub - IL_010f: ret } // end of method Match01::CompareTo$cont@4 .method assembly static int32 'CompareTo$cont@4-1'(class Match01/Test1 this, + object obj, class Match01/Test1 objTemp, class [FSharp.Core]Microsoft.FSharp.Core.Unit unitVar) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 244 (0xf4) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 253 (0xfd) + .maxstack 5 .locals init (int32 V_0, int32 V_1, class Match01/Test1/X11 V_2, @@ -1273,123 +1257,118 @@ class Match01/Test1/X13 V_9, class Match01/Test1/X14 V_10, class Match01/Test1/X14 V_11) - IL_0000: ldarg.0 - IL_0001: ldfld int32 Match01/Test1::_tag - IL_0006: stloc.0 - IL_0007: ldarg.1 - IL_0008: ldfld int32 Match01/Test1::_tag - IL_000d: stloc.1 - IL_000e: ldloc.0 - IL_000f: ldloc.1 - IL_0010: bne.un IL_00f0 - - IL_0015: ldarg.0 - IL_0016: call instance int32 Match01/Test1::get_Tag() - IL_001b: switch ( - IL_0030, - IL_005d, - IL_008e, - IL_00bf) - IL_0030: ldarg.0 - IL_0031: castclass Match01/Test1/X11 - IL_0036: stloc.2 - IL_0037: ldarg.1 - IL_0038: castclass Match01/Test1/X11 - IL_003d: stloc.3 - IL_003e: ldloc.2 - IL_003f: ldfld int32 Match01/Test1/X11::item - IL_0044: stloc.s V_4 - IL_0046: ldloc.3 - IL_0047: ldfld int32 Match01/Test1/X11::item - IL_004c: stloc.s V_5 - IL_004e: ldloc.s V_4 - IL_0050: ldloc.s V_5 - IL_0052: bge.s IL_0056 - - IL_0054: ldc.i4.m1 - IL_0055: ret - - IL_0056: ldloc.s V_4 - IL_0058: ldloc.s V_5 - IL_005a: cgt - IL_005c: ret - - IL_005d: ldarg.0 - IL_005e: castclass Match01/Test1/X12 - IL_0063: stloc.s V_6 - IL_0065: ldarg.1 - IL_0066: castclass Match01/Test1/X12 - IL_006b: stloc.s V_7 - IL_006d: ldloc.s V_6 - IL_006f: ldfld int32 Match01/Test1/X12::item - IL_0074: stloc.s V_4 - IL_0076: ldloc.s V_7 - IL_0078: ldfld int32 Match01/Test1/X12::item - IL_007d: stloc.s V_5 - IL_007f: ldloc.s V_4 - IL_0081: ldloc.s V_5 - IL_0083: bge.s IL_0087 - - IL_0085: ldc.i4.m1 - IL_0086: ret - - IL_0087: ldloc.s V_4 - IL_0089: ldloc.s V_5 - IL_008b: cgt - IL_008d: ret - - IL_008e: ldarg.0 - IL_008f: castclass Match01/Test1/X13 - IL_0094: stloc.s V_8 - IL_0096: ldarg.1 - IL_0097: castclass Match01/Test1/X13 - IL_009c: stloc.s V_9 - IL_009e: ldloc.s V_8 - IL_00a0: ldfld int32 Match01/Test1/X13::item - IL_00a5: stloc.s V_4 - IL_00a7: ldloc.s V_9 + IL_0000: ldarg.1 + IL_0001: unbox.any Match01/Test1 + IL_0006: brfalse IL_00fb + + IL_000b: ldarg.0 + IL_000c: ldfld int32 Match01/Test1::_tag + IL_0011: stloc.0 + IL_0012: ldarg.2 + IL_0013: ldfld int32 Match01/Test1::_tag + IL_0018: stloc.1 + IL_0019: ldloc.0 + IL_001a: ldloc.1 + IL_001b: bne.un IL_00f7 + + IL_0020: ldarg.0 + IL_0021: call instance int32 Match01/Test1::get_Tag() + IL_0026: switch ( + IL_003b, + IL_0067, + IL_0097, + IL_00c7) + IL_003b: ldarg.0 + IL_003c: castclass Match01/Test1/X11 + IL_0041: stloc.2 + IL_0042: ldarg.2 + IL_0043: castclass Match01/Test1/X11 + IL_0048: stloc.3 + IL_0049: ldloc.2 + IL_004a: ldfld int32 Match01/Test1/X11::item + IL_004f: stloc.s V_4 + IL_0051: ldloc.3 + IL_0052: ldfld int32 Match01/Test1/X11::item + IL_0057: stloc.s V_5 + IL_0059: ldloc.s V_4 + IL_005b: ldloc.s V_5 + IL_005d: cgt + IL_005f: ldloc.s V_4 + IL_0061: ldloc.s V_5 + IL_0063: clt + IL_0065: sub + IL_0066: ret + + IL_0067: ldarg.0 + IL_0068: castclass Match01/Test1/X12 + IL_006d: stloc.s V_6 + IL_006f: ldarg.2 + IL_0070: castclass Match01/Test1/X12 + IL_0075: stloc.s V_7 + IL_0077: ldloc.s V_6 + IL_0079: ldfld int32 Match01/Test1/X12::item + IL_007e: stloc.s V_4 + IL_0080: ldloc.s V_7 + IL_0082: ldfld int32 Match01/Test1/X12::item + IL_0087: stloc.s V_5 + IL_0089: ldloc.s V_4 + IL_008b: ldloc.s V_5 + IL_008d: cgt + IL_008f: ldloc.s V_4 + IL_0091: ldloc.s V_5 + IL_0093: clt + IL_0095: sub + IL_0096: ret + + IL_0097: ldarg.0 + IL_0098: castclass Match01/Test1/X13 + IL_009d: stloc.s V_8 + IL_009f: ldarg.2 + IL_00a0: castclass Match01/Test1/X13 + IL_00a5: stloc.s V_9 + IL_00a7: ldloc.s V_8 IL_00a9: ldfld int32 Match01/Test1/X13::item - IL_00ae: stloc.s V_5 - IL_00b0: ldloc.s V_4 - IL_00b2: ldloc.s V_5 - IL_00b4: bge.s IL_00b8 - - IL_00b6: ldc.i4.m1 - IL_00b7: ret - - IL_00b8: ldloc.s V_4 - IL_00ba: ldloc.s V_5 - IL_00bc: cgt - IL_00be: ret - - IL_00bf: ldarg.0 - IL_00c0: castclass Match01/Test1/X14 - IL_00c5: stloc.s V_10 - IL_00c7: ldarg.1 + IL_00ae: stloc.s V_4 + IL_00b0: ldloc.s V_9 + IL_00b2: ldfld int32 Match01/Test1/X13::item + IL_00b7: stloc.s V_5 + IL_00b9: ldloc.s V_4 + IL_00bb: ldloc.s V_5 + IL_00bd: cgt + IL_00bf: ldloc.s V_4 + IL_00c1: ldloc.s V_5 + IL_00c3: clt + IL_00c5: sub + IL_00c6: ret + + IL_00c7: ldarg.0 IL_00c8: castclass Match01/Test1/X14 - IL_00cd: stloc.s V_11 - IL_00cf: ldloc.s V_10 - IL_00d1: ldfld int32 Match01/Test1/X14::item - IL_00d6: stloc.s V_4 - IL_00d8: ldloc.s V_11 - IL_00da: ldfld int32 Match01/Test1/X14::item - IL_00df: stloc.s V_5 - IL_00e1: ldloc.s V_4 - IL_00e3: ldloc.s V_5 - IL_00e5: bge.s IL_00e9 - - IL_00e7: ldc.i4.m1 - IL_00e8: ret - + IL_00cd: stloc.s V_10 + IL_00cf: ldarg.2 + IL_00d0: castclass Match01/Test1/X14 + IL_00d5: stloc.s V_11 + IL_00d7: ldloc.s V_10 + IL_00d9: ldfld int32 Match01/Test1/X14::item + IL_00de: stloc.s V_4 + IL_00e0: ldloc.s V_11 + IL_00e2: ldfld int32 Match01/Test1/X14::item + IL_00e7: stloc.s V_5 IL_00e9: ldloc.s V_4 IL_00eb: ldloc.s V_5 IL_00ed: cgt - IL_00ef: ret - - IL_00f0: ldloc.0 - IL_00f1: ldloc.1 - IL_00f2: sub - IL_00f3: ret + IL_00ef: ldloc.s V_4 + IL_00f1: ldloc.s V_5 + IL_00f3: clt + IL_00f5: sub + IL_00f6: ret + + IL_00f7: ldloc.0 + IL_00f8: ldloc.1 + IL_00f9: sub + IL_00fa: ret + + IL_00fb: ldc.i4.1 + IL_00fc: ret } // end of method Match01::'CompareTo$cont@4-1' .method public static int32 select1(class Match01/Test1 x) cil managed @@ -1431,7 +1410,7 @@ } // end of class Match01 .class private abstract auto ansi sealed ''.$Match01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -1447,4 +1426,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\Inlining\Match01_fs\Match01.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\Inlining\Match01_fs\Match01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/StructUnion01.fs.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/StructUnion01.fs.il.bsl index 0c4130e2cce..489023a16aa 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/StructUnion01.fs.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/StructUnion01.fs.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,59 +21,59 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.StructUnion01 { - // Offset: 0x00000000 Length: 0x000008BD + // Offset: 0x00000000 Length: 0x000008B3 // WARNING: managed resource file FSharpSignatureData.StructUnion01 created } .mresource public FSharpOptimizationData.StructUnion01 { - // Offset: 0x000008C8 Length: 0x00000421 + // Offset: 0x000008B8 Length: 0x0000042D // WARNING: managed resource file FSharpOptimizationData.StructUnion01 created } .module StructUnion01.exe -// MVID: {624E944C-488D-8510-A745-03834C944E62} +// MVID: {628F4C90-26FB-FE0F-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03BD0000 +// Image base: 0x0000021459770000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed StructUnion01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class sequential autochar serializable sealed nested public beforefieldinit U - extends [mscorlib]System.ValueType - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.ValueType + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .pack 0 .size 1 .custom instance void [FSharp.Core]Microsoft.FSharp.Core.StructAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static valuetype StructUnion01/U NewU(int32 item1, int32 item2) cil managed @@ -93,8 +93,8 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 @@ -109,8 +109,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -121,8 +121,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -133,8 +133,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -146,8 +146,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 27 (0x1b) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -162,7 +162,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 27 (0x1b) .maxstack 8 IL_0000: ldstr "%+A" @@ -177,16 +177,16 @@ .method public hidebysig virtual final instance int32 CompareTo(valuetype StructUnion01/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 81 (0x51) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 76 (0x4c) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3) IL_0000: ldarg.0 IL_0001: pop - IL_0002: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0002: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0007: stloc.1 IL_0008: ldarg.0 IL_0009: ldfld int32 StructUnion01/U::item1 @@ -196,56 +196,48 @@ IL_0016: stloc.3 IL_0017: ldloc.2 IL_0018: ldloc.3 - IL_0019: bge.s IL_001f - - IL_001b: ldc.i4.m1 - IL_001c: nop - IL_001d: br.s IL_0024 + IL_0019: cgt + IL_001b: ldloc.2 + IL_001c: ldloc.3 + IL_001d: clt + IL_001f: sub + IL_0020: stloc.0 + IL_0021: ldloc.0 + IL_0022: ldc.i4.0 + IL_0023: bge.s IL_0027 - IL_001f: ldloc.2 - IL_0020: ldloc.3 - IL_0021: cgt - IL_0023: nop - IL_0024: stloc.0 IL_0025: ldloc.0 - IL_0026: ldc.i4.0 - IL_0027: bge.s IL_002b + IL_0026: ret - IL_0029: ldloc.0 - IL_002a: ret + IL_0027: ldloc.0 + IL_0028: ldc.i4.0 + IL_0029: ble.s IL_002d IL_002b: ldloc.0 - IL_002c: ldc.i4.0 - IL_002d: ble.s IL_0031 - - IL_002f: ldloc.0 - IL_0030: ret - - IL_0031: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0036: stloc.1 - IL_0037: ldarg.0 - IL_0038: ldfld int32 StructUnion01/U::item2 - IL_003d: stloc.2 - IL_003e: ldarga.s obj - IL_0040: ldfld int32 StructUnion01/U::item2 - IL_0045: stloc.3 + IL_002c: ret + + IL_002d: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0032: stloc.1 + IL_0033: ldarg.0 + IL_0034: ldfld int32 StructUnion01/U::item2 + IL_0039: stloc.2 + IL_003a: ldarga.s obj + IL_003c: ldfld int32 StructUnion01/U::item2 + IL_0041: stloc.3 + IL_0042: ldloc.2 + IL_0043: ldloc.3 + IL_0044: cgt IL_0046: ldloc.2 IL_0047: ldloc.3 - IL_0048: bge.s IL_004c - - IL_004a: ldc.i4.m1 + IL_0048: clt + IL_004a: sub IL_004b: ret - - IL_004c: ldloc.2 - IL_004d: ldloc.3 - IL_004e: cgt - IL_0050: ret } // end of method U::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -257,11 +249,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 76 (0x4c) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 71 (0x47) + .maxstack 5 .locals init (valuetype StructUnion01/U V_0, int32 V_1, int32 V_2, @@ -279,54 +271,46 @@ IL_0017: stloc.3 IL_0018: ldloc.2 IL_0019: ldloc.3 - IL_001a: bge.s IL_0020 - - IL_001c: ldc.i4.m1 - IL_001d: nop - IL_001e: br.s IL_0025 + IL_001a: cgt + IL_001c: ldloc.2 + IL_001d: ldloc.3 + IL_001e: clt + IL_0020: sub + IL_0021: stloc.1 + IL_0022: ldloc.1 + IL_0023: ldc.i4.0 + IL_0024: bge.s IL_0028 - IL_0020: ldloc.2 - IL_0021: ldloc.3 - IL_0022: cgt - IL_0024: nop - IL_0025: stloc.1 IL_0026: ldloc.1 - IL_0027: ldc.i4.0 - IL_0028: bge.s IL_002c + IL_0027: ret - IL_002a: ldloc.1 - IL_002b: ret + IL_0028: ldloc.1 + IL_0029: ldc.i4.0 + IL_002a: ble.s IL_002e IL_002c: ldloc.1 - IL_002d: ldc.i4.0 - IL_002e: ble.s IL_0032 - - IL_0030: ldloc.1 - IL_0031: ret - - IL_0032: ldarg.0 - IL_0033: ldfld int32 StructUnion01/U::item2 - IL_0038: stloc.2 - IL_0039: ldloca.s V_0 - IL_003b: ldfld int32 StructUnion01/U::item2 - IL_0040: stloc.3 + IL_002d: ret + + IL_002e: ldarg.0 + IL_002f: ldfld int32 StructUnion01/U::item2 + IL_0034: stloc.2 + IL_0035: ldloca.s V_0 + IL_0037: ldfld int32 StructUnion01/U::item2 + IL_003c: stloc.3 + IL_003d: ldloc.2 + IL_003e: ldloc.3 + IL_003f: cgt IL_0041: ldloc.2 IL_0042: ldloc.3 - IL_0043: bge.s IL_0047 - - IL_0045: ldc.i4.m1 + IL_0043: clt + IL_0045: sub IL_0046: ret - - IL_0047: ldloc.2 - IL_0048: ldloc.3 - IL_0049: cgt - IL_004b: ret } // end of method U::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 50 (0x32) .maxstack 7 .locals init (int32 V_0) @@ -369,20 +353,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: call instance int32 StructUnion01/U::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: call instance int32 StructUnion01/U::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method U::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 52 (0x34) .maxstack 4 .locals init (valuetype StructUnion01/U V_0) @@ -418,7 +402,7 @@ .method public hidebysig virtual final instance bool Equals(valuetype StructUnion01/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 @@ -443,7 +427,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 23 (0x17) .maxstack 8 IL_0000: ldarg.1 @@ -462,9 +446,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 StructUnion01/U::get_Tag() } // end of property U::Tag .property instance int32 Item1() @@ -472,8 +456,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 StructUnion01/U::get_Item1() } // end of property U::Item1 .property instance int32 Item2() @@ -481,8 +465,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 StructUnion01/U::get_Item2() } // end of property U::Item2 } // end of class U @@ -735,7 +719,7 @@ } // end of class StructUnion01 .class private abstract auto ansi sealed ''.$StructUnion01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -751,4 +735,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\Inlining\StructUnion01_fs\StructUnion01.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\Inlining\StructUnion01_fs\StructUnion01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.debug.bsl index fa7fde26e1a..e364665021b 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.EqualsOnUnions01 { - // Offset: 0x00000000 Length: 0x0000067D + // Offset: 0x00000000 Length: 0x00000673 // WARNING: managed resource file FSharpSignatureData.EqualsOnUnions01 created } .mresource public FSharpOptimizationData.EqualsOnUnions01 { - // Offset: 0x00000688 Length: 0x000001C7 + // Offset: 0x00000678 Length: 0x000001CD // WARNING: managed resource file FSharpOptimizationData.EqualsOnUnions01 created } .module EqualsOnUnions01.exe -// MVID: {624E3948-BBFB-14A0-A745-038348394E62} +// MVID: {628F4C90-3A79-D23A-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x036B0000 +// Image base: 0x000002A4D8200000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed EqualsOnUnions01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto autochar serializable nested public beforefieldinit U - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .class abstract auto ansi sealed nested public Tags - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field public static literal int32 A = int32(0x00000000) .field public static literal int32 B = int32(0x00000001) @@ -73,16 +73,16 @@ .class auto ansi serializable nested assembly beforefieldinit specialname _A extends EqualsOnUnions01/U { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 24 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..$EqualsOnUnion - 73 30 31 2B 55 2B 5F 41 40 44 65 62 75 67 54 79 // s01+U+_A@DebugTy - 70 65 50 72 6F 78 79 00 00 ) // peProxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 24 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..$EqualsOnUnion + 73 30 31 2B 55 2B 5F 41 40 44 65 62 75 67 54 79 // s01+U+_A@DebugTy + 70 65 50 72 6F 78 79 00 00 ) // peProxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .method assembly specialname rtspecialname instance void .ctor() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -95,20 +95,20 @@ .class auto ansi serializable nested public beforefieldinit specialname B extends EqualsOnUnions01/U { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 23 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..#EqualsOnUnion - 73 30 31 2B 55 2B 42 40 44 65 62 75 67 54 79 70 // s01+U+B@DebugTyp - 65 50 72 6F 78 79 00 00 ) // eProxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 23 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..#EqualsOnUnion + 73 30 31 2B 55 2B 42 40 44 65 62 75 67 54 79 70 // s01+U+B@DebugTyp + 65 50 72 6F 78 79 00 00 ) // eProxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 @@ -122,8 +122,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,28 +136,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 EqualsOnUnions01/U/B::get_Item() } // end of property B::Item } // end of class B .class auto ansi nested assembly beforefieldinit specialname _A@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class EqualsOnUnions01/U/_A _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class EqualsOnUnions01/U/_A obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class EqualsOnUnions01/U/_A EqualsOnUnions01/U/_A@DebugTypeProxy::_obj @@ -167,21 +167,21 @@ } // end of class _A@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname B@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class EqualsOnUnions01/U/B _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class EqualsOnUnions01/U/B obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class EqualsOnUnions01/U/B EqualsOnUnions01/U/B@DebugTypeProxy::_obj @@ -191,8 +191,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -206,16 +206,16 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 EqualsOnUnions01/U/B@DebugTypeProxy::get_Item() } // end of property B@DebugTypeProxy::Item } // end of class B@DebugTypeProxy .field static assembly initonly class EqualsOnUnions01/U _unique_A - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method private specialname rtspecialname static void .cctor() cil managed { @@ -229,12 +229,12 @@ .method assembly specialname rtspecialname instance void .ctor() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ret } // end of method U::.ctor @@ -252,8 +252,8 @@ .method public hidebysig instance bool get_IsA() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -278,8 +278,8 @@ .method public hidebysig instance bool get_IsB() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -292,8 +292,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -310,8 +310,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -325,7 +325,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -339,26 +339,26 @@ .method public hidebysig virtual final instance int32 CompareTo(class EqualsOnUnions01/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 137 (0x89) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 136 (0x88) + .maxstack 5 .locals init (int32 V_0, class EqualsOnUnions01/U V_1, int32 V_2, class EqualsOnUnions01/U V_3, class EqualsOnUnions01/U/B V_4, class EqualsOnUnions01/U/B V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8, - class [mscorlib]System.Collections.IComparer V_9, + class [System.Runtime]System.Collections.IComparer V_9, int32 V_10, int32 V_11) IL_0000: ldarg.0 - IL_0001: brfalse IL_0082 + IL_0001: brfalse IL_0081 IL_0006: ldarg.1 - IL_0007: brfalse IL_0080 + IL_0007: brfalse IL_007f IL_000c: ldarg.0 IL_000d: stloc.1 @@ -384,11 +384,11 @@ IL_0029: stloc.2 IL_002a: ldloc.0 IL_002b: ldloc.2 - IL_002c: bne.un.s IL_007c + IL_002c: bne.un.s IL_007b IL_002e: ldarg.0 IL_002f: isinst EqualsOnUnions01/U/B - IL_0034: brfalse.s IL_007a + IL_0034: brfalse.s IL_0079 IL_0036: ldarg.0 IL_0037: castclass EqualsOnUnions01/U/B @@ -396,7 +396,7 @@ IL_003e: ldarg.1 IL_003f: castclass EqualsOnUnions01/U/B IL_0044: stloc.s V_5 - IL_0046: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0046: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_004b: stloc.s V_6 IL_004d: ldloc.s V_4 IL_004f: ldfld int32 EqualsOnUnions01/U/B::item @@ -412,41 +412,38 @@ IL_0069: stloc.s V_11 IL_006b: ldloc.s V_10 IL_006d: ldloc.s V_11 - IL_006f: bge.s IL_0073 - - IL_0071: ldc.i4.m1 - IL_0072: ret + IL_006f: cgt + IL_0071: ldloc.s V_10 + IL_0073: ldloc.s V_11 + IL_0075: clt + IL_0077: sub + IL_0078: ret - IL_0073: ldloc.s V_10 - IL_0075: ldloc.s V_11 - IL_0077: cgt - IL_0079: ret - - IL_007a: ldc.i4.0 - IL_007b: ret + IL_0079: ldc.i4.0 + IL_007a: ret - IL_007c: ldloc.0 - IL_007d: ldloc.2 - IL_007e: sub - IL_007f: ret + IL_007b: ldloc.0 + IL_007c: ldloc.2 + IL_007d: sub + IL_007e: ret - IL_0080: ldc.i4.1 - IL_0081: ret + IL_007f: ldc.i4.1 + IL_0080: ret - IL_0082: ldarg.1 - IL_0083: brfalse.s IL_0087 + IL_0081: ldarg.1 + IL_0082: brfalse.s IL_0086 - IL_0085: ldc.i4.m1 - IL_0086: ret + IL_0084: ldc.i4.m1 + IL_0085: ret - IL_0087: ldc.i4.0 - IL_0088: ret + IL_0086: ldc.i4.0 + IL_0087: ret } // end of method U::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -458,11 +455,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 152 (0x98) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 151 (0x97) + .maxstack 5 .locals init (class EqualsOnUnions01/U V_0, int32 V_1, class EqualsOnUnions01/U V_2, @@ -470,21 +467,21 @@ class EqualsOnUnions01/U V_4, class EqualsOnUnions01/U/B V_5, class EqualsOnUnions01/U/B V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9, - class [mscorlib]System.Collections.IComparer V_10, + class [System.Runtime]System.Collections.IComparer V_10, int32 V_11, int32 V_12) IL_0000: ldarg.1 IL_0001: unbox.any EqualsOnUnions01/U IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse IL_008c + IL_0008: brfalse IL_008b IL_000d: ldarg.1 IL_000e: unbox.any EqualsOnUnions01/U - IL_0013: brfalse IL_008a + IL_0013: brfalse IL_0089 IL_0018: ldarg.0 IL_0019: stloc.2 @@ -510,11 +507,11 @@ IL_0037: stloc.3 IL_0038: ldloc.1 IL_0039: ldloc.3 - IL_003a: bne.un.s IL_0086 + IL_003a: bne.un.s IL_0085 IL_003c: ldarg.0 IL_003d: isinst EqualsOnUnions01/U/B - IL_0042: brfalse.s IL_0084 + IL_0042: brfalse.s IL_0083 IL_0044: ldarg.0 IL_0045: castclass EqualsOnUnions01/U/B @@ -538,49 +535,46 @@ IL_0073: stloc.s V_12 IL_0075: ldloc.s V_11 IL_0077: ldloc.s V_12 - IL_0079: bge.s IL_007d - - IL_007b: ldc.i4.m1 - IL_007c: ret - - IL_007d: ldloc.s V_11 - IL_007f: ldloc.s V_12 - IL_0081: cgt - IL_0083: ret - - IL_0084: ldc.i4.0 - IL_0085: ret - - IL_0086: ldloc.1 - IL_0087: ldloc.3 - IL_0088: sub - IL_0089: ret + IL_0079: cgt + IL_007b: ldloc.s V_11 + IL_007d: ldloc.s V_12 + IL_007f: clt + IL_0081: sub + IL_0082: ret + + IL_0083: ldc.i4.0 + IL_0084: ret + + IL_0085: ldloc.1 + IL_0086: ldloc.3 + IL_0087: sub + IL_0088: ret - IL_008a: ldc.i4.1 - IL_008b: ret + IL_0089: ldc.i4.1 + IL_008a: ret - IL_008c: ldarg.1 - IL_008d: unbox.any EqualsOnUnions01/U - IL_0092: brfalse.s IL_0096 + IL_008b: ldarg.1 + IL_008c: unbox.any EqualsOnUnions01/U + IL_0091: brfalse.s IL_0095 - IL_0094: ldc.i4.m1 - IL_0095: ret + IL_0093: ldc.i4.m1 + IL_0094: ret - IL_0096: ldc.i4.0 - IL_0097: ret + IL_0095: ldc.i4.0 + IL_0096: ret } // end of method U::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 71 (0x47) .maxstack 7 .locals init (int32 V_0, class EqualsOnUnions01/U/B V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, class EqualsOnUnions01/U V_5) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0045 @@ -637,20 +631,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 EqualsOnUnions01/U::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 EqualsOnUnions01/U::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method U::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 126 (0x7e) .maxstack 4 .locals init (class EqualsOnUnions01/U V_0, @@ -661,10 +655,10 @@ class EqualsOnUnions01/U V_5, class EqualsOnUnions01/U/B V_6, class EqualsOnUnions01/U/B V_7, - class [mscorlib]System.Collections.IEqualityComparer V_8, + class [System.Runtime]System.Collections.IEqualityComparer V_8, int32 V_9, int32 V_10, - class [mscorlib]System.Collections.IEqualityComparer V_11) + class [System.Runtime]System.Collections.IEqualityComparer V_11) IL_0000: ldarg.0 IL_0001: brfalse IL_0076 @@ -747,7 +741,7 @@ .method public hidebysig virtual final instance bool Equals(class EqualsOnUnions01/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 95 (0x5f) .maxstack 4 .locals init (int32 V_0, @@ -825,7 +819,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class EqualsOnUnions01/U V_0) @@ -846,30 +840,30 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 EqualsOnUnions01/U::get_Tag() } // end of property U::Tag .property class EqualsOnUnions01/U A() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get class EqualsOnUnions01/U EqualsOnUnions01/U::get_A() } // end of property U::A .property instance bool IsA() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool EqualsOnUnions01/U::get_IsA() } // end of property U::IsA .property instance bool IsB() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool EqualsOnUnions01/U::get_IsB() } // end of property U::IsB } // end of class U @@ -877,7 +871,7 @@ } // end of class EqualsOnUnions01 .class private abstract auto ansi sealed ''.$EqualsOnUnions01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -893,4 +887,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\Misc\EqualsOnUnions01_fs\EqualsOnUnions01.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\Misc\EqualsOnUnions01_fs\EqualsOnUnions01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.release.bsl index b9657c69cb1..d71aaabcf5a 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/EqualsOnUnions01.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.EqualsOnUnions01 { - // Offset: 0x00000000 Length: 0x00000681 + // Offset: 0x00000000 Length: 0x00000691 // WARNING: managed resource file FSharpSignatureData.EqualsOnUnions01 created } .mresource public FSharpOptimizationData.EqualsOnUnions01 { - // Offset: 0x00000688 Length: 0x000001C7 + // Offset: 0x00000698 Length: 0x000001CD // WARNING: managed resource file FSharpOptimizationData.EqualsOnUnions01 created } .module EqualsOnUnions01.exe -// MVID: {624E382D-BBFB-14A0-A745-03832D384E62} +// MVID: {628FBBC7-134D-7F80-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03CA0000 +// Image base: 0x000001B02C300000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed EqualsOnUnions01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class abstract auto autochar serializable nested public beforefieldinit U - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .class abstract auto ansi sealed nested public Tags - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field public static literal int32 A = int32(0x00000000) .field public static literal int32 B = int32(0x00000001) @@ -73,16 +73,16 @@ .class auto ansi serializable nested assembly beforefieldinit specialname _A extends EqualsOnUnions01/U { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 24 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..$EqualsOnUnion - 73 30 31 2B 55 2B 5F 41 40 44 65 62 75 67 54 79 // s01+U+_A@DebugTy - 70 65 50 72 6F 78 79 00 00 ) // peProxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 24 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..$EqualsOnUnion + 73 30 31 2B 55 2B 5F 41 40 44 65 62 75 67 54 79 // s01+U+_A@DebugTy + 70 65 50 72 6F 78 79 00 00 ) // peProxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .method assembly specialname rtspecialname instance void .ctor() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -95,20 +95,20 @@ .class auto ansi serializable nested public beforefieldinit specialname B extends EqualsOnUnions01/U { - .custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 23 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..#EqualsOnUnion - 73 30 31 2B 55 2B 42 40 44 65 62 75 67 54 79 70 // s01+U+B@DebugTyp - 65 50 72 6F 78 79 00 00 ) // eProxy.. - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [System.Runtime]System.Type) = ( 01 00 23 45 71 75 61 6C 73 4F 6E 55 6E 69 6F 6E // ..#EqualsOnUnion + 73 30 31 2B 55 2B 42 40 44 65 62 75 67 54 79 70 // s01+U+B@DebugTyp + 65 50 72 6F 78 79 00 00 ) // eProxy.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 @@ -122,8 +122,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -136,28 +136,28 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 EqualsOnUnions01/U/B::get_Item() } // end of property B::Item } // end of class B .class auto ansi nested assembly beforefieldinit specialname _A@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class EqualsOnUnions01/U/_A _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class EqualsOnUnions01/U/_A obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class EqualsOnUnions01/U/_A EqualsOnUnions01/U/_A@DebugTypeProxy::_obj @@ -167,21 +167,21 @@ } // end of class _A@DebugTypeProxy .class auto ansi nested assembly beforefieldinit specialname B@DebugTypeProxy - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field assembly class EqualsOnUnions01/U/B _obj - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor(class EqualsOnUnions01/U/B obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld class EqualsOnUnions01/U/B EqualsOnUnions01/U/B@DebugTypeProxy::_obj @@ -191,8 +191,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 @@ -206,16 +206,16 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 EqualsOnUnions01/U/B@DebugTypeProxy::get_Item() } // end of property B@DebugTypeProxy::Item } // end of class B@DebugTypeProxy .field static assembly initonly class EqualsOnUnions01/U _unique_A - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method private specialname rtspecialname static void .cctor() cil managed { @@ -229,12 +229,12 @@ .method assembly specialname rtspecialname instance void .ctor() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ret } // end of method U::.ctor @@ -252,8 +252,8 @@ .method public hidebysig instance bool get_IsA() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -278,8 +278,8 @@ .method public hidebysig instance bool get_IsB() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 10 (0xa) .maxstack 8 IL_0000: ldarg.0 @@ -292,8 +292,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -310,8 +310,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -325,7 +325,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -339,23 +339,23 @@ .method public hidebysig virtual final instance int32 CompareTo(class EqualsOnUnions01/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 122 (0x7a) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 121 (0x79) + .maxstack 5 .locals init (int32 V_0, class EqualsOnUnions01/U V_1, int32 V_2, class EqualsOnUnions01/U V_3, class EqualsOnUnions01/U/B V_4, class EqualsOnUnions01/U/B V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.0 - IL_0001: brfalse IL_0073 + IL_0001: brfalse IL_0072 IL_0006: ldarg.1 - IL_0007: brfalse.s IL_0071 + IL_0007: brfalse.s IL_0070 IL_0009: ldarg.0 IL_000a: stloc.1 @@ -381,11 +381,11 @@ IL_0026: stloc.2 IL_0027: ldloc.0 IL_0028: ldloc.2 - IL_0029: bne.un.s IL_006d + IL_0029: bne.un.s IL_006c IL_002b: ldarg.0 IL_002c: isinst EqualsOnUnions01/U/B - IL_0031: brfalse.s IL_006b + IL_0031: brfalse.s IL_006a IL_0033: ldarg.0 IL_0034: castclass EqualsOnUnions01/U/B @@ -393,7 +393,7 @@ IL_003b: ldarg.1 IL_003c: castclass EqualsOnUnions01/U/B IL_0041: stloc.s V_5 - IL_0043: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0043: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0048: stloc.s V_6 IL_004a: ldloc.s V_4 IL_004c: ldfld int32 EqualsOnUnions01/U/B::item @@ -403,41 +403,38 @@ IL_005a: stloc.s V_8 IL_005c: ldloc.s V_7 IL_005e: ldloc.s V_8 - IL_0060: bge.s IL_0064 - - IL_0062: ldc.i4.m1 - IL_0063: ret + IL_0060: cgt + IL_0062: ldloc.s V_7 + IL_0064: ldloc.s V_8 + IL_0066: clt + IL_0068: sub + IL_0069: ret - IL_0064: ldloc.s V_7 - IL_0066: ldloc.s V_8 - IL_0068: cgt - IL_006a: ret - - IL_006b: ldc.i4.0 - IL_006c: ret + IL_006a: ldc.i4.0 + IL_006b: ret - IL_006d: ldloc.0 - IL_006e: ldloc.2 - IL_006f: sub - IL_0070: ret + IL_006c: ldloc.0 + IL_006d: ldloc.2 + IL_006e: sub + IL_006f: ret - IL_0071: ldc.i4.1 - IL_0072: ret + IL_0070: ldc.i4.1 + IL_0071: ret - IL_0073: ldarg.1 - IL_0074: brfalse.s IL_0078 + IL_0072: ldarg.1 + IL_0073: brfalse.s IL_0077 - IL_0076: ldc.i4.m1 - IL_0077: ret + IL_0075: ldc.i4.m1 + IL_0076: ret - IL_0078: ldc.i4.0 - IL_0079: ret + IL_0077: ldc.i4.0 + IL_0078: ret } // end of method U::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -449,11 +446,11 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 137 (0x89) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 136 (0x88) + .maxstack 5 .locals init (class EqualsOnUnions01/U V_0, int32 V_1, class EqualsOnUnions01/U V_2, @@ -461,18 +458,18 @@ class EqualsOnUnions01/U V_4, class EqualsOnUnions01/U/B V_5, class EqualsOnUnions01/U/B V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9) IL_0000: ldarg.1 IL_0001: unbox.any EqualsOnUnions01/U IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse IL_007d + IL_0008: brfalse IL_007c IL_000d: ldarg.1 IL_000e: unbox.any EqualsOnUnions01/U - IL_0013: brfalse.s IL_007b + IL_0013: brfalse.s IL_007a IL_0015: ldarg.0 IL_0016: stloc.2 @@ -498,11 +495,11 @@ IL_0034: stloc.3 IL_0035: ldloc.1 IL_0036: ldloc.3 - IL_0037: bne.un.s IL_0077 + IL_0037: bne.un.s IL_0076 IL_0039: ldarg.0 IL_003a: isinst EqualsOnUnions01/U/B - IL_003f: brfalse.s IL_0075 + IL_003f: brfalse.s IL_0074 IL_0041: ldarg.0 IL_0042: castclass EqualsOnUnions01/U/B @@ -520,47 +517,44 @@ IL_0064: stloc.s V_9 IL_0066: ldloc.s V_8 IL_0068: ldloc.s V_9 - IL_006a: bge.s IL_006e - - IL_006c: ldc.i4.m1 - IL_006d: ret - - IL_006e: ldloc.s V_8 - IL_0070: ldloc.s V_9 - IL_0072: cgt - IL_0074: ret - - IL_0075: ldc.i4.0 - IL_0076: ret - - IL_0077: ldloc.1 - IL_0078: ldloc.3 - IL_0079: sub - IL_007a: ret + IL_006a: cgt + IL_006c: ldloc.s V_8 + IL_006e: ldloc.s V_9 + IL_0070: clt + IL_0072: sub + IL_0073: ret + + IL_0074: ldc.i4.0 + IL_0075: ret + + IL_0076: ldloc.1 + IL_0077: ldloc.3 + IL_0078: sub + IL_0079: ret - IL_007b: ldc.i4.1 - IL_007c: ret + IL_007a: ldc.i4.1 + IL_007b: ret - IL_007d: ldarg.1 - IL_007e: unbox.any EqualsOnUnions01/U - IL_0083: brfalse.s IL_0087 + IL_007c: ldarg.1 + IL_007d: unbox.any EqualsOnUnions01/U + IL_0082: brfalse.s IL_0086 - IL_0085: ldc.i4.m1 - IL_0086: ret + IL_0084: ldc.i4.m1 + IL_0085: ret - IL_0087: ldc.i4.0 - IL_0088: ret + IL_0086: ldc.i4.0 + IL_0087: ret } // end of method U::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 64 (0x40) .maxstack 7 .locals init (int32 V_0, class EqualsOnUnions01/U/B V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, class EqualsOnUnions01/U V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003e @@ -613,20 +607,20 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 EqualsOnUnions01/U::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 EqualsOnUnions01/U::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method U::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 111 (0x6f) .maxstack 4 .locals init (class EqualsOnUnions01/U V_0, @@ -637,7 +631,7 @@ class EqualsOnUnions01/U V_5, class EqualsOnUnions01/U/B V_6, class EqualsOnUnions01/U/B V_7, - class [mscorlib]System.Collections.IEqualityComparer V_8) + class [System.Runtime]System.Collections.IEqualityComparer V_8) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0067 @@ -714,7 +708,7 @@ .method public hidebysig virtual final instance bool Equals(class EqualsOnUnions01/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 95 (0x5f) .maxstack 4 .locals init (int32 V_0, @@ -792,7 +786,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class EqualsOnUnions01/U V_0) @@ -813,30 +807,30 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 EqualsOnUnions01/U::get_Tag() } // end of property U::Tag .property class EqualsOnUnions01/U A() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get class EqualsOnUnions01/U EqualsOnUnions01/U::get_A() } // end of property U::A .property instance bool IsA() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool EqualsOnUnions01/U::get_IsA() } // end of property U::IsA .property instance bool IsB() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance bool EqualsOnUnions01/U::get_IsB() } // end of property U::IsB } // end of class U @@ -844,7 +838,7 @@ } // end of class EqualsOnUnions01 .class private abstract auto ansi sealed ''.$EqualsOnUnions01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -860,4 +854,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\Misc\EqualsOnUnions01_fs\EqualsOnUnions01.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\Misc\EqualsOnUnions01_fs\EqualsOnUnions01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.debug.bsl index 322039b5737..7c310b26824 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,63 +21,63 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Structs01 { - // Offset: 0x00000000 Length: 0x00000777 + // Offset: 0x00000000 Length: 0x0000076D // WARNING: managed resource file FSharpSignatureData.Structs01 created } .mresource public FSharpOptimizationData.Structs01 { - // Offset: 0x00000780 Length: 0x00000231 + // Offset: 0x00000778 Length: 0x00000237 // WARNING: managed resource file FSharpOptimizationData.Structs01 created } .module Structs01.exe -// MVID: {624E3948-701F-5E27-A745-038348394E62} +// MVID: {628F4C90-ED12-88DB-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x052A0000 +// Image base: 0x0000015E059D0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Experiment.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class sequential ansi serializable sealed nested public Test - extends [mscorlib]System.ValueType - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.ValueType + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field public int32 Field .method public hidebysig virtual final instance int32 CompareTo(valuetype Experiment.Test/Test obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 47 (0x2f) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 46 (0x2e) + .maxstack 5 .locals init (valuetype Experiment.Test/Test& V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6) IL_0000: ldarga.s obj IL_0002: stloc.0 - IL_0003: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0003: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldfld int32 Experiment.Test/Test::Field @@ -93,21 +93,18 @@ IL_001e: stloc.s V_6 IL_0020: ldloc.s V_5 IL_0022: ldloc.s V_6 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.s V_5 - IL_002a: ldloc.s V_6 - IL_002c: cgt - IL_002e: ret + IL_0024: cgt + IL_0026: ldloc.s V_5 + IL_0028: ldloc.s V_6 + IL_002a: clt + IL_002c: sub + IL_002d: ret } // end of method Test::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -119,17 +116,17 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 52 (0x34) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 51 (0x33) + .maxstack 5 .locals init (valuetype Experiment.Test/Test V_0, valuetype Experiment.Test/Test& V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.1 @@ -153,27 +150,24 @@ IL_0023: stloc.s V_7 IL_0025: ldloc.s V_6 IL_0027: ldloc.s V_7 - IL_0029: bge.s IL_002d - - IL_002b: ldc.i4.m1 - IL_002c: ret - - IL_002d: ldloc.s V_6 - IL_002f: ldloc.s V_7 - IL_0031: cgt - IL_0033: ret + IL_0029: cgt + IL_002b: ldloc.s V_6 + IL_002d: ldloc.s V_7 + IL_002f: clt + IL_0031: sub + IL_0032: ret } // end of method Test::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 31 (0x1f) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4 0x9e3779b9 @@ -202,29 +196,29 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: call instance int32 Experiment.Test/Test::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: call instance int32 Experiment.Test/Test::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Test::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (object V_0, valuetype Experiment.Test/Test V_1, valuetype Experiment.Test/Test& V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 @@ -271,7 +265,7 @@ .method public hidebysig virtual final instance bool Equals(valuetype Experiment.Test/Test obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 18 (0x12) .maxstack 4 .locals init (valuetype Experiment.Test/Test& V_0) @@ -288,7 +282,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 30 (0x1e) .maxstack 4 .locals init (object V_0, @@ -331,7 +325,7 @@ } // end of class Experiment.Test .class private abstract auto ansi sealed '.$Experiment'.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -347,4 +341,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\Misc\Structs01_fs\Structs01.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\Misc\Structs01_fs\Structs01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.release.bsl index 7fa59f10ce1..fab1602c18a 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs01.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,60 +21,60 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Structs01 { - // Offset: 0x00000000 Length: 0x0000077C + // Offset: 0x00000000 Length: 0x0000078C // WARNING: managed resource file FSharpSignatureData.Structs01 created } .mresource public FSharpOptimizationData.Structs01 { - // Offset: 0x00000780 Length: 0x00000231 + // Offset: 0x00000790 Length: 0x00000237 // WARNING: managed resource file FSharpOptimizationData.Structs01 created } .module Structs01.exe -// MVID: {624E382D-701F-5E27-A745-03832D384E62} +// MVID: {628FBBC7-63FE-A29D-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03890000 +// Image base: 0x0000026623040000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Experiment.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class sequential ansi serializable sealed nested public Test - extends [mscorlib]System.ValueType - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.ValueType + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field public int32 Field .method public hidebysig virtual final instance int32 CompareTo(valuetype Experiment.Test/Test obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 34 (0x22) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 33 (0x21) + .maxstack 5 .locals init (valuetype Experiment.Test/Test& V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3) IL_0000: ldarga.s obj IL_0002: stloc.0 - IL_0003: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0003: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldfld int32 Experiment.Test/Test::Field @@ -84,21 +84,18 @@ IL_0016: stloc.3 IL_0017: ldloc.2 IL_0018: ldloc.3 - IL_0019: bge.s IL_001d - - IL_001b: ldc.i4.m1 - IL_001c: ret - - IL_001d: ldloc.2 - IL_001e: ldloc.3 - IL_001f: cgt - IL_0021: ret + IL_0019: cgt + IL_001b: ldloc.2 + IL_001c: ldloc.3 + IL_001d: clt + IL_001f: sub + IL_0020: ret } // end of method Test::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -110,14 +107,14 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 40 (0x28) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 39 (0x27) + .maxstack 5 .locals init (valuetype Experiment.Test/Test V_0, valuetype Experiment.Test/Test& V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.1 @@ -135,25 +132,22 @@ IL_0019: stloc.s V_4 IL_001b: ldloc.3 IL_001c: ldloc.s V_4 - IL_001e: bge.s IL_0022 - - IL_0020: ldc.i4.m1 - IL_0021: ret - - IL_0022: ldloc.3 - IL_0023: ldloc.s V_4 - IL_0025: cgt - IL_0027: ret + IL_001e: cgt + IL_0020: ldloc.3 + IL_0021: ldloc.s V_4 + IL_0023: clt + IL_0025: sub + IL_0026: ret } // end of method Test::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 27 (0x1b) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4 0x9e3779b9 @@ -178,26 +172,26 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: call instance int32 Experiment.Test/Test::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: call instance int32 Experiment.Test/Test::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Test::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 42 (0x2a) .maxstack 4 .locals init (object V_0, valuetype Experiment.Test/Test V_1, valuetype Experiment.Test/Test& V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 @@ -238,7 +232,7 @@ .method public hidebysig virtual final instance bool Equals(valuetype Experiment.Test/Test obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 18 (0x12) .maxstack 4 .locals init (valuetype Experiment.Test/Test& V_0) @@ -255,7 +249,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 30 (0x1e) .maxstack 4 .locals init (object V_0, @@ -298,7 +292,7 @@ } // end of class Experiment.Test .class private abstract auto ansi sealed '.$Experiment'.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -314,4 +308,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\Misc\Structs01_fs\Structs01.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\Misc\Structs01_fs\Structs01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.debug.bsl index e93c7197b53..cc8f56cd993 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,44 +21,44 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Structs02 { - // Offset: 0x00000000 Length: 0x000007B1 + // Offset: 0x00000000 Length: 0x000007A7 // WARNING: managed resource file FSharpSignatureData.Structs02 created } .mresource public FSharpOptimizationData.Structs02 { - // Offset: 0x000007B8 Length: 0x00000237 + // Offset: 0x000007B0 Length: 0x0000023D // WARNING: managed resource file FSharpOptimizationData.Structs02 created } .module Structs02.exe -// MVID: {624E3948-7040-5E27-A745-038348394E62} +// MVID: {628F4C90-A85C-11CB-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03310000 +// Image base: 0x00000200752B0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Experiment.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class sequential ansi serializable sealed nested public Repro - extends [mscorlib]System.ValueType - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.ValueType + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.StructAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) @@ -66,6 +66,7 @@ .method public hidebysig specialname instance int32 get_hash() cil managed { + .custom instance void [runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -76,19 +77,19 @@ .method public hidebysig virtual final instance int32 CompareTo(valuetype Experiment.Test/Repro obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 47 (0x2f) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 46 (0x2e) + .maxstack 5 .locals init (valuetype Experiment.Test/Repro& V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6) IL_0000: ldarga.s obj IL_0002: stloc.0 - IL_0003: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0003: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldfld int32 Experiment.Test/Repro::hash@ @@ -104,21 +105,18 @@ IL_001e: stloc.s V_6 IL_0020: ldloc.s V_5 IL_0022: ldloc.s V_6 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.s V_5 - IL_002a: ldloc.s V_6 - IL_002c: cgt - IL_002e: ret + IL_0024: cgt + IL_0026: ldloc.s V_5 + IL_0028: ldloc.s V_6 + IL_002a: clt + IL_002c: sub + IL_002d: ret } // end of method Repro::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -130,17 +128,17 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 52 (0x34) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 51 (0x33) + .maxstack 5 .locals init (valuetype Experiment.Test/Repro V_0, valuetype Experiment.Test/Repro& V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.1 @@ -164,27 +162,24 @@ IL_0023: stloc.s V_7 IL_0025: ldloc.s V_6 IL_0027: ldloc.s V_7 - IL_0029: bge.s IL_002d - - IL_002b: ldc.i4.m1 - IL_002c: ret - - IL_002d: ldloc.s V_6 - IL_002f: ldloc.s V_7 - IL_0031: cgt - IL_0033: ret + IL_0029: cgt + IL_002b: ldloc.s V_6 + IL_002d: ldloc.s V_7 + IL_002f: clt + IL_0031: sub + IL_0032: ret } // end of method Repro::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 31 (0x1f) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4 0x9e3779b9 @@ -213,29 +208,29 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: call instance int32 Experiment.Test/Repro::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: call instance int32 Experiment.Test/Repro::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Repro::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (object V_0, valuetype Experiment.Test/Repro V_1, valuetype Experiment.Test/Repro& V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 @@ -314,7 +309,7 @@ .method public hidebysig virtual final instance bool Equals(valuetype Experiment.Test/Repro obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 18 (0x12) .maxstack 4 .locals init (valuetype Experiment.Test/Repro& V_0) @@ -331,7 +326,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 30 (0x1e) .maxstack 4 .locals init (object V_0, @@ -380,7 +375,7 @@ } // end of class Experiment.Test .class private abstract auto ansi sealed '.$Experiment'.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -396,4 +391,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\Misc\Structs02_fs\Structs02.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\Misc\Structs02_fs\Structs02.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.release.bsl index 4f963bb223b..ed4eefc32ed 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/Structs02.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,44 +21,44 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.Structs02 { - // Offset: 0x00000000 Length: 0x000007B6 + // Offset: 0x00000000 Length: 0x000007C6 // WARNING: managed resource file FSharpSignatureData.Structs02 created } .mresource public FSharpOptimizationData.Structs02 { - // Offset: 0x000007C0 Length: 0x00000237 + // Offset: 0x000007D0 Length: 0x0000023D // WARNING: managed resource file FSharpOptimizationData.Structs02 created } .module Structs02.exe -// MVID: {624E382D-7040-5E27-A745-03832D384E62} +// MVID: {628FBBC7-2059-FCB3-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03840000 +// Image base: 0x00000201110E0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed Experiment.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class sequential ansi serializable sealed nested public Repro - extends [mscorlib]System.ValueType - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.ValueType + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.StructAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) @@ -66,6 +66,7 @@ .method public hidebysig specialname instance int32 get_hash() cil managed { + .custom instance void [runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -76,16 +77,16 @@ .method public hidebysig virtual final instance int32 CompareTo(valuetype Experiment.Test/Repro obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 34 (0x22) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 33 (0x21) + .maxstack 5 .locals init (valuetype Experiment.Test/Repro& V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3) IL_0000: ldarga.s obj IL_0002: stloc.0 - IL_0003: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0003: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldfld int32 Experiment.Test/Repro::hash@ @@ -95,21 +96,18 @@ IL_0016: stloc.3 IL_0017: ldloc.2 IL_0018: ldloc.3 - IL_0019: bge.s IL_001d - - IL_001b: ldc.i4.m1 - IL_001c: ret - - IL_001d: ldloc.2 - IL_001e: ldloc.3 - IL_001f: cgt - IL_0021: ret + IL_0019: cgt + IL_001b: ldloc.2 + IL_001c: ldloc.3 + IL_001d: clt + IL_001f: sub + IL_0020: ret } // end of method Repro::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -121,14 +119,14 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 40 (0x28) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 39 (0x27) + .maxstack 5 .locals init (valuetype Experiment.Test/Repro V_0, valuetype Experiment.Test/Repro& V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.1 @@ -146,25 +144,22 @@ IL_0019: stloc.s V_4 IL_001b: ldloc.3 IL_001c: ldloc.s V_4 - IL_001e: bge.s IL_0022 - - IL_0020: ldc.i4.m1 - IL_0021: ret - - IL_0022: ldloc.3 - IL_0023: ldloc.s V_4 - IL_0025: cgt - IL_0027: ret + IL_001e: cgt + IL_0020: ldloc.3 + IL_0021: ldloc.s V_4 + IL_0023: clt + IL_0025: sub + IL_0026: ret } // end of method Repro::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 27 (0x1b) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4 0x9e3779b9 @@ -189,26 +184,26 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: call instance int32 Experiment.Test/Repro::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: call instance int32 Experiment.Test/Repro::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Repro::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 42 (0x2a) .maxstack 4 .locals init (object V_0, valuetype Experiment.Test/Repro V_1, valuetype Experiment.Test/Repro& V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 @@ -281,7 +276,7 @@ .method public hidebysig virtual final instance bool Equals(valuetype Experiment.Test/Repro obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 18 (0x12) .maxstack 4 .locals init (valuetype Experiment.Test/Repro& V_0) @@ -298,7 +293,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 30 (0x1e) .maxstack 4 .locals init (object V_0, @@ -347,7 +342,7 @@ } // end of class Experiment.Test .class private abstract auto ansi sealed '.$Experiment'.Test - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -363,4 +358,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\Misc\Structs02_fs\Structs02.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\Misc\Structs02_fs\Structs02.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.bsl index 7a53b8f06a4..8f04d1e815d 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,44 +21,44 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.StructsAsArrayElements01 { - // Offset: 0x00000000 Length: 0x0000079E + // Offset: 0x00000000 Length: 0x00000794 // WARNING: managed resource file FSharpSignatureData.StructsAsArrayElements01 created } .mresource public FSharpOptimizationData.StructsAsArrayElements01 { - // Offset: 0x000007A8 Length: 0x0000022C + // Offset: 0x00000798 Length: 0x00000232 // WARNING: managed resource file FSharpOptimizationData.StructsAsArrayElements01 created } .module StructsAsArrayElements01.exe -// MVID: {624E3948-B2AF-FECC-A745-038348394E62} +// MVID: {628F4C90-460B-6F2F-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03790000 +// Image base: 0x000002012B2F0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed StructsAsArrayElements01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class sequential ansi serializable sealed nested public T - extends [mscorlib]System.ValueType - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.ValueType + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.StructAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) @@ -66,19 +66,19 @@ .method public hidebysig virtual final instance int32 CompareTo(valuetype StructsAsArrayElements01/T obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 47 (0x2f) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 46 (0x2e) + .maxstack 5 .locals init (valuetype StructsAsArrayElements01/T& V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6) IL_0000: ldarga.s obj IL_0002: stloc.0 - IL_0003: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0003: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldfld int32 StructsAsArrayElements01/T::i @@ -94,21 +94,18 @@ IL_001e: stloc.s V_6 IL_0020: ldloc.s V_5 IL_0022: ldloc.s V_6 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.s V_5 - IL_002a: ldloc.s V_6 - IL_002c: cgt - IL_002e: ret + IL_0024: cgt + IL_0026: ldloc.s V_5 + IL_0028: ldloc.s V_6 + IL_002a: clt + IL_002c: sub + IL_002d: ret } // end of method T::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -120,17 +117,17 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 52 (0x34) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 51 (0x33) + .maxstack 5 .locals init (valuetype StructsAsArrayElements01/T V_0, valuetype StructsAsArrayElements01/T& V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.1 @@ -154,27 +151,24 @@ IL_0023: stloc.s V_7 IL_0025: ldloc.s V_6 IL_0027: ldloc.s V_7 - IL_0029: bge.s IL_002d - - IL_002b: ldc.i4.m1 - IL_002c: ret - - IL_002d: ldloc.s V_6 - IL_002f: ldloc.s V_7 - IL_0031: cgt - IL_0033: ret + IL_0029: cgt + IL_002b: ldloc.s V_6 + IL_002d: ldloc.s V_7 + IL_002f: clt + IL_0031: sub + IL_0032: ret } // end of method T::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 31 (0x1f) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4 0x9e3779b9 @@ -203,29 +197,29 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: call instance int32 StructsAsArrayElements01/T::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: call instance int32 StructsAsArrayElements01/T::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method T::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (object V_0, valuetype StructsAsArrayElements01/T V_1, valuetype StructsAsArrayElements01/T& V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 @@ -272,7 +266,7 @@ .method public hidebysig virtual final instance bool Equals(valuetype StructsAsArrayElements01/T obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 18 (0x12) .maxstack 4 .locals init (valuetype StructsAsArrayElements01/T& V_0) @@ -289,7 +283,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 30 (0x1e) .maxstack 4 .locals init (object V_0, @@ -334,14 +328,14 @@ } // end of class StructsAsArrayElements01 .class private abstract auto ansi sealed ''.$StructsAsArrayElements01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly valuetype StructsAsArrayElements01/T[] a@11 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -371,4 +365,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\Misc\StructsAsArrayElements01_fs\StructsAsArrayElements01.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\Misc\StructsAsArrayElements01_fs\StructsAsArrayElements01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.release.bsl index c23b1b8a739..10db4563bb1 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Misc/StructsAsArrayElements01.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,44 +21,44 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.StructsAsArrayElements01 { - // Offset: 0x00000000 Length: 0x000007A2 + // Offset: 0x00000000 Length: 0x000007B2 // WARNING: managed resource file FSharpSignatureData.StructsAsArrayElements01 created } .mresource public FSharpOptimizationData.StructsAsArrayElements01 { - // Offset: 0x000007A8 Length: 0x0000022C + // Offset: 0x000007B8 Length: 0x00000232 // WARNING: managed resource file FSharpOptimizationData.StructsAsArrayElements01 created } .module StructsAsArrayElements01.exe -// MVID: {624E382D-B2AF-FECC-A745-03832D384E62} +// MVID: {628FBBC7-C00B-FCA6-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03480000 +// Image base: 0x000002105FF00000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed StructsAsArrayElements01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class sequential ansi serializable sealed nested public T - extends [mscorlib]System.ValueType - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.ValueType + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.StructAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) @@ -66,16 +66,16 @@ .method public hidebysig virtual final instance int32 CompareTo(valuetype StructsAsArrayElements01/T obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 34 (0x22) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 33 (0x21) + .maxstack 5 .locals init (valuetype StructsAsArrayElements01/T& V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3) IL_0000: ldarga.s obj IL_0002: stloc.0 - IL_0003: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0003: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldfld int32 StructsAsArrayElements01/T::i @@ -85,21 +85,18 @@ IL_0016: stloc.3 IL_0017: ldloc.2 IL_0018: ldloc.3 - IL_0019: bge.s IL_001d - - IL_001b: ldc.i4.m1 - IL_001c: ret - - IL_001d: ldloc.2 - IL_001e: ldloc.3 - IL_001f: cgt - IL_0021: ret + IL_0019: cgt + IL_001b: ldloc.2 + IL_001c: ldloc.3 + IL_001d: clt + IL_001f: sub + IL_0020: ret } // end of method T::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -111,14 +108,14 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 40 (0x28) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 39 (0x27) + .maxstack 5 .locals init (valuetype StructsAsArrayElements01/T V_0, valuetype StructsAsArrayElements01/T& V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.1 @@ -136,25 +133,22 @@ IL_0019: stloc.s V_4 IL_001b: ldloc.3 IL_001c: ldloc.s V_4 - IL_001e: bge.s IL_0022 - - IL_0020: ldc.i4.m1 - IL_0021: ret - - IL_0022: ldloc.3 - IL_0023: ldloc.s V_4 - IL_0025: cgt - IL_0027: ret + IL_001e: cgt + IL_0020: ldloc.3 + IL_0021: ldloc.s V_4 + IL_0023: clt + IL_0025: sub + IL_0026: ret } // end of method T::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 27 (0x1b) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4 0x9e3779b9 @@ -179,26 +173,26 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: call instance int32 StructsAsArrayElements01/T::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: call instance int32 StructsAsArrayElements01/T::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method T::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 42 (0x2a) .maxstack 4 .locals init (object V_0, valuetype StructsAsArrayElements01/T V_1, valuetype StructsAsArrayElements01/T& V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 @@ -239,7 +233,7 @@ .method public hidebysig virtual final instance bool Equals(valuetype StructsAsArrayElements01/T obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 18 (0x12) .maxstack 4 .locals init (valuetype StructsAsArrayElements01/T& V_0) @@ -256,7 +250,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 30 (0x1e) .maxstack 4 .locals init (object V_0, @@ -301,14 +295,14 @@ } // end of class StructsAsArrayElements01 .class private abstract auto ansi sealed ''.$StructsAsArrayElements01 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly valuetype StructsAsArrayElements01/T[] a@11 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -338,4 +332,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\Misc\StructsAsArrayElements01_fs\StructsAsArrayElements01.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\Misc\StructsAsArrayElements01_fs\StructsAsArrayElements01.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/AssemblyHasMvidSection.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/AssemblyHasMvidSection.fs new file mode 100644 index 00000000000..7c8872ff4e2 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/AssemblyHasMvidSection.fs @@ -0,0 +1,19 @@ +module AssemblyHasMvidSection + +open System +open System.IO +open System.Reflection +open FSharp.Compiler.ComponentTests.EmittedIL + +let pathToDll = + let d = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.Combine(d, "SimpleFsProgram.dll") + +Console.WriteLine($"Verify mvid section for: {pathToDll}"); +let stream = File.OpenRead(pathToDll); +let mvid = MvidReader.ReadAssemblyMvidOrEmpty(stream) + +let message = $"Mvid for {pathToDll} = {mvid}" +printfn $"{message}" + +if mvid = Guid.Empty then failwith message \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/MvidReader.cs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/MvidReader.cs new file mode 100644 index 00000000000..e0965929739 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/MvidReader.cs @@ -0,0 +1,207 @@ +using System; +using System.IO; + +namespace FSharp.Compiler.ComponentTests.EmittedIL +{ + public static class MvidReader + { + private static readonly Guid s_empty = Guid.Empty; + + public static Guid ReadAssemblyMvidOrEmpty(Stream stream) + { + return ReadAssemblyMvidOrEmpty(new BinaryReader(stream)); + } + + private static Guid ReadAssemblyMvidOrEmpty(BinaryReader reader) + { + // DOS Header: Magic number (2) + if (!ReadUInt16(reader, out ushort magicNumber) || magicNumber != 0x5a4d) // "MZ" + { + return s_empty; + } + + // DOS Header: Address of PE Signature (at 0x3C) + if (!MoveTo(0x3C, reader)) + { + return s_empty; + } + if (!ReadUInt32(reader, out uint pointerToPeSignature)) + { + return s_empty; + } + + // jump over the MS DOS Stub to the PE Signature + if (!MoveTo(pointerToPeSignature, reader)) + { + return s_empty; + } + + // PE Signature ('P' 'E' null null) + if (!ReadUInt32(reader, out uint peSig) || peSig != 0x00004550) + { + return s_empty; + } + + // COFF Header: Machine (2) + if (!Skip(2, reader)) + { + return s_empty; + } + + // COFF Header: NumberOfSections (2) + if (!ReadUInt16(reader, out ushort sections)) + { + return s_empty; + } + + // COFF Header: TimeDateStamp (4), PointerToSymbolTable (4), NumberOfSymbols (4) + if (!Skip(12, reader)) + { + return s_empty; + } + + // COFF Header: OptionalHeaderSize (2) + if (!ReadUInt16(reader, out ushort optionalHeaderSize)) + { + return s_empty; + } + + // COFF Header: Characteristics (2) + if (!Skip(2, reader)) + { + return s_empty; + } + + // Optional header + if (!Skip(optionalHeaderSize, reader)) + { + return s_empty; + } + + // Section headers + return FindMvidInSections(sections, reader); + } + + private static Guid FindMvidInSections(ushort count, BinaryReader reader) + { + for (int i = 0; i < count; i++) + { + // Section: Name (8) + if (!ReadBytes(reader, 8, out byte[] name)) + { + return s_empty; + } + + if (name!.Length == 8 && name[0] == '.' && + name[1] == 'm' && name[2] == 'v' && name[3] == 'i' && name[4] == 'd' && name[5] == '\0') + { + // Section: VirtualSize (4) + if (!ReadUInt32(reader, out uint virtualSize) || virtualSize != 16) + { + // The .mvid section only stores a Guid + return s_empty; + } + + // Section: VirtualAddress (4), SizeOfRawData (4) + if (!Skip(8, reader)) + { + return s_empty; + } + + // Section: PointerToRawData (4) + if (!ReadUInt32(reader, out uint pointerToRawData)) + { + return s_empty; + } + + return ReadMvidSection(reader, pointerToRawData); + } + else + { + // Section: VirtualSize (4), VirtualAddress (4), SizeOfRawData (4), + // PointerToRawData (4), PointerToRelocations (4), PointerToLineNumbers (4), + // NumberOfRelocations (2), NumberOfLineNumbers (2), Characteristics (4) + if (!Skip(4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 4, reader)) + { + return s_empty; + } + } + } + + return s_empty; + } + + private static Guid ReadMvidSection(BinaryReader reader, uint pointerToMvidSection) + { + if (!MoveTo(pointerToMvidSection, reader)) + { + return s_empty; + } + + if (!ReadBytes(reader, 16, out byte[] guidBytes)) + { + return s_empty; + } + + return new Guid(guidBytes!); + } + + private static bool ReadUInt16(BinaryReader reader, out ushort output) + { + if (reader.BaseStream.Position + 2 >= reader.BaseStream.Length) + { + output = 0; + return false; + } + + output = reader.ReadUInt16(); + return true; + } + + private static bool ReadUInt32(BinaryReader reader, out uint output) + { + if (reader.BaseStream.Position + 4 >= reader.BaseStream.Length) + { + output = 0; + return false; + } + + output = reader.ReadUInt32(); + return true; + } + + private static bool ReadBytes(BinaryReader reader, int count, out byte[] output) + { + if (reader.BaseStream.Position + count >= reader.BaseStream.Length) + { + output = null; + return false; + } + + output = reader.ReadBytes(count); + return true; + } + + private static bool Skip(int bytes, BinaryReader reader) + { + if (reader.BaseStream.Position + bytes >= reader.BaseStream.Length) + { + return false; + } + + reader.BaseStream.Seek(bytes, SeekOrigin.Current); + return true; + } + + private static bool MoveTo(uint position, BinaryReader reader) + { + if (position >= reader.BaseStream.Length) + { + return false; + } + + reader.BaseStream.Seek(position, SeekOrigin.Begin); + return true; + } + } +} \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/Platform.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/Platform.fs index 0094d9fdb70..1150e43e476 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/Platform.fs +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/Platform.fs @@ -3,6 +3,7 @@ open Xunit open FSharp.Test open FSharp.Test.Compiler +open System.IO open System.Runtime.InteropServices module Platform = @@ -134,3 +135,40 @@ module Platform = |> withReferences [ buildPlatformedDll |> withPlatform ExecutionPlatform.X64 ] |> compileExeAndRun |> shouldSucceed + + [] + let withRefOnlyGeneratesMvidSection compilation = + + let mvidReader = + CsFromPath (Path.Combine(__SOURCE_DIRECTORY__, "MvidReader.cs")) + |> withName "MvidReader" + + let assemblyHasMvidSection = + FsFromPath (Path.Combine(__SOURCE_DIRECTORY__, "SimpleFsProgram.fs")) + |> asLibrary + |> withRefOnly + + compilation + |> asExe + |> withReferences [mvidReader] + |> withReferences [assemblyHasMvidSection] + |> compileExeAndRun + |> shouldSucceed + + [] + let withoutRefOnlyGeneratesNoMvidSection compilation = + + let mvidReader = + CsFromPath (Path.Combine(__SOURCE_DIRECTORY__, "MvidReader.cs")) + |> withName "MvidReader" + + let assemblyHasMvidSection = + FsFromPath (Path.Combine(__SOURCE_DIRECTORY__, "SimpleFsProgram.fs")) + |> asLibrary + + compilation + |> asExe + |> withReferences [mvidReader] + |> withReferences [assemblyHasMvidSection] + |> compileExeAndRun + |> shouldFail diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/SimpleFsProgram.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/SimpleFsProgram.fs new file mode 100644 index 00000000000..21896b6dbe7 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Platform/SimpleFsProgram.fs @@ -0,0 +1 @@ +namespace NothingMuch diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.debug.bsl index a859e5bf0d7..99591a2d86a 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,52 +21,52 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelModule { - // Offset: 0x00000000 Length: 0x0000116C + // Offset: 0x00000000 Length: 0x00001162 // WARNING: managed resource file FSharpSignatureData.ToplevelModule created } .mresource public FSharpOptimizationData.ToplevelModule { - // Offset: 0x00001170 Length: 0x000003FD + // Offset: 0x00001168 Length: 0x00000403 // WARNING: managed resource file FSharpOptimizationData.ToplevelModule created } .module ToplevelModule.exe -// MVID: {624CBE98-FD28-3DB9-A745-038398BE4C62} +// MVID: {628F4C90-B9AE-2DE4-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x034B0000 +// Image base: 0x00000191AC370000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/Expr NewNum(int32 item) cil managed { @@ -82,12 +82,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/Expr::item @@ -97,8 +97,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -109,8 +109,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -122,8 +122,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -137,7 +137,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -151,22 +151,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -174,7 +174,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/Expr::item @@ -190,33 +190,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 - - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003f: ldc.i4.m1 - IL_0040: ret + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -228,29 +225,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -274,41 +271,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -349,30 +343,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, class ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -419,7 +413,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/Expr V_0, @@ -457,7 +451,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/Expr V_0) @@ -478,9 +472,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -488,15 +482,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -506,7 +500,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/MyExn::Data0@ @@ -519,21 +513,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -548,15 +542,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -592,34 +586,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -666,9 +660,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -712,19 +706,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -740,7 +734,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -750,7 +744,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -776,24 +770,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -809,12 +803,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/Expr::item @@ -824,8 +818,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -836,8 +830,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -849,8 +843,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -864,7 +858,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -878,22 +872,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -901,7 +895,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/ABC/Expr::item @@ -917,33 +911,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 - - IL_0031: ldc.i4.m1 - IL_0032: ret + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret - - IL_003a: ldc.i4.1 - IL_003b: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003f: ldc.i4.m1 - IL_0040: ret + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -955,29 +946,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any ABC/ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -1001,41 +992,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any ABC/ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any ABC/ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1076,30 +1064,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, class ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -1146,7 +1134,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, @@ -1184,7 +1172,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/ABC/Expr V_0) @@ -1205,9 +1193,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1215,15 +1203,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1233,7 +1221,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/MyExn::Data0@ @@ -1246,21 +1234,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1275,15 +1263,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -1319,34 +1307,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -1393,9 +1381,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1439,19 +1427,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1467,7 +1455,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1477,7 +1465,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1517,8 +1505,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1546,8 +1534,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1561,12 +1549,12 @@ } // end of class ABC .class private abstract auto ansi sealed ''.$ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -1587,4 +1575,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\SerializableAttribute\ToplevelModule_fs\ToplevelModule.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelModule_fs\ToplevelModule.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.release.bsl index 44c983ee14c..4145b82faa6 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,52 +21,52 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelModule { - // Offset: 0x00000000 Length: 0x00001170 + // Offset: 0x00000000 Length: 0x00001180 // WARNING: managed resource file FSharpSignatureData.ToplevelModule created } .mresource public FSharpOptimizationData.ToplevelModule { - // Offset: 0x00001178 Length: 0x000003FD + // Offset: 0x00001188 Length: 0x00000403 // WARNING: managed resource file FSharpOptimizationData.ToplevelModule created } .module ToplevelModule.exe -// MVID: {624CBC42-FD28-3DB9-A745-038342BC4C62} +// MVID: {628FBBC7-604B-50A5-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03770000 +// Image base: 0x00000192020C0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/Expr NewNum(int32 item) cil managed { @@ -82,12 +82,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/Expr::item @@ -97,8 +97,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -109,8 +109,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -122,8 +122,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -137,7 +137,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -151,19 +151,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -171,7 +171,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/Expr::item @@ -181,33 +181,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret - - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -219,26 +216,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -256,39 +253,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret - - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_003b: ldarg.1 - IL_003c: unbox.any ABC/Expr - IL_0041: brfalse.s IL_0045 + IL_003a: ldarg.1 + IL_003b: unbox.any ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0043: ldc.i4.m1 - IL_0044: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -325,27 +319,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, class ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -386,7 +380,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/Expr V_0, @@ -424,7 +418,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/Expr V_0) @@ -445,9 +439,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -455,15 +449,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -473,7 +467,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/MyExn::Data0@ @@ -486,21 +480,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -515,13 +509,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -553,31 +547,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -618,9 +612,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -664,19 +658,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -692,7 +686,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -702,7 +696,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -728,24 +722,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -761,12 +755,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/Expr::item @@ -776,8 +770,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -788,8 +782,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -801,8 +795,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -816,7 +810,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -830,19 +824,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -850,7 +844,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/ABC/Expr::item @@ -860,33 +854,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_0026: ldc.i4.m1 - IL_0027: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret - - IL_002e: ldc.i4.1 - IL_002f: ret - - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -898,26 +889,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any ABC/ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -935,39 +926,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret - - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_003b: ldarg.1 - IL_003c: unbox.any ABC/ABC/Expr - IL_0041: brfalse.s IL_0045 + IL_003a: ldarg.1 + IL_003b: unbox.any ABC/ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0043: ldc.i4.m1 - IL_0044: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -1004,27 +992,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, class ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1065,7 +1053,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, @@ -1103,7 +1091,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/ABC/Expr V_0) @@ -1124,9 +1112,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1134,15 +1122,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1152,7 +1140,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/MyExn::Data0@ @@ -1165,21 +1153,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1194,13 +1182,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -1232,31 +1220,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -1297,9 +1285,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1343,19 +1331,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1371,7 +1359,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1381,7 +1369,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1421,8 +1409,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1450,8 +1438,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1465,12 +1453,12 @@ } // end of class ABC .class private abstract auto ansi sealed ''.$ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -1491,4 +1479,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\SerializableAttribute\ToplevelModule_fs\ToplevelModule.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelModule_fs\ToplevelModule.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.debug.bsl index f16ff4f9814..8d7da403aad 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,52 +21,52 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelModule60 { - // Offset: 0x00000000 Length: 0x00001180 + // Offset: 0x00000000 Length: 0x00001176 // WARNING: managed resource file FSharpSignatureData.ToplevelModule60 created } .mresource public FSharpOptimizationData.ToplevelModule60 { - // Offset: 0x00001188 Length: 0x000003FF + // Offset: 0x00001180 Length: 0x00000405 // WARNING: managed resource file FSharpOptimizationData.ToplevelModule60 created } .module ToplevelModule60.exe -// MVID: {624CBE98-053E-0189-A745-038398BE4C62} +// MVID: {628F4C90-79E1-223C-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x036C0000 +// Image base: 0x0000021A85AA0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/Expr NewNum(int32 item) cil managed { @@ -82,12 +82,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/Expr::item @@ -97,8 +97,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -109,8 +109,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -122,8 +122,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -137,7 +137,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -151,22 +151,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -174,7 +174,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/Expr::item @@ -190,33 +190,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 - - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003f: ldc.i4.m1 - IL_0040: ret + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -228,29 +225,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -274,41 +271,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -349,30 +343,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, class ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -419,7 +413,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/Expr V_0, @@ -457,7 +451,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/Expr V_0) @@ -478,9 +472,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -488,15 +482,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -506,7 +500,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/MyExn::Data0@ @@ -519,21 +513,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -548,15 +542,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -592,34 +586,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -666,9 +660,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -712,19 +706,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -740,7 +734,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -750,7 +744,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -776,24 +770,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -809,12 +803,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/Expr::item @@ -824,8 +818,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -836,8 +830,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -849,8 +843,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -864,7 +858,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -878,22 +872,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -901,7 +895,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/ABC/Expr::item @@ -917,33 +911,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 - - IL_0031: ldc.i4.m1 - IL_0032: ret + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret - - IL_003a: ldc.i4.1 - IL_003b: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003f: ldc.i4.m1 - IL_0040: ret + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -955,29 +946,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any ABC/ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -1001,41 +992,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any ABC/ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any ABC/ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1076,30 +1064,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, class ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -1146,7 +1134,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, @@ -1184,7 +1172,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/ABC/Expr V_0) @@ -1205,9 +1193,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1215,15 +1203,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1233,7 +1221,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/MyExn::Data0@ @@ -1246,21 +1234,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1275,15 +1263,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -1319,34 +1307,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -1393,9 +1381,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1439,19 +1427,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1467,7 +1455,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1477,7 +1465,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1517,8 +1505,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1546,8 +1534,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1561,12 +1549,12 @@ } // end of class ABC .class private abstract auto ansi sealed ''.$ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -1587,4 +1575,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\SerializableAttribute\ToplevelModule_LangVersion60_fs\ToplevelModule60.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelModule_LangVersion60_fs\ToplevelModule60.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.release.bsl index 31e20245075..11b27d4f216 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelModule60.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,52 +21,52 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelModule60 { - // Offset: 0x00000000 Length: 0x00001184 + // Offset: 0x00000000 Length: 0x00001194 // WARNING: managed resource file FSharpSignatureData.ToplevelModule60 created } .mresource public FSharpOptimizationData.ToplevelModule60 { - // Offset: 0x00001188 Length: 0x000003FF + // Offset: 0x00001198 Length: 0x00000405 // WARNING: managed resource file FSharpOptimizationData.ToplevelModule60 created } .module ToplevelModule60.exe -// MVID: {624CBC42-053E-0189-A745-038342BC4C62} +// MVID: {628FBBC7-BB53-D545-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x035B0000 +// Image base: 0x00000289DFBE0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/Expr NewNum(int32 item) cil managed { @@ -82,12 +82,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/Expr::item @@ -97,8 +97,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -109,8 +109,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -122,8 +122,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -137,7 +137,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -151,19 +151,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -171,7 +171,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/Expr::item @@ -181,33 +181,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret - - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -219,26 +216,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -256,39 +253,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret - - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_003b: ldarg.1 - IL_003c: unbox.any ABC/Expr - IL_0041: brfalse.s IL_0045 + IL_003a: ldarg.1 + IL_003b: unbox.any ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0043: ldc.i4.m1 - IL_0044: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -325,27 +319,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class ABC/Expr V_0, class ABC/Expr V_1, class ABC/Expr V_2, class ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -386,7 +380,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/Expr V_0, @@ -424,7 +418,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/Expr V_0) @@ -445,9 +439,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -455,15 +449,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -473,7 +467,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/MyExn::Data0@ @@ -486,21 +480,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -515,13 +509,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -553,31 +547,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -618,9 +612,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -664,19 +658,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -692,7 +686,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -702,7 +696,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -728,24 +722,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -761,12 +755,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/Expr::item @@ -776,8 +770,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -788,8 +782,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -801,8 +795,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -816,7 +810,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -830,19 +824,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -850,7 +844,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 ABC/ABC/Expr::item @@ -860,33 +854,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_0026: ldc.i4.m1 - IL_0027: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret - - IL_002e: ldc.i4.1 - IL_002f: ret - - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -898,26 +889,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any ABC/ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -935,39 +926,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret - - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_003b: ldarg.1 - IL_003c: unbox.any ABC/ABC/Expr - IL_0041: brfalse.s IL_0045 + IL_003a: ldarg.1 + IL_003b: unbox.any ABC/ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0043: ldc.i4.m1 - IL_0044: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -1004,27 +992,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, class ABC/ABC/Expr V_1, class ABC/ABC/Expr V_2, class ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1065,7 +1053,7 @@ .method public hidebysig virtual final instance bool Equals(class ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class ABC/ABC/Expr V_0, @@ -1103,7 +1091,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class ABC/ABC/Expr V_0) @@ -1124,9 +1112,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1134,15 +1122,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1152,7 +1140,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 ABC/ABC/MyExn::Data0@ @@ -1165,21 +1153,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1194,13 +1182,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -1232,31 +1220,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -1297,9 +1285,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1343,19 +1331,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1371,7 +1359,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1381,7 +1369,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1421,8 +1409,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1450,8 +1438,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -1465,12 +1453,12 @@ } // end of class ABC .class private abstract auto ansi sealed ''.$ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -1491,4 +1479,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\SerializableAttribute\ToplevelModule_LangVersion60_fs\ToplevelModule60.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelModule_LangVersion60_fs\ToplevelModule60.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.debug.bsl index 662171e228e..44992dcf054 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,48 +21,48 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelNamespace { - // Offset: 0x00000000 Length: 0x0000187A + // Offset: 0x00000000 Length: 0x00001870 // WARNING: managed resource file FSharpSignatureData.ToplevelNamespace created } .mresource public FSharpOptimizationData.ToplevelNamespace { - // Offset: 0x00001880 Length: 0x0000055C + // Offset: 0x00001878 Length: 0x00000562 // WARNING: managed resource file FSharpOptimizationData.ToplevelNamespace created } .module ToplevelNamespace.exe -// MVID: {624CBE98-962F-9DFD-A745-038398BE4C62} +// MVID: {628F4C90-5D8B-1F9F-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03330000 +// Image base: 0x000002285D250000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto autochar serializable sealed beforefieldinit XYZ.Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.Expr NewNum(int32 item) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, @@ -77,12 +77,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.Expr::item @@ -92,8 +92,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -104,8 +104,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -117,8 +117,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -132,7 +132,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -146,22 +146,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -169,7 +169,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.Expr::item @@ -185,33 +185,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 - - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003f: ldc.i4.m1 - IL_0040: ret + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -223,29 +220,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any XYZ.Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -269,41 +266,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any XYZ.Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any XYZ.Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -344,30 +338,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, class XYZ.Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -414,7 +408,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.Expr V_0, @@ -452,7 +446,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.Expr V_0) @@ -473,9 +467,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -483,15 +477,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.Expr::get_Item() } // end of property Expr::Item } // end of class XYZ.Expr .class public auto ansi serializable beforefieldinit XYZ.MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -501,7 +495,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.MyExn::Data0@ @@ -514,21 +508,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -543,15 +537,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -587,34 +581,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -661,9 +655,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -707,19 +701,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -735,7 +729,7 @@ } // end of class XYZ.MyExn .class public auto ansi serializable XYZ.A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -745,7 +739,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -771,24 +765,24 @@ } // end of class XYZ.A .class public abstract auto ansi sealed XYZ.ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/Expr NewNum(int32 item) cil managed { @@ -804,12 +798,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/Expr::item @@ -819,8 +813,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -831,8 +825,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -844,8 +838,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -859,7 +853,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -873,22 +867,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -896,7 +890,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/Expr::item @@ -912,33 +906,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_003f: ldc.i4.m1 - IL_0040: ret - - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -950,29 +941,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -996,41 +987,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any XYZ.ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any XYZ.ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1071,30 +1059,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, class XYZ.ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -1141,7 +1129,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, @@ -1179,7 +1167,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0) @@ -1200,9 +1188,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1210,15 +1198,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1228,7 +1216,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/MyExn::Data0@ @@ -1241,21 +1229,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1270,15 +1258,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -1314,34 +1302,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -1388,9 +1376,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1434,19 +1422,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1462,7 +1450,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1472,7 +1460,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1498,24 +1486,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -1531,12 +1519,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/Expr::item @@ -1546,8 +1534,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -1558,8 +1546,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -1571,8 +1559,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -1586,7 +1574,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -1600,22 +1588,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -1623,7 +1611,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/ABC/Expr::item @@ -1639,33 +1627,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_003f: ldc.i4.m1 - IL_0040: ret - - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -1677,29 +1662,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -1723,41 +1708,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0044: ldc.i4.1 - IL_0045: ret - - IL_0046: ldarg.1 - IL_0047: unbox.any XYZ.ABC/ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any XYZ.ABC/ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1798,30 +1780,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, class XYZ.ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -1868,7 +1850,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, @@ -1906,7 +1888,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0) @@ -1927,9 +1909,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1937,15 +1919,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1955,7 +1937,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/MyExn::Data0@ @@ -1968,21 +1950,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1997,15 +1979,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -2041,34 +2023,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -2115,9 +2097,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -2161,19 +2143,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -2189,7 +2171,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -2199,7 +2181,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -2239,8 +2221,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2268,8 +2250,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2283,12 +2265,12 @@ } // end of class XYZ.ABC .class private abstract auto ansi sealed ''.$ToplevelNamespace - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -2309,4 +2291,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_fs\ToplevelNamespace.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_fs\ToplevelNamespace.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.release.bsl index d4746e376d8..c26c87956ab 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,48 +21,48 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelNamespace { - // Offset: 0x00000000 Length: 0x0000187E + // Offset: 0x00000000 Length: 0x0000188E // WARNING: managed resource file FSharpSignatureData.ToplevelNamespace created } .mresource public FSharpOptimizationData.ToplevelNamespace { - // Offset: 0x00001888 Length: 0x0000055C + // Offset: 0x00001898 Length: 0x00000562 // WARNING: managed resource file FSharpOptimizationData.ToplevelNamespace created } .module ToplevelNamespace.exe -// MVID: {624CBC42-962F-9DFD-A745-038342BC4C62} +// MVID: {628FBBC7-2DCF-3629-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03580000 +// Image base: 0x0000028D685A0000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto autochar serializable sealed beforefieldinit XYZ.Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.Expr NewNum(int32 item) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, @@ -77,12 +77,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.Expr::item @@ -92,8 +92,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -104,8 +104,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -117,8 +117,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -132,7 +132,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -146,19 +146,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -166,7 +166,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.Expr::item @@ -176,33 +176,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -214,26 +211,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any XYZ.Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -251,39 +248,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_003a: ldarg.1 + IL_003b: unbox.any XYZ.Expr + IL_0040: brfalse.s IL_0044 - IL_003b: ldarg.1 - IL_003c: unbox.any XYZ.Expr - IL_0041: brfalse.s IL_0045 + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0043: ldc.i4.m1 - IL_0044: ret - - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -320,27 +314,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, class XYZ.Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -381,7 +375,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.Expr V_0, @@ -419,7 +413,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.Expr V_0) @@ -440,9 +434,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -450,15 +444,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.Expr::get_Item() } // end of property Expr::Item } // end of class XYZ.Expr .class public auto ansi serializable beforefieldinit XYZ.MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -468,7 +462,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.MyExn::Data0@ @@ -481,21 +475,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -510,13 +504,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -548,31 +542,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -613,9 +607,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -659,19 +653,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -687,7 +681,7 @@ } // end of class XYZ.MyExn .class public auto ansi serializable XYZ.A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -697,7 +691,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -723,24 +717,24 @@ } // end of class XYZ.A .class public abstract auto ansi sealed XYZ.ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/Expr NewNum(int32 item) cil managed { @@ -756,12 +750,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/Expr::item @@ -771,8 +765,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -783,8 +777,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -796,8 +790,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -811,7 +805,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -825,19 +819,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -845,7 +839,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/Expr::item @@ -855,33 +849,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -893,26 +884,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -930,39 +921,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0030: ldc.i4.m1 - IL_0031: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_003a: ldarg.1 + IL_003b: unbox.any XYZ.ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_003b: ldarg.1 - IL_003c: unbox.any XYZ.ABC/Expr - IL_0041: brfalse.s IL_0045 - - IL_0043: ldc.i4.m1 - IL_0044: ret - - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -999,27 +987,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, class XYZ.ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1060,7 +1048,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, @@ -1098,7 +1086,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0) @@ -1119,9 +1107,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1129,15 +1117,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1147,7 +1135,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/MyExn::Data0@ @@ -1160,21 +1148,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1189,13 +1177,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -1227,31 +1215,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -1292,9 +1280,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1338,19 +1326,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1366,7 +1354,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1376,7 +1364,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1402,24 +1390,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -1435,12 +1423,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/Expr::item @@ -1450,8 +1438,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -1462,8 +1450,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -1475,8 +1463,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -1490,7 +1478,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -1504,19 +1492,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -1524,7 +1512,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/ABC/Expr::item @@ -1534,33 +1522,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret - - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -1572,26 +1557,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -1609,39 +1594,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret - - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_003b: ldarg.1 - IL_003c: unbox.any XYZ.ABC/ABC/Expr - IL_0041: brfalse.s IL_0045 + IL_003a: ldarg.1 + IL_003b: unbox.any XYZ.ABC/ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0043: ldc.i4.m1 - IL_0044: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -1678,27 +1660,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, class XYZ.ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1739,7 +1721,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, @@ -1777,7 +1759,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0) @@ -1798,9 +1780,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1808,15 +1790,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1826,7 +1808,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/MyExn::Data0@ @@ -1839,21 +1821,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1868,13 +1850,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -1906,31 +1888,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -1971,9 +1953,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -2017,19 +1999,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -2045,7 +2027,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -2055,7 +2037,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -2095,8 +2077,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2124,8 +2106,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2139,12 +2121,12 @@ } // end of class XYZ.ABC .class private abstract auto ansi sealed ''.$ToplevelNamespace - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -2165,4 +2147,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_fs\ToplevelNamespace.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_fs\ToplevelNamespace.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.debug.bsl index 2fa267da654..6e7e3c29032 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,48 +21,48 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelNamespace60 { - // Offset: 0x00000000 Length: 0x0000188E + // Offset: 0x00000000 Length: 0x00001884 // WARNING: managed resource file FSharpSignatureData.ToplevelNamespace60 created } .mresource public FSharpOptimizationData.ToplevelNamespace60 { - // Offset: 0x00001898 Length: 0x0000055E + // Offset: 0x00001888 Length: 0x00000564 // WARNING: managed resource file FSharpOptimizationData.ToplevelNamespace60 created } .module ToplevelNamespace60.exe -// MVID: {624CBE98-3418-1DAD-A745-038398BE4C62} +// MVID: {628F4C90-D42A-0CFD-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03B40000 +// Image base: 0x00000172650D0000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto autochar serializable sealed beforefieldinit XYZ.Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.Expr NewNum(int32 item) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, @@ -77,12 +77,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.Expr::item @@ -92,8 +92,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -104,8 +104,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -117,8 +117,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -132,7 +132,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -146,22 +146,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -169,7 +169,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.Expr::item @@ -185,33 +185,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 - - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003f: ldc.i4.m1 - IL_0040: ret + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -223,29 +220,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any XYZ.Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -269,41 +266,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any XYZ.Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any XYZ.Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -344,30 +338,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, class XYZ.Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -414,7 +408,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.Expr V_0, @@ -452,7 +446,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.Expr V_0) @@ -473,9 +467,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -483,15 +477,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.Expr::get_Item() } // end of property Expr::Item } // end of class XYZ.Expr .class public auto ansi serializable beforefieldinit XYZ.MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -501,7 +495,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.MyExn::Data0@ @@ -514,21 +508,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -543,15 +537,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -587,34 +581,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -661,9 +655,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -707,19 +701,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -735,7 +729,7 @@ } // end of class XYZ.MyExn .class public auto ansi serializable XYZ.A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -745,7 +739,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -771,24 +765,24 @@ } // end of class XYZ.A .class public abstract auto ansi sealed XYZ.ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/Expr NewNum(int32 item) cil managed { @@ -804,12 +798,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/Expr::item @@ -819,8 +813,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -831,8 +825,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -844,8 +838,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -859,7 +853,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -873,22 +867,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -896,7 +890,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/Expr::item @@ -912,33 +906,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_003f: ldc.i4.m1 - IL_0040: ret - - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -950,29 +941,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -996,41 +987,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_0044: ldc.i4.1 - IL_0045: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0046: ldarg.1 - IL_0047: unbox.any XYZ.ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any XYZ.ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1071,30 +1059,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, class XYZ.ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -1141,7 +1129,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, @@ -1179,7 +1167,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0) @@ -1200,9 +1188,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1210,15 +1198,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1228,7 +1216,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/MyExn::Data0@ @@ -1241,21 +1229,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1270,15 +1258,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -1314,34 +1302,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -1388,9 +1376,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1434,19 +1422,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1462,7 +1450,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1472,7 +1460,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1498,24 +1486,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -1531,12 +1519,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/Expr::item @@ -1546,8 +1534,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -1558,8 +1546,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -1571,8 +1559,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -1586,7 +1574,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -1600,22 +1588,22 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 67 (0x43) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 66 (0x42) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IComparer V_5, + class [System.Runtime]System.Collections.IComparer V_5, int32 V_6, int32 V_7) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_003c + IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: brfalse.s IL_003a + IL_0004: brfalse.s IL_0039 IL_0006: ldarg.0 IL_0007: pop @@ -1623,7 +1611,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/ABC/Expr::item @@ -1639,33 +1627,30 @@ IL_0029: stloc.s V_7 IL_002b: ldloc.s V_6 IL_002d: ldloc.s V_7 - IL_002f: bge.s IL_0033 + IL_002f: cgt + IL_0031: ldloc.s V_6 + IL_0033: ldloc.s V_7 + IL_0035: clt + IL_0037: sub + IL_0038: ret - IL_0031: ldc.i4.m1 - IL_0032: ret - - IL_0033: ldloc.s V_6 - IL_0035: ldloc.s V_7 - IL_0037: cgt - IL_0039: ret + IL_0039: ldc.i4.1 + IL_003a: ret - IL_003a: ldc.i4.1 - IL_003b: ret + IL_003b: ldarg.1 + IL_003c: brfalse.s IL_0040 - IL_003c: ldarg.1 - IL_003d: brfalse.s IL_0041 + IL_003e: ldc.i4.m1 + IL_003f: ret - IL_003f: ldc.i4.m1 - IL_0040: ret - - IL_0041: ldc.i4.0 - IL_0042: ret + IL_0040: ldc.i4.0 + IL_0041: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -1677,29 +1662,29 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 82 (0x52) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 81 (0x51) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_0046 + IL_0008: brfalse.s IL_0045 IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/ABC/Expr - IL_0010: brfalse.s IL_0044 + IL_0010: brfalse.s IL_0043 IL_0012: ldarg.0 IL_0013: pop @@ -1723,41 +1708,38 @@ IL_0033: stloc.s V_8 IL_0035: ldloc.s V_7 IL_0037: ldloc.s V_8 - IL_0039: bge.s IL_003d - - IL_003b: ldc.i4.m1 - IL_003c: ret + IL_0039: cgt + IL_003b: ldloc.s V_7 + IL_003d: ldloc.s V_8 + IL_003f: clt + IL_0041: sub + IL_0042: ret - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: ret + IL_0043: ldc.i4.1 + IL_0044: ret - IL_0044: ldc.i4.1 - IL_0045: ret - - IL_0046: ldarg.1 - IL_0047: unbox.any XYZ.ABC/ABC/Expr - IL_004c: brfalse.s IL_0050 + IL_0045: ldarg.1 + IL_0046: unbox.any XYZ.ABC/ABC/Expr + IL_004b: brfalse.s IL_004f - IL_004e: ldc.i4.m1 - IL_004f: ret + IL_004d: ldc.i4.m1 + IL_004e: ret - IL_0050: ldc.i4.0 - IL_0051: ret + IL_004f: ldc.i4.0 + IL_0050: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 43 (0x2b) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1798,30 +1780,30 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, class XYZ.ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -1868,7 +1850,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, @@ -1906,7 +1888,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0) @@ -1927,9 +1909,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1937,15 +1919,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1955,7 +1937,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/MyExn::Data0@ @@ -1968,21 +1950,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1997,15 +1979,15 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 41 (0x29) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0027 @@ -2041,34 +2023,34 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 78 (0x4e) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0046 IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0044 @@ -2115,9 +2097,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -2161,19 +2143,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -2189,7 +2171,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -2199,7 +2181,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -2239,8 +2221,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2268,8 +2250,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2283,12 +2265,12 @@ } // end of class XYZ.ABC .class private abstract auto ansi sealed ''.$ToplevelNamespace60 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -2309,4 +2291,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_LangVersion60_fs\ToplevelNamespace60.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_LangVersion60_fs\ToplevelNamespace60.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.release.bsl index 9e01a892a0c..1728bb5cb5f 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/SerializableAttribute/ToplevelNamespace60.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,48 +21,48 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.ToplevelNamespace60 { - // Offset: 0x00000000 Length: 0x00001892 + // Offset: 0x00000000 Length: 0x000018A2 // WARNING: managed resource file FSharpSignatureData.ToplevelNamespace60 created } .mresource public FSharpOptimizationData.ToplevelNamespace60 { - // Offset: 0x00001898 Length: 0x0000055E + // Offset: 0x000018A8 Length: 0x00000564 // WARNING: managed resource file FSharpOptimizationData.ToplevelNamespace60 created } .module ToplevelNamespace60.exe -// MVID: {624CBC42-3418-1DAD-A745-038342BC4C62} +// MVID: {628FBBC7-F27A-D2D9-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x030B0000 +// Image base: 0x000001DDA9B20000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto autochar serializable sealed beforefieldinit XYZ.Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.Expr NewNum(int32 item) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, @@ -77,12 +77,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.Expr::item @@ -92,8 +92,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -104,8 +104,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -117,8 +117,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -132,7 +132,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -146,19 +146,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -166,7 +166,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.Expr::item @@ -176,33 +176,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -214,26 +211,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any XYZ.Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -251,39 +248,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_003a: ldarg.1 + IL_003b: unbox.any XYZ.Expr + IL_0040: brfalse.s IL_0044 - IL_003b: ldarg.1 - IL_003c: unbox.any XYZ.Expr - IL_0041: brfalse.s IL_0045 + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0043: ldc.i4.m1 - IL_0044: ret - - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class XYZ.Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -320,27 +314,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class XYZ.Expr V_0, class XYZ.Expr V_1, class XYZ.Expr V_2, class XYZ.Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -381,7 +375,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.Expr V_0, @@ -419,7 +413,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.Expr V_0) @@ -440,9 +434,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -450,15 +444,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.Expr::get_Item() } // end of property Expr::Item } // end of class XYZ.Expr .class public auto ansi serializable beforefieldinit XYZ.MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -468,7 +462,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.MyExn::Data0@ @@ -481,21 +475,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -510,13 +504,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -548,31 +542,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -613,9 +607,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -659,19 +653,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -687,7 +681,7 @@ } // end of class XYZ.MyExn .class public auto ansi serializable XYZ.A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -697,7 +691,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -723,24 +717,24 @@ } // end of class XYZ.A .class public abstract auto ansi sealed XYZ.ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/Expr NewNum(int32 item) cil managed { @@ -756,12 +750,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/Expr::item @@ -771,8 +765,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -783,8 +777,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -796,8 +790,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -811,7 +805,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -825,19 +819,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -845,7 +839,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/Expr::item @@ -855,33 +849,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret - - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -893,26 +884,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -930,39 +921,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0030: ldc.i4.m1 - IL_0031: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_003a: ldarg.1 + IL_003b: unbox.any XYZ.ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_003b: ldarg.1 - IL_003c: unbox.any XYZ.ABC/Expr - IL_0041: brfalse.s IL_0045 - - IL_0043: ldc.i4.m1 - IL_0044: ret - - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -999,27 +987,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, class XYZ.ABC/Expr V_1, class XYZ.ABC/Expr V_2, class XYZ.ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1060,7 +1048,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0, @@ -1098,7 +1086,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/Expr V_0) @@ -1119,9 +1107,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1129,15 +1117,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1147,7 +1135,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/MyExn::Data0@ @@ -1160,21 +1148,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1189,13 +1177,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -1227,31 +1215,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -1292,9 +1280,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -1338,19 +1326,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -1366,7 +1354,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -1376,7 +1364,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -1402,24 +1390,24 @@ } // end of class A .class abstract auto ansi sealed nested public ABC - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit Expr - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class XYZ.ABC/ABC/Expr NewNum(int32 item) cil managed { @@ -1435,12 +1423,12 @@ .method assembly specialname rtspecialname instance void .ctor(int32 item) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/Expr::item @@ -1450,8 +1438,8 @@ .method public hidebysig instance int32 get_Item() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -1462,8 +1450,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -1475,8 +1463,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -1490,7 +1478,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -1504,19 +1492,19 @@ .method public hidebysig virtual final instance int32 CompareTo(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 55 (0x37) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 54 (0x36) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IComparer V_2, + class [System.Runtime]System.Collections.IComparer V_2, int32 V_3, int32 V_4) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0030 + IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 - IL_0004: brfalse.s IL_002e + IL_0004: brfalse.s IL_002d IL_0006: ldarg.0 IL_0007: pop @@ -1524,7 +1512,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.2 IL_0012: ldloc.0 IL_0013: ldfld int32 XYZ.ABC/ABC/Expr::item @@ -1534,33 +1522,30 @@ IL_001f: stloc.s V_4 IL_0021: ldloc.3 IL_0022: ldloc.s V_4 - IL_0024: bge.s IL_0028 - - IL_0026: ldc.i4.m1 - IL_0027: ret + IL_0024: cgt + IL_0026: ldloc.3 + IL_0027: ldloc.s V_4 + IL_0029: clt + IL_002b: sub + IL_002c: ret - IL_0028: ldloc.3 - IL_0029: ldloc.s V_4 - IL_002b: cgt - IL_002d: ret - - IL_002e: ldc.i4.1 - IL_002f: ret + IL_002d: ldc.i4.1 + IL_002e: ret - IL_0030: ldarg.1 - IL_0031: brfalse.s IL_0035 + IL_002f: ldarg.1 + IL_0030: brfalse.s IL_0034 - IL_0033: ldc.i4.m1 - IL_0034: ret + IL_0032: ldc.i4.m1 + IL_0033: ret - IL_0035: ldc.i4.0 - IL_0036: ret + IL_0034: ldc.i4.0 + IL_0035: ret } // end of method Expr::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -1572,26 +1557,26 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 71 (0x47) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 70 (0x46) + .maxstack 5 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5) IL_0000: ldarg.1 IL_0001: unbox.any XYZ.ABC/ABC/Expr IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_003b + IL_0008: brfalse.s IL_003a IL_000a: ldarg.1 IL_000b: unbox.any XYZ.ABC/ABC/Expr - IL_0010: brfalse.s IL_0039 + IL_0010: brfalse.s IL_0038 IL_0012: ldarg.0 IL_0013: pop @@ -1609,39 +1594,36 @@ IL_0028: stloc.s V_5 IL_002a: ldloc.s V_4 IL_002c: ldloc.s V_5 - IL_002e: bge.s IL_0032 - - IL_0030: ldc.i4.m1 - IL_0031: ret - - IL_0032: ldloc.s V_4 - IL_0034: ldloc.s V_5 - IL_0036: cgt - IL_0038: ret + IL_002e: cgt + IL_0030: ldloc.s V_4 + IL_0032: ldloc.s V_5 + IL_0034: clt + IL_0036: sub + IL_0037: ret - IL_0039: ldc.i4.1 - IL_003a: ret + IL_0038: ldc.i4.1 + IL_0039: ret - IL_003b: ldarg.1 - IL_003c: unbox.any XYZ.ABC/ABC/Expr - IL_0041: brfalse.s IL_0045 + IL_003a: ldarg.1 + IL_003b: unbox.any XYZ.ABC/ABC/Expr + IL_0040: brfalse.s IL_0044 - IL_0043: ldc.i4.m1 - IL_0044: ret + IL_0042: ldc.i4.m1 + IL_0043: ret - IL_0045: ldc.i4.0 - IL_0046: ret + IL_0044: ldc.i4.0 + IL_0045: ret } // end of method Expr::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 38 (0x26) .maxstack 7 .locals init (int32 V_0, class XYZ.ABC/ABC/Expr V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0024 @@ -1678,27 +1660,27 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/Expr::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Expr::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 49 (0x31) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, class XYZ.ABC/ABC/Expr V_1, class XYZ.ABC/ABC/Expr V_2, class XYZ.ABC/ABC/Expr V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4) + class [System.Runtime]System.Collections.IEqualityComparer V_4) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0029 @@ -1739,7 +1721,7 @@ .method public hidebysig virtual final instance bool Equals(class XYZ.ABC/ABC/Expr obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0, @@ -1777,7 +1759,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class XYZ.ABC/ABC/Expr V_0) @@ -1798,9 +1780,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Tag() } // end of property Expr::Tag .property instance int32 Item() @@ -1808,15 +1790,15 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 XYZ.ABC/ABC/Expr::get_Item() } // end of property Expr::Item } // end of class Expr .class auto ansi serializable nested public beforefieldinit MyExn - extends [mscorlib]System.Exception - implements [mscorlib]System.Collections.IStructuralEquatable + extends [System.Runtime]System.Exception + implements [System.Runtime]System.Collections.IStructuralEquatable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 05 00 00 00 00 00 ) .field assembly int32 Data0@ @@ -1826,7 +1808,7 @@ // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 XYZ.ABC/ABC/MyExn::Data0@ @@ -1839,21 +1821,21 @@ // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Exception::.ctor() + IL_0001: call instance void [System.Runtime]System.Exception::.ctor() IL_0006: ret } // end of method MyExn::.ctor .method family specialname rtspecialname - instance void .ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo info, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext context) cil managed + instance void .ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo info, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext context) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 - IL_0003: call instance void [mscorlib]System.Exception::.ctor(class [mscorlib]System.Runtime.Serialization.SerializationInfo, - valuetype [mscorlib]System.Runtime.Serialization.StreamingContext) + IL_0003: call instance void [System.Runtime]System.Exception::.ctor(class [System.Runtime]System.Runtime.Serialization.SerializationInfo, + valuetype [System.Runtime]System.Runtime.Serialization.StreamingContext) IL_0008: ret } // end of method MyExn::.ctor @@ -1868,13 +1850,13 @@ } // end of method MyExn::get_Data0 .method public hidebysig virtual instance int32 - GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 37 (0x25) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1) + class [System.Runtime]System.Collections.IEqualityComparer V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0023 @@ -1906,31 +1888,31 @@ .method public hidebysig virtual instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 XYZ.ABC/ABC/MyExn::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method MyExn::GetHashCode .method public hidebysig virtual instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 67 (0x43) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0, - class [mscorlib]System.Exception V_1, + .locals init (class [System.Runtime]System.Exception V_0, + class [System.Runtime]System.Exception V_1, object V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b IL_0003: ldarg.1 - IL_0004: isinst [mscorlib]System.Exception + IL_0004: isinst [System.Runtime]System.Exception IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 @@ -1971,9 +1953,9 @@ } // end of method MyExn::Equals .method public hidebysig instance bool - Equals(class [mscorlib]System.Exception obj) cil managed + Equals(class [System.Runtime]System.Exception obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 56 (0x38) .maxstack 4 .locals init (object V_0) @@ -2017,19 +1999,19 @@ .method public hidebysig virtual instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 - .locals init (class [mscorlib]System.Exception V_0) + .locals init (class [System.Runtime]System.Exception V_0) IL_0000: ldarg.1 - IL_0001: isinst [mscorlib]System.Exception + IL_0001: isinst [System.Runtime]System.Exception IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: ldarg.0 IL_000b: ldloc.0 - IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [mscorlib]System.Exception) + IL_000c: callvirt instance bool XYZ.ABC/ABC/MyExn::Equals(class [System.Runtime]System.Exception) IL_0011: ret IL_0012: ldc.i4.0 @@ -2045,7 +2027,7 @@ } // end of class MyExn .class auto ansi serializable nested public A - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) .field assembly string x @@ -2055,7 +2037,7 @@ // Code size 16 (0x10) .maxstack 8 IL_0000: ldarg.0 - IL_0001: callvirt instance void [mscorlib]System.Object::.ctor() + IL_0001: callvirt instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: pop IL_0008: ldarg.0 @@ -2095,8 +2077,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2124,8 +2106,8 @@ .method public specialname static string get_greeting() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr "hello" @@ -2139,12 +2121,12 @@ } // end of class XYZ.ABC .class private abstract auto ansi sealed ''.$ToplevelNamespace60 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .field static assembly int32 init@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static void main@() cil managed { .entrypoint @@ -2165,4 +2147,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file c:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_LangVersion60_fs\ToplevelNamespace60.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\SerializableAttribute\ToplevelNamespace_LangVersion60_fs\ToplevelNamespace60.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/StructGettersReadOnly.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/StructGettersReadOnly.fs new file mode 100644 index 00000000000..ccb94a97e50 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/StructGettersReadOnly.fs @@ -0,0 +1,130 @@ +namespace FSharp.Compiler.ComponentTests.EmittedIL + +open Microsoft.FSharp.Core +open Xunit +open FSharp.Test.Compiler +open FSharp.Test.ReflectionHelper + +module ``Struct getters readonly`` = + + let structRecord = + FSharp + """ + module Test + + [] type MyRecord = { MyField : int } + """ + + [] + let ``Struct record has readonly attribute on getter`` () = + structRecord + |> compileAssembly + |> getType "Test+MyRecord" + |> getMethod "get_MyField" + |> should haveAttribute "IsReadOnlyAttribute" + + [] + let ``Struct record has readonly attribute on getter in IL`` () = + structRecord + |> compile + |> shouldSucceed + |> verifyIL [ """ + .method public hidebysig specialname + instance int32 get_MyField() cil managed + { + .custom instance void [runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldfld int32 Test/MyRecord::MyField@ + IL_0006: ret + }""" ] + + let nonStructRecord = + FSharp + """ + module Test + + type MyRecord = { MyField : int } + """ + + [] + let ``Non-struct record doesn't have readonly getters`` () = + nonStructRecord + |> compileAssembly + |> getType "Test+MyRecord" + |> getMethod "get_MyField" + |> shouldn't haveAttribute "IsReadOnlyAttribute" + + [] + let ``Non-struct record doesn't have readonly getters in IL`` () = + nonStructRecord + |> compile + |> shouldSucceed + |> verifyIL [ """ + .method public hidebysig specialname + instance int32 get_MyField() cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldfld int32 Test/MyRecord::MyField@ + IL_0006: ret + } """ ] + + [] + let ``Struct anonymous record has readonly attribute on getter`` () = + FSharp + """ + module Test + + let myRecord = struct {| MyField = 3 |} + """ + |> compileAssembly + |> getFirstAnonymousType + |> getMethod "get_MyField" + |> should haveAttribute "IsReadOnlyAttribute" + + [] + let ``Non-struct anonymous record doesn't have readonly attribute on getter`` () = + FSharp + """ + module Test + + let myRecord = {| MyField = 3 |} + """ + |> compileAssembly + |> getFirstAnonymousType + |> getMethod "get_MyField" + |> shouldn't haveAttribute "IsReadOnlyAttribute" + + [] + let ``Struct has readonly getters`` () = + FSharp + """ + module Test + + [] + type MyStruct = + val MyField: int + """ + |> compileAssembly + |> getType "Test+MyStruct" + |> getMethod "get_MyField" + |> should haveAttribute "IsReadOnlyAttribute" + + [] + let ``Custom getter on a struct doesn't have readonly attribute`` () = + FSharp + """ + module Test + + [] + type MyStruct = + val mutable x: int + member this.MyField with get () = this.x <- 4 + """ + |> compileAssembly + |> getType "Test+MyStruct" + |> getMethod "get_MyField" + |> shouldn't haveAttribute "IsReadOnlyAttribute" diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.debug.bsl index 1e35a8e9c26..0e84741e970 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.debug.bsl @@ -65,6 +65,7 @@ .method public hidebysig specialname instance float64 get_F() cil managed { + .custom instance void [runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -409,6 +410,7 @@ .method public hidebysig specialname instance float64 get_D() cil managed { + .custom instance void [runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.release.bsl index caa632f0fa0..9d6c3245635 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Structure/FloatsAndDoubles.fs.il.release.bsl @@ -65,6 +65,7 @@ .method public hidebysig specialname instance float64 get_F() cil managed { + .custom instance void [runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -376,6 +377,7 @@ .method public hidebysig specialname instance float64 get_D() cil managed { + .custom instance void [runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.debug.bsl index 343fcf8ef45..298db7135ad 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,56 +21,56 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction16 { - // Offset: 0x00000000 Length: 0x000006BA + // Offset: 0x00000000 Length: 0x000006B0 // WARNING: managed resource file FSharpSignatureData.TestFunction16 created } .mresource public FSharpOptimizationData.TestFunction16 { - // Offset: 0x000006C0 Length: 0x000001CD + // Offset: 0x000006B8 Length: 0x000001D3 // WARNING: managed resource file FSharpOptimizationData.TestFunction16 created } .module TestFunction16.exe -// MVID: {624E339D-A624-45C5-A745-03839D334E62} +// MVID: {628F4C90-4649-1055-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03AF0000 +// Image base: 0x000001ECE7610000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction16 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit U - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class TestFunction16/U NewU(int32 item1, int32 item2) cil managed @@ -90,12 +90,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction16/U::item1 @@ -108,8 +108,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -120,8 +120,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -132,8 +132,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -145,8 +145,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -160,7 +160,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -174,120 +174,112 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction16/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 140 (0x8c) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 132 (0x84) + .maxstack 5 .locals init (class TestFunction16/U V_0, class TestFunction16/U V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8, - class [mscorlib]System.Collections.IComparer V_9, + class [System.Runtime]System.Collections.IComparer V_9, int32 V_10, int32 V_11, - class [mscorlib]System.Collections.IComparer V_12, + class [System.Runtime]System.Collections.IComparer V_12, int32 V_13, int32 V_14) IL_0000: ldarg.0 - IL_0001: brfalse IL_0085 + IL_0001: brfalse IL_007d IL_0006: ldarg.1 - IL_0007: brfalse IL_0083 - - IL_000c: ldarg.0 - IL_000d: pop - IL_000e: ldarg.0 - IL_000f: stloc.0 - IL_0010: ldarg.1 - IL_0011: stloc.1 - IL_0012: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0017: stloc.3 - IL_0018: ldloc.0 - IL_0019: ldfld int32 TestFunction16/U::item1 - IL_001e: stloc.s V_4 - IL_0020: ldloc.1 - IL_0021: ldfld int32 TestFunction16/U::item1 - IL_0026: stloc.s V_5 - IL_0028: ldloc.3 - IL_0029: stloc.s V_6 - IL_002b: ldloc.s V_4 - IL_002d: stloc.s V_7 - IL_002f: ldloc.s V_5 - IL_0031: stloc.s V_8 - IL_0033: ldloc.s V_7 - IL_0035: ldloc.s V_8 - IL_0037: bge.s IL_003d - - IL_0039: ldc.i4.m1 - IL_003a: nop - IL_003b: br.s IL_0044 - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: nop - IL_0044: stloc.2 - IL_0045: ldloc.2 - IL_0046: ldc.i4.0 - IL_0047: bge.s IL_004b - - IL_0049: ldloc.2 - IL_004a: ret - - IL_004b: ldloc.2 - IL_004c: ldc.i4.0 - IL_004d: ble.s IL_0051 - - IL_004f: ldloc.2 - IL_0050: ret - - IL_0051: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0056: stloc.s V_9 - IL_0058: ldloc.0 - IL_0059: ldfld int32 TestFunction16/U::item2 - IL_005e: stloc.s V_10 - IL_0060: ldloc.1 - IL_0061: ldfld int32 TestFunction16/U::item2 - IL_0066: stloc.s V_11 - IL_0068: ldloc.s V_9 - IL_006a: stloc.s V_12 - IL_006c: ldloc.s V_10 - IL_006e: stloc.s V_13 - IL_0070: ldloc.s V_11 - IL_0072: stloc.s V_14 - IL_0074: ldloc.s V_13 - IL_0076: ldloc.s V_14 - IL_0078: bge.s IL_007c - - IL_007a: ldc.i4.m1 - IL_007b: ret + IL_0007: brfalse.s IL_007b - IL_007c: ldloc.s V_13 - IL_007e: ldloc.s V_14 - IL_0080: cgt - IL_0082: ret - - IL_0083: ldc.i4.1 - IL_0084: ret - - IL_0085: ldarg.1 - IL_0086: brfalse.s IL_008a + IL_0009: ldarg.0 + IL_000a: pop + IL_000b: ldarg.0 + IL_000c: stloc.0 + IL_000d: ldarg.1 + IL_000e: stloc.1 + IL_000f: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0014: stloc.3 + IL_0015: ldloc.0 + IL_0016: ldfld int32 TestFunction16/U::item1 + IL_001b: stloc.s V_4 + IL_001d: ldloc.1 + IL_001e: ldfld int32 TestFunction16/U::item1 + IL_0023: stloc.s V_5 + IL_0025: ldloc.3 + IL_0026: stloc.s V_6 + IL_0028: ldloc.s V_4 + IL_002a: stloc.s V_7 + IL_002c: ldloc.s V_5 + IL_002e: stloc.s V_8 + IL_0030: ldloc.s V_7 + IL_0032: ldloc.s V_8 + IL_0034: cgt + IL_0036: ldloc.s V_7 + IL_0038: ldloc.s V_8 + IL_003a: clt + IL_003c: sub + IL_003d: stloc.2 + IL_003e: ldloc.2 + IL_003f: ldc.i4.0 + IL_0040: bge.s IL_0044 + + IL_0042: ldloc.2 + IL_0043: ret + + IL_0044: ldloc.2 + IL_0045: ldc.i4.0 + IL_0046: ble.s IL_004a + + IL_0048: ldloc.2 + IL_0049: ret + + IL_004a: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_004f: stloc.s V_9 + IL_0051: ldloc.0 + IL_0052: ldfld int32 TestFunction16/U::item2 + IL_0057: stloc.s V_10 + IL_0059: ldloc.1 + IL_005a: ldfld int32 TestFunction16/U::item2 + IL_005f: stloc.s V_11 + IL_0061: ldloc.s V_9 + IL_0063: stloc.s V_12 + IL_0065: ldloc.s V_10 + IL_0067: stloc.s V_13 + IL_0069: ldloc.s V_11 + IL_006b: stloc.s V_14 + IL_006d: ldloc.s V_13 + IL_006f: ldloc.s V_14 + IL_0071: cgt + IL_0073: ldloc.s V_13 + IL_0075: ldloc.s V_14 + IL_0077: clt + IL_0079: sub + IL_007a: ret + + IL_007b: ldc.i4.1 + IL_007c: ret + + IL_007d: ldarg.1 + IL_007e: brfalse.s IL_0082 - IL_0088: ldc.i4.m1 - IL_0089: ret + IL_0080: ldc.i4.m1 + IL_0081: ret - IL_008a: ldc.i4.0 - IL_008b: ret + IL_0082: ldc.i4.0 + IL_0083: ret } // end of method U::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -299,138 +291,130 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 151 (0x97) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 140 (0x8c) + .maxstack 5 .locals init (class TestFunction16/U V_0, class TestFunction16/U V_1, class TestFunction16/U V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9, - class [mscorlib]System.Collections.IComparer V_10, + class [System.Runtime]System.Collections.IComparer V_10, int32 V_11, int32 V_12, - class [mscorlib]System.Collections.IComparer V_13, + class [System.Runtime]System.Collections.IComparer V_13, int32 V_14, int32 V_15) IL_0000: ldarg.1 IL_0001: unbox.any TestFunction16/U IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse IL_008b + IL_0008: brfalse.s IL_0080 - IL_000d: ldarg.1 - IL_000e: unbox.any TestFunction16/U - IL_0013: brfalse IL_0089 - - IL_0018: ldarg.0 - IL_0019: pop - IL_001a: ldarg.0 - IL_001b: stloc.1 - IL_001c: ldloc.0 - IL_001d: stloc.2 - IL_001e: ldarg.2 - IL_001f: stloc.s V_4 - IL_0021: ldloc.1 - IL_0022: ldfld int32 TestFunction16/U::item1 - IL_0027: stloc.s V_5 - IL_0029: ldloc.2 - IL_002a: ldfld int32 TestFunction16/U::item1 - IL_002f: stloc.s V_6 - IL_0031: ldloc.s V_4 - IL_0033: stloc.s V_7 - IL_0035: ldloc.s V_5 - IL_0037: stloc.s V_8 - IL_0039: ldloc.s V_6 - IL_003b: stloc.s V_9 + IL_000a: ldarg.1 + IL_000b: unbox.any TestFunction16/U + IL_0010: brfalse.s IL_007e + + IL_0012: ldarg.0 + IL_0013: pop + IL_0014: ldarg.0 + IL_0015: stloc.1 + IL_0016: ldloc.0 + IL_0017: stloc.2 + IL_0018: ldarg.2 + IL_0019: stloc.s V_4 + IL_001b: ldloc.1 + IL_001c: ldfld int32 TestFunction16/U::item1 + IL_0021: stloc.s V_5 + IL_0023: ldloc.2 + IL_0024: ldfld int32 TestFunction16/U::item1 + IL_0029: stloc.s V_6 + IL_002b: ldloc.s V_4 + IL_002d: stloc.s V_7 + IL_002f: ldloc.s V_5 + IL_0031: stloc.s V_8 + IL_0033: ldloc.s V_6 + IL_0035: stloc.s V_9 + IL_0037: ldloc.s V_8 + IL_0039: ldloc.s V_9 + IL_003b: cgt IL_003d: ldloc.s V_8 IL_003f: ldloc.s V_9 - IL_0041: bge.s IL_0047 + IL_0041: clt + IL_0043: sub + IL_0044: stloc.3 + IL_0045: ldloc.3 + IL_0046: ldc.i4.0 + IL_0047: bge.s IL_004b - IL_0043: ldc.i4.m1 - IL_0044: nop - IL_0045: br.s IL_004e + IL_0049: ldloc.3 + IL_004a: ret - IL_0047: ldloc.s V_8 - IL_0049: ldloc.s V_9 - IL_004b: cgt - IL_004d: nop - IL_004e: stloc.3 - IL_004f: ldloc.3 - IL_0050: ldc.i4.0 - IL_0051: bge.s IL_0055 - - IL_0053: ldloc.3 - IL_0054: ret - - IL_0055: ldloc.3 - IL_0056: ldc.i4.0 - IL_0057: ble.s IL_005b - - IL_0059: ldloc.3 - IL_005a: ret - - IL_005b: ldarg.2 - IL_005c: stloc.s V_10 - IL_005e: ldloc.1 - IL_005f: ldfld int32 TestFunction16/U::item2 - IL_0064: stloc.s V_11 - IL_0066: ldloc.2 - IL_0067: ldfld int32 TestFunction16/U::item2 - IL_006c: stloc.s V_12 - IL_006e: ldloc.s V_10 - IL_0070: stloc.s V_13 - IL_0072: ldloc.s V_11 - IL_0074: stloc.s V_14 - IL_0076: ldloc.s V_12 - IL_0078: stloc.s V_15 - IL_007a: ldloc.s V_14 - IL_007c: ldloc.s V_15 - IL_007e: bge.s IL_0082 + IL_004b: ldloc.3 + IL_004c: ldc.i4.0 + IL_004d: ble.s IL_0051 - IL_0080: ldc.i4.m1 - IL_0081: ret + IL_004f: ldloc.3 + IL_0050: ret - IL_0082: ldloc.s V_14 - IL_0084: ldloc.s V_15 - IL_0086: cgt - IL_0088: ret + IL_0051: ldarg.2 + IL_0052: stloc.s V_10 + IL_0054: ldloc.1 + IL_0055: ldfld int32 TestFunction16/U::item2 + IL_005a: stloc.s V_11 + IL_005c: ldloc.2 + IL_005d: ldfld int32 TestFunction16/U::item2 + IL_0062: stloc.s V_12 + IL_0064: ldloc.s V_10 + IL_0066: stloc.s V_13 + IL_0068: ldloc.s V_11 + IL_006a: stloc.s V_14 + IL_006c: ldloc.s V_12 + IL_006e: stloc.s V_15 + IL_0070: ldloc.s V_14 + IL_0072: ldloc.s V_15 + IL_0074: cgt + IL_0076: ldloc.s V_14 + IL_0078: ldloc.s V_15 + IL_007a: clt + IL_007c: sub + IL_007d: ret - IL_0089: ldc.i4.1 - IL_008a: ret + IL_007e: ldc.i4.1 + IL_007f: ret - IL_008b: ldarg.1 - IL_008c: unbox.any TestFunction16/U - IL_0091: brfalse.s IL_0095 + IL_0080: ldarg.1 + IL_0081: unbox.any TestFunction16/U + IL_0086: brfalse.s IL_008a - IL_0093: ldc.i4.m1 - IL_0094: ret + IL_0088: ldc.i4.m1 + IL_0089: ret - IL_0095: ldc.i4.0 - IL_0096: ret + IL_008a: ldc.i4.0 + IL_008b: ret } // end of method U::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 75 (0x4b) .maxstack 7 .locals init (int32 V_0, class TestFunction16/U V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, - class [mscorlib]System.Collections.IEqualityComparer V_5, + class [System.Runtime]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0049 @@ -490,34 +474,34 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction16/U::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction16/U::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method U::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 94 (0x5e) .maxstack 4 .locals init (class TestFunction16/U V_0, class TestFunction16/U V_1, class TestFunction16/U V_2, class TestFunction16/U V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7, - class [mscorlib]System.Collections.IEqualityComparer V_8, + class [System.Runtime]System.Collections.IEqualityComparer V_7, + class [System.Runtime]System.Collections.IEqualityComparer V_8, int32 V_9, int32 V_10, - class [mscorlib]System.Collections.IEqualityComparer V_11) + class [System.Runtime]System.Collections.IEqualityComparer V_11) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0056 @@ -582,7 +566,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction16/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class TestFunction16/U V_0, @@ -629,7 +613,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction16/U V_0) @@ -650,9 +634,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 TestFunction16/U::get_Tag() } // end of property U::Tag .property instance int32 Item1() @@ -660,8 +644,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction16/U::get_Item1() } // end of property U::Item1 .property instance int32 Item2() @@ -669,13 +653,13 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction16/U::get_Item2() } // end of property U::Item2 } // end of class U - .method public static class [mscorlib]System.Tuple`2 + .method public static class [System.Runtime]System.Tuple`2 TestFunction16(int32 inp) cil managed { // Code size 16 (0x10) @@ -688,15 +672,15 @@ IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldloc.0 - IL_000a: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_000a: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_000f: ret } // end of method TestFunction16::TestFunction16 } // end of class TestFunction16 .class private abstract auto ansi sealed ''.$TestFunction16 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -712,4 +696,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\TestFunctions\TestFunction16_fs\TestFunction16.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\TestFunctions\TestFunction16_fs\TestFunction16.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.release.bsl index 5102890f79f..9187098dbfe 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction16.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,56 +21,56 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction16 { - // Offset: 0x00000000 Length: 0x000006BE + // Offset: 0x00000000 Length: 0x000006CE // WARNING: managed resource file FSharpSignatureData.TestFunction16 created } .mresource public FSharpOptimizationData.TestFunction16 { - // Offset: 0x000006C8 Length: 0x000001CD + // Offset: 0x000006D8 Length: 0x000001D3 // WARNING: managed resource file FSharpOptimizationData.TestFunction16 created } .module TestFunction16.exe -// MVID: {624E31F9-A624-45C5-A745-0383F9314E62} +// MVID: {628FBBC7-4288-ADF9-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x05080000 +// Image base: 0x0000022FE2560000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction16 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit U - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class TestFunction16/U NewU(int32 item1, int32 item2) cil managed @@ -90,12 +90,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction16/U::item1 @@ -108,8 +108,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -120,8 +120,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -132,8 +132,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -145,8 +145,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -160,7 +160,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -174,23 +174,23 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction16/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 111 (0x6f) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 106 (0x6a) + .maxstack 5 .locals init (class TestFunction16/U V_0, class TestFunction16/U V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0068 + IL_0001: brfalse.s IL_0063 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0066 + IL_0004: brfalse.s IL_0061 IL_0006: ldarg.0 IL_0007: pop @@ -198,7 +198,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 TestFunction16/U::item1 @@ -208,68 +208,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.s V_6 - IL_0047: ldloc.0 - IL_0048: ldfld int32 TestFunction16/U::item2 - IL_004d: stloc.s V_7 - IL_004f: ldloc.1 - IL_0050: ldfld int32 TestFunction16/U::item2 - IL_0055: stloc.s V_8 - IL_0057: ldloc.s V_7 - IL_0059: ldloc.s V_8 - IL_005b: bge.s IL_005f - - IL_005d: ldc.i4.m1 - IL_005e: ret - - IL_005f: ldloc.s V_7 - IL_0061: ldloc.s V_8 - IL_0063: cgt - IL_0065: ret + IL_003b: ret - IL_0066: ldc.i4.1 + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.s V_6 + IL_0043: ldloc.0 + IL_0044: ldfld int32 TestFunction16/U::item2 + IL_0049: stloc.s V_7 + IL_004b: ldloc.1 + IL_004c: ldfld int32 TestFunction16/U::item2 + IL_0051: stloc.s V_8 + IL_0053: ldloc.s V_7 + IL_0055: ldloc.s V_8 + IL_0057: cgt + IL_0059: ldloc.s V_7 + IL_005b: ldloc.s V_8 + IL_005d: clt + IL_005f: sub + IL_0060: ret + + IL_0061: ldc.i4.1 + IL_0062: ret + + IL_0063: ldarg.1 + IL_0064: brfalse.s IL_0068 + + IL_0066: ldc.i4.m1 IL_0067: ret - IL_0068: ldarg.1 - IL_0069: brfalse.s IL_006d - - IL_006b: ldc.i4.m1 - IL_006c: ret - - IL_006d: ldc.i4.0 - IL_006e: ret + IL_0068: ldc.i4.0 + IL_0069: ret } // end of method U::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -281,30 +273,30 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 121 (0x79) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 116 (0x74) + .maxstack 5 .locals init (class TestFunction16/U V_0, class TestFunction16/U V_1, class TestFunction16/U V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9) IL_0000: ldarg.1 IL_0001: unbox.any TestFunction16/U IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_006d + IL_0008: brfalse.s IL_0068 IL_000a: ldarg.1 IL_000b: unbox.any TestFunction16/U - IL_0010: brfalse.s IL_006b + IL_0010: brfalse.s IL_0066 IL_0012: ldarg.0 IL_0013: pop @@ -322,75 +314,67 @@ IL_0029: stloc.s V_6 IL_002b: ldloc.s V_5 IL_002d: ldloc.s V_6 - IL_002f: bge.s IL_0035 - - IL_0031: ldc.i4.m1 - IL_0032: nop - IL_0033: br.s IL_003c + IL_002f: cgt + IL_0031: ldloc.s V_5 + IL_0033: ldloc.s V_6 + IL_0035: clt + IL_0037: sub + IL_0038: stloc.3 + IL_0039: ldloc.3 + IL_003a: ldc.i4.0 + IL_003b: bge.s IL_003f - IL_0035: ldloc.s V_5 - IL_0037: ldloc.s V_6 - IL_0039: cgt - IL_003b: nop - IL_003c: stloc.3 IL_003d: ldloc.3 - IL_003e: ldc.i4.0 - IL_003f: bge.s IL_0043 + IL_003e: ret - IL_0041: ldloc.3 - IL_0042: ret + IL_003f: ldloc.3 + IL_0040: ldc.i4.0 + IL_0041: ble.s IL_0045 IL_0043: ldloc.3 - IL_0044: ldc.i4.0 - IL_0045: ble.s IL_0049 - - IL_0047: ldloc.3 - IL_0048: ret - - IL_0049: ldarg.2 - IL_004a: stloc.s V_7 - IL_004c: ldloc.1 - IL_004d: ldfld int32 TestFunction16/U::item2 - IL_0052: stloc.s V_8 - IL_0054: ldloc.2 - IL_0055: ldfld int32 TestFunction16/U::item2 - IL_005a: stloc.s V_9 - IL_005c: ldloc.s V_8 - IL_005e: ldloc.s V_9 - IL_0060: bge.s IL_0064 - - IL_0062: ldc.i4.m1 - IL_0063: ret - - IL_0064: ldloc.s V_8 - IL_0066: ldloc.s V_9 - IL_0068: cgt - IL_006a: ret - - IL_006b: ldc.i4.1 - IL_006c: ret - - IL_006d: ldarg.1 - IL_006e: unbox.any TestFunction16/U - IL_0073: brfalse.s IL_0077 - - IL_0075: ldc.i4.m1 - IL_0076: ret - - IL_0077: ldc.i4.0 - IL_0078: ret + IL_0044: ret + + IL_0045: ldarg.2 + IL_0046: stloc.s V_7 + IL_0048: ldloc.1 + IL_0049: ldfld int32 TestFunction16/U::item2 + IL_004e: stloc.s V_8 + IL_0050: ldloc.2 + IL_0051: ldfld int32 TestFunction16/U::item2 + IL_0056: stloc.s V_9 + IL_0058: ldloc.s V_8 + IL_005a: ldloc.s V_9 + IL_005c: cgt + IL_005e: ldloc.s V_8 + IL_0060: ldloc.s V_9 + IL_0062: clt + IL_0064: sub + IL_0065: ret + + IL_0066: ldc.i4.1 + IL_0067: ret + + IL_0068: ldarg.1 + IL_0069: unbox.any TestFunction16/U + IL_006e: brfalse.s IL_0072 + + IL_0070: ldc.i4.m1 + IL_0071: ret + + IL_0072: ldc.i4.0 + IL_0073: ret } // end of method U::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 7 .locals init (int32 V_0, class TestFunction16/U V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b @@ -442,28 +426,28 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction16/U::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction16/U::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method U::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 70 (0x46) .maxstack 4 .locals init (class TestFunction16/U V_0, class TestFunction16/U V_1, class TestFunction16/U V_2, class TestFunction16/U V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, - class [mscorlib]System.Collections.IEqualityComparer V_5) + class [System.Runtime]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_5) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003e @@ -516,7 +500,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction16/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class TestFunction16/U V_0, @@ -563,7 +547,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction16/U V_0) @@ -584,9 +568,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 TestFunction16/U::get_Tag() } // end of property U::Tag .property instance int32 Item1() @@ -594,8 +578,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction16/U::get_Item1() } // end of property U::Item1 .property instance int32 Item2() @@ -603,13 +587,13 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction16/U::get_Item2() } // end of property U::Item2 } // end of class U - .method public static class [mscorlib]System.Tuple`2 + .method public static class [System.Runtime]System.Tuple`2 TestFunction16(int32 inp) cil managed { // Code size 16 (0x10) @@ -622,15 +606,15 @@ IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldloc.0 - IL_000a: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_000a: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_000f: ret } // end of method TestFunction16::TestFunction16 } // end of class TestFunction16 .class private abstract auto ansi sealed ''.$TestFunction16 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -646,4 +630,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\TestFunctions\TestFunction16_fs\TestFunction16.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\TestFunctions\TestFunction16_fs\TestFunction16.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.debug.bsl index 8a556885362..ded94e51adc 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction17 { - // Offset: 0x00000000 Length: 0x000006A5 + // Offset: 0x00000000 Length: 0x0000069B // WARNING: managed resource file FSharpSignatureData.TestFunction17 created } .mresource public FSharpOptimizationData.TestFunction17 { - // Offset: 0x000006B0 Length: 0x000001CD + // Offset: 0x000006A0 Length: 0x000001D3 // WARNING: managed resource file FSharpOptimizationData.TestFunction17 created } .module TestFunction17.exe -// MVID: {624E339D-A624-45A8-A745-03839D334E62} +// MVID: {628F4C90-9846-1B91-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03950000 +// Image base: 0x000001E4B3470000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction17 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto ansi serializable sealed nested public R - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 02 00 00 00 00 00 ) .field assembly int32 x@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field assembly int32 y@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance int32 get_x() cil managed { @@ -92,7 +92,7 @@ // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction17/R::x@ @@ -105,7 +105,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -119,112 +119,104 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction17/R obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 127 (0x7f) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 119 (0x77) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9, - class [mscorlib]System.Collections.IComparer V_10, + class [System.Runtime]System.Collections.IComparer V_10, int32 V_11, int32 V_12) IL_0000: ldarg.0 - IL_0001: brfalse IL_0078 - - IL_0006: ldarg.1 - IL_0007: brfalse.s IL_0076 - - IL_0009: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_000e: stloc.1 - IL_000f: ldarg.0 - IL_0010: ldfld int32 TestFunction17/R::x@ - IL_0015: stloc.2 - IL_0016: ldarg.1 - IL_0017: ldfld int32 TestFunction17/R::x@ - IL_001c: stloc.3 - IL_001d: ldloc.1 - IL_001e: stloc.s V_4 - IL_0020: ldloc.2 - IL_0021: stloc.s V_5 - IL_0023: ldloc.3 - IL_0024: stloc.s V_6 - IL_0026: ldloc.s V_5 - IL_0028: ldloc.s V_6 - IL_002a: bge.s IL_0030 - - IL_002c: ldc.i4.m1 - IL_002d: nop - IL_002e: br.s IL_0037 - - IL_0030: ldloc.s V_5 - IL_0032: ldloc.s V_6 - IL_0034: cgt - IL_0036: nop - IL_0037: stloc.0 - IL_0038: ldloc.0 - IL_0039: ldc.i4.0 - IL_003a: bge.s IL_003e - - IL_003c: ldloc.0 - IL_003d: ret - - IL_003e: ldloc.0 - IL_003f: ldc.i4.0 - IL_0040: ble.s IL_0044 - - IL_0042: ldloc.0 - IL_0043: ret - - IL_0044: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0049: stloc.s V_7 - IL_004b: ldarg.0 - IL_004c: ldfld int32 TestFunction17/R::y@ - IL_0051: stloc.s V_8 - IL_0053: ldarg.1 - IL_0054: ldfld int32 TestFunction17/R::y@ - IL_0059: stloc.s V_9 - IL_005b: ldloc.s V_7 - IL_005d: stloc.s V_10 - IL_005f: ldloc.s V_8 - IL_0061: stloc.s V_11 - IL_0063: ldloc.s V_9 - IL_0065: stloc.s V_12 - IL_0067: ldloc.s V_11 - IL_0069: ldloc.s V_12 - IL_006b: bge.s IL_006f - - IL_006d: ldc.i4.m1 - IL_006e: ret - - IL_006f: ldloc.s V_11 - IL_0071: ldloc.s V_12 - IL_0073: cgt - IL_0075: ret - - IL_0076: ldc.i4.1 - IL_0077: ret - - IL_0078: ldarg.1 - IL_0079: brfalse.s IL_007d + IL_0001: brfalse.s IL_0070 - IL_007b: ldc.i4.m1 - IL_007c: ret + IL_0003: ldarg.1 + IL_0004: brfalse.s IL_006e - IL_007d: ldc.i4.0 - IL_007e: ret + IL_0006: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000b: stloc.1 + IL_000c: ldarg.0 + IL_000d: ldfld int32 TestFunction17/R::x@ + IL_0012: stloc.2 + IL_0013: ldarg.1 + IL_0014: ldfld int32 TestFunction17/R::x@ + IL_0019: stloc.3 + IL_001a: ldloc.1 + IL_001b: stloc.s V_4 + IL_001d: ldloc.2 + IL_001e: stloc.s V_5 + IL_0020: ldloc.3 + IL_0021: stloc.s V_6 + IL_0023: ldloc.s V_5 + IL_0025: ldloc.s V_6 + IL_0027: cgt + IL_0029: ldloc.s V_5 + IL_002b: ldloc.s V_6 + IL_002d: clt + IL_002f: sub + IL_0030: stloc.0 + IL_0031: ldloc.0 + IL_0032: ldc.i4.0 + IL_0033: bge.s IL_0037 + + IL_0035: ldloc.0 + IL_0036: ret + + IL_0037: ldloc.0 + IL_0038: ldc.i4.0 + IL_0039: ble.s IL_003d + + IL_003b: ldloc.0 + IL_003c: ret + + IL_003d: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0042: stloc.s V_7 + IL_0044: ldarg.0 + IL_0045: ldfld int32 TestFunction17/R::y@ + IL_004a: stloc.s V_8 + IL_004c: ldarg.1 + IL_004d: ldfld int32 TestFunction17/R::y@ + IL_0052: stloc.s V_9 + IL_0054: ldloc.s V_7 + IL_0056: stloc.s V_10 + IL_0058: ldloc.s V_8 + IL_005a: stloc.s V_11 + IL_005c: ldloc.s V_9 + IL_005e: stloc.s V_12 + IL_0060: ldloc.s V_11 + IL_0062: ldloc.s V_12 + IL_0064: cgt + IL_0066: ldloc.s V_11 + IL_0068: ldloc.s V_12 + IL_006a: clt + IL_006c: sub + IL_006d: ret + + IL_006e: ldc.i4.1 + IL_006f: ret + + IL_0070: ldarg.1 + IL_0071: brfalse.s IL_0075 + + IL_0073: ldc.i4.m1 + IL_0074: ret + + IL_0075: ldc.i4.0 + IL_0076: ret } // end of method R::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -236,24 +228,24 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 142 (0x8e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 134 (0x86) + .maxstack 5 .locals init (class TestFunction17/R V_0, class TestFunction17/R V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8, - class [mscorlib]System.Collections.IComparer V_9, + class [System.Runtime]System.Collections.IComparer V_9, int32 V_10, int32 V_11, - class [mscorlib]System.Collections.IComparer V_12, + class [System.Runtime]System.Collections.IComparer V_12, int32 V_13, int32 V_14) IL_0000: ldarg.1 @@ -262,106 +254,98 @@ IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldarg.0 - IL_000a: brfalse IL_0082 - - IL_000f: ldarg.1 - IL_0010: unbox.any TestFunction17/R - IL_0015: brfalse.s IL_0080 - - IL_0017: ldarg.2 - IL_0018: stloc.3 - IL_0019: ldarg.0 - IL_001a: ldfld int32 TestFunction17/R::x@ - IL_001f: stloc.s V_4 - IL_0021: ldloc.1 - IL_0022: ldfld int32 TestFunction17/R::x@ - IL_0027: stloc.s V_5 - IL_0029: ldloc.3 - IL_002a: stloc.s V_6 - IL_002c: ldloc.s V_4 - IL_002e: stloc.s V_7 - IL_0030: ldloc.s V_5 - IL_0032: stloc.s V_8 - IL_0034: ldloc.s V_7 - IL_0036: ldloc.s V_8 - IL_0038: bge.s IL_003e - - IL_003a: ldc.i4.m1 - IL_003b: nop - IL_003c: br.s IL_0045 - - IL_003e: ldloc.s V_7 - IL_0040: ldloc.s V_8 - IL_0042: cgt - IL_0044: nop - IL_0045: stloc.2 - IL_0046: ldloc.2 - IL_0047: ldc.i4.0 - IL_0048: bge.s IL_004c - - IL_004a: ldloc.2 - IL_004b: ret + IL_000a: brfalse.s IL_007a + + IL_000c: ldarg.1 + IL_000d: unbox.any TestFunction17/R + IL_0012: brfalse.s IL_0078 + + IL_0014: ldarg.2 + IL_0015: stloc.3 + IL_0016: ldarg.0 + IL_0017: ldfld int32 TestFunction17/R::x@ + IL_001c: stloc.s V_4 + IL_001e: ldloc.1 + IL_001f: ldfld int32 TestFunction17/R::x@ + IL_0024: stloc.s V_5 + IL_0026: ldloc.3 + IL_0027: stloc.s V_6 + IL_0029: ldloc.s V_4 + IL_002b: stloc.s V_7 + IL_002d: ldloc.s V_5 + IL_002f: stloc.s V_8 + IL_0031: ldloc.s V_7 + IL_0033: ldloc.s V_8 + IL_0035: cgt + IL_0037: ldloc.s V_7 + IL_0039: ldloc.s V_8 + IL_003b: clt + IL_003d: sub + IL_003e: stloc.2 + IL_003f: ldloc.2 + IL_0040: ldc.i4.0 + IL_0041: bge.s IL_0045 + + IL_0043: ldloc.2 + IL_0044: ret + + IL_0045: ldloc.2 + IL_0046: ldc.i4.0 + IL_0047: ble.s IL_004b + + IL_0049: ldloc.2 + IL_004a: ret + + IL_004b: ldarg.2 + IL_004c: stloc.s V_9 + IL_004e: ldarg.0 + IL_004f: ldfld int32 TestFunction17/R::y@ + IL_0054: stloc.s V_10 + IL_0056: ldloc.1 + IL_0057: ldfld int32 TestFunction17/R::y@ + IL_005c: stloc.s V_11 + IL_005e: ldloc.s V_9 + IL_0060: stloc.s V_12 + IL_0062: ldloc.s V_10 + IL_0064: stloc.s V_13 + IL_0066: ldloc.s V_11 + IL_0068: stloc.s V_14 + IL_006a: ldloc.s V_13 + IL_006c: ldloc.s V_14 + IL_006e: cgt + IL_0070: ldloc.s V_13 + IL_0072: ldloc.s V_14 + IL_0074: clt + IL_0076: sub + IL_0077: ret + + IL_0078: ldc.i4.1 + IL_0079: ret + + IL_007a: ldarg.1 + IL_007b: unbox.any TestFunction17/R + IL_0080: brfalse.s IL_0084 + + IL_0082: ldc.i4.m1 + IL_0083: ret - IL_004c: ldloc.2 - IL_004d: ldc.i4.0 - IL_004e: ble.s IL_0052 - - IL_0050: ldloc.2 - IL_0051: ret - - IL_0052: ldarg.2 - IL_0053: stloc.s V_9 - IL_0055: ldarg.0 - IL_0056: ldfld int32 TestFunction17/R::y@ - IL_005b: stloc.s V_10 - IL_005d: ldloc.1 - IL_005e: ldfld int32 TestFunction17/R::y@ - IL_0063: stloc.s V_11 - IL_0065: ldloc.s V_9 - IL_0067: stloc.s V_12 - IL_0069: ldloc.s V_10 - IL_006b: stloc.s V_13 - IL_006d: ldloc.s V_11 - IL_006f: stloc.s V_14 - IL_0071: ldloc.s V_13 - IL_0073: ldloc.s V_14 - IL_0075: bge.s IL_0079 - - IL_0077: ldc.i4.m1 - IL_0078: ret - - IL_0079: ldloc.s V_13 - IL_007b: ldloc.s V_14 - IL_007d: cgt - IL_007f: ret - - IL_0080: ldc.i4.1 - IL_0081: ret - - IL_0082: ldarg.1 - IL_0083: unbox.any TestFunction17/R - IL_0088: brfalse.s IL_008c - - IL_008a: ldc.i4.m1 - IL_008b: ret - - IL_008c: ldc.i4.0 - IL_008d: ret + IL_0084: ldc.i4.0 + IL_0085: ret } // end of method R::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 68 (0x44) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0042 @@ -415,32 +399,32 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction17/R::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction17/R::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method R::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 84 (0x54) .maxstack 4 .locals init (class TestFunction17/R V_0, class TestFunction17/R V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IEqualityComparer V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6, + class [System.Runtime]System.Collections.IEqualityComparer V_5, + class [System.Runtime]System.Collections.IEqualityComparer V_6, int32 V_7, int32 V_8, - class [mscorlib]System.Collections.IEqualityComparer V_9) + class [System.Runtime]System.Collections.IEqualityComparer V_9) IL_0000: ldarg.0 IL_0001: brfalse.s IL_004c @@ -499,7 +483,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction17/R obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 47 (0x2f) .maxstack 8 IL_0000: ldarg.0 @@ -538,7 +522,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction17/R V_0) @@ -571,7 +555,7 @@ } // end of property R::y } // end of class R - .method public static class [mscorlib]System.Tuple`2 + .method public static class [System.Runtime]System.Tuple`2 TestFunction17(int32 inp) cil managed { // Code size 16 (0x10) @@ -584,15 +568,15 @@ IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldloc.0 - IL_000a: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_000a: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_000f: ret } // end of method TestFunction17::TestFunction17 } // end of class TestFunction17 .class private abstract auto ansi sealed ''.$TestFunction17 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -608,4 +592,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\TestFunctions\TestFunction17_fs\TestFunction17.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\TestFunctions\TestFunction17_fs\TestFunction17.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.release.bsl index 97ec3e65a06..d34dc778f67 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction17.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction17 { - // Offset: 0x00000000 Length: 0x000006A9 + // Offset: 0x00000000 Length: 0x000006B9 // WARNING: managed resource file FSharpSignatureData.TestFunction17 created } .mresource public FSharpOptimizationData.TestFunction17 { - // Offset: 0x000006B0 Length: 0x000001CD + // Offset: 0x000006C0 Length: 0x000001D3 // WARNING: managed resource file FSharpOptimizationData.TestFunction17 created } .module TestFunction17.exe -// MVID: {624E31F9-A624-45A8-A745-0383F9314E62} +// MVID: {628FBBC7-FD30-37B3-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03C50000 +// Image base: 0x000002560FC20000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction17 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto ansi serializable sealed nested public R - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 02 00 00 00 00 00 ) .field assembly int32 x@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field assembly int32 y@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance int32 get_x() cil managed { @@ -92,7 +92,7 @@ // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction17/R::x@ @@ -105,7 +105,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -119,23 +119,23 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction17/R obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 99 (0x63) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 94 (0x5e) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_005c + IL_0001: brfalse.s IL_0057 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_005a + IL_0004: brfalse.s IL_0055 - IL_0006: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0006: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_000b: stloc.1 IL_000c: ldarg.0 IL_000d: ldfld int32 TestFunction17/R::x@ @@ -145,68 +145,60 @@ IL_0019: stloc.3 IL_001a: ldloc.2 IL_001b: ldloc.3 - IL_001c: bge.s IL_0022 - - IL_001e: ldc.i4.m1 - IL_001f: nop - IL_0020: br.s IL_0027 + IL_001c: cgt + IL_001e: ldloc.2 + IL_001f: ldloc.3 + IL_0020: clt + IL_0022: sub + IL_0023: stloc.0 + IL_0024: ldloc.0 + IL_0025: ldc.i4.0 + IL_0026: bge.s IL_002a - IL_0022: ldloc.2 - IL_0023: ldloc.3 - IL_0024: cgt - IL_0026: nop - IL_0027: stloc.0 IL_0028: ldloc.0 - IL_0029: ldc.i4.0 - IL_002a: bge.s IL_002e + IL_0029: ret - IL_002c: ldloc.0 - IL_002d: ret + IL_002a: ldloc.0 + IL_002b: ldc.i4.0 + IL_002c: ble.s IL_0030 IL_002e: ldloc.0 - IL_002f: ldc.i4.0 - IL_0030: ble.s IL_0034 - - IL_0032: ldloc.0 - IL_0033: ret - - IL_0034: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0039: stloc.s V_4 - IL_003b: ldarg.0 - IL_003c: ldfld int32 TestFunction17/R::y@ - IL_0041: stloc.s V_5 - IL_0043: ldarg.1 - IL_0044: ldfld int32 TestFunction17/R::y@ - IL_0049: stloc.s V_6 - IL_004b: ldloc.s V_5 - IL_004d: ldloc.s V_6 - IL_004f: bge.s IL_0053 - - IL_0051: ldc.i4.m1 - IL_0052: ret - - IL_0053: ldloc.s V_5 - IL_0055: ldloc.s V_6 - IL_0057: cgt - IL_0059: ret - - IL_005a: ldc.i4.1 + IL_002f: ret + + IL_0030: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0035: stloc.s V_4 + IL_0037: ldarg.0 + IL_0038: ldfld int32 TestFunction17/R::y@ + IL_003d: stloc.s V_5 + IL_003f: ldarg.1 + IL_0040: ldfld int32 TestFunction17/R::y@ + IL_0045: stloc.s V_6 + IL_0047: ldloc.s V_5 + IL_0049: ldloc.s V_6 + IL_004b: cgt + IL_004d: ldloc.s V_5 + IL_004f: ldloc.s V_6 + IL_0051: clt + IL_0053: sub + IL_0054: ret + + IL_0055: ldc.i4.1 + IL_0056: ret + + IL_0057: ldarg.1 + IL_0058: brfalse.s IL_005c + + IL_005a: ldc.i4.m1 IL_005b: ret - IL_005c: ldarg.1 - IL_005d: brfalse.s IL_0061 - - IL_005f: ldc.i4.m1 - IL_0060: ret - - IL_0061: ldc.i4.0 - IL_0062: ret + IL_005c: ldc.i4.0 + IL_005d: ret } // end of method R::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -218,18 +210,18 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 116 (0x74) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 111 (0x6f) + .maxstack 5 .locals init (class TestFunction17/R V_0, class TestFunction17/R V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 @@ -238,11 +230,11 @@ IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldarg.0 - IL_000a: brfalse.s IL_0068 + IL_000a: brfalse.s IL_0063 IL_000c: ldarg.1 IL_000d: unbox.any TestFunction17/R - IL_0012: brfalse.s IL_0066 + IL_0012: brfalse.s IL_0061 IL_0014: ldarg.2 IL_0015: stloc.3 @@ -254,74 +246,66 @@ IL_0024: stloc.s V_5 IL_0026: ldloc.s V_4 IL_0028: ldloc.s V_5 - IL_002a: bge.s IL_0030 - - IL_002c: ldc.i4.m1 - IL_002d: nop - IL_002e: br.s IL_0037 + IL_002a: cgt + IL_002c: ldloc.s V_4 + IL_002e: ldloc.s V_5 + IL_0030: clt + IL_0032: sub + IL_0033: stloc.2 + IL_0034: ldloc.2 + IL_0035: ldc.i4.0 + IL_0036: bge.s IL_003a - IL_0030: ldloc.s V_4 - IL_0032: ldloc.s V_5 - IL_0034: cgt - IL_0036: nop - IL_0037: stloc.2 IL_0038: ldloc.2 - IL_0039: ldc.i4.0 - IL_003a: bge.s IL_003e + IL_0039: ret - IL_003c: ldloc.2 - IL_003d: ret + IL_003a: ldloc.2 + IL_003b: ldc.i4.0 + IL_003c: ble.s IL_0040 IL_003e: ldloc.2 - IL_003f: ldc.i4.0 - IL_0040: ble.s IL_0044 + IL_003f: ret - IL_0042: ldloc.2 - IL_0043: ret + IL_0040: ldarg.2 + IL_0041: stloc.s V_6 + IL_0043: ldarg.0 + IL_0044: ldfld int32 TestFunction17/R::y@ + IL_0049: stloc.s V_7 + IL_004b: ldloc.1 + IL_004c: ldfld int32 TestFunction17/R::y@ + IL_0051: stloc.s V_8 + IL_0053: ldloc.s V_7 + IL_0055: ldloc.s V_8 + IL_0057: cgt + IL_0059: ldloc.s V_7 + IL_005b: ldloc.s V_8 + IL_005d: clt + IL_005f: sub + IL_0060: ret - IL_0044: ldarg.2 - IL_0045: stloc.s V_6 - IL_0047: ldarg.0 - IL_0048: ldfld int32 TestFunction17/R::y@ - IL_004d: stloc.s V_7 - IL_004f: ldloc.1 - IL_0050: ldfld int32 TestFunction17/R::y@ - IL_0055: stloc.s V_8 - IL_0057: ldloc.s V_7 - IL_0059: ldloc.s V_8 - IL_005b: bge.s IL_005f - - IL_005d: ldc.i4.m1 - IL_005e: ret - - IL_005f: ldloc.s V_7 - IL_0061: ldloc.s V_8 - IL_0063: cgt - IL_0065: ret - - IL_0066: ldc.i4.1 - IL_0067: ret - - IL_0068: ldarg.1 - IL_0069: unbox.any TestFunction17/R - IL_006e: brfalse.s IL_0072 - - IL_0070: ldc.i4.m1 - IL_0071: ret - - IL_0072: ldc.i4.0 - IL_0073: ret + IL_0061: ldc.i4.1 + IL_0062: ret + + IL_0063: ldarg.1 + IL_0064: unbox.any TestFunction17/R + IL_0069: brfalse.s IL_006d + + IL_006b: ldc.i4.m1 + IL_006c: ret + + IL_006d: ldc.i4.0 + IL_006e: ret } // end of method R::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 55 (0x37) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -367,26 +351,26 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction17/R::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction17/R::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method R::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 62 (0x3e) .maxstack 4 .locals init (class TestFunction17/R V_0, class TestFunction17/R V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0036 @@ -433,7 +417,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction17/R obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 47 (0x2f) .maxstack 8 IL_0000: ldarg.0 @@ -472,7 +456,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction17/R V_0) @@ -505,7 +489,7 @@ } // end of property R::y } // end of class R - .method public static class [mscorlib]System.Tuple`2 + .method public static class [System.Runtime]System.Tuple`2 TestFunction17(int32 inp) cil managed { // Code size 16 (0x10) @@ -518,15 +502,15 @@ IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldloc.0 - IL_000a: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_000a: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_000f: ret } // end of method TestFunction17::TestFunction17 } // end of class TestFunction17 .class private abstract auto ansi sealed ''.$TestFunction17 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -542,4 +526,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\TestFunctions\TestFunction17_fs\TestFunction17.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\TestFunctions\TestFunction17_fs\TestFunction17.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.debug.bsl index 1df32e48d5e..6edae290c3b 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,56 +21,56 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction21 { - // Offset: 0x00000000 Length: 0x000006AC + // Offset: 0x00000000 Length: 0x000006A2 // WARNING: managed resource file FSharpSignatureData.TestFunction21 created } .mresource public FSharpOptimizationData.TestFunction21 { - // Offset: 0x000006B0 Length: 0x000001CD + // Offset: 0x000006A8 Length: 0x000001D3 // WARNING: managed resource file FSharpOptimizationData.TestFunction21 created } .module TestFunction21.exe -// MVID: {624E339D-A643-45E6-A745-03839D334E62} +// MVID: {628F4C90-83B6-1458-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03000000 +// Image base: 0x000001767E840000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction21 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit U - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class TestFunction21/U NewU(int32 item1, int32 item2) cil managed @@ -90,12 +90,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction21/U::item1 @@ -108,8 +108,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -120,8 +120,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -132,8 +132,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -145,8 +145,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -160,7 +160,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -174,120 +174,112 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction21/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 140 (0x8c) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 132 (0x84) + .maxstack 5 .locals init (class TestFunction21/U V_0, class TestFunction21/U V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8, - class [mscorlib]System.Collections.IComparer V_9, + class [System.Runtime]System.Collections.IComparer V_9, int32 V_10, int32 V_11, - class [mscorlib]System.Collections.IComparer V_12, + class [System.Runtime]System.Collections.IComparer V_12, int32 V_13, int32 V_14) IL_0000: ldarg.0 - IL_0001: brfalse IL_0085 + IL_0001: brfalse IL_007d IL_0006: ldarg.1 - IL_0007: brfalse IL_0083 - - IL_000c: ldarg.0 - IL_000d: pop - IL_000e: ldarg.0 - IL_000f: stloc.0 - IL_0010: ldarg.1 - IL_0011: stloc.1 - IL_0012: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0017: stloc.3 - IL_0018: ldloc.0 - IL_0019: ldfld int32 TestFunction21/U::item1 - IL_001e: stloc.s V_4 - IL_0020: ldloc.1 - IL_0021: ldfld int32 TestFunction21/U::item1 - IL_0026: stloc.s V_5 - IL_0028: ldloc.3 - IL_0029: stloc.s V_6 - IL_002b: ldloc.s V_4 - IL_002d: stloc.s V_7 - IL_002f: ldloc.s V_5 - IL_0031: stloc.s V_8 - IL_0033: ldloc.s V_7 - IL_0035: ldloc.s V_8 - IL_0037: bge.s IL_003d - - IL_0039: ldc.i4.m1 - IL_003a: nop - IL_003b: br.s IL_0044 - - IL_003d: ldloc.s V_7 - IL_003f: ldloc.s V_8 - IL_0041: cgt - IL_0043: nop - IL_0044: stloc.2 - IL_0045: ldloc.2 - IL_0046: ldc.i4.0 - IL_0047: bge.s IL_004b - - IL_0049: ldloc.2 - IL_004a: ret + IL_0007: brfalse.s IL_007b - IL_004b: ldloc.2 - IL_004c: ldc.i4.0 - IL_004d: ble.s IL_0051 - - IL_004f: ldloc.2 - IL_0050: ret - - IL_0051: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0056: stloc.s V_9 - IL_0058: ldloc.0 - IL_0059: ldfld int32 TestFunction21/U::item2 - IL_005e: stloc.s V_10 - IL_0060: ldloc.1 - IL_0061: ldfld int32 TestFunction21/U::item2 - IL_0066: stloc.s V_11 - IL_0068: ldloc.s V_9 - IL_006a: stloc.s V_12 - IL_006c: ldloc.s V_10 - IL_006e: stloc.s V_13 - IL_0070: ldloc.s V_11 - IL_0072: stloc.s V_14 - IL_0074: ldloc.s V_13 - IL_0076: ldloc.s V_14 - IL_0078: bge.s IL_007c - - IL_007a: ldc.i4.m1 - IL_007b: ret - - IL_007c: ldloc.s V_13 - IL_007e: ldloc.s V_14 - IL_0080: cgt - IL_0082: ret - - IL_0083: ldc.i4.1 - IL_0084: ret - - IL_0085: ldarg.1 - IL_0086: brfalse.s IL_008a + IL_0009: ldarg.0 + IL_000a: pop + IL_000b: ldarg.0 + IL_000c: stloc.0 + IL_000d: ldarg.1 + IL_000e: stloc.1 + IL_000f: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0014: stloc.3 + IL_0015: ldloc.0 + IL_0016: ldfld int32 TestFunction21/U::item1 + IL_001b: stloc.s V_4 + IL_001d: ldloc.1 + IL_001e: ldfld int32 TestFunction21/U::item1 + IL_0023: stloc.s V_5 + IL_0025: ldloc.3 + IL_0026: stloc.s V_6 + IL_0028: ldloc.s V_4 + IL_002a: stloc.s V_7 + IL_002c: ldloc.s V_5 + IL_002e: stloc.s V_8 + IL_0030: ldloc.s V_7 + IL_0032: ldloc.s V_8 + IL_0034: cgt + IL_0036: ldloc.s V_7 + IL_0038: ldloc.s V_8 + IL_003a: clt + IL_003c: sub + IL_003d: stloc.2 + IL_003e: ldloc.2 + IL_003f: ldc.i4.0 + IL_0040: bge.s IL_0044 + + IL_0042: ldloc.2 + IL_0043: ret + + IL_0044: ldloc.2 + IL_0045: ldc.i4.0 + IL_0046: ble.s IL_004a + + IL_0048: ldloc.2 + IL_0049: ret + + IL_004a: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_004f: stloc.s V_9 + IL_0051: ldloc.0 + IL_0052: ldfld int32 TestFunction21/U::item2 + IL_0057: stloc.s V_10 + IL_0059: ldloc.1 + IL_005a: ldfld int32 TestFunction21/U::item2 + IL_005f: stloc.s V_11 + IL_0061: ldloc.s V_9 + IL_0063: stloc.s V_12 + IL_0065: ldloc.s V_10 + IL_0067: stloc.s V_13 + IL_0069: ldloc.s V_11 + IL_006b: stloc.s V_14 + IL_006d: ldloc.s V_13 + IL_006f: ldloc.s V_14 + IL_0071: cgt + IL_0073: ldloc.s V_13 + IL_0075: ldloc.s V_14 + IL_0077: clt + IL_0079: sub + IL_007a: ret + + IL_007b: ldc.i4.1 + IL_007c: ret + + IL_007d: ldarg.1 + IL_007e: brfalse.s IL_0082 - IL_0088: ldc.i4.m1 - IL_0089: ret + IL_0080: ldc.i4.m1 + IL_0081: ret - IL_008a: ldc.i4.0 - IL_008b: ret + IL_0082: ldc.i4.0 + IL_0083: ret } // end of method U::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -299,138 +291,130 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 151 (0x97) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 140 (0x8c) + .maxstack 5 .locals init (class TestFunction21/U V_0, class TestFunction21/U V_1, class TestFunction21/U V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9, - class [mscorlib]System.Collections.IComparer V_10, + class [System.Runtime]System.Collections.IComparer V_10, int32 V_11, int32 V_12, - class [mscorlib]System.Collections.IComparer V_13, + class [System.Runtime]System.Collections.IComparer V_13, int32 V_14, int32 V_15) IL_0000: ldarg.1 IL_0001: unbox.any TestFunction21/U IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse IL_008b + IL_0008: brfalse.s IL_0080 - IL_000d: ldarg.1 - IL_000e: unbox.any TestFunction21/U - IL_0013: brfalse IL_0089 - - IL_0018: ldarg.0 - IL_0019: pop - IL_001a: ldarg.0 - IL_001b: stloc.1 - IL_001c: ldloc.0 - IL_001d: stloc.2 - IL_001e: ldarg.2 - IL_001f: stloc.s V_4 - IL_0021: ldloc.1 - IL_0022: ldfld int32 TestFunction21/U::item1 - IL_0027: stloc.s V_5 - IL_0029: ldloc.2 - IL_002a: ldfld int32 TestFunction21/U::item1 - IL_002f: stloc.s V_6 - IL_0031: ldloc.s V_4 - IL_0033: stloc.s V_7 - IL_0035: ldloc.s V_5 - IL_0037: stloc.s V_8 - IL_0039: ldloc.s V_6 - IL_003b: stloc.s V_9 + IL_000a: ldarg.1 + IL_000b: unbox.any TestFunction21/U + IL_0010: brfalse.s IL_007e + + IL_0012: ldarg.0 + IL_0013: pop + IL_0014: ldarg.0 + IL_0015: stloc.1 + IL_0016: ldloc.0 + IL_0017: stloc.2 + IL_0018: ldarg.2 + IL_0019: stloc.s V_4 + IL_001b: ldloc.1 + IL_001c: ldfld int32 TestFunction21/U::item1 + IL_0021: stloc.s V_5 + IL_0023: ldloc.2 + IL_0024: ldfld int32 TestFunction21/U::item1 + IL_0029: stloc.s V_6 + IL_002b: ldloc.s V_4 + IL_002d: stloc.s V_7 + IL_002f: ldloc.s V_5 + IL_0031: stloc.s V_8 + IL_0033: ldloc.s V_6 + IL_0035: stloc.s V_9 + IL_0037: ldloc.s V_8 + IL_0039: ldloc.s V_9 + IL_003b: cgt IL_003d: ldloc.s V_8 IL_003f: ldloc.s V_9 - IL_0041: bge.s IL_0047 + IL_0041: clt + IL_0043: sub + IL_0044: stloc.3 + IL_0045: ldloc.3 + IL_0046: ldc.i4.0 + IL_0047: bge.s IL_004b - IL_0043: ldc.i4.m1 - IL_0044: nop - IL_0045: br.s IL_004e + IL_0049: ldloc.3 + IL_004a: ret - IL_0047: ldloc.s V_8 - IL_0049: ldloc.s V_9 - IL_004b: cgt - IL_004d: nop - IL_004e: stloc.3 - IL_004f: ldloc.3 - IL_0050: ldc.i4.0 - IL_0051: bge.s IL_0055 - - IL_0053: ldloc.3 - IL_0054: ret - - IL_0055: ldloc.3 - IL_0056: ldc.i4.0 - IL_0057: ble.s IL_005b - - IL_0059: ldloc.3 - IL_005a: ret - - IL_005b: ldarg.2 - IL_005c: stloc.s V_10 - IL_005e: ldloc.1 - IL_005f: ldfld int32 TestFunction21/U::item2 - IL_0064: stloc.s V_11 - IL_0066: ldloc.2 - IL_0067: ldfld int32 TestFunction21/U::item2 - IL_006c: stloc.s V_12 - IL_006e: ldloc.s V_10 - IL_0070: stloc.s V_13 - IL_0072: ldloc.s V_11 - IL_0074: stloc.s V_14 - IL_0076: ldloc.s V_12 - IL_0078: stloc.s V_15 - IL_007a: ldloc.s V_14 - IL_007c: ldloc.s V_15 - IL_007e: bge.s IL_0082 + IL_004b: ldloc.3 + IL_004c: ldc.i4.0 + IL_004d: ble.s IL_0051 - IL_0080: ldc.i4.m1 - IL_0081: ret + IL_004f: ldloc.3 + IL_0050: ret - IL_0082: ldloc.s V_14 - IL_0084: ldloc.s V_15 - IL_0086: cgt - IL_0088: ret + IL_0051: ldarg.2 + IL_0052: stloc.s V_10 + IL_0054: ldloc.1 + IL_0055: ldfld int32 TestFunction21/U::item2 + IL_005a: stloc.s V_11 + IL_005c: ldloc.2 + IL_005d: ldfld int32 TestFunction21/U::item2 + IL_0062: stloc.s V_12 + IL_0064: ldloc.s V_10 + IL_0066: stloc.s V_13 + IL_0068: ldloc.s V_11 + IL_006a: stloc.s V_14 + IL_006c: ldloc.s V_12 + IL_006e: stloc.s V_15 + IL_0070: ldloc.s V_14 + IL_0072: ldloc.s V_15 + IL_0074: cgt + IL_0076: ldloc.s V_14 + IL_0078: ldloc.s V_15 + IL_007a: clt + IL_007c: sub + IL_007d: ret - IL_0089: ldc.i4.1 - IL_008a: ret + IL_007e: ldc.i4.1 + IL_007f: ret - IL_008b: ldarg.1 - IL_008c: unbox.any TestFunction21/U - IL_0091: brfalse.s IL_0095 + IL_0080: ldarg.1 + IL_0081: unbox.any TestFunction21/U + IL_0086: brfalse.s IL_008a - IL_0093: ldc.i4.m1 - IL_0094: ret + IL_0088: ldc.i4.m1 + IL_0089: ret - IL_0095: ldc.i4.0 - IL_0096: ret + IL_008a: ldc.i4.0 + IL_008b: ret } // end of method U::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 75 (0x4b) .maxstack 7 .locals init (int32 V_0, class TestFunction21/U V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, - class [mscorlib]System.Collections.IEqualityComparer V_5, + class [System.Runtime]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7) + class [System.Runtime]System.Collections.IEqualityComparer V_7) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0049 @@ -490,34 +474,34 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction21/U::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction21/U::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method U::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 94 (0x5e) .maxstack 4 .locals init (class TestFunction21/U V_0, class TestFunction21/U V_1, class TestFunction21/U V_2, class TestFunction21/U V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IEqualityComparer V_7, - class [mscorlib]System.Collections.IEqualityComparer V_8, + class [System.Runtime]System.Collections.IEqualityComparer V_7, + class [System.Runtime]System.Collections.IEqualityComparer V_8, int32 V_9, int32 V_10, - class [mscorlib]System.Collections.IEqualityComparer V_11) + class [System.Runtime]System.Collections.IEqualityComparer V_11) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0056 @@ -582,7 +566,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction21/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class TestFunction21/U V_0, @@ -629,7 +613,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction21/U V_0) @@ -650,9 +634,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 TestFunction21/U::get_Tag() } // end of property U::Tag .property instance int32 Item1() @@ -660,8 +644,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction21/U::get_Item1() } // end of property U::Item1 .property instance int32 Item2() @@ -669,8 +653,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction21/U::get_Item2() } // end of property U::Item2 } // end of class U @@ -679,14 +663,14 @@ extends class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 { .field public class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 clo2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 clo2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 @@ -716,14 +700,14 @@ extends class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2> { .field public class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2> clo1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2> clo1) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 @@ -769,8 +753,8 @@ IL_000a: ldfld int32 TestFunction21/U::item1 IL_000f: stloc.2 IL_0010: ldstr "a = %A, a = %A" - IL_0015: newobj instance void class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`5>,class [mscorlib]System.IO.TextWriter,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [mscorlib]System.Tuple`2>::.ctor(string) - IL_001a: call !!0 [FSharp.Core]Microsoft.FSharp.Core.ExtraTopLevelOperators::PrintFormatLine>>(class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`4) + IL_0015: newobj instance void class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`5>,class [System.Runtime]System.IO.TextWriter,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [System.Runtime]System.Tuple`2>::.ctor(string) + IL_001a: call !!0 [FSharp.Core]Microsoft.FSharp.Core.ExtraTopLevelOperators::PrintFormatLine>>(class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`4) IL_001f: stloc.3 IL_0020: ldloc.3 IL_0021: newobj instance void TestFunction21/TestFunction21@7::.ctor(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>) @@ -786,7 +770,7 @@ } // end of class TestFunction21 .class private abstract auto ansi sealed ''.$TestFunction21 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -802,4 +786,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\TestFunctions\TestFunction21_fs\TestFunction21.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\TestFunctions\TestFunction21_fs\TestFunction21.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.release.bsl index b832ffd5973..b27ba780bfe 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction21.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,56 +21,56 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction21 { - // Offset: 0x00000000 Length: 0x000006B0 + // Offset: 0x00000000 Length: 0x000006C0 // WARNING: managed resource file FSharpSignatureData.TestFunction21 created } .mresource public FSharpOptimizationData.TestFunction21 { - // Offset: 0x000006B8 Length: 0x000001CD + // Offset: 0x000006C8 Length: 0x000001D3 // WARNING: managed resource file FSharpOptimizationData.TestFunction21 created } .module TestFunction21.exe -// MVID: {624E31F9-A643-45E6-A745-0383F9314E62} +// MVID: {628FBBC7-1AB2-D0AF-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03DA0000 +// Image base: 0x0000022606FE0000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction21 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto autochar serializable sealed nested public beforefieldinit U - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { - .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl - 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. + .custom instance void [System.Runtime]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string) = ( 01 00 15 7B 5F 5F 44 65 62 75 67 44 69 73 70 6C // ...{__DebugDispl + 61 79 28 29 2C 6E 71 7D 00 00 ) // ay(),nq}.. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 01 00 00 00 00 00 ) .field assembly initonly int32 item1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .field assembly initonly int32 item2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method public static class TestFunction21/U NewU(int32 item1, int32 item2) cil managed @@ -90,12 +90,12 @@ instance void .ctor(int32 item1, int32 item2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction21/U::item1 @@ -108,8 +108,8 @@ .method public hidebysig instance int32 get_Item1() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -120,8 +120,8 @@ .method public hidebysig instance int32 get_Item2() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 @@ -132,8 +132,8 @@ .method public hidebysig instance int32 get_Tag() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 @@ -145,8 +145,8 @@ .method assembly hidebysig specialname instance object __DebugDisplay() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+0.8A" @@ -160,7 +160,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -174,23 +174,23 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction21/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 111 (0x6f) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 106 (0x6a) + .maxstack 5 .locals init (class TestFunction21/U V_0, class TestFunction21/U V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_0068 + IL_0001: brfalse.s IL_0063 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_0066 + IL_0004: brfalse.s IL_0061 IL_0006: ldarg.0 IL_0007: pop @@ -198,7 +198,7 @@ IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: stloc.1 - IL_000c: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_0011: stloc.3 IL_0012: ldloc.0 IL_0013: ldfld int32 TestFunction21/U::item1 @@ -208,68 +208,60 @@ IL_0020: stloc.s V_5 IL_0022: ldloc.s V_4 IL_0024: ldloc.s V_5 - IL_0026: bge.s IL_002c - - IL_0028: ldc.i4.m1 - IL_0029: nop - IL_002a: br.s IL_0033 + IL_0026: cgt + IL_0028: ldloc.s V_4 + IL_002a: ldloc.s V_5 + IL_002c: clt + IL_002e: sub + IL_002f: stloc.2 + IL_0030: ldloc.2 + IL_0031: ldc.i4.0 + IL_0032: bge.s IL_0036 - IL_002c: ldloc.s V_4 - IL_002e: ldloc.s V_5 - IL_0030: cgt - IL_0032: nop - IL_0033: stloc.2 IL_0034: ldloc.2 - IL_0035: ldc.i4.0 - IL_0036: bge.s IL_003a + IL_0035: ret - IL_0038: ldloc.2 - IL_0039: ret + IL_0036: ldloc.2 + IL_0037: ldc.i4.0 + IL_0038: ble.s IL_003c IL_003a: ldloc.2 - IL_003b: ldc.i4.0 - IL_003c: ble.s IL_0040 - - IL_003e: ldloc.2 - IL_003f: ret - - IL_0040: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0045: stloc.s V_6 - IL_0047: ldloc.0 - IL_0048: ldfld int32 TestFunction21/U::item2 - IL_004d: stloc.s V_7 - IL_004f: ldloc.1 - IL_0050: ldfld int32 TestFunction21/U::item2 - IL_0055: stloc.s V_8 - IL_0057: ldloc.s V_7 - IL_0059: ldloc.s V_8 - IL_005b: bge.s IL_005f - - IL_005d: ldc.i4.m1 - IL_005e: ret - - IL_005f: ldloc.s V_7 - IL_0061: ldloc.s V_8 - IL_0063: cgt - IL_0065: ret + IL_003b: ret - IL_0066: ldc.i4.1 + IL_003c: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0041: stloc.s V_6 + IL_0043: ldloc.0 + IL_0044: ldfld int32 TestFunction21/U::item2 + IL_0049: stloc.s V_7 + IL_004b: ldloc.1 + IL_004c: ldfld int32 TestFunction21/U::item2 + IL_0051: stloc.s V_8 + IL_0053: ldloc.s V_7 + IL_0055: ldloc.s V_8 + IL_0057: cgt + IL_0059: ldloc.s V_7 + IL_005b: ldloc.s V_8 + IL_005d: clt + IL_005f: sub + IL_0060: ret + + IL_0061: ldc.i4.1 + IL_0062: ret + + IL_0063: ldarg.1 + IL_0064: brfalse.s IL_0068 + + IL_0066: ldc.i4.m1 IL_0067: ret - IL_0068: ldarg.1 - IL_0069: brfalse.s IL_006d - - IL_006b: ldc.i4.m1 - IL_006c: ret - - IL_006d: ldc.i4.0 - IL_006e: ret + IL_0068: ldc.i4.0 + IL_0069: ret } // end of method U::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -281,30 +273,30 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 121 (0x79) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 116 (0x74) + .maxstack 5 .locals init (class TestFunction21/U V_0, class TestFunction21/U V_1, class TestFunction21/U V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9) IL_0000: ldarg.1 IL_0001: unbox.any TestFunction21/U IL_0006: stloc.0 IL_0007: ldarg.0 - IL_0008: brfalse.s IL_006d + IL_0008: brfalse.s IL_0068 IL_000a: ldarg.1 IL_000b: unbox.any TestFunction21/U - IL_0010: brfalse.s IL_006b + IL_0010: brfalse.s IL_0066 IL_0012: ldarg.0 IL_0013: pop @@ -322,75 +314,67 @@ IL_0029: stloc.s V_6 IL_002b: ldloc.s V_5 IL_002d: ldloc.s V_6 - IL_002f: bge.s IL_0035 - - IL_0031: ldc.i4.m1 - IL_0032: nop - IL_0033: br.s IL_003c + IL_002f: cgt + IL_0031: ldloc.s V_5 + IL_0033: ldloc.s V_6 + IL_0035: clt + IL_0037: sub + IL_0038: stloc.3 + IL_0039: ldloc.3 + IL_003a: ldc.i4.0 + IL_003b: bge.s IL_003f - IL_0035: ldloc.s V_5 - IL_0037: ldloc.s V_6 - IL_0039: cgt - IL_003b: nop - IL_003c: stloc.3 IL_003d: ldloc.3 - IL_003e: ldc.i4.0 - IL_003f: bge.s IL_0043 + IL_003e: ret - IL_0041: ldloc.3 - IL_0042: ret + IL_003f: ldloc.3 + IL_0040: ldc.i4.0 + IL_0041: ble.s IL_0045 IL_0043: ldloc.3 - IL_0044: ldc.i4.0 - IL_0045: ble.s IL_0049 - - IL_0047: ldloc.3 - IL_0048: ret - - IL_0049: ldarg.2 - IL_004a: stloc.s V_7 - IL_004c: ldloc.1 - IL_004d: ldfld int32 TestFunction21/U::item2 - IL_0052: stloc.s V_8 - IL_0054: ldloc.2 - IL_0055: ldfld int32 TestFunction21/U::item2 - IL_005a: stloc.s V_9 - IL_005c: ldloc.s V_8 - IL_005e: ldloc.s V_9 - IL_0060: bge.s IL_0064 - - IL_0062: ldc.i4.m1 - IL_0063: ret - - IL_0064: ldloc.s V_8 - IL_0066: ldloc.s V_9 - IL_0068: cgt - IL_006a: ret - - IL_006b: ldc.i4.1 - IL_006c: ret - - IL_006d: ldarg.1 - IL_006e: unbox.any TestFunction21/U - IL_0073: brfalse.s IL_0077 - - IL_0075: ldc.i4.m1 - IL_0076: ret - - IL_0077: ldc.i4.0 - IL_0078: ret + IL_0044: ret + + IL_0045: ldarg.2 + IL_0046: stloc.s V_7 + IL_0048: ldloc.1 + IL_0049: ldfld int32 TestFunction21/U::item2 + IL_004e: stloc.s V_8 + IL_0050: ldloc.2 + IL_0051: ldfld int32 TestFunction21/U::item2 + IL_0056: stloc.s V_9 + IL_0058: ldloc.s V_8 + IL_005a: ldloc.s V_9 + IL_005c: cgt + IL_005e: ldloc.s V_8 + IL_0060: ldloc.s V_9 + IL_0062: clt + IL_0064: sub + IL_0065: ret + + IL_0066: ldc.i4.1 + IL_0067: ret + + IL_0068: ldarg.1 + IL_0069: unbox.any TestFunction21/U + IL_006e: brfalse.s IL_0072 + + IL_0070: ldc.i4.m1 + IL_0071: ret + + IL_0072: ldc.i4.0 + IL_0073: ret } // end of method U::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 61 (0x3d) .maxstack 7 .locals init (int32 V_0, class TestFunction21/U V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003b @@ -442,28 +426,28 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction21/U::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction21/U::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method U::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 70 (0x46) .maxstack 4 .locals init (class TestFunction21/U V_0, class TestFunction21/U V_1, class TestFunction21/U V_2, class TestFunction21/U V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, - class [mscorlib]System.Collections.IEqualityComparer V_5) + class [System.Runtime]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_5) IL_0000: ldarg.0 IL_0001: brfalse.s IL_003e @@ -516,7 +500,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction21/U obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 53 (0x35) .maxstack 4 .locals init (class TestFunction21/U V_0, @@ -563,7 +547,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction21/U V_0) @@ -584,9 +568,9 @@ .property instance int32 Tag() { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .get instance int32 TestFunction21/U::get_Tag() } // end of property U::Tag .property instance int32 Item1() @@ -594,8 +578,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction21/U::get_Item1() } // end of property U::Item1 .property instance int32 Item2() @@ -603,8 +587,8 @@ .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags, int32, int32) = ( 01 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .get instance int32 TestFunction21/U::get_Item2() } // end of property U::Item2 } // end of class U @@ -613,14 +597,14 @@ extends class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 { .field public class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 clo2 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 clo2) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 @@ -650,14 +634,14 @@ extends class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2> { .field public class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2> clo1 - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) .method assembly specialname rtspecialname instance void .ctor(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2> clo1) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 @@ -703,8 +687,8 @@ IL_000a: ldfld int32 TestFunction21/U::item1 IL_000f: stloc.2 IL_0010: ldstr "a = %A, a = %A" - IL_0015: newobj instance void class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`5>,class [mscorlib]System.IO.TextWriter,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [mscorlib]System.Tuple`2>::.ctor(string) - IL_001a: call !!0 [FSharp.Core]Microsoft.FSharp.Core.ExtraTopLevelOperators::PrintFormatLine>>(class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`4) + IL_0015: newobj instance void class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`5>,class [System.Runtime]System.IO.TextWriter,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [System.Runtime]System.Tuple`2>::.ctor(string) + IL_001a: call !!0 [FSharp.Core]Microsoft.FSharp.Core.ExtraTopLevelOperators::PrintFormatLine>>(class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`4) IL_001f: stloc.3 IL_0020: ldloc.3 IL_0021: newobj instance void TestFunction21/TestFunction21@7::.ctor(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>) @@ -720,7 +704,7 @@ } // end of class TestFunction21 .class private abstract auto ansi sealed ''.$TestFunction21 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -736,4 +720,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net472\tests\EmittedIL\TestFunctions\TestFunction21_fs\TestFunction21.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\TestFunctions\TestFunction21_fs\TestFunction21.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.debug.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.debug.bsl index 7461bfbb39c..1139c1cdb0d 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.debug.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.debug.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction24 { - // Offset: 0x00000000 Length: 0x00000779 + // Offset: 0x00000000 Length: 0x0000076F // WARNING: managed resource file FSharpSignatureData.TestFunction24 created } .mresource public FSharpOptimizationData.TestFunction24 { - // Offset: 0x00000780 Length: 0x00000228 + // Offset: 0x00000778 Length: 0x0000022E // WARNING: managed resource file FSharpOptimizationData.TestFunction24 created } .module TestFunction24.exe -// MVID: {624F4F78-A643-4587-A745-0383784F4F62} +// MVID: {628F4C90-2576-C1EA-A745-0383904C8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x02D80000 +// Image base: 0x0000018C43700000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction24 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto ansi serializable sealed nested public Point - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 02 00 00 00 00 00 ) .field public int32 x@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field public int32 y@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance int32 get_x() cil managed { @@ -114,7 +114,7 @@ // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction24/Point::x@ @@ -127,7 +127,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -141,112 +141,104 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction24/Point obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 127 (0x7f) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 119 (0x77) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6, - class [mscorlib]System.Collections.IComparer V_7, + class [System.Runtime]System.Collections.IComparer V_7, int32 V_8, int32 V_9, - class [mscorlib]System.Collections.IComparer V_10, + class [System.Runtime]System.Collections.IComparer V_10, int32 V_11, int32 V_12) IL_0000: ldarg.0 - IL_0001: brfalse IL_0078 - - IL_0006: ldarg.1 - IL_0007: brfalse.s IL_0076 - - IL_0009: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_000e: stloc.1 - IL_000f: ldarg.0 - IL_0010: ldfld int32 TestFunction24/Point::x@ - IL_0015: stloc.2 - IL_0016: ldarg.1 - IL_0017: ldfld int32 TestFunction24/Point::x@ - IL_001c: stloc.3 - IL_001d: ldloc.1 - IL_001e: stloc.s V_4 - IL_0020: ldloc.2 - IL_0021: stloc.s V_5 - IL_0023: ldloc.3 - IL_0024: stloc.s V_6 - IL_0026: ldloc.s V_5 - IL_0028: ldloc.s V_6 - IL_002a: bge.s IL_0030 - - IL_002c: ldc.i4.m1 - IL_002d: nop - IL_002e: br.s IL_0037 - - IL_0030: ldloc.s V_5 - IL_0032: ldloc.s V_6 - IL_0034: cgt - IL_0036: nop - IL_0037: stloc.0 - IL_0038: ldloc.0 - IL_0039: ldc.i4.0 - IL_003a: bge.s IL_003e - - IL_003c: ldloc.0 - IL_003d: ret - - IL_003e: ldloc.0 - IL_003f: ldc.i4.0 - IL_0040: ble.s IL_0044 - - IL_0042: ldloc.0 - IL_0043: ret - - IL_0044: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0049: stloc.s V_7 - IL_004b: ldarg.0 - IL_004c: ldfld int32 TestFunction24/Point::y@ - IL_0051: stloc.s V_8 - IL_0053: ldarg.1 - IL_0054: ldfld int32 TestFunction24/Point::y@ - IL_0059: stloc.s V_9 - IL_005b: ldloc.s V_7 - IL_005d: stloc.s V_10 - IL_005f: ldloc.s V_8 - IL_0061: stloc.s V_11 - IL_0063: ldloc.s V_9 - IL_0065: stloc.s V_12 - IL_0067: ldloc.s V_11 - IL_0069: ldloc.s V_12 - IL_006b: bge.s IL_006f - - IL_006d: ldc.i4.m1 - IL_006e: ret - - IL_006f: ldloc.s V_11 - IL_0071: ldloc.s V_12 - IL_0073: cgt - IL_0075: ret - - IL_0076: ldc.i4.1 - IL_0077: ret - - IL_0078: ldarg.1 - IL_0079: brfalse.s IL_007d + IL_0001: brfalse.s IL_0070 - IL_007b: ldc.i4.m1 - IL_007c: ret + IL_0003: ldarg.1 + IL_0004: brfalse.s IL_006e - IL_007d: ldc.i4.0 - IL_007e: ret + IL_0006: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_000b: stloc.1 + IL_000c: ldarg.0 + IL_000d: ldfld int32 TestFunction24/Point::x@ + IL_0012: stloc.2 + IL_0013: ldarg.1 + IL_0014: ldfld int32 TestFunction24/Point::x@ + IL_0019: stloc.3 + IL_001a: ldloc.1 + IL_001b: stloc.s V_4 + IL_001d: ldloc.2 + IL_001e: stloc.s V_5 + IL_0020: ldloc.3 + IL_0021: stloc.s V_6 + IL_0023: ldloc.s V_5 + IL_0025: ldloc.s V_6 + IL_0027: cgt + IL_0029: ldloc.s V_5 + IL_002b: ldloc.s V_6 + IL_002d: clt + IL_002f: sub + IL_0030: stloc.0 + IL_0031: ldloc.0 + IL_0032: ldc.i4.0 + IL_0033: bge.s IL_0037 + + IL_0035: ldloc.0 + IL_0036: ret + + IL_0037: ldloc.0 + IL_0038: ldc.i4.0 + IL_0039: ble.s IL_003d + + IL_003b: ldloc.0 + IL_003c: ret + + IL_003d: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0042: stloc.s V_7 + IL_0044: ldarg.0 + IL_0045: ldfld int32 TestFunction24/Point::y@ + IL_004a: stloc.s V_8 + IL_004c: ldarg.1 + IL_004d: ldfld int32 TestFunction24/Point::y@ + IL_0052: stloc.s V_9 + IL_0054: ldloc.s V_7 + IL_0056: stloc.s V_10 + IL_0058: ldloc.s V_8 + IL_005a: stloc.s V_11 + IL_005c: ldloc.s V_9 + IL_005e: stloc.s V_12 + IL_0060: ldloc.s V_11 + IL_0062: ldloc.s V_12 + IL_0064: cgt + IL_0066: ldloc.s V_11 + IL_0068: ldloc.s V_12 + IL_006a: clt + IL_006c: sub + IL_006d: ret + + IL_006e: ldc.i4.1 + IL_006f: ret + + IL_0070: ldarg.1 + IL_0071: brfalse.s IL_0075 + + IL_0073: ldc.i4.m1 + IL_0074: ret + + IL_0075: ldc.i4.0 + IL_0076: ret } // end of method Point::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -258,24 +250,24 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 142 (0x8e) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 134 (0x86) + .maxstack 5 .locals init (class TestFunction24/Point V_0, class TestFunction24/Point V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8, - class [mscorlib]System.Collections.IComparer V_9, + class [System.Runtime]System.Collections.IComparer V_9, int32 V_10, int32 V_11, - class [mscorlib]System.Collections.IComparer V_12, + class [System.Runtime]System.Collections.IComparer V_12, int32 V_13, int32 V_14) IL_0000: ldarg.1 @@ -284,106 +276,98 @@ IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldarg.0 - IL_000a: brfalse IL_0082 - - IL_000f: ldarg.1 - IL_0010: unbox.any TestFunction24/Point - IL_0015: brfalse.s IL_0080 - - IL_0017: ldarg.2 - IL_0018: stloc.3 - IL_0019: ldarg.0 - IL_001a: ldfld int32 TestFunction24/Point::x@ - IL_001f: stloc.s V_4 - IL_0021: ldloc.1 - IL_0022: ldfld int32 TestFunction24/Point::x@ - IL_0027: stloc.s V_5 - IL_0029: ldloc.3 - IL_002a: stloc.s V_6 - IL_002c: ldloc.s V_4 - IL_002e: stloc.s V_7 - IL_0030: ldloc.s V_5 - IL_0032: stloc.s V_8 - IL_0034: ldloc.s V_7 - IL_0036: ldloc.s V_8 - IL_0038: bge.s IL_003e - - IL_003a: ldc.i4.m1 - IL_003b: nop - IL_003c: br.s IL_0045 - - IL_003e: ldloc.s V_7 - IL_0040: ldloc.s V_8 - IL_0042: cgt - IL_0044: nop - IL_0045: stloc.2 - IL_0046: ldloc.2 - IL_0047: ldc.i4.0 - IL_0048: bge.s IL_004c - - IL_004a: ldloc.2 - IL_004b: ret + IL_000a: brfalse.s IL_007a + + IL_000c: ldarg.1 + IL_000d: unbox.any TestFunction24/Point + IL_0012: brfalse.s IL_0078 + + IL_0014: ldarg.2 + IL_0015: stloc.3 + IL_0016: ldarg.0 + IL_0017: ldfld int32 TestFunction24/Point::x@ + IL_001c: stloc.s V_4 + IL_001e: ldloc.1 + IL_001f: ldfld int32 TestFunction24/Point::x@ + IL_0024: stloc.s V_5 + IL_0026: ldloc.3 + IL_0027: stloc.s V_6 + IL_0029: ldloc.s V_4 + IL_002b: stloc.s V_7 + IL_002d: ldloc.s V_5 + IL_002f: stloc.s V_8 + IL_0031: ldloc.s V_7 + IL_0033: ldloc.s V_8 + IL_0035: cgt + IL_0037: ldloc.s V_7 + IL_0039: ldloc.s V_8 + IL_003b: clt + IL_003d: sub + IL_003e: stloc.2 + IL_003f: ldloc.2 + IL_0040: ldc.i4.0 + IL_0041: bge.s IL_0045 + + IL_0043: ldloc.2 + IL_0044: ret + + IL_0045: ldloc.2 + IL_0046: ldc.i4.0 + IL_0047: ble.s IL_004b + + IL_0049: ldloc.2 + IL_004a: ret + + IL_004b: ldarg.2 + IL_004c: stloc.s V_9 + IL_004e: ldarg.0 + IL_004f: ldfld int32 TestFunction24/Point::y@ + IL_0054: stloc.s V_10 + IL_0056: ldloc.1 + IL_0057: ldfld int32 TestFunction24/Point::y@ + IL_005c: stloc.s V_11 + IL_005e: ldloc.s V_9 + IL_0060: stloc.s V_12 + IL_0062: ldloc.s V_10 + IL_0064: stloc.s V_13 + IL_0066: ldloc.s V_11 + IL_0068: stloc.s V_14 + IL_006a: ldloc.s V_13 + IL_006c: ldloc.s V_14 + IL_006e: cgt + IL_0070: ldloc.s V_13 + IL_0072: ldloc.s V_14 + IL_0074: clt + IL_0076: sub + IL_0077: ret + + IL_0078: ldc.i4.1 + IL_0079: ret + + IL_007a: ldarg.1 + IL_007b: unbox.any TestFunction24/Point + IL_0080: brfalse.s IL_0084 + + IL_0082: ldc.i4.m1 + IL_0083: ret - IL_004c: ldloc.2 - IL_004d: ldc.i4.0 - IL_004e: ble.s IL_0052 - - IL_0050: ldloc.2 - IL_0051: ret - - IL_0052: ldarg.2 - IL_0053: stloc.s V_9 - IL_0055: ldarg.0 - IL_0056: ldfld int32 TestFunction24/Point::y@ - IL_005b: stloc.s V_10 - IL_005d: ldloc.1 - IL_005e: ldfld int32 TestFunction24/Point::y@ - IL_0063: stloc.s V_11 - IL_0065: ldloc.s V_9 - IL_0067: stloc.s V_12 - IL_0069: ldloc.s V_10 - IL_006b: stloc.s V_13 - IL_006d: ldloc.s V_11 - IL_006f: stloc.s V_14 - IL_0071: ldloc.s V_13 - IL_0073: ldloc.s V_14 - IL_0075: bge.s IL_0079 - - IL_0077: ldc.i4.m1 - IL_0078: ret - - IL_0079: ldloc.s V_13 - IL_007b: ldloc.s V_14 - IL_007d: cgt - IL_007f: ret - - IL_0080: ldc.i4.1 - IL_0081: ret - - IL_0082: ldarg.1 - IL_0083: unbox.any TestFunction24/Point - IL_0088: brfalse.s IL_008c - - IL_008a: ldc.i4.m1 - IL_008b: ret - - IL_008c: ldc.i4.0 - IL_008d: ret + IL_0084: ldc.i4.0 + IL_0085: ret } // end of method Point::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 68 (0x44) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_1, int32 V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3, - class [mscorlib]System.Collections.IEqualityComparer V_4, + class [System.Runtime]System.Collections.IEqualityComparer V_3, + class [System.Runtime]System.Collections.IEqualityComparer V_4, int32 V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6) + class [System.Runtime]System.Collections.IEqualityComparer V_6) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0042 @@ -437,32 +421,32 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction24/Point::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction24/Point::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Point::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 84 (0x54) .maxstack 4 .locals init (class TestFunction24/Point V_0, class TestFunction24/Point V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_2, int32 V_3, int32 V_4, - class [mscorlib]System.Collections.IEqualityComparer V_5, - class [mscorlib]System.Collections.IEqualityComparer V_6, + class [System.Runtime]System.Collections.IEqualityComparer V_5, + class [System.Runtime]System.Collections.IEqualityComparer V_6, int32 V_7, int32 V_8, - class [mscorlib]System.Collections.IEqualityComparer V_9) + class [System.Runtime]System.Collections.IEqualityComparer V_9) IL_0000: ldarg.0 IL_0001: brfalse.s IL_004c @@ -521,7 +505,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction24/Point obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 47 (0x2f) .maxstack 8 IL_0000: ldarg.0 @@ -560,7 +544,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction24/Point V_0) @@ -632,10 +616,10 @@ IL_001e: ldloc.s V_5 IL_0020: ldloc.s V_6 IL_0022: conv.i - IL_0023: sizeof [mscorlib]System.Int32 + IL_0023: sizeof [System.Runtime]System.Int32 IL_0029: mul IL_002a: add - IL_002b: ldobj [mscorlib]System.Int32 + IL_002b: ldobj [System.Runtime]System.Int32 IL_0030: ldloc.1 IL_0031: stloc.s V_7 IL_0033: ldc.i4.1 @@ -647,10 +631,10 @@ IL_003e: ldloc.s V_9 IL_0040: ldloc.s V_10 IL_0042: conv.i - IL_0043: sizeof [mscorlib]System.Int32 + IL_0043: sizeof [System.Runtime]System.Int32 IL_0049: mul IL_004a: add - IL_004b: ldobj [mscorlib]System.Int32 + IL_004b: ldobj [System.Runtime]System.Int32 IL_0050: add IL_0051: ret } // end of method TestFunction24::pinObject @@ -672,9 +656,9 @@ IL_0010: conv.i IL_0011: stloc.1 IL_0012: ldloc.1 - IL_0013: ldobj [mscorlib]System.Int32 + IL_0013: ldobj [System.Runtime]System.Int32 IL_0018: ldloc.1 - IL_0019: ldobj [mscorlib]System.Int32 + IL_0019: ldobj [System.Runtime]System.Int32 IL_001e: add IL_001f: ret } // end of method TestFunction24::pinRef @@ -696,31 +680,31 @@ native int V_10, int32 V_11) IL_0000: ldc.i4.6 - IL_0001: newarr [mscorlib]System.Double + IL_0001: newarr [System.Runtime]System.Double IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.r8 0.0 - IL_0011: stelem [mscorlib]System.Double + IL_0011: stelem [System.Runtime]System.Double IL_0016: dup IL_0017: ldc.i4.1 IL_0018: ldc.r8 1.5 - IL_0021: stelem [mscorlib]System.Double + IL_0021: stelem [System.Runtime]System.Double IL_0026: dup IL_0027: ldc.i4.2 IL_0028: ldc.r8 2.2999999999999998 - IL_0031: stelem [mscorlib]System.Double + IL_0031: stelem [System.Runtime]System.Double IL_0036: dup IL_0037: ldc.i4.3 IL_0038: ldc.r8 3.3999999999999999 - IL_0041: stelem [mscorlib]System.Double + IL_0041: stelem [System.Runtime]System.Double IL_0046: dup IL_0047: ldc.i4.4 IL_0048: ldc.r8 4.0999999999999996 - IL_0051: stelem [mscorlib]System.Double + IL_0051: stelem [System.Runtime]System.Double IL_0056: dup IL_0057: ldc.i4.5 IL_0058: ldc.r8 5.9000000000000004 - IL_0061: stelem [mscorlib]System.Double + IL_0061: stelem [System.Runtime]System.Double IL_0066: stloc.0 IL_0067: ldloc.0 IL_0068: stloc.2 @@ -733,7 +717,7 @@ IL_0074: ldloc.2 IL_0075: ldc.i4.0 - IL_0076: ldelema [mscorlib]System.Double + IL_0076: ldelema [System.Runtime]System.Double IL_007b: stloc.3 IL_007c: ldloc.3 IL_007d: conv.i @@ -760,10 +744,10 @@ IL_0098: ldloc.s V_6 IL_009a: ldloc.s V_7 IL_009c: conv.i - IL_009d: sizeof [mscorlib]System.Double + IL_009d: sizeof [System.Runtime]System.Double IL_00a3: mul IL_00a4: add - IL_00a5: ldobj [mscorlib]System.Double + IL_00a5: ldobj [System.Runtime]System.Double IL_00aa: ldloc.1 IL_00ab: stloc.s V_8 IL_00ad: ldc.i4.1 @@ -775,10 +759,10 @@ IL_00b8: ldloc.s V_10 IL_00ba: ldloc.s V_11 IL_00bc: conv.i - IL_00bd: sizeof [mscorlib]System.Double + IL_00bd: sizeof [System.Runtime]System.Double IL_00c3: mul IL_00c4: add - IL_00c5: ldobj [mscorlib]System.Double + IL_00c5: ldobj [System.Runtime]System.Double IL_00ca: add IL_00cb: ret } // end of method TestFunction24::pinArray1 @@ -799,35 +783,35 @@ native int V_9, int32 V_10) IL_0000: ldc.i4.6 - IL_0001: newarr [mscorlib]System.Double + IL_0001: newarr [System.Runtime]System.Double IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.r8 0.0 - IL_0011: stelem [mscorlib]System.Double + IL_0011: stelem [System.Runtime]System.Double IL_0016: dup IL_0017: ldc.i4.1 IL_0018: ldc.r8 1.5 - IL_0021: stelem [mscorlib]System.Double + IL_0021: stelem [System.Runtime]System.Double IL_0026: dup IL_0027: ldc.i4.2 IL_0028: ldc.r8 2.2999999999999998 - IL_0031: stelem [mscorlib]System.Double + IL_0031: stelem [System.Runtime]System.Double IL_0036: dup IL_0037: ldc.i4.3 IL_0038: ldc.r8 3.3999999999999999 - IL_0041: stelem [mscorlib]System.Double + IL_0041: stelem [System.Runtime]System.Double IL_0046: dup IL_0047: ldc.i4.4 IL_0048: ldc.r8 4.0999999999999996 - IL_0051: stelem [mscorlib]System.Double + IL_0051: stelem [System.Runtime]System.Double IL_0056: dup IL_0057: ldc.i4.5 IL_0058: ldc.r8 5.9000000000000004 - IL_0061: stelem [mscorlib]System.Double + IL_0061: stelem [System.Runtime]System.Double IL_0066: stloc.0 IL_0067: ldloc.0 IL_0068: ldc.i4.0 - IL_0069: ldelema [mscorlib]System.Double + IL_0069: ldelema [System.Runtime]System.Double IL_006e: stloc.2 IL_006f: ldloc.2 IL_0070: conv.i @@ -843,10 +827,10 @@ IL_007e: ldloc.s V_5 IL_0080: ldloc.s V_6 IL_0082: conv.i - IL_0083: sizeof [mscorlib]System.Double + IL_0083: sizeof [System.Runtime]System.Double IL_0089: mul IL_008a: add - IL_008b: ldobj [mscorlib]System.Double + IL_008b: ldobj [System.Runtime]System.Double IL_0090: ldloc.1 IL_0091: stloc.s V_7 IL_0093: ldc.i4.1 @@ -858,15 +842,15 @@ IL_009e: ldloc.s V_9 IL_00a0: ldloc.s V_10 IL_00a2: conv.i - IL_00a3: sizeof [mscorlib]System.Double + IL_00a3: sizeof [System.Runtime]System.Double IL_00a9: mul IL_00aa: add - IL_00ab: ldobj [mscorlib]System.Double + IL_00ab: ldobj [System.Runtime]System.Double IL_00b0: add IL_00b1: ret } // end of method TestFunction24::pinArray2 - .method public static class [mscorlib]System.Tuple`2 + .method public static class [System.Runtime]System.Tuple`2 pinString() cil managed { // Code size 93 (0x5d) @@ -891,7 +875,7 @@ IL_000b: ldloc.2 IL_000c: conv.i - IL_000d: call int32 [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::get_OffsetToStringData() + IL_000d: call int32 [System.Runtime]System.Runtime.CompilerServices.RuntimeHelpers::get_OffsetToStringData() IL_0012: add IL_0013: nop IL_0014: br.s IL_0018 @@ -910,10 +894,10 @@ IL_0025: ldloc.s V_5 IL_0027: ldloc.s V_6 IL_0029: conv.i - IL_002a: sizeof [mscorlib]System.Char + IL_002a: sizeof [System.Runtime]System.Char IL_0030: mul IL_0031: add - IL_0032: ldobj [mscorlib]System.Char + IL_0032: ldobj [System.Runtime]System.Char IL_0037: ldloc.1 IL_0038: stloc.s V_7 IL_003a: ldc.i4.1 @@ -925,19 +909,19 @@ IL_0045: ldloc.s V_9 IL_0047: ldloc.s V_10 IL_0049: conv.i - IL_004a: sizeof [mscorlib]System.Char + IL_004a: sizeof [System.Runtime]System.Char IL_0050: mul IL_0051: add - IL_0052: ldobj [mscorlib]System.Char - IL_0057: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_0052: ldobj [System.Runtime]System.Char + IL_0057: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_005c: ret } // end of method TestFunction24::pinString } // end of class TestFunction24 .class private abstract auto ansi sealed ''.$TestFunction24 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -953,4 +937,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net472\tests\EmittedIL\TestFunctions\TestFunction24_fs\TestFunction24.res +// WARNING: Created Win32 resource file C:\dev\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Debug\net6.0\tests\EmittedIL\TestFunctions\TestFunction24_fs\TestFunction24.res diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.release.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.release.bsl index 48412c6b3d6..51afb9c71dd 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.release.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/TestFunctions/TestFunction24.fs.il.release.bsl @@ -4,10 +4,10 @@ // Metadata version: v4.0.30319 -.assembly extern mscorlib +.assembly extern System.Runtime { - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. - .ver 4:0:0:0 + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: + .ver 6:0:0:0 } .assembly extern FSharp.Core { @@ -21,50 +21,50 @@ int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) // --- The following custom attribute is added automatically, do not uncomment ------- - // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) + // .custom instance void [System.Runtime]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .mresource public FSharpSignatureData.TestFunction24 { - // Offset: 0x00000000 Length: 0x0000077D + // Offset: 0x00000000 Length: 0x0000078D // WARNING: managed resource file FSharpSignatureData.TestFunction24 created } .mresource public FSharpOptimizationData.TestFunction24 { - // Offset: 0x00000788 Length: 0x00000228 + // Offset: 0x00000798 Length: 0x0000022E // WARNING: managed resource file FSharpOptimizationData.TestFunction24 created } .module TestFunction24.exe -// MVID: {624F4DF2-A643-4587-A745-0383F24D4F62} +// MVID: {628FBBC7-30D0-AD8E-A745-0383C7BB8F62} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY -// Image base: 0x03D60000 +// Image base: 0x0000013F6FC80000 // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi sealed TestFunction24 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .class auto ansi serializable sealed nested public Point - extends [mscorlib]System.Object - implements class [mscorlib]System.IEquatable`1, - [mscorlib]System.Collections.IStructuralEquatable, - class [mscorlib]System.IComparable`1, - [mscorlib]System.IComparable, - [mscorlib]System.Collections.IStructuralComparable + extends [System.Runtime]System.Object + implements class [System.Runtime]System.IEquatable`1, + [System.Runtime]System.Collections.IStructuralEquatable, + class [System.Runtime]System.IComparable`1, + [System.Runtime]System.IComparable, + [System.Runtime]System.Collections.IStructuralComparable { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 02 00 00 00 00 00 ) .field public int32 x@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field public int32 y@ - .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [System.Runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [System.Runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance int32 get_x() cil managed { @@ -114,7 +114,7 @@ // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() + IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 TestFunction24/Point::x@ @@ -127,7 +127,7 @@ .method public strict virtual instance string ToString() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr "%+A" @@ -141,23 +141,23 @@ .method public hidebysig virtual final instance int32 CompareTo(class TestFunction24/Point obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 99 (0x63) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 94 (0x5e) + .maxstack 5 .locals init (int32 V_0, - class [mscorlib]System.Collections.IComparer V_1, + class [System.Runtime]System.Collections.IComparer V_1, int32 V_2, int32 V_3, - class [mscorlib]System.Collections.IComparer V_4, + class [System.Runtime]System.Collections.IComparer V_4, int32 V_5, int32 V_6) IL_0000: ldarg.0 - IL_0001: brfalse.s IL_005c + IL_0001: brfalse.s IL_0057 IL_0003: ldarg.1 - IL_0004: brfalse.s IL_005a + IL_0004: brfalse.s IL_0055 - IL_0006: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0006: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() IL_000b: stloc.1 IL_000c: ldarg.0 IL_000d: ldfld int32 TestFunction24/Point::x@ @@ -167,68 +167,60 @@ IL_0019: stloc.3 IL_001a: ldloc.2 IL_001b: ldloc.3 - IL_001c: bge.s IL_0022 - - IL_001e: ldc.i4.m1 - IL_001f: nop - IL_0020: br.s IL_0027 + IL_001c: cgt + IL_001e: ldloc.2 + IL_001f: ldloc.3 + IL_0020: clt + IL_0022: sub + IL_0023: stloc.0 + IL_0024: ldloc.0 + IL_0025: ldc.i4.0 + IL_0026: bge.s IL_002a - IL_0022: ldloc.2 - IL_0023: ldloc.3 - IL_0024: cgt - IL_0026: nop - IL_0027: stloc.0 IL_0028: ldloc.0 - IL_0029: ldc.i4.0 - IL_002a: bge.s IL_002e + IL_0029: ret - IL_002c: ldloc.0 - IL_002d: ret + IL_002a: ldloc.0 + IL_002b: ldc.i4.0 + IL_002c: ble.s IL_0030 IL_002e: ldloc.0 - IL_002f: ldc.i4.0 - IL_0030: ble.s IL_0034 - - IL_0032: ldloc.0 - IL_0033: ret - - IL_0034: call class [mscorlib]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() - IL_0039: stloc.s V_4 - IL_003b: ldarg.0 - IL_003c: ldfld int32 TestFunction24/Point::y@ - IL_0041: stloc.s V_5 - IL_0043: ldarg.1 - IL_0044: ldfld int32 TestFunction24/Point::y@ - IL_0049: stloc.s V_6 - IL_004b: ldloc.s V_5 - IL_004d: ldloc.s V_6 - IL_004f: bge.s IL_0053 - - IL_0051: ldc.i4.m1 - IL_0052: ret - - IL_0053: ldloc.s V_5 - IL_0055: ldloc.s V_6 - IL_0057: cgt - IL_0059: ret - - IL_005a: ldc.i4.1 + IL_002f: ret + + IL_0030: call class [System.Runtime]System.Collections.IComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericComparer() + IL_0035: stloc.s V_4 + IL_0037: ldarg.0 + IL_0038: ldfld int32 TestFunction24/Point::y@ + IL_003d: stloc.s V_5 + IL_003f: ldarg.1 + IL_0040: ldfld int32 TestFunction24/Point::y@ + IL_0045: stloc.s V_6 + IL_0047: ldloc.s V_5 + IL_0049: ldloc.s V_6 + IL_004b: cgt + IL_004d: ldloc.s V_5 + IL_004f: ldloc.s V_6 + IL_0051: clt + IL_0053: sub + IL_0054: ret + + IL_0055: ldc.i4.1 + IL_0056: ret + + IL_0057: ldarg.1 + IL_0058: brfalse.s IL_005c + + IL_005a: ldc.i4.m1 IL_005b: ret - IL_005c: ldarg.1 - IL_005d: brfalse.s IL_0061 - - IL_005f: ldc.i4.m1 - IL_0060: ret - - IL_0061: ldc.i4.0 - IL_0062: ret + IL_005c: ldc.i4.0 + IL_005d: ret } // end of method Point::CompareTo .method public hidebysig virtual final instance int32 CompareTo(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 @@ -240,18 +232,18 @@ .method public hidebysig virtual final instance int32 CompareTo(object obj, - class [mscorlib]System.Collections.IComparer comp) cil managed + class [System.Runtime]System.Collections.IComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) - // Code size 116 (0x74) - .maxstack 4 + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + // Code size 111 (0x6f) + .maxstack 5 .locals init (class TestFunction24/Point V_0, class TestFunction24/Point V_1, int32 V_2, - class [mscorlib]System.Collections.IComparer V_3, + class [System.Runtime]System.Collections.IComparer V_3, int32 V_4, int32 V_5, - class [mscorlib]System.Collections.IComparer V_6, + class [System.Runtime]System.Collections.IComparer V_6, int32 V_7, int32 V_8) IL_0000: ldarg.1 @@ -260,11 +252,11 @@ IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldarg.0 - IL_000a: brfalse.s IL_0068 + IL_000a: brfalse.s IL_0063 IL_000c: ldarg.1 IL_000d: unbox.any TestFunction24/Point - IL_0012: brfalse.s IL_0066 + IL_0012: brfalse.s IL_0061 IL_0014: ldarg.2 IL_0015: stloc.3 @@ -276,74 +268,66 @@ IL_0024: stloc.s V_5 IL_0026: ldloc.s V_4 IL_0028: ldloc.s V_5 - IL_002a: bge.s IL_0030 - - IL_002c: ldc.i4.m1 - IL_002d: nop - IL_002e: br.s IL_0037 + IL_002a: cgt + IL_002c: ldloc.s V_4 + IL_002e: ldloc.s V_5 + IL_0030: clt + IL_0032: sub + IL_0033: stloc.2 + IL_0034: ldloc.2 + IL_0035: ldc.i4.0 + IL_0036: bge.s IL_003a - IL_0030: ldloc.s V_4 - IL_0032: ldloc.s V_5 - IL_0034: cgt - IL_0036: nop - IL_0037: stloc.2 IL_0038: ldloc.2 - IL_0039: ldc.i4.0 - IL_003a: bge.s IL_003e + IL_0039: ret - IL_003c: ldloc.2 - IL_003d: ret + IL_003a: ldloc.2 + IL_003b: ldc.i4.0 + IL_003c: ble.s IL_0040 IL_003e: ldloc.2 - IL_003f: ldc.i4.0 - IL_0040: ble.s IL_0044 + IL_003f: ret - IL_0042: ldloc.2 - IL_0043: ret + IL_0040: ldarg.2 + IL_0041: stloc.s V_6 + IL_0043: ldarg.0 + IL_0044: ldfld int32 TestFunction24/Point::y@ + IL_0049: stloc.s V_7 + IL_004b: ldloc.1 + IL_004c: ldfld int32 TestFunction24/Point::y@ + IL_0051: stloc.s V_8 + IL_0053: ldloc.s V_7 + IL_0055: ldloc.s V_8 + IL_0057: cgt + IL_0059: ldloc.s V_7 + IL_005b: ldloc.s V_8 + IL_005d: clt + IL_005f: sub + IL_0060: ret - IL_0044: ldarg.2 - IL_0045: stloc.s V_6 - IL_0047: ldarg.0 - IL_0048: ldfld int32 TestFunction24/Point::y@ - IL_004d: stloc.s V_7 - IL_004f: ldloc.1 - IL_0050: ldfld int32 TestFunction24/Point::y@ - IL_0055: stloc.s V_8 - IL_0057: ldloc.s V_7 - IL_0059: ldloc.s V_8 - IL_005b: bge.s IL_005f - - IL_005d: ldc.i4.m1 - IL_005e: ret - - IL_005f: ldloc.s V_7 - IL_0061: ldloc.s V_8 - IL_0063: cgt - IL_0065: ret - - IL_0066: ldc.i4.1 - IL_0067: ret - - IL_0068: ldarg.1 - IL_0069: unbox.any TestFunction24/Point - IL_006e: brfalse.s IL_0072 - - IL_0070: ldc.i4.m1 - IL_0071: ret - - IL_0072: ldc.i4.0 - IL_0073: ret + IL_0061: ldc.i4.1 + IL_0062: ret + + IL_0063: ldarg.1 + IL_0064: unbox.any TestFunction24/Point + IL_0069: brfalse.s IL_006d + + IL_006b: ldc.i4.m1 + IL_006c: ret + + IL_006d: ldc.i4.0 + IL_006e: ret } // end of method Point::CompareTo .method public hidebysig virtual final - instance int32 GetHashCode(class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + instance int32 GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 55 (0x37) .maxstack 7 .locals init (int32 V_0, - class [mscorlib]System.Collections.IEqualityComparer V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2) + class [System.Runtime]System.Collections.IEqualityComparer V_1, + class [System.Runtime]System.Collections.IEqualityComparer V_2) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0035 @@ -389,26 +373,26 @@ .method public hidebysig virtual final instance int32 GetHashCode() cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 - IL_0001: call class [mscorlib]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() - IL_0006: callvirt instance int32 TestFunction24/Point::GetHashCode(class [mscorlib]System.Collections.IEqualityComparer) + IL_0001: call class [System.Runtime]System.Collections.IEqualityComparer [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives::get_GenericEqualityComparer() + IL_0006: callvirt instance int32 TestFunction24/Point::GetHashCode(class [System.Runtime]System.Collections.IEqualityComparer) IL_000b: ret } // end of method Point::GetHashCode .method public hidebysig virtual final instance bool Equals(object obj, - class [mscorlib]System.Collections.IEqualityComparer comp) cil managed + class [System.Runtime]System.Collections.IEqualityComparer comp) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 62 (0x3e) .maxstack 4 .locals init (class TestFunction24/Point V_0, class TestFunction24/Point V_1, - class [mscorlib]System.Collections.IEqualityComparer V_2, - class [mscorlib]System.Collections.IEqualityComparer V_3) + class [System.Runtime]System.Collections.IEqualityComparer V_2, + class [System.Runtime]System.Collections.IEqualityComparer V_3) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0036 @@ -455,7 +439,7 @@ .method public hidebysig virtual final instance bool Equals(class TestFunction24/Point obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 47 (0x2f) .maxstack 8 IL_0000: ldarg.0 @@ -494,7 +478,7 @@ .method public hidebysig virtual final instance bool Equals(object obj) cil managed { - .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 20 (0x14) .maxstack 4 .locals init (class TestFunction24/Point V_0) @@ -558,10 +542,10 @@ IL_0017: ldloc.3 IL_0018: ldloc.s V_4 IL_001a: conv.i - IL_001b: sizeof [mscorlib]System.Int32 + IL_001b: sizeof [System.Runtime]System.Int32 IL_0021: mul IL_0022: add - IL_0023: ldobj [mscorlib]System.Int32 + IL_0023: ldobj [System.Runtime]System.Int32 IL_0028: ldloc.1 IL_0029: stloc.s V_5 IL_002b: ldc.i4.1 @@ -569,10 +553,10 @@ IL_002e: ldloc.s V_5 IL_0030: ldloc.s V_6 IL_0032: conv.i - IL_0033: sizeof [mscorlib]System.Int32 + IL_0033: sizeof [System.Runtime]System.Int32 IL_0039: mul IL_003a: add - IL_003b: ldobj [mscorlib]System.Int32 + IL_003b: ldobj [System.Runtime]System.Int32 IL_0040: add IL_0041: ret } // end of method TestFunction24::pinObject @@ -594,9 +578,9 @@ IL_0010: conv.i IL_0011: stloc.1 IL_0012: ldloc.1 - IL_0013: ldobj [mscorlib]System.Int32 + IL_0013: ldobj [System.Runtime]System.Int32 IL_0018: ldloc.1 - IL_0019: ldobj [mscorlib]System.Int32 + IL_0019: ldobj [System.Runtime]System.Int32 IL_001e: add IL_001f: ret } // end of method TestFunction24::pinRef @@ -614,31 +598,31 @@ native int V_6, int32 V_7) IL_0000: ldc.i4.6 - IL_0001: newarr [mscorlib]System.Double + IL_0001: newarr [System.Runtime]System.Double IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.r8 0.0 - IL_0011: stelem [mscorlib]System.Double + IL_0011: stelem [System.Runtime]System.Double IL_0016: dup IL_0017: ldc.i4.1 IL_0018: ldc.r8 1.5 - IL_0021: stelem [mscorlib]System.Double + IL_0021: stelem [System.Runtime]System.Double IL_0026: dup IL_0027: ldc.i4.2 IL_0028: ldc.r8 2.2999999999999998 - IL_0031: stelem [mscorlib]System.Double + IL_0031: stelem [System.Runtime]System.Double IL_0036: dup IL_0037: ldc.i4.3 IL_0038: ldc.r8 3.3999999999999999 - IL_0041: stelem [mscorlib]System.Double + IL_0041: stelem [System.Runtime]System.Double IL_0046: dup IL_0047: ldc.i4.4 IL_0048: ldc.r8 4.0999999999999996 - IL_0051: stelem [mscorlib]System.Double + IL_0051: stelem [System.Runtime]System.Double IL_0056: dup IL_0057: ldc.i4.5 IL_0058: ldc.r8 5.9000000000000004 - IL_0061: stelem [mscorlib]System.Double + IL_0061: stelem [System.Runtime]System.Double IL_0066: stloc.0 IL_0067: ldloc.0 IL_0068: stloc.2 @@ -651,7 +635,7 @@ IL_0074: ldloc.2 IL_0075: ldc.i4.0 - IL_0076: ldelema [mscorlib]System.Double + IL_0076: ldelema [System.Runtime]System.Double IL_007b: stloc.3 IL_007c: ldloc.3 IL_007d: conv.i @@ -674,10 +658,10 @@ IL_0090: ldloc.s V_4 IL_0092: ldloc.s V_5 IL_0094: conv.i - IL_0095: sizeof [mscorlib]System.Double + IL_0095: sizeof [System.Runtime]System.Double IL_009b: mul IL_009c: add - IL_009d: ldobj [mscorlib]System.Double + IL_009d: ldobj [System.Runtime]System.Double IL_00a2: ldloc.1 IL_00a3: stloc.s V_6 IL_00a5: ldc.i4.1 @@ -685,10 +669,10 @@ IL_00a8: ldloc.s V_6 IL_00aa: ldloc.s V_7 IL_00ac: conv.i - IL_00ad: sizeof [mscorlib]System.Double + IL_00ad: sizeof [System.Runtime]System.Double IL_00b3: mul IL_00b4: add - IL_00b5: ldobj [mscorlib]System.Double + IL_00b5: ldobj [System.Runtime]System.Double IL_00ba: add IL_00bb: ret } // end of method TestFunction24::pinArray1 @@ -705,35 +689,35 @@ native int V_5, int32 V_6) IL_0000: ldc.i4.6 - IL_0001: newarr [mscorlib]System.Double + IL_0001: newarr [System.Runtime]System.Double IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.r8 0.0 - IL_0011: stelem [mscorlib]System.Double + IL_0011: stelem [System.Runtime]System.Double IL_0016: dup IL_0017: ldc.i4.1 IL_0018: ldc.r8 1.5 - IL_0021: stelem [mscorlib]System.Double + IL_0021: stelem [System.Runtime]System.Double IL_0026: dup IL_0027: ldc.i4.2 IL_0028: ldc.r8 2.2999999999999998 - IL_0031: stelem [mscorlib]System.Double + IL_0031: stelem [System.Runtime]System.Double IL_0036: dup IL_0037: ldc.i4.3 IL_0038: ldc.r8 3.3999999999999999 - IL_0041: stelem [mscorlib]System.Double + IL_0041: stelem [System.Runtime]System.Double IL_0046: dup IL_0047: ldc.i4.4 IL_0048: ldc.r8 4.0999999999999996 - IL_0051: stelem [mscorlib]System.Double + IL_0051: stelem [System.Runtime]System.Double IL_0056: dup IL_0057: ldc.i4.5 IL_0058: ldc.r8 5.9000000000000004 - IL_0061: stelem [mscorlib]System.Double + IL_0061: stelem [System.Runtime]System.Double IL_0066: stloc.0 IL_0067: ldloc.0 IL_0068: ldc.i4.0 - IL_0069: ldelema [mscorlib]System.Double + IL_0069: ldelema [System.Runtime]System.Double IL_006e: stloc.2 IL_006f: ldloc.2 IL_0070: conv.i @@ -745,10 +729,10 @@ IL_0077: ldloc.3 IL_0078: ldloc.s V_4 IL_007a: conv.i - IL_007b: sizeof [mscorlib]System.Double + IL_007b: sizeof [System.Runtime]System.Double IL_0081: mul IL_0082: add - IL_0083: ldobj [mscorlib]System.Double + IL_0083: ldobj [System.Runtime]System.Double IL_0088: ldloc.1 IL_0089: stloc.s V_5 IL_008b: ldc.i4.1 @@ -756,15 +740,15 @@ IL_008e: ldloc.s V_5 IL_0090: ldloc.s V_6 IL_0092: conv.i - IL_0093: sizeof [mscorlib]System.Double + IL_0093: sizeof [System.Runtime]System.Double IL_0099: mul IL_009a: add - IL_009b: ldobj [mscorlib]System.Double + IL_009b: ldobj [System.Runtime]System.Double IL_00a0: add IL_00a1: ret } // end of method TestFunction24::pinArray2 - .method public static class [mscorlib]System.Tuple`2 + .method public static class [System.Runtime]System.Tuple`2 pinString() cil managed { // Code size 77 (0x4d) @@ -785,7 +769,7 @@ IL_000b: ldloc.2 IL_000c: conv.i - IL_000d: call int32 [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::get_OffsetToStringData() + IL_000d: call int32 [System.Runtime]System.Runtime.CompilerServices.RuntimeHelpers::get_OffsetToStringData() IL_0012: add IL_0013: nop IL_0014: br.s IL_0018 @@ -800,10 +784,10 @@ IL_001e: ldloc.3 IL_001f: ldloc.s V_4 IL_0021: conv.i - IL_0022: sizeof [mscorlib]System.Char + IL_0022: sizeof [System.Runtime]System.Char IL_0028: mul IL_0029: add - IL_002a: ldobj [mscorlib]System.Char + IL_002a: ldobj [System.Runtime]System.Char IL_002f: ldloc.1 IL_0030: stloc.s V_5 IL_0032: ldc.i4.1 @@ -811,19 +795,19 @@ IL_0035: ldloc.s V_5 IL_0037: ldloc.s V_6 IL_0039: conv.i - IL_003a: sizeof [mscorlib]System.Char + IL_003a: sizeof [System.Runtime]System.Char IL_0040: mul IL_0041: add - IL_0042: ldobj [mscorlib]System.Char - IL_0047: newobj instance void class [mscorlib]System.Tuple`2::.ctor(!0, - !1) + IL_0042: ldobj [System.Runtime]System.Char + IL_0047: newobj instance void class [System.Runtime]System.Tuple`2::.ctor(!0, + !1) IL_004c: ret } // end of method TestFunction24::pinString } // end of class TestFunction24 .class private abstract auto ansi sealed ''.$TestFunction24 - extends [mscorlib]System.Object + extends [System.Runtime]System.Object { .method public static void main@() cil managed { @@ -839,4 +823,4 @@ // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file C:\kevinransom\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\release\net472\tests\EmittedIL\TestFunctions\TestFunction24_fs\TestFunction24.res +// WARNING: Created Win32 resource file C:\Users\vzari\code\fsharp\artifacts\bin\FSharp.Compiler.ComponentTests\Release\net6.0\tests\EmittedIL\TestFunctions\TestFunction24_fs\TestFunction24.res diff --git a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/InvalidNumericLiteralTests.fs b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/InvalidNumericLiteralTests.fs index 90cf5dd9db1..cb7cafe5aec 100644 --- a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/InvalidNumericLiteralTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/InvalidNumericLiteralTests.fs @@ -12,6 +12,7 @@ module ``Numeric Literals`` = [] [] + [] [] [] [] @@ -30,7 +31,7 @@ module ``Numeric Literals`` = |> typecheck |> shouldFail |> withSingleDiagnostic (Error 1156, Line 1, Col 9, Line 1, Col (9 + (String.length literal)), - "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger).") + "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint).") [] let ``3_(dot)1415F is invalid numeric literal``() = @@ -38,7 +39,7 @@ module ``Numeric Literals`` = |> typecheck |> shouldFail |> withDiagnostics [ - (Error 1156, Line 1, Col 9, Line 1, Col 11, "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger).";) + (Error 1156, Line 1, Col 9, Line 1, Col 11, "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint).") (Error 599, Line 1, Col 11, Line 1, Col 12,"Missing qualification after '.'")] [] @@ -68,7 +69,7 @@ let x = 1N "Operation could not be completed due to earlier error" ] - // Regressiont test for FSharp1.0: 2543 - Decimal literals do not support exponents + // Regression test for FSharp1.0: 2543 - Decimal literals do not support exponents [] [] [] diff --git a/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj b/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj index 5caee3b58ac..a899d457f86 100644 --- a/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj +++ b/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj @@ -32,6 +32,7 @@ + @@ -91,6 +92,7 @@ + @@ -121,6 +123,7 @@ + diff --git a/tests/FSharp.Compiler.ComponentTests/Language/AttributeCheckingTests.fs b/tests/FSharp.Compiler.ComponentTests/Language/AttributeCheckingTests.fs index 7b94f335e58..0896a2a67f2 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/AttributeCheckingTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/AttributeCheckingTests.fs @@ -41,4 +41,496 @@ type C() = """ |> ignoreWarnings |> compile - |> shouldSucceed \ No newline at end of file + |> shouldSucceed + + [] + let ``Obsolete attribute is not taken into account when used on on a member and and instantiate the type`` () = + Fsx """ +open System + +type C() = + + [] + member _.Update() = () + +let c = C() + """ + |> ignoreWarnings + |> compile + |> shouldSucceed + + [] + let ``Obsolete attribute is taken into account when used on type and and instantiate the type`` () = + Fsx """ +open System + +[] +type C() = + + member _.Update() = () + +let c = C() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 9, Line 9, Col 10, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on a member and invoking the member`` () = + Fsx """ +open System + +type C() = + [] + member _.Update() = () + +let c = C() +c.Update() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 1, Line 9, Col 9, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on type and invoking the member`` () = + Fsx """ +open System + +[] +type C() = + member _.Update() = () + +let c = C() +c.Update() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 8, Col 9, Line 8, Col 10, "This construct is deprecated. Use B instead"); + (Error 101, Line 9, Col 1, Line 9, Col 9, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on struct type and invoking the member`` () = + Fsx """ +open System + +[] +[] +type C = + member _.Update() = () + +let c = C() +c.Update() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 9, Line 9, Col 10, "This construct is deprecated. Use B instead"); + (Error 101, Line 10, Col 1, Line 10, Col 9, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on struct type and instantiate the type`` () = + Fsx """ +open System + +[] +[] +type C = + member _.Update() = () + +let c = C() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 9, Line 9, Col 10, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on a struct member and invoking the member`` () = + Fsx """ +open System + +[] +type C = + [] + member _.Update() = () + +let c = C() +c.Update() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 10, Col 1, Line 10, Col 9, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on a record property`` () = + Fsx """ +open System + +type C = + { [] X: int } + +let c = { X = 0 } + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 7, Col 9, Line 7, Col 18, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on a record and member invocation`` () = + Fsx """ +open System + +[] +type C = + { X : int } + + static member Update() = () + +C.Update() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 10, Col 1, Line 10, Col 2, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on a record member and method invocation`` () = + Fsx """ +open System + +type C = + { X : int } + [] + static member Update() = () + +C.Update() + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 1, Line 9, Col 9, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an enum and invocation`` () = + Fsx """ +open System + +[] +type Color = + | Red = 0 + | Green = 1 + +let c = Color.Red + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 9, Line 9, Col 14, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an enum entry and invocation`` () = + Fsx """ +open System + +type Color = + | [] Red = 0 + | Green = 1 + +let c = Color.Red + """ + |> ignoreWarnings + |> compile + |> shouldSucceed + + [] + let ``Obsolete attribute is taken into account when used on an type and use extension method`` () = + Fsx """ + +open System +open System.Runtime.CompilerServices + +[] +type Button = { Text : string } + +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + { this with Text = text } + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 13, Col 37, Line 13, Col 43, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an type property and use extension method`` () = + Fsx """ + +open System +open System.Runtime.CompilerServices + +type Button = { [] Text : string } + +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + { this with Text = text } + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 13, Col 9, Line 13, Col 34, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an type and property and use extension method`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +[] +type Button = { [] Text : string } + +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + { this with Text = text } + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 12, Col 37, Line 12, Col 43, "This construct is deprecated. Use B instead"); + (Error 101, Line 13, Col 9, Line 13, Col 34, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an type property and set via module`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +type Button = { [] Text : string } + +module Button = + + let set text = { Text = text } + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 20, Line 9, Col 36, "This construct is deprecated. Use B instead") + ] + + + [] + let ``Obsolete attribute is taken into account when used on an type and set property via module`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + + [] +type Button = { [] Text : string } + +module Button = + + let set text = { Text = text } + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 10, Col 20, Line 10, Col 36, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an type property and set property via module using an extension method`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +type Button = { [] Text : string } + +module Button = + + let set text = { Text = text } +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + Button.set text + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 9, Col 20, Line 9, Col 36, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an module and set property via module using an extension method`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +type Button = { Text : string } + +[] +module Button = + + let set text = { Text = text } + +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + Button.set text + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 17, Col 9, Line 17, Col 15, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an moudle and function and set property via module using an extesnion method`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +type Button = { Text : string } + +[] +module Button = + + [] + let set text = { Text = text } + +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + Button.set text + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 18, Col 9, Line 18, Col 15, "This construct is deprecated. Use B instead") + ] + + [] + let ``Obsolete attribute is taken into account when used on an moudle function and set property via module using an extesnion method`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +type Button = { Text : string } + +module Button = + + [] + let set text = { Text = text } + +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + Button.set text + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 17, Col 9, Line 17, Col 19, "This construct is deprecated. Use B instead") + ] + + + [] + let ``Obsolete attribute is taken into account when used on an type extensions and used on an instance`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +type Button = { Text : string } + +[] +[] +type ButtonExtensions = + + [] + static member inline text(this: Button, text: string) = + { this with Text = text } + +let b = { Text = "Hello" } +b.text("Hello 2") |> ignore + """ + |> ignoreWarnings + |> compile + |> shouldSucceed + + [] + let ``Obsolete attribute is taken into account when used on an type extensions static function and used on an instance`` () = + Fsx """ +open System +open System.Runtime.CompilerServices + +type Button = { Text : string } + +[] +type ButtonExtensions = + + [] + [] + static member inline text(this: Button, text: string) = + { this with Text = text } + +let b = { Text = "Hello" } +b.text("Hello 2") |> ignore + """ + |> ignoreWarnings + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 101, Line 16, Col 1, Line 16, Col 7, "This construct is deprecated. Use B instead") + ] \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Scripting/Interactive.fs b/tests/FSharp.Compiler.ComponentTests/Scripting/Interactive.fs index efdd5918cb4..faf21a9c7a9 100644 --- a/tests/FSharp.Compiler.ComponentTests/Scripting/Interactive.fs +++ b/tests/FSharp.Compiler.ComponentTests/Scripting/Interactive.fs @@ -14,6 +14,14 @@ module ``Interactive tests`` = |> withEvalTypeEquals typeof |> withEvalValueEquals 2 + [] + let ``EntryPoint attribute in FSI should produce a compiler warning`` () = + Fsx "[] let myFunc _ = 0" + |> eval + |> shouldFail + |> withDiagnostics [ + (Warning 2304, Line 1, Col 3, Line 1, Col 13, "Functions with [] are not invoked in FSI. 'myFunc' was not invoked. Execute 'myFunc ' in order to invoke 'myFunc' with the appropriate string array of command line arguments.") + ] module ``External FSI tests`` = [] @@ -24,6 +32,6 @@ module ``External FSI tests`` = [] let ``Invalid expression should fail``() = - Fsx "1+a" - |> runFsi - |> shouldFail \ No newline at end of file + Fsx "1+a" + |> runFsi + |> shouldFail diff --git a/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs b/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs index cf4c136d61e..2d54bbbea11 100644 --- a/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs +++ b/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs @@ -71,7 +71,7 @@ type DependencyManagerInteractiveTests() = let nativeProbingRoots () = Seq.empty - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -100,7 +100,7 @@ type DependencyManagerInteractiveTests() = let nativeProbingRoots () = Seq.empty - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -123,7 +123,7 @@ type DependencyManagerInteractiveTests() = let nativeProbingRoots () = Seq.empty - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -154,7 +154,7 @@ type DependencyManagerInteractiveTests() = let assemblyProbingPaths () = Seq.empty let nativeProbingRoots () = Seq.empty - use dp1 = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp1 = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -182,7 +182,7 @@ type DependencyManagerInteractiveTests() = Assert.Equal(1, result2.Roots |> Seq.length) Assert.True((result2.Roots |> Seq.head).EndsWith("/fsharp.data/3.3.3/")) - use dp2 = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp2 = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let idm2 = dp2.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") if RuntimeInformation.IsOSPlatform(OSPlatform.Windows) then @@ -209,7 +209,7 @@ type DependencyManagerInteractiveTests() = let nativeProbingRoots () = Seq.empty - use dp1 = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp1 = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -285,7 +285,7 @@ TorchSharp.Tensor.LongTensor.From([| 0L .. 100L |]).Device // Restore packages, Get Reference dll paths and package roots let result = - use dp = new DependencyProvider(AssemblyResolutionProbe(assemblyProbingPaths), NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(AssemblyResolutionProbe(assemblyProbingPaths), NativeResolutionProbe(nativeProbingRoots), false) let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") dp.Resolve(idm, ".fsx", packagemanagerlines, reportError, "net6.0") @@ -350,7 +350,7 @@ printfn ""%A"" result let scriptText = code.Replace("$(REFERENCES)", referenceText) // Use the dependency manager to resolve assemblies and native paths - use dp = new DependencyProvider(AssemblyResolutionProbe(assemblyProbingPaths), NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(AssemblyResolutionProbe(assemblyProbingPaths), NativeResolutionProbe(nativeProbingRoots), false) use script = new FSharpScript() let opt = script.Eval(scriptText) |> getValue @@ -381,7 +381,7 @@ printfn ""%A"" result // Restore packages, Get Reference dll paths and package roots let result = - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") dp.Resolve(idm, ".fsx", packagemanagerlines, reportError, "net6.0") @@ -462,7 +462,7 @@ printfn ""%A"" result // Restore packages, Get Reference dll paths and package roots let result = - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") dp.Resolve(idm, ".fsx", packagemanagerlines, reportError, "net6.0") @@ -519,7 +519,7 @@ x |> Seq.iter(fun r -> // Restore packages, Get Reference dll paths and package roots let result = - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") dp.Resolve(idm, ".fsx", packagemanagerlines, reportError, "net6.0") @@ -545,7 +545,7 @@ x |> Seq.iter(fun r -> // Restore packages, Get Reference dll paths and package roots let result = - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") dp.Resolve(idm, ".csx", packagemanagerlines, reportError, "net6.0") @@ -569,7 +569,7 @@ x |> Seq.iter(fun r -> // Set up native resolver to resolve dll's do - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) // Invoking a non-existent dll via pinvoke cause a probe. which should invoke the call back try Native.NoneSuch() |> ignore with _ -> () @@ -613,7 +613,7 @@ x |> Seq.iter(fun r -> // Set up native resolver to resolve dll's do - use dp = new DependencyProvider(AssemblyResolutionProbe(assemblyProbingPaths), NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(AssemblyResolutionProbe(assemblyProbingPaths), NativeResolutionProbe(nativeProbingRoots), false) // Invoking a non-existent dll via pinvoke cause a probe. which should invoke the call back try Native.NoneSuch() |> ignore with _ -> () @@ -678,7 +678,7 @@ x |> Seq.iter(fun r -> let mutable finalPath:string = null do initialPath <- appendSemiColon (Environment.GetEnvironmentVariable("PATH")) - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") let mutable currentPath:string = null if RuntimeInformation.IsOSPlatform(OSPlatform.Windows) then @@ -695,7 +695,7 @@ x |> Seq.iter(fun r -> do initialPath <- appendSemiColon (Environment.GetEnvironmentVariable("PATH")) let mutable currentPath:string = null - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") let result = dp.Resolve(idm, ".fsx", [|"r", "Microsoft.Data.Sqlite,3.1.7"|], reportError, "net6.0") Assert.Equal(true, result.Success) @@ -810,7 +810,7 @@ x |> Seq.iter(fun r -> let mutable foundCorrectError = false let mutable foundWrongError = false - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -833,7 +833,7 @@ x |> Seq.iter(fun r -> let mutable foundCorrectError = false let mutable foundWrongError = false - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -856,7 +856,7 @@ x |> Seq.iter(fun r -> let mutable foundCorrectError = false let mutable foundWrongError = false - use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots)) + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) let reportError = let report errorType code message = match errorType with @@ -873,4 +873,38 @@ x |> Seq.iter(fun r -> Assert.Equal(foundWrongError, false) () + + [] + member _.``Verify that clear cache doesn't fail and clears the cache``() = + let nativeProbingRoots () = Seq.empty + let mutable foundCorrectError = false + let mutable foundWrongError = false + + use dp = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), true) + let reportError = + let report errorType code message = + match errorType with + | ErrorReportType.Error -> + if code = 3217 then foundCorrectError <- true + else foundWrongError <- true + | ErrorReportType.Warning -> printfn "PackageManagementWarning %d : %s" code message + ResolvingErrorReport (report) + + 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, "net6.0", null, "", "", "", -1) // Wait forever + + // Clear the results + foundCorrectError <- false + foundWrongError <- false + + // Now clear the cache --- this will ensure that resolving produces a timeout error. If we read from the cache the test will fail + dp.ClearResultsCache(Seq.empty, "", reportError) + + let result = dp.Resolve(idm, ".fsx", [|"r", "FSharp.Data,3.3.3"; "r", "timeout=0"|], reportError, "net6.0", null, "", "", "", -1) // Wait forever + Assert.Equal(false, result.Success) + Assert.Equal(foundCorrectError, true) + Assert.Equal(foundWrongError, false) + () 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 bbc18f60f13..743c0da36fa 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,13 @@ Exe net472;net6.0 net6.0 + + $(NoWarn);NU1505 $(NoWarn);44;75; true false @@ -31,6 +38,75 @@ Symbols.fs + + SyntaxTree\TypeTests.fs + + + SyntaxTree\ExpressionTests.fs + + + SyntaxTree\StringTests.fs + + + SyntaxTree\ModuleOrNamespaceTests.fs + + + SyntaxTree\ModuleOrNamespaceSigTests.fs + + + SyntaxTree\SignatureTypeTests.fs + + + SyntaxTree\MeasureTests.fs + + + SyntaxTree\MatchClauseTests.fs + + + SyntaxTree\SourceIdentifierTests.fs + + + SyntaxTree\NestedModuleTests.fs + + + SyntaxTree\BindingTests.fs + + + SyntaxTree\ParsedHashDirectiveTests.fs + + + SyntaxTree\LambdaTests.fs + + + SyntaxTree\IfThenElseTests.fs + + + SyntaxTree\UnionCaseTests.fs + + + SyntaxTree\EnumCaseTests.fs + + + SyntaxTree\PatternTests.fs + + + SyntaxTree\ExceptionTests.fs + + + SyntaxTree\MemberFlagTests.fs + + + SyntaxTree\ComputationExpressionTests.fs + + + SyntaxTree\ConditionalDirectiveTests.fs + + + SyntaxTree\CodeCommentTests.fs + + + SyntaxTree\OperatorNameTests.fs + FileSystemTests.fs diff --git a/tests/FSharp.Compiler.Service.Tests/FSharp.CompilerService.SurfaceArea.netstandard.expected b/tests/FSharp.Compiler.Service.Tests/FSharp.CompilerService.SurfaceArea.netstandard.expected index 6135b7a3266..090d64e02c7 100644 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.CompilerService.SurfaceArea.netstandard.expected +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.CompilerService.SurfaceArea.netstandard.expected @@ -2216,7 +2216,10 @@ FSharp.Compiler.DependencyManager.DependencyProvider: System.Tuple`2[System.Int3 FSharp.Compiler.DependencyManager.DependencyProvider: System.Tuple`2[System.String,FSharp.Compiler.DependencyManager.IDependencyManagerProvider] TryFindDependencyManagerInPath(System.Collections.Generic.IEnumerable`1[System.String], System.String, FSharp.Compiler.DependencyManager.ResolvingErrorReport, System.String) FSharp.Compiler.DependencyManager.DependencyProvider: Void .ctor() FSharp.Compiler.DependencyManager.DependencyProvider: Void .ctor(FSharp.Compiler.DependencyManager.AssemblyResolutionProbe, FSharp.Compiler.DependencyManager.NativeResolutionProbe) +FSharp.Compiler.DependencyManager.DependencyProvider: Void .ctor(FSharp.Compiler.DependencyManager.AssemblyResolutionProbe, FSharp.Compiler.DependencyManager.NativeResolutionProbe, Boolean) FSharp.Compiler.DependencyManager.DependencyProvider: Void .ctor(FSharp.Compiler.DependencyManager.NativeResolutionProbe) +FSharp.Compiler.DependencyManager.DependencyProvider: Void .ctor(FSharp.Compiler.DependencyManager.NativeResolutionProbe, Boolean) +FSharp.Compiler.DependencyManager.DependencyProvider: Void ClearResultsCache(System.Collections.Generic.IEnumerable`1[System.String], System.String, FSharp.Compiler.DependencyManager.ResolvingErrorReport) FSharp.Compiler.DependencyManager.ErrorReportType FSharp.Compiler.DependencyManager.ErrorReportType+Tags: Int32 Error FSharp.Compiler.DependencyManager.ErrorReportType+Tags: Int32 Warning @@ -2248,6 +2251,7 @@ FSharp.Compiler.DependencyManager.IDependencyManagerProvider: System.String get_ FSharp.Compiler.DependencyManager.IDependencyManagerProvider: System.String get_Name() FSharp.Compiler.DependencyManager.IDependencyManagerProvider: System.String[] HelpMessages FSharp.Compiler.DependencyManager.IDependencyManagerProvider: System.String[] get_HelpMessages() +FSharp.Compiler.DependencyManager.IDependencyManagerProvider: Void ClearResultsCache() FSharp.Compiler.DependencyManager.IResolveDependenciesResult FSharp.Compiler.DependencyManager.IResolveDependenciesResult: Boolean Success FSharp.Compiler.DependencyManager.IResolveDependenciesResult: Boolean get_Success() @@ -5700,25 +5704,6 @@ FSharp.Compiler.Syntax.PrettyNaming: System.String FormatAndOtherOverloadsString FSharp.Compiler.Syntax.PrettyNaming: System.String FsiDynamicModulePrefix FSharp.Compiler.Syntax.PrettyNaming: System.String NormalizeIdentifierBackticks(System.String) FSharp.Compiler.Syntax.PrettyNaming: System.String get_FsiDynamicModulePrefix() -FSharp.Compiler.Syntax.PropertyKeyword -FSharp.Compiler.Syntax.PropertyKeyword+And: FSharp.Compiler.Text.Range Item -FSharp.Compiler.Syntax.PropertyKeyword+And: FSharp.Compiler.Text.Range get_Item() -FSharp.Compiler.Syntax.PropertyKeyword+Tags: Int32 And -FSharp.Compiler.Syntax.PropertyKeyword+Tags: Int32 With -FSharp.Compiler.Syntax.PropertyKeyword+With: FSharp.Compiler.Text.Range Item -FSharp.Compiler.Syntax.PropertyKeyword+With: FSharp.Compiler.Text.Range get_Item() -FSharp.Compiler.Syntax.PropertyKeyword: Boolean IsAnd -FSharp.Compiler.Syntax.PropertyKeyword: Boolean IsWith -FSharp.Compiler.Syntax.PropertyKeyword: Boolean get_IsAnd() -FSharp.Compiler.Syntax.PropertyKeyword: Boolean get_IsWith() -FSharp.Compiler.Syntax.PropertyKeyword: FSharp.Compiler.Syntax.PropertyKeyword NewAnd(FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.PropertyKeyword: FSharp.Compiler.Syntax.PropertyKeyword NewWith(FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.PropertyKeyword: FSharp.Compiler.Syntax.PropertyKeyword+And -FSharp.Compiler.Syntax.PropertyKeyword: FSharp.Compiler.Syntax.PropertyKeyword+Tags -FSharp.Compiler.Syntax.PropertyKeyword: FSharp.Compiler.Syntax.PropertyKeyword+With -FSharp.Compiler.Syntax.PropertyKeyword: Int32 Tag -FSharp.Compiler.Syntax.PropertyKeyword: Int32 get_Tag() -FSharp.Compiler.Syntax.PropertyKeyword: System.String ToString() FSharp.Compiler.Syntax.QualifiedNameOfFile FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident Id FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident Item @@ -5762,6 +5747,12 @@ FSharp.Compiler.Syntax.SeqExprOnly: Int32 Tag FSharp.Compiler.Syntax.SeqExprOnly: Int32 get_Tag() FSharp.Compiler.Syntax.SeqExprOnly: System.String ToString() FSharp.Compiler.Syntax.SynAccess +FSharp.Compiler.Syntax.SynAccess+Internal: FSharp.Compiler.Text.Range get_range() +FSharp.Compiler.Syntax.SynAccess+Internal: FSharp.Compiler.Text.Range range +FSharp.Compiler.Syntax.SynAccess+Private: FSharp.Compiler.Text.Range get_range() +FSharp.Compiler.Syntax.SynAccess+Private: FSharp.Compiler.Text.Range range +FSharp.Compiler.Syntax.SynAccess+Public: FSharp.Compiler.Text.Range get_range() +FSharp.Compiler.Syntax.SynAccess+Public: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynAccess+Tags: Int32 Internal FSharp.Compiler.Syntax.SynAccess+Tags: Int32 Private FSharp.Compiler.Syntax.SynAccess+Tags: Int32 Public @@ -5774,16 +5765,15 @@ FSharp.Compiler.Syntax.SynAccess: Boolean IsPublic FSharp.Compiler.Syntax.SynAccess: Boolean get_IsInternal() FSharp.Compiler.Syntax.SynAccess: Boolean get_IsPrivate() FSharp.Compiler.Syntax.SynAccess: Boolean get_IsPublic() -FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess Internal -FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess Private -FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess Public -FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess get_Internal() -FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess get_Private() -FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess get_Public() +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess NewInternal(FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess NewPrivate(FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess NewPublic(FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess+Internal +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess+Private +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess+Public FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Syntax.SynAccess+Tags -FSharp.Compiler.Syntax.SynAccess: Int32 CompareTo(FSharp.Compiler.Syntax.SynAccess) -FSharp.Compiler.Syntax.SynAccess: Int32 CompareTo(System.Object) -FSharp.Compiler.Syntax.SynAccess: Int32 CompareTo(System.Object, System.Collections.IComparer) +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Text.Range Range +FSharp.Compiler.Syntax.SynAccess: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynAccess: Int32 GetHashCode() FSharp.Compiler.Syntax.SynAccess: Int32 GetHashCode(System.Collections.IEqualityComparer) FSharp.Compiler.Syntax.SynAccess: Int32 Tag @@ -7367,6 +7357,14 @@ FSharp.Compiler.Syntax.SynMemberDefn+AutoProperty: Microsoft.FSharp.Core.FSharpO FSharp.Compiler.Syntax.SynMemberDefn+AutoProperty: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_getSetRange() FSharp.Compiler.Syntax.SynMemberDefn+AutoProperty: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_withKeyword() FSharp.Compiler.Syntax.SynMemberDefn+AutoProperty: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] withKeyword +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia get_trivia() +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia trivia +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: FSharp.Compiler.Text.Range get_range() +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: FSharp.Compiler.Text.Range range +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynBinding] get_memberDefnForGet() +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynBinding] get_memberDefnForSet() +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynBinding] memberDefnForGet +FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynBinding] memberDefnForSet FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.Syntax.SynSimplePats ctorArgs FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.Syntax.SynSimplePats get_ctorArgs() FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.Text.Range get_range() @@ -7425,6 +7423,7 @@ FSharp.Compiler.Syntax.SynMemberDefn+Open: FSharp.Compiler.Text.Range get_range( FSharp.Compiler.Syntax.SynMemberDefn+Open: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynMemberDefn+Tags: Int32 AbstractSlot FSharp.Compiler.Syntax.SynMemberDefn+Tags: Int32 AutoProperty +FSharp.Compiler.Syntax.SynMemberDefn+Tags: Int32 GetSetMember FSharp.Compiler.Syntax.SynMemberDefn+Tags: Int32 ImplicitCtor FSharp.Compiler.Syntax.SynMemberDefn+Tags: Int32 ImplicitInherit FSharp.Compiler.Syntax.SynMemberDefn+Tags: Int32 Inherit @@ -7440,6 +7439,7 @@ FSharp.Compiler.Syntax.SynMemberDefn+ValField: FSharp.Compiler.Text.Range get_ra FSharp.Compiler.Syntax.SynMemberDefn+ValField: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsAbstractSlot FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsAutoProperty +FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsGetSetMember FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsImplicitCtor FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsImplicitInherit FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsInherit @@ -7451,6 +7451,7 @@ FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsOpen FSharp.Compiler.Syntax.SynMemberDefn: Boolean IsValField FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsAbstractSlot() FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsAutoProperty() +FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsGetSetMember() FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsImplicitCtor() FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsImplicitInherit() FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsInherit() @@ -7462,6 +7463,7 @@ FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsOpen() FSharp.Compiler.Syntax.SynMemberDefn: Boolean get_IsValField() FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewAbstractSlot(FSharp.Compiler.Syntax.SynValSig, FSharp.Compiler.Syntax.SynMemberFlags, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewAutoProperty(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], Boolean, FSharp.Compiler.Syntax.Ident, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynType], FSharp.Compiler.Syntax.SynMemberKind, Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SynMemberKind,FSharp.Compiler.Syntax.SynMemberFlags], FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range, FSharp.Compiler.Syntax.SynExpr, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewGetSetMember(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynBinding], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynBinding], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia) FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewImplicitCtor(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynSimplePats, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], FSharp.Compiler.Xml.PreXmlDoc, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewImplicitInherit(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Syntax.SynExpr, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewInherit(FSharp.Compiler.Syntax.SynType, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], FSharp.Compiler.Text.Range) @@ -7473,6 +7475,7 @@ FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewOp FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewValField(FSharp.Compiler.Syntax.SynField, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn+AbstractSlot FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn+AutoProperty +FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn+ImplicitInherit FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn+Inherit @@ -7960,8 +7963,6 @@ FSharp.Compiler.Syntax.SynPat+LongIdent: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.SynPat+LongIdent: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynPat+LongIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident] extraId FSharp.Compiler.Syntax.SynPat+LongIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident] get_extraId() -FSharp.Compiler.Syntax.SynPat+LongIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.PropertyKeyword] get_propertyKeyword() -FSharp.Compiler.Syntax.SynPat+LongIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.PropertyKeyword] propertyKeyword FSharp.Compiler.Syntax.SynPat+LongIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess] accessibility FSharp.Compiler.Syntax.SynPat+LongIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess] get_accessibility() FSharp.Compiler.Syntax.SynPat+LongIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynValTyparDecls] get_typarDecls() @@ -8083,7 +8084,7 @@ FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewDeprecatedCharRa FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewFromParseError(FSharp.Compiler.Syntax.SynPat, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewInstanceMember(FSharp.Compiler.Syntax.Ident, FSharp.Compiler.Syntax.Ident, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewIsInst(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewLongIdent(FSharp.Compiler.Syntax.SynLongIdent, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.PropertyKeyword], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynValTyparDecls], FSharp.Compiler.Syntax.SynArgPats, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewLongIdent(FSharp.Compiler.Syntax.SynLongIdent, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynValTyparDecls], FSharp.Compiler.Syntax.SynArgPats, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewNamed(FSharp.Compiler.Syntax.SynIdent, Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewNull(FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Syntax.SynPat NewOptionalVal(FSharp.Compiler.Syntax.Ident, FSharp.Compiler.Text.Range) @@ -8399,6 +8400,8 @@ FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.Syntax.SynType argType FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.Syntax.SynType get_argType() FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.Syntax.SynType get_returnType() FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.Syntax.SynType returnType +FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia get_trivia() +FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia trivia FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.SynType+Fun: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynType+HashConstraint: FSharp.Compiler.Syntax.SynType get_innerType() @@ -8522,7 +8525,7 @@ FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewAnon(FSharp.Co FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewAnonRecd(Boolean, Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`2[FSharp.Compiler.Syntax.Ident,FSharp.Compiler.Syntax.SynType]], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewApp(FSharp.Compiler.Syntax.SynType, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynType], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Boolean, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewArray(Int32, FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewFun(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewFun(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia) FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewHashConstraint(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewLongIdent(FSharp.Compiler.Syntax.SynLongIdent) FSharp.Compiler.Syntax.SynType: FSharp.Compiler.Syntax.SynType NewLongIdentApp(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Syntax.SynLongIdent, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynType], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], FSharp.Compiler.Text.Range) @@ -9406,6 +9409,17 @@ FSharp.Compiler.SyntaxTrivia.SynMemberFlagsTrivia: Microsoft.FSharp.Core.FSharpO FSharp.Compiler.SyntaxTrivia.SynMemberFlagsTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_StaticRange() FSharp.Compiler.SyntaxTrivia.SynMemberFlagsTrivia: System.String ToString() FSharp.Compiler.SyntaxTrivia.SynMemberFlagsTrivia: Void .ctor(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range]) +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: FSharp.Compiler.Text.Range WithKeyword +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: FSharp.Compiler.Text.Range get_WithKeyword() +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] AndKeyword +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] GetKeyword +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] SetKeyword +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_AndKeyword() +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_GetKeyword() +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_SetKeyword() +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: System.String ToString() +FSharp.Compiler.SyntaxTrivia.SynMemberGetSetTrivia: Void .ctor(FSharp.Compiler.Text.Range, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range]) FSharp.Compiler.SyntaxTrivia.SynModuleDeclNestedModuleTrivia FSharp.Compiler.SyntaxTrivia.SynModuleDeclNestedModuleTrivia: FSharp.Compiler.SyntaxTrivia.SynModuleDeclNestedModuleTrivia Zero FSharp.Compiler.SyntaxTrivia.SynModuleDeclNestedModuleTrivia: FSharp.Compiler.SyntaxTrivia.SynModuleDeclNestedModuleTrivia get_Zero() @@ -9454,6 +9468,11 @@ FSharp.Compiler.SyntaxTrivia.SynTypeDefnTrivia: Microsoft.FSharp.Core.FSharpOpti FSharp.Compiler.SyntaxTrivia.SynTypeDefnTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_WithKeyword() FSharp.Compiler.SyntaxTrivia.SynTypeDefnTrivia: System.String ToString() FSharp.Compiler.SyntaxTrivia.SynTypeDefnTrivia: Void .ctor(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range]) +FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia +FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia: FSharp.Compiler.Text.Range ArrowRange +FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia: FSharp.Compiler.Text.Range get_ArrowRange() +FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia: System.String ToString() +FSharp.Compiler.SyntaxTrivia.SynTypeFunTrivia: Void .ctor(FSharp.Compiler.Text.Range) FSharp.Compiler.SyntaxTrivia.SynUnionCaseTrivia FSharp.Compiler.SyntaxTrivia.SynUnionCaseTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] BarRange FSharp.Compiler.SyntaxTrivia.SynUnionCaseTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_BarRange() @@ -9462,12 +9481,14 @@ FSharp.Compiler.SyntaxTrivia.SynUnionCaseTrivia: Void .ctor(Microsoft.FSharp.Cor FSharp.Compiler.SyntaxTrivia.SynValSigTrivia FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: FSharp.Compiler.SyntaxTrivia.SynValSigTrivia Zero FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: FSharp.Compiler.SyntaxTrivia.SynValSigTrivia get_Zero() +FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] EqualsRange FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] ValKeyword FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] WithKeyword +FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_EqualsRange() FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_ValKeyword() FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_WithKeyword() FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: System.String ToString() -FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Void .ctor(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range]) +FSharp.Compiler.SyntaxTrivia.SynValSigTrivia: Void .ctor(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range]) FSharp.Compiler.Text.ISourceText FSharp.Compiler.Text.ISourceText: Boolean ContentEquals(FSharp.Compiler.Text.ISourceText) FSharp.Compiler.Text.ISourceText: Boolean SubTextEquals(System.String, Int32) diff --git a/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj b/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj index d9d740dc622..e04fd102a12 100644 --- a/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj +++ b/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj @@ -36,6 +36,75 @@ CompilerService\Symbols.fs + + SyntaxTree\TypeTests.fs + + + SyntaxTree\ExpressionTests.fs + + + SyntaxTree\StringTests.fs + + + SyntaxTree\ModuleOrNamespaceTests.fs + + + SyntaxTree\ModuleOrNamespaceSigTests.fs + + + SyntaxTree\SignatureTypeTests.fs + + + SyntaxTree\MeasureTests.fs + + + SyntaxTree\MatchClauseTests.fs + + + SyntaxTree\SourceIdentifierTests.fs + + + SyntaxTree\NestedModuleTests.fs + + + SyntaxTree\BindingTests.fs + + + SyntaxTree\ParsedHashDirectiveTests.fs + + + SyntaxTree\LambdaTests.fs + + + SyntaxTree\IfThenElseTests.fs + + + SyntaxTree\UnionCaseTests.fs + + + SyntaxTree\EnumCaseTests.fs + + + SyntaxTree\PatternTests.fs + + + SyntaxTree\ExceptionTests.fs + + + SyntaxTree\MemberFlagTests.fs + + + SyntaxTree\ComputationExpressionTests.fs + + + SyntaxTree\ConditionalDirectiveTests.fs + + + SyntaxTree\CodeCommentTests.fs + + + SyntaxTree\OperatorNameTests.fs + CompilerService\EditorTests.fs diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj index 9efb5755e4e..42a431f2c27 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj @@ -83,6 +83,7 @@ + diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/NestedTaskFailures.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/NestedTaskFailures.fs new file mode 100644 index 00000000000..964b87a2847 --- /dev/null +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/NestedTaskFailures.fs @@ -0,0 +1,124 @@ +namespace FSharp.Core.UnitTests.Control.Tasks + +// The tasks below fail state machine comilation. This failure was causing subsequent problems in code generation. +// See https://github.com/dotnet/fsharp/issues/13404 + +#nowarn "3511" // state machine not staticlly compilable - this is a separate issue, see https://github.com/dotnet/fsharp/issues/13404 + +open System +open Microsoft.FSharp.Control +open Xunit + +module NestedTasksFailingStateMachine = + module Example1 = + let transfers = [| Some 2,1 |] + + let FetchInternalTransfers (includeConfirmeds: int) = + task { + + let! mapPrioritiesTransfers = + task { + if includeConfirmeds > 1 then + + transfers + |> Array.map(fun (loanid,c) -> loanid.Value, 4) + |> Array.map(fun (k,vs) -> k, 1) + |> Array.map(fun (id,c) -> c,true) + |> ignore + + } + + return [| 1 |], 1 + + } + + module Example2 = + open System.Linq + + let ``get pending internal transfers`` nonAllowedPriority (loanIds:Guid[]) = + task { return [||] } + + let FetchInternalTransfers (includeConfirmeds: bool) (transferStep: string) (inform: bool) (workflow: string) = + task { + let canReserve = true + + let! transfers = + task { // This is the only real async here + do! System.Threading.Tasks.Task.Delay 500 + return [| // simulates data from external source + Some (Guid.NewGuid()),DateTime.Now,"3","4",5m,Some 6,Some "1",Some 71,Some "7",true,DateTime.Now; + Some (Guid.NewGuid()),DateTime.Now,"3","4",5m,Some 6,Some "1",Some 72,Some "7",true,DateTime.Now; + Some (Guid.NewGuid()),DateTime.Now,"3","4",5m,Some 6,Some "1",Some 73,Some "7",true,DateTime.Now; + |] + } + + let totalCount = transfers |> Array.length + + let checkIfTransfersPending notAllowedPriority = + task { + let transferIds = transfers |> Array.filter(fun (id,c,fa,ta,ts,ir,eb,o,r,me,rm) -> id.IsSome) |> Array.map(fun (id,c,fa,ta,ts,ir,eb,o,r,me,rm) -> id.Value) |> Array.distinct + let! pendingTransfers = ``get pending internal transfers`` notAllowedPriority transferIds + return + transfers + |> Array.map(fun (id,c,fa,ta,ts,ir,eb,o,r,me,rm) -> + c,fa,ta,ts,ir,eb, id.IsNone || (not (pendingTransfers.Contains id.Value)), r,me,rm + ) + } + + let! mapPrioritiesTransfers = + task { + match transferStep with + | "All" -> + + let minOrder = + transfers + |> Array.filter(fun (loanid,c,fa,ta,ts,ir,eb,o,r,me,rm) -> loanid.IsSome && o.IsSome) + |> Array.map(fun (loanid,c,fa,ta,ts,ir,eb,o,r,me,rm) -> loanid.Value, o.Value) + |> Array.groupBy(fun (loanid,_) -> loanid) + |> Array.map(fun (k,vs) -> k, vs |> Array.map(fun (_,o) -> o) |> Array.min) + |> Map.ofArray + + let mappedTransfers = + transfers |> Array.map(fun (id,c,fa,ta,ts,ir,eb,o,r,me,rm) -> + let isPrio = includeConfirmeds || o.IsNone || id.IsNone || minOrder.[id.Value] = o.Value + c,fa,ta,ts,ir,eb, isPrio, r, me, rm + ) + + return mappedTransfers + | "Step1" + | "Postprocessing" -> + return + transfers |> Array.map(fun (id, c, fa, ta, ts, ir, eb, o, r, me, rm) -> + c, fa, ta, ts, ir, eb, true, r, me, rm + ) + | "Step2" -> + return! checkIfTransfersPending 1 + | "Step3" -> + return! checkIfTransfersPending 2 + | "Rebalancing" -> + return! checkIfTransfersPending 4 + | _ -> return failwith ("Unknown internal transfer step: " + transferStep) + } + + return canReserve, mapPrioritiesTransfers, totalCount + + } + + let test = FetchInternalTransfers false "All" true "Bank2" + System.Threading.Tasks.Task.WaitAll test + let result = test.Result |> printfn "%A" + +type NestedStateMachineTests() = + [] + member _.NestedStateMachineFailure1() = + let test = NestedTasksFailingStateMachine.Example1.FetchInternalTransfers 2 + test.Result |> printfn "%A" + + [] + member _.NestedStateMachineFailure2() = + let test = NestedTasksFailingStateMachine.Example2.FetchInternalTransfers false "All" true "Bank2" + System.Threading.Tasks.Task.WaitAll test + let (a, b, c) = test.Result + if a <> true then failwith "failed - expected true" + if b.Length <> 3 then failwith "failed - expected results of length 3" + if c <> 3 then failwith "failed - expected 3" diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/Tasks.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/Tasks.fs index 8e1d6b9d2a1..bf6c8cc1e14 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/Tasks.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/Tasks.fs @@ -23,13 +23,7 @@ open System.Diagnostics open System.Threading open System.Threading.Tasks open Microsoft.FSharp.Control -#if STANDALONE -[] -type FactAttribute() = inherit Attribute() -#else open Xunit -#endif - type ITaskThing = abstract member Taskify : 'a option -> 'a Task @@ -38,19 +32,20 @@ type ITaskThing = type SupportBothDisposables() = let mutable called = false interface IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = task { System.Console.WriteLine "incrementing" called <- true } |> ValueTask interface IDisposable with - member __.Dispose() = failwith "dispose" + member _.Dispose() = failwith "dispose" member x.Disposed = called #endif + type SmokeTestsForCompilation() = [] - member __.tinyTask() = + member _.tinyTask() = task { return 1 } @@ -59,7 +54,7 @@ type SmokeTestsForCompilation() = if t.Result <> 1 then failwith "failed" [] - member __.tbind() = + member _.tbind() = task { let! x = Task.FromResult(1) return 1 + x @@ -69,7 +64,7 @@ type SmokeTestsForCompilation() = if t.Result <> 2 then failwith "failed" [] - member __.tnested() = + member _.tnested() = task { let! x = task { return 1 } return x @@ -79,7 +74,7 @@ type SmokeTestsForCompilation() = if t.Result <> 1 then failwith "failed" [] - member __.tcatch0() = + member _.tcatch0() = task { try return 1 @@ -91,7 +86,7 @@ type SmokeTestsForCompilation() = if t.Result <> 1 then failwith "failed" [] - member __.tcatch1() = + member _.tcatch1() = task { try let! x = Task.FromResult 1 @@ -105,7 +100,7 @@ type SmokeTestsForCompilation() = [] - member __.t3() = + member _.t3() = let t2() = task { System.Console.WriteLine("hello") @@ -122,7 +117,7 @@ type SmokeTestsForCompilation() = if t.Result <> 2 then failwith "failed" [] - member __.t3b() = + member _.t3b() = task { System.Console.WriteLine("hello") let! x = Task.FromResult(1) @@ -134,7 +129,7 @@ type SmokeTestsForCompilation() = if t.Result <> 2 then failwith "failed" [] - member __.t3c() = + member _.t3c() = task { System.Console.WriteLine("hello") do! Task.Delay(100) @@ -147,7 +142,7 @@ type SmokeTestsForCompilation() = [] // This tests an exception match - member __.t67() = + member _.t67() = task { try do! Task.Delay(0) @@ -163,7 +158,7 @@ type SmokeTestsForCompilation() = [] // This tests compiling an incomplete exception match - member __.t68() = + member _.t68() = task { try do! Task.Delay(0) @@ -176,7 +171,7 @@ type SmokeTestsForCompilation() = if t.Result <> () then failwith "failed" [] - member __.testCompileAsyncWhileLoop() = + member _.testCompileAsyncWhileLoop() = task { let mutable i = 0 while i < 5 do @@ -199,7 +194,7 @@ module Helpers = type Basics() = [] - member __.testShortCircuitResult() = + member _.testShortCircuitResult() = printfn "Running testShortCircuitResult..." let t = task { @@ -212,7 +207,7 @@ type Basics() = require (t.Result = 3) "wrong result" [] - member __.testDelay() = + member _.testDelay() = printfn "Running testDelay..." let mutable x = 0 let t = @@ -226,7 +221,7 @@ type Basics() = t.Wait() [] - member __.testNoDelay() = + member _.testNoDelay() = printfn "Running testNoDelay..." let mutable x = 0 let t = @@ -239,7 +234,7 @@ type Basics() = t.Wait() [] - member __.testNonBlocking() = + member _.testNonBlocking() = printfn "Running testNonBlocking..." let sw = Stopwatch() sw.Start() @@ -253,7 +248,7 @@ type Basics() = t.Wait() [] - member __.testCatching1() = + member _.testCatching1() = printfn "Running testCatching1..." let mutable x = 0 let mutable y = 0 @@ -277,7 +272,7 @@ type Basics() = require (x = 0) "ran past failure" [] - member __.testCatching2() = + member _.testCatching2() = printfn "Running testCatching2..." let mutable x = 0 let mutable y = 0 @@ -300,7 +295,7 @@ type Basics() = require (x = 0) "ran past failure" [] - member __.testNestedCatching() = + member _.testNestedCatching() = printfn "Running testNestedCatching..." let mutable counter = 1 let mutable caughtInner = 0 @@ -337,7 +332,7 @@ type Basics() = require (caughtOuter = 2) "didn't catch outer" [] - member __.testWhileLoopSync() = + member _.testWhileLoopSync() = printfn "Running testWhileLoopSync..." let t = task { @@ -351,7 +346,7 @@ type Basics() = require (t.Result = 10) "didn't do sync while loop properly - wrong result" [] - member __.testWhileLoopAsyncZeroIteration() = + member _.testWhileLoopAsyncZeroIteration() = printfn "Running testWhileLoopAsyncZeroIteration..." for i in 1 .. 5 do let t = @@ -366,7 +361,7 @@ type Basics() = require (t.Result = 0) "didn't do while loop properly" [] - member __.testWhileLoopAsyncOneIteration() = + member _.testWhileLoopAsyncOneIteration() = printfn "Running testWhileLoopAsyncOneIteration..." for i in 1 .. 5 do let t = @@ -381,7 +376,7 @@ type Basics() = require (t.Result = 1) "didn't do while loop properly" [] - member __.testWhileLoopAsync() = + member _.testWhileLoopAsync() = printfn "Running testWhileLoopAsync..." for i in 1 .. 5 do let t = @@ -396,7 +391,7 @@ type Basics() = require (t.Result = 10) "didn't do while loop properly" [] - member __.testTryFinallyHappyPath() = + member _.testTryFinallyHappyPath() = printfn "Running testTryFinallyHappyPath..." for i in 1 .. 5 do let mutable ran = false @@ -412,7 +407,7 @@ type Basics() = t.Wait() require ran "never ran" [] - member __.testTryFinallySadPath() = + member _.testTryFinallySadPath() = printfn "Running testTryFinallySadPath..." for i in 1 .. 5 do let mutable ran = false @@ -433,7 +428,7 @@ type Basics() = require ran "never ran" [] - member __.testTryFinallyCaught() = + member _.testTryFinallyCaught() = printfn "Running testTryFinallyCaught..." for i in 1 .. 5 do let mutable ran = false @@ -455,13 +450,13 @@ type Basics() = require ran "never ran" [] - member __.testUsing() = + member _.testUsing() = printfn "Running testUsing..." for i in 1 .. 5 do let mutable disposed = false let t = task { - use d = { new IDisposable with member __.Dispose() = disposed <- true } + use d = { new IDisposable with member _.Dispose() = disposed <- true } require (not disposed) "disposed way early" do! Task.Delay(100) require (not disposed) "disposed kinda early" @@ -471,7 +466,7 @@ type Basics() = #if NETCOREAPP [] - member __.testUsingAsyncDisposableSync() = + member _.testUsingAsyncDisposableSync() = printfn "Running testUsingAsyncDisposableSync..." for i in 1 .. 5 do let mutable disposed = 0 @@ -479,7 +474,7 @@ type Basics() = task { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = task { System.Console.WriteLine "incrementing" disposed <- disposed + 1 } @@ -496,7 +491,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableAsync() = + member _.testUsingAsyncDisposableAsync() = printfn "Running testUsingAsyncDisposableAsync..." for i in 1 .. 5 do let mutable disposed = 0 @@ -504,7 +499,7 @@ type Basics() = task { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = task { do! Task.Delay(10) disposed <- disposed + 1 @@ -520,7 +515,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableExnAsync() = + member _.testUsingAsyncDisposableExnAsync() = printfn "Running testUsingAsyncDisposableExnAsync..." for i in 1 .. 5 do let mutable disposed = 0 @@ -528,7 +523,7 @@ type Basics() = task { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = task { do! Task.Delay(10) disposed <- disposed + 1 @@ -545,7 +540,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableExnSync() = + member _.testUsingAsyncDisposableExnSync() = printfn "Running testUsingAsyncDisposableExnSync..." for i in 1 .. 5 do let mutable disposed = 0 @@ -553,7 +548,7 @@ type Basics() = task { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = task { disposed <- disposed + 1 do! Task.Delay(10) @@ -570,7 +565,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableDelayExnSync() = + member _.testUsingAsyncDisposableDelayExnSync() = printfn "Running testUsingAsyncDisposableDelayExnSync..." for i in 1 .. 5 do let mutable disposed = 0 @@ -578,7 +573,7 @@ type Basics() = task { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = task { disposed <- disposed + 1 do! Task.Delay(10) @@ -598,7 +593,7 @@ type Basics() = [] // Test use! resolves - member __.testUsingBindAsyncDisposableSync() = + member _.testUsingBindAsyncDisposableSync() = printfn "Running testUsingBindAsyncDisposableSync..." for i in 1 .. 5 do let mutable disposed = 0 @@ -609,7 +604,7 @@ type Basics() = do! Task.Delay(10) return { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = task { System.Console.WriteLine "incrementing" disposed <- disposed + 1 } @@ -627,7 +622,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableSyncSupportingBothDisposables() = + member _.testUsingAsyncDisposableSyncSupportingBothDisposables() = printfn "Running testUsingAsyncDisposableSyncSupportingBothDisposables..." for i in 1 .. 5 do let disp = new SupportBothDisposables() @@ -645,7 +640,7 @@ type Basics() = #endif [] - member __.testUsingFromTask() = + member _.testUsingFromTask() = printfn "Running testUsingFromTask..." let mutable disposedInner = false let mutable disposed = false @@ -654,9 +649,9 @@ type Basics() = use! d = task { do! Task.Delay(50) - use i = { new IDisposable with member __.Dispose() = disposedInner <- true } + use i = { new IDisposable with member _.Dispose() = disposedInner <- true } require (not disposed && not disposedInner) "disposed inner early" - return { new IDisposable with member __.Dispose() = disposed <- true } + return { new IDisposable with member _.Dispose() = disposed <- true } } require disposedInner "did not dispose inner after task completion" require (not disposed) "disposed way early" @@ -667,7 +662,7 @@ type Basics() = require disposed "never disposed C" [] - member __.testUsingSadPath() = + member _.testUsingSadPath() = printfn "Running testUsingSadPath..." let mutable disposedInner = false let mutable disposed = false @@ -677,10 +672,10 @@ type Basics() = use! d = task { do! Task.Delay(50) - use i = { new IDisposable with member __.Dispose() = disposedInner <- true } + use i = { new IDisposable with member _.Dispose() = disposedInner <- true } failtest "uhoh" require (not disposed && not disposedInner) "disposed inner early" - return { new IDisposable with member __.Dispose() = disposed <- true } + return { new IDisposable with member _.Dispose() = disposed <- true } } () with @@ -696,7 +691,7 @@ type Basics() = require (not disposed) "disposed thing that never should've existed" [] - member __.testForLoopA() = + member _.testForLoopA() = printfn "Running testForLoopA..." let list = ["a"; "b"; "c"] |> Seq.ofList let t = @@ -713,7 +708,7 @@ type Basics() = t.Wait() [] - member __.testForLoopComplex() = + member _.testForLoopComplex() = printfn "Running testForLoopComplex..." let mutable disposed = false let wrapList = @@ -721,26 +716,26 @@ type Basics() = let getEnumerator() = let raw = raw.GetEnumerator() { new IEnumerator with - member __.MoveNext() = + member _.MoveNext() = require (not disposed) "moved next after disposal" raw.MoveNext() - member __.Current = + member _.Current = require (not disposed) "accessed current after disposal" raw.Current - member __.Current = + member _.Current = require (not disposed) "accessed current (boxed) after disposal" box raw.Current - member __.Dispose() = + member _.Dispose() = require (not disposed) "disposed twice" disposed <- true raw.Dispose() - member __.Reset() = + member _.Reset() = require (not disposed) "reset after disposal" raw.Reset() } { new IEnumerable with - member __.GetEnumerator() : IEnumerator = getEnumerator() - member __.GetEnumerator() : IEnumerator = upcast getEnumerator() + member _.GetEnumerator() : IEnumerator = getEnumerator() + member _.GetEnumerator() : IEnumerator = upcast getEnumerator() } let t = task { @@ -772,7 +767,7 @@ type Basics() = require (t.Result = 1) "wrong result" [] - member __.testForLoopSadPath() = + member _.testForLoopSadPath() = printfn "Running testForLoopSadPath..." for i in 1 .. 5 do let wrapList = ["a"; "b"; "c"] @@ -788,7 +783,7 @@ type Basics() = require (t.Result = 1) "wrong result" [] - member __.testForLoopSadPathComplex() = + member _.testForLoopSadPathComplex() = printfn "Running testForLoopSadPathComplex..." for i in 1 .. 5 do let mutable disposed = false @@ -797,26 +792,26 @@ type Basics() = let getEnumerator() = let raw = raw.GetEnumerator() { new IEnumerator with - member __.MoveNext() = + member _.MoveNext() = require (not disposed) "moved next after disposal" raw.MoveNext() - member __.Current = + member _.Current = require (not disposed) "accessed current after disposal" raw.Current - member __.Current = + member _.Current = require (not disposed) "accessed current (boxed) after disposal" box raw.Current - member __.Dispose() = + member _.Dispose() = require (not disposed) "disposed twice" disposed <- true raw.Dispose() - member __.Reset() = + member _.Reset() = require (not disposed) "reset after disposal" raw.Reset() } { new IEnumerable with - member __.GetEnumerator() : IEnumerator = getEnumerator() - member __.GetEnumerator() : IEnumerator = upcast getEnumerator() + member _.GetEnumerator() : IEnumerator = getEnumerator() + member _.GetEnumerator() : IEnumerator = upcast getEnumerator() } let mutable caught = false let t = @@ -843,7 +838,7 @@ type Basics() = require disposed "never disposed A" [] - member __.testExceptionAttachedToTaskWithoutAwait() = + member _.testExceptionAttachedToTaskWithoutAwait() = for i in 1 .. 5 do let mutable ranA = false let mutable ranB = false @@ -876,7 +871,7 @@ type Basics() = require caught "didn't catch" [] - member __.testExceptionAttachedToTaskWithAwait() = + member _.testExceptionAttachedToTaskWithAwait() = printfn "running testExceptionAttachedToTaskWithAwait" for i in 1 .. 5 do let mutable ranA = false @@ -911,7 +906,7 @@ type Basics() = require caught "didn't catch" [] - member __.testExceptionThrownInFinally() = + member _.testExceptionThrownInFinally() = printfn "running testExceptionThrownInFinally" for i in 1 .. 5 do let mutable ranInitial = false @@ -939,7 +934,7 @@ type Basics() = require (ranFinally = 1) "didn't run finally exactly once" [] - member __.test2ndExceptionThrownInFinally() = + member _.test2ndExceptionThrownInFinally() = printfn "running test2ndExceptionThrownInFinally" for i in 1 .. 5 do let mutable ranInitial = false @@ -968,7 +963,7 @@ type Basics() = require (ranFinally = 1) "didn't run finally exactly once" [] - member __.testFixedStackWhileLoop() = + member _.testFixedStackWhileLoop() = printfn "running testFixedStackWhileLoop" for i in 1 .. 100 do let t = @@ -989,7 +984,7 @@ type Basics() = require (t.Result = BIG) "didn't get to big number" [] - member __.testFixedStackForLoop() = + member _.testFixedStackForLoop() = for i in 1 .. 100 do printfn "running testFixedStackForLoop" let mutable ran = false @@ -1010,7 +1005,7 @@ type Basics() = require ran "didn't run all" [] - member __.testTypeInference() = + member _.testTypeInference() = let t1 : string Task = task { return "hello" @@ -1023,7 +1018,7 @@ type Basics() = t2.Wait() [] - member __.testNoStackOverflowWithImmediateResult() = + member _.testNoStackOverflowWithImmediateResult() = printfn "running testNoStackOverflowWithImmediateResult" let longLoop = task { @@ -1035,7 +1030,7 @@ type Basics() = longLoop.Wait() [] - member __.testNoStackOverflowWithYieldResult() = + member _.testNoStackOverflowWithYieldResult() = printfn "running testNoStackOverflowWithYieldResult" let longLoop = task { @@ -1052,7 +1047,7 @@ type Basics() = longLoop.Wait() [] - member __.testSmallTailRecursion() = + member _.testSmallTailRecursion() = printfn "running testSmallTailRecursion" let rec loop n = task { @@ -1070,7 +1065,7 @@ type Basics() = shortLoop.Wait() [] - member __.testTryOverReturnFrom() = + member _.testTryOverReturnFrom() = printfn "running testTryOverReturnFrom" let inner() = task { @@ -1089,7 +1084,7 @@ type Basics() = require (t.Result = 2) "didn't catch" [] - member __.testTryFinallyOverReturnFromWithException() = + member _.testTryFinallyOverReturnFromWithException() = printfn "running testTryFinallyOverReturnFromWithException" let inner() = task { @@ -1113,7 +1108,7 @@ type Basics() = require (m = 1) "didn't run finally" [] - member __.testTryFinallyOverReturnFromWithoutException() = + member _.testTryFinallyOverReturnFromWithoutException() = printfn "running testTryFinallyOverReturnFromWithoutException" let inner() = task { @@ -1136,21 +1131,21 @@ type Basics() = require (m = 1) "didn't run finally" // no need to call this, we just want to check that it compiles w/o warnings - member __.testTrivialReturnCompiles (x : 'a) : 'a Task = + member _.testTrivialReturnCompiles (x : 'a) : 'a Task = task { do! Task.Yield() return x } // no need to call this, we just want to check that it compiles w/o warnings - member __.testTrivialTransformedReturnCompiles (x : 'a) (f : 'a -> 'b) : 'b Task = + member _.testTrivialTransformedReturnCompiles (x : 'a) (f : 'a -> 'b) : 'b Task = task { do! Task.Yield() return f x } [] - member __.testAsyncsMixedWithTasks() = + member _.testAsyncsMixedWithTasks() = let t = task { do! Task.Delay(1) @@ -1167,7 +1162,7 @@ type Basics() = [] // no need to call this, we just want to check that it compiles w/o warnings - member __.testDefaultInferenceForReturnFrom() = + member _.testDefaultInferenceForReturnFrom() = let t = task { return Some "x" } task { let! r = t @@ -1180,7 +1175,7 @@ type Basics() = [] // no need to call this, just check that it compiles - member __.testCompilerInfersArgumentOfReturnFrom() = + member _.testCompilerInfersArgumentOfReturnFrom() = task { if true then return 1 else return! failwith "" @@ -1191,7 +1186,7 @@ type Basics() = type BasicsNotInParallel() = [] - member __.testTaskUsesSyncContext() = + member _.testTaskUsesSyncContext() = printfn "Running testBackgroundTask..." for i in 1 .. 5 do let mutable ran = false @@ -1221,7 +1216,7 @@ type BasicsNotInParallel() = SynchronizationContext.SetSynchronizationContext oldSyncContext [] - member __.testBackgroundTaskEscapesSyncContext() = + member _.testBackgroundTaskEscapesSyncContext() = printfn "Running testBackgroundTask..." for i in 1 .. 5 do let mutable ran = false @@ -1242,7 +1237,7 @@ type BasicsNotInParallel() = SynchronizationContext.SetSynchronizationContext oldSyncContext [] - member __.testBackgroundTaskStaysOnSameThreadIfAlreadyOnBackground() = + member _.testBackgroundTaskStaysOnSameThreadIfAlreadyOnBackground() = printfn "Running testBackgroundTask..." for i in 1 .. 5 do let mutable ran = false @@ -1328,60 +1323,3 @@ module Issue12184f = return result } -#if STANDALONE -module M = - [] - let main argv = - printfn "Running tests..." - try - Basics().testShortCircuitResult() - Basics().testDelay() - Basics().testNoDelay() - Basics().testNonBlocking() - - Basics().testCatching1() - Basics().testCatching2() - Basics().testNestedCatching() - Basics().testWhileLoopSync() - Basics().testWhileLoopAsyncZeroIteration() - Basics().testWhileLoopAsyncOneIteration() - Basics().testWhileLoopAsync() - Basics().testTryFinallyHappyPath() - Basics().testTryFinallySadPath() - Basics().testTryFinallyCaught() - Basics().testUsing() - Basics().testUsingFromTask() - Basics().testUsingSadPath() - Basics().testForLoopA() - Basics().testForLoopSadPath() - Basics().testForLoopSadPathComplex() - Basics().testExceptionAttachedToTaskWithoutAwait() - Basics().testExceptionAttachedToTaskWithAwait() - Basics().testExceptionThrownInFinally() - Basics().test2ndExceptionThrownInFinally() - Basics().testFixedStackWhileLoop() - Basics().testFixedStackForLoop() - Basics().testTypeInference() - Basics().testNoStackOverflowWithImmediateResult() - Basics().testNoStackOverflowWithYieldResult() - ////// we don't support TCO, so large tail recursions will stack overflow - ////// or at least use O(n) heap. but small ones should at least function OK. - //testSmallTailRecursion() - Basics().testTryOverReturnFrom() - Basics().testTryFinallyOverReturnFromWithException() - Basics().testTryFinallyOverReturnFromWithoutException() - Basics().testAsyncsMixedWithTasks() - printfn "Passed all tests!" - with exn -> - eprintfn "************************************" - eprintfn "Exception: %O" exn - printfn "Test failed... exiting..." - eprintfn "************************************" - exit 1 - - printfn "Tests passed ok..., sleeping a bit in case there are background delayed exceptions" - Thread.Sleep(500) - printfn "Exiting..." - //System.Console.ReadLine() - 0 -#endif diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/TasksDynamic.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/TasksDynamic.fs index 72d62f1e567..81919c25ef3 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/TasksDynamic.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/TasksDynamic.fs @@ -25,15 +25,9 @@ open System.Diagnostics open System.Threading open System.Threading.Tasks open Microsoft.FSharp.Control -#if STANDALONE -[] -type FactAttribute() = inherit Attribute() -#else open Xunit open System.Runtime.CompilerServices -#endif - // Delegates to task, except 'Run' which is deliberately not inlined, hence no chance // of static compilation of state machines. type TaskBuilderDynamic() = @@ -171,7 +165,7 @@ type ITaskThing = type SmokeTestsForCompilation() = [] - member __.tinyTask() = + member _.tinyTask() = taskDynamic { return 1 } @@ -180,7 +174,7 @@ type SmokeTestsForCompilation() = if t.Result <> 1 then failwith "failed" [] - member __.tbind() = + member _.tbind() = taskDynamic { let! x = Task.FromResult(1) return 1 + x @@ -190,7 +184,7 @@ type SmokeTestsForCompilation() = if t.Result <> 2 then failwith "failed" [] - member __.tnested() = + member _.tnested() = taskDynamic { let! x = taskDynamic { return 1 } return x @@ -200,7 +194,7 @@ type SmokeTestsForCompilation() = if t.Result <> 1 then failwith "failed" [] - member __.tcatch0() = + member _.tcatch0() = taskDynamic { try return 1 @@ -212,7 +206,7 @@ type SmokeTestsForCompilation() = if t.Result <> 1 then failwith "failed" [] - member __.tcatch1() = + member _.tcatch1() = taskDynamic { try let! x = Task.FromResult 1 @@ -226,7 +220,7 @@ type SmokeTestsForCompilation() = [] - member __.t3() = + member _.t3() = let t2() = taskDynamic { System.Console.WriteLine("hello") @@ -243,7 +237,7 @@ type SmokeTestsForCompilation() = if t.Result <> 2 then failwith "failed" [] - member __.t3b() = + member _.t3b() = taskDynamic { System.Console.WriteLine("hello") let! x = Task.FromResult(1) @@ -255,7 +249,7 @@ type SmokeTestsForCompilation() = if t.Result <> 2 then failwith "failed" [] - member __.t3c() = + member _.t3c() = taskDynamic { System.Console.WriteLine("hello") do! Task.Delay(100) @@ -268,7 +262,7 @@ type SmokeTestsForCompilation() = [] // This tests an exception match - member __.t67() = + member _.t67() = taskDynamic { try do! Task.Delay(0) @@ -284,7 +278,7 @@ type SmokeTestsForCompilation() = [] // This tests compiling an incomplete exception match - member __.t68() = + member _.t68() = taskDynamic { try do! Task.Delay(0) @@ -297,7 +291,7 @@ type SmokeTestsForCompilation() = if t.Result <> () then failwith "failed" [] - member __.testCompileAsyncWhileLoop() = + member _.testCompileAsyncWhileLoop() = taskDynamic { let mutable i = 0 while i < 5 do @@ -321,7 +315,7 @@ module Helpers = type Basics() = [] - member __.testShortCircuitResult() = + member _.testShortCircuitResult() = printfn "Running testShortCircuitResult..." let t = taskDynamic { @@ -334,7 +328,7 @@ type Basics() = require (t.Result = 3) "wrong result" [] - member __.testDelay() = + member _.testDelay() = printfn "Running testDelay..." let mutable x = 0 let t = @@ -348,7 +342,7 @@ type Basics() = t.Wait() [] - member __.testNoDelay() = + member _.testNoDelay() = printfn "Running testNoDelay..." let mutable x = 0 let t = @@ -361,7 +355,7 @@ type Basics() = t.Wait() [] - member __.testNonBlocking() = + member _.testNonBlocking() = printfn "Running testNonBlocking..." let sw = Stopwatch() sw.Start() @@ -375,7 +369,7 @@ type Basics() = t.Wait() [] - member __.testCatching1() = + member _.testCatching1() = printfn "Running testCatching1..." let mutable x = 0 let mutable y = 0 @@ -399,7 +393,7 @@ type Basics() = require (x = 0) "ran past failure" [] - member __.testCatching2() = + member _.testCatching2() = printfn "Running testCatching2..." let mutable x = 0 let mutable y = 0 @@ -422,7 +416,7 @@ type Basics() = require (x = 0) "ran past failure" [] - member __.testNestedCatching() = + member _.testNestedCatching() = printfn "Running testNestedCatching..." let mutable counter = 1 let mutable caughtInner = 0 @@ -459,7 +453,7 @@ type Basics() = require (caughtOuter = 2) "didn't catch outer" [] - member __.testWhileLoopSync() = + member _.testWhileLoopSync() = printfn "Running testWhileLoopSync..." let t = taskDynamic { @@ -473,7 +467,7 @@ type Basics() = require (t.Result = 10) "didn't do sync while loop properly - wrong result" [] - member __.testWhileLoopAsyncZeroIteration() = + member _.testWhileLoopAsyncZeroIteration() = printfn "Running testWhileLoopAsyncZeroIteration..." for i in 1 .. 5 do let t = @@ -488,7 +482,7 @@ type Basics() = require (t.Result = 0) "didn't do while loop properly" [] - member __.testWhileLoopAsyncOneIteration() = + member _.testWhileLoopAsyncOneIteration() = printfn "Running testWhileLoopAsyncOneIteration..." for i in 1 .. 5 do let t = @@ -503,7 +497,7 @@ type Basics() = require (t.Result = 1) "didn't do while loop properly" [] - member __.testWhileLoopAsync() = + member _.testWhileLoopAsync() = printfn "Running testWhileLoopAsync..." for i in 1 .. 5 do let t = @@ -518,7 +512,7 @@ type Basics() = require (t.Result = 10) "didn't do while loop properly" [] - member __.testTryFinallyHappyPath() = + member _.testTryFinallyHappyPath() = printfn "Running testTryFinallyHappyPath..." for i in 1 .. 5 do let mutable ran = false @@ -534,7 +528,7 @@ type Basics() = t.Wait() require ran "never ran" [] - member __.testTryFinallySadPath() = + member _.testTryFinallySadPath() = printfn "Running testTryFinallySadPath..." for i in 1 .. 5 do let mutable ran = false @@ -555,7 +549,7 @@ type Basics() = require ran "never ran" [] - member __.testTryFinallyCaught() = + member _.testTryFinallyCaught() = printfn "Running testTryFinallyCaught..." for i in 1 .. 5 do let mutable ran = false @@ -577,13 +571,13 @@ type Basics() = require ran "never ran" [] - member __.testUsing() = + member _.testUsing() = printfn "Running testUsing..." for i in 1 .. 5 do let mutable disposed = false let t = taskDynamic { - use d = { new IDisposable with member __.Dispose() = disposed <- true } + use d = { new IDisposable with member _.Dispose() = disposed <- true } require (not disposed) "disposed way early" do! Task.Delay(100) require (not disposed) "disposed kinda early" @@ -593,7 +587,7 @@ type Basics() = #if NETCOREAPP [] - member __.testUsingAsyncDisposableSync() = + member _.testUsingAsyncDisposableSync() = printfn "Running testUsing..." for i in 1 .. 5 do let mutable disposed = 0 @@ -601,7 +595,7 @@ type Basics() = taskDynamic { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = taskDynamic { System.Console.WriteLine "incrementing" disposed <- disposed + 1 } @@ -618,7 +612,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableAsync() = + member _.testUsingAsyncDisposableAsync() = printfn "Running testUsing..." for i in 1 .. 5 do let mutable disposed = 0 @@ -626,7 +620,7 @@ type Basics() = taskDynamic { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = taskDynamic { do! Task.Delay(10) disposed <- disposed + 1 @@ -642,7 +636,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableExnAsync() = + member _.testUsingAsyncDisposableExnAsync() = printfn "Running testUsing..." for i in 1 .. 5 do let mutable disposed = 0 @@ -650,7 +644,7 @@ type Basics() = taskDynamic { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = taskDynamic { do! Task.Delay(10) disposed <- disposed + 1 @@ -667,7 +661,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableExnSync() = + member _.testUsingAsyncDisposableExnSync() = printfn "Running testUsing..." for i in 1 .. 5 do let mutable disposed = 0 @@ -675,7 +669,7 @@ type Basics() = taskDynamic { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = taskDynamic { disposed <- disposed + 1 do! Task.Delay(10) @@ -692,7 +686,7 @@ type Basics() = require (disposed <= 1) "too many dispose on B" [] - member __.testUsingAsyncDisposableDelayExnSync() = + member _.testUsingAsyncDisposableDelayExnSync() = printfn "Running testUsing..." for i in 1 .. 5 do let mutable disposed = 0 @@ -700,7 +694,7 @@ type Basics() = taskDynamic { use d = { new IAsyncDisposable with - member __.DisposeAsync() = + member _.DisposeAsync() = taskDynamic { disposed <- disposed + 1 do! Task.Delay(10) @@ -720,7 +714,7 @@ type Basics() = #endif [] - member __.testUsingFromTask() = + member _.testUsingFromTask() = printfn "Running testUsingFromTask..." let mutable disposedInner = false let mutable disposed = false @@ -729,9 +723,9 @@ type Basics() = use! d = taskDynamic { do! Task.Delay(50) - use i = { new IDisposable with member __.Dispose() = disposedInner <- true } + use i = { new IDisposable with member _.Dispose() = disposedInner <- true } require (not disposed && not disposedInner) "disposed inner early" - return { new IDisposable with member __.Dispose() = disposed <- true } + return { new IDisposable with member _.Dispose() = disposed <- true } } require disposedInner "did not dispose inner after task completion" require (not disposed) "disposed way early" @@ -742,7 +736,7 @@ type Basics() = require disposed "never disposed C" [] - member __.testUsingSadPath() = + member _.testUsingSadPath() = printfn "Running testUsingSadPath..." let mutable disposedInner = false let mutable disposed = false @@ -752,10 +746,10 @@ type Basics() = use! d = taskDynamic { do! Task.Delay(50) - use i = { new IDisposable with member __.Dispose() = disposedInner <- true } + use i = { new IDisposable with member _.Dispose() = disposedInner <- true } failtest "uhoh" require (not disposed && not disposedInner) "disposed inner early" - return { new IDisposable with member __.Dispose() = disposed <- true } + return { new IDisposable with member _.Dispose() = disposed <- true } } () with @@ -771,7 +765,7 @@ type Basics() = require (not disposed) "disposed thing that never should've existed" [] - member __.testForLoopA() = + member _.testForLoopA() = printfn "Running testForLoopA..." let list = ["a"; "b"; "c"] |> Seq.ofList let t = @@ -788,7 +782,7 @@ type Basics() = t.Wait() [] - member __.testForLoopComplex() = + member _.testForLoopComplex() = printfn "Running testForLoopComplex..." let mutable disposed = false let wrapList = @@ -796,26 +790,26 @@ type Basics() = let getEnumerator() = let raw = raw.GetEnumerator() { new IEnumerator with - member __.MoveNext() = + member _.MoveNext() = require (not disposed) "moved next after disposal" raw.MoveNext() - member __.Current = + member _.Current = require (not disposed) "accessed current after disposal" raw.Current - member __.Current = + member _.Current = require (not disposed) "accessed current (boxed) after disposal" box raw.Current - member __.Dispose() = + member _.Dispose() = require (not disposed) "disposed twice" disposed <- true raw.Dispose() - member __.Reset() = + member _.Reset() = require (not disposed) "reset after disposal" raw.Reset() } { new IEnumerable with - member __.GetEnumerator() : IEnumerator = getEnumerator() - member __.GetEnumerator() : IEnumerator = upcast getEnumerator() + member _.GetEnumerator() : IEnumerator = getEnumerator() + member _.GetEnumerator() : IEnumerator = upcast getEnumerator() } let t = taskDynamic { @@ -847,7 +841,7 @@ type Basics() = require (t.Result = 1) "wrong result" [] - member __.testForLoopSadPath() = + member _.testForLoopSadPath() = printfn "Running testForLoopSadPath..." for i in 1 .. 5 do let wrapList = ["a"; "b"; "c"] @@ -863,7 +857,7 @@ type Basics() = require (t.Result = 1) "wrong result" [] - member __.testForLoopSadPathComplex() = + member _.testForLoopSadPathComplex() = printfn "Running testForLoopSadPathComplex..." for i in 1 .. 5 do let mutable disposed = false @@ -872,26 +866,26 @@ type Basics() = let getEnumerator() = let raw = raw.GetEnumerator() { new IEnumerator with - member __.MoveNext() = + member _.MoveNext() = require (not disposed) "moved next after disposal" raw.MoveNext() - member __.Current = + member _.Current = require (not disposed) "accessed current after disposal" raw.Current - member __.Current = + member _.Current = require (not disposed) "accessed current (boxed) after disposal" box raw.Current - member __.Dispose() = + member _.Dispose() = require (not disposed) "disposed twice" disposed <- true raw.Dispose() - member __.Reset() = + member _.Reset() = require (not disposed) "reset after disposal" raw.Reset() } { new IEnumerable with - member __.GetEnumerator() : IEnumerator = getEnumerator() - member __.GetEnumerator() : IEnumerator = upcast getEnumerator() + member _.GetEnumerator() : IEnumerator = getEnumerator() + member _.GetEnumerator() : IEnumerator = upcast getEnumerator() } let mutable caught = false let t = @@ -918,7 +912,7 @@ type Basics() = require disposed "never disposed A" [] - member __.testExceptionAttachedToTaskWithoutAwait() = + member _.testExceptionAttachedToTaskWithoutAwait() = for i in 1 .. 5 do let mutable ranA = false let mutable ranB = false @@ -951,7 +945,7 @@ type Basics() = require caught "didn't catch" [] - member __.testExceptionAttachedToTaskWithAwait() = + member _.testExceptionAttachedToTaskWithAwait() = printfn "running testExceptionAttachedToTaskWithAwait" for i in 1 .. 5 do let mutable ranA = false @@ -986,7 +980,7 @@ type Basics() = require caught "didn't catch" [] - member __.testExceptionThrownInFinally() = + member _.testExceptionThrownInFinally() = printfn "running testExceptionThrownInFinally" for i in 1 .. 5 do let mutable ranInitial = false @@ -1014,7 +1008,7 @@ type Basics() = require (ranFinally = 1) "didn't run finally exactly once" [] - member __.test2ndExceptionThrownInFinally() = + member _.test2ndExceptionThrownInFinally() = printfn "running test2ndExceptionThrownInFinally" for i in 1 .. 5 do let mutable ranInitial = false @@ -1043,7 +1037,7 @@ type Basics() = require (ranFinally = 1) "didn't run finally exactly once" [] - member __.testFixedStackWhileLoop() = + member _.testFixedStackWhileLoop() = printfn "running testFixedStackWhileLoop" for i in 1 .. 100 do let t = @@ -1064,7 +1058,7 @@ type Basics() = require (t.Result = BIG) "didn't get to big number" [] - member __.testFixedStackForLoop() = + member _.testFixedStackForLoop() = for i in 1 .. 100 do printfn "running testFixedStackForLoop" let mutable ran = false @@ -1085,7 +1079,7 @@ type Basics() = require ran "didn't run all" [] - member __.testTypeInference() = + member _.testTypeInference() = let t1 : string Task = taskDynamic { return "hello" @@ -1098,7 +1092,7 @@ type Basics() = t2.Wait() [] - member __.testNoStackOverflowWithImmediateResult() = + member _.testNoStackOverflowWithImmediateResult() = printfn "running testNoStackOverflowWithImmediateResult" let longLoop = taskDynamic { @@ -1110,7 +1104,7 @@ type Basics() = longLoop.Wait() [] - member __.testNoStackOverflowWithYieldResult() = + member _.testNoStackOverflowWithYieldResult() = printfn "running testNoStackOverflowWithYieldResult" let longLoop = taskDynamic { @@ -1127,7 +1121,7 @@ type Basics() = longLoop.Wait() [] - member __.testSmallTailRecursion() = + member _.testSmallTailRecursion() = printfn "running testSmallTailRecursion" let rec loop n = taskDynamic { @@ -1145,7 +1139,7 @@ type Basics() = shortLoop.Wait() [] - member __.testTryOverReturnFrom() = + member _.testTryOverReturnFrom() = printfn "running testTryOverReturnFrom" let inner() = taskDynamic { @@ -1164,7 +1158,7 @@ type Basics() = require (t.Result = 2) "didn't catch" [] - member __.testTryFinallyOverReturnFromWithException() = + member _.testTryFinallyOverReturnFromWithException() = printfn "running testTryFinallyOverReturnFromWithException" let inner() = taskDynamic { @@ -1188,7 +1182,7 @@ type Basics() = require (m = 1) "didn't run finally" [] - member __.testTryFinallyOverReturnFromWithoutException() = + member _.testTryFinallyOverReturnFromWithoutException() = printfn "running testTryFinallyOverReturnFromWithoutException" let inner() = taskDynamic { @@ -1211,21 +1205,21 @@ type Basics() = require (m = 1) "didn't run finally" // no need to call this, we just want to check that it compiles w/o warnings - member __.testTrivialReturnCompiles (x : 'a) : 'a Task = + member _.testTrivialReturnCompiles (x : 'a) : 'a Task = taskDynamic { do! Task.Yield() return x } // no need to call this, we just want to check that it compiles w/o warnings - member __.testTrivialTransformedReturnCompiles (x : 'a) (f : 'a -> 'b) : 'b Task = + member _.testTrivialTransformedReturnCompiles (x : 'a) (f : 'a -> 'b) : 'b Task = taskDynamic { do! Task.Yield() return f x } [] - member __.testAsyncsMixedWithTasks() = + member _.testAsyncsMixedWithTasks() = let t = taskDynamic { do! Task.Delay(1) @@ -1242,7 +1236,7 @@ type Basics() = [] // no need to call this, we just want to check that it compiles w/o warnings - member __.testDefaultInferenceForReturnFrom() = + member _.testDefaultInferenceForReturnFrom() = let t = taskDynamic { return Some "x" } taskDynamic { let! r = t @@ -1255,7 +1249,7 @@ type Basics() = [] // no need to call this, just check that it compiles - member __.testCompilerInfersArgumentOfReturnFrom() = + member _.testCompilerInfersArgumentOfReturnFrom() = taskDynamic { if true then return 1 else return! failwith "" @@ -1267,7 +1261,7 @@ type Basics() = type BasicsNotInParallel() = [] - member __.testTaskUsesSyncContext() = + member _.testTaskUsesSyncContext() = printfn "Running testBackgroundTask..." for i in 1 .. 5 do let mutable ran = false @@ -1297,7 +1291,7 @@ type BasicsNotInParallel() = SynchronizationContext.SetSynchronizationContext oldSyncContext [] - member __.testBackgroundTaskEscapesSyncContext() = + member _.testBackgroundTaskEscapesSyncContext() = printfn "Running testBackgroundTask..." for i in 1 .. 5 do let mutable ran = false @@ -1318,7 +1312,7 @@ type BasicsNotInParallel() = SynchronizationContext.SetSynchronizationContext oldSyncContext [] - member __.testBackgroundTaskStaysOnSameThreadIfAlreadyOnBackground() = + member _.testBackgroundTaskStaysOnSameThreadIfAlreadyOnBackground() = printfn "Running testBackgroundTask..." for i in 1 .. 5 do let mutable ran = false @@ -1340,60 +1334,3 @@ type BasicsNotInParallel() = require ran "never ran") taskOuter.Wait() -#if STANDALONE -module M = - [] - let main argv = - printfn "Running tests..." - try - Basics().testShortCircuitResult() - Basics().testDelay() - Basics().testNoDelay() - Basics().testNonBlocking() - - Basics().testCatching1() - Basics().testCatching2() - Basics().testNestedCatching() - Basics().testWhileLoopSync() - Basics().testWhileLoopAsyncZeroIteration() - Basics().testWhileLoopAsyncOneIteration() - Basics().testWhileLoopAsync() - Basics().testTryFinallyHappyPath() - Basics().testTryFinallySadPath() - Basics().testTryFinallyCaught() - Basics().testUsing() - Basics().testUsingFromTask() - Basics().testUsingSadPath() - Basics().testForLoopA() - Basics().testForLoopSadPath() - Basics().testForLoopSadPathComplex() - Basics().testExceptionAttachedToTaskWithoutAwait() - Basics().testExceptionAttachedToTaskWithAwait() - Basics().testExceptionThrownInFinally() - Basics().test2ndExceptionThrownInFinally() - Basics().testFixedStackWhileLoop() - Basics().testFixedStackForLoop() - Basics().testTypeInference() - Basics().testNoStackOverflowWithImmediateResult() - Basics().testNoStackOverflowWithYieldResult() - ////// we don't support TCO, so large tail recursions will stack overflow - ////// or at least use O(n) heap. but small ones should at least function OK. - //testSmallTailRecursion() - Basics().testTryOverReturnFrom() - Basics().testTryFinallyOverReturnFromWithException() - Basics().testTryFinallyOverReturnFromWithoutException() - Basics().testAsyncsMixedWithTasks() - printfn "Passed all tests!" - with exn -> - eprintfn "************************************" - eprintfn "Exception: %O" exn - printfn "Test failed... exiting..." - eprintfn "************************************" - exit 1 - - printfn "Tests passed ok..., sleeping a bit in case there are background delayed exceptions" - Thread.Sleep(500) - printfn "Exiting..." - //System.Console.ReadLine() - 0 -#endif diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/OptionModule.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/OptionModule.fs index 50e6b325d8e..cecad68f233 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/OptionModule.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/OptionModule.fs @@ -117,6 +117,7 @@ type OptionModule() = Assert.False( Option.contains None None) Assert.True( Option.contains None (Some None)) + [] member this.OfToNullable() = Assert.True( Option.ofNullable (System.Nullable()) = None) diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/ResultTests.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/ResultTests.fs index adc300ba498..dd597bce129 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/ResultTests.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Core/ResultTests.fs @@ -17,6 +17,8 @@ open Result type ResultTests() = + let assertWasNotCalledThunk () = raise (exn "Thunk should not have been called.") + let fail_if_empty email= if String.IsNullOrEmpty(email) then Error Empty else Ok email @@ -81,4 +83,93 @@ type ResultTests() = |> bind addOneOk |> shouldBeErrorWithValue "Error" + [] + member this.IsOk() = + Assert.True(Result.isOk (Ok 1)) + Assert.False(Result.isOk (Error 1)) + [] + member this.IsError() = + Assert.False(Result.isError (Ok 1)) + Assert.True(Result.isError (Error 1)) + + [] + member this.DefaultValue() = + Assert.AreEqual(Result.defaultValue 3 (Error 42), 3) + Assert.AreEqual(Result.defaultValue 3 (Ok 42), 42) + Assert.AreEqual(Result.defaultValue "1" (Error "x"), "1") + Assert.AreEqual(Result.defaultValue "1" (Ok "x"), "x") + + [] + member this.DefaultWith() = + Assert.AreEqual(Result.defaultWith (fun () -> 3) (Error 42), 3) + Assert.AreEqual(Result.defaultWith (fun () -> "1") (Error "42"), "1") + + Assert.AreEqual(Result.defaultWith assertWasNotCalledThunk (Ok 42), 42) + Assert.AreEqual(Result.defaultWith assertWasNotCalledThunk (Ok "1"), "1") + + [] + member this.Count() = + Assert.AreEqual(Result.count (Ok 1), 1) + Assert.AreEqual(Result.count (Error 1), 0) + + [] + member this.Fold() = + Assert.AreEqual(Result.fold (fun accum x -> accum + x * 2) 0 (Error 2), 0) + Assert.AreEqual(Result.fold (fun accum x -> accum + x * 2) 0 (Ok 1), 2) + Assert.AreEqual(Result.fold (fun accum x -> accum + x * 2) 10 (Ok 1), 12) + + [] + member this.FoldBack() = + Assert.AreEqual(Result.foldBack (fun x accum -> accum + x * 2) (Error 2) 0, 0) + Assert.AreEqual(Result.foldBack (fun x accum -> accum + x * 2) (Ok 1) 0, 2) + Assert.AreEqual(Result.foldBack (fun x accum -> accum + x * 2) (Ok 1) 10, 12) + + [] + member this.Exists() = + Assert.AreEqual(Result.exists (fun x -> x >= 5) (Error 6), false) + Assert.AreEqual(Result.exists (fun x -> x >= 5) (Ok 42), true) + Assert.AreEqual(Result.exists (fun x -> x >= 5) (Ok 4), false) + + [] + member this.ForAll() = + Assert.AreEqual(Result.forall (fun x -> x >= 5) (Error 1), true) + Assert.AreEqual(Result.forall (fun x -> x >= 5) (Ok 42), true) + Assert.AreEqual(Result.forall (fun x -> x >= 5) (Ok 4), false) + + [] + member this.Contains() = + Assert.AreEqual(Result.contains 99 (Error 99), false) + Assert.AreEqual(Result.contains 99 (Ok 99), true) + Assert.AreEqual(Result.contains 99 (Ok 100), false) + + [] + member this.Iterate() = + let mutable i = 0 + let increment _ = + i <- i + 1 + + Result.iter increment (Error "Hello world") + Assert.AreEqual(0, i) + Result.iter increment (Ok "Hello world") + Assert.AreEqual(1, i) + + [] + member this.ToArray() = + Assert.AreEqual(Result.toArray (Error 42), [| |]) + Assert.AreEqual(Result.toArray (Ok 42), [| 42 |]) + + [] + member this.ToList() = + Assert.AreEqual(Result.toList (Error 42), [ ]) + Assert.AreEqual(Result.toList (Ok 42), [ 42 ]) + + [] + member this.ToOption() = + Assert.AreEqual(Result.toOption (Error 42), None) + Assert.AreEqual(Result.toOption (Ok 42), Some 42) + + [] + member this.ToValueOption() = + Assert.AreEqual(Result.toValueOption (Error 42), ValueNone) + Assert.AreEqual(Result.toValueOption (Ok 42), ValueSome 42) \ No newline at end of file diff --git a/tests/FSharp.Core.UnitTests/SurfaceArea.fs b/tests/FSharp.Core.UnitTests/SurfaceArea.fs index f778675c2f6..31d2fa41d15 100644 --- a/tests/FSharp.Core.UnitTests/SurfaceArea.fs +++ b/tests/FSharp.Core.UnitTests/SurfaceArea.fs @@ -1964,6 +1964,21 @@ Microsoft.FSharp.Core.RequiresExplicitTypeArgumentsAttribute: Void .ctor() Microsoft.FSharp.Core.ResultModule: Microsoft.FSharp.Core.FSharpResult`2[T,TResult] MapError[TError,TResult,T](Microsoft.FSharp.Core.FSharpFunc`2[TError,TResult], Microsoft.FSharp.Core.FSharpResult`2[T,TError]) Microsoft.FSharp.Core.ResultModule: Microsoft.FSharp.Core.FSharpResult`2[TResult,TError] Bind[T,TResult,TError](Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.FSharpResult`2[TResult,TError]], Microsoft.FSharp.Core.FSharpResult`2[T,TError]) Microsoft.FSharp.Core.ResultModule: Microsoft.FSharp.Core.FSharpResult`2[TResult,TError] Map[T,TResult,TError](Microsoft.FSharp.Core.FSharpFunc`2[T,TResult], Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Boolean Contains[T,TError](T, Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Boolean Exists[T,TError](Microsoft.FSharp.Core.FSharpFunc`2[T,System.Boolean], Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Boolean ForAll[T,TError](Microsoft.FSharp.Core.FSharpFunc`2[T,System.Boolean], Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Boolean IsError[T,TError](Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Boolean IsOk[T,TError](Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Int32 Count[T,TError](Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Microsoft.FSharp.Collections.FSharpList`1[T] ToList[T,TError](Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Microsoft.FSharp.Core.FSharpOption`1[T] ToOption[T,TError](Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Microsoft.FSharp.Core.FSharpValueOption`1[T] ToValueOption[T,TError](Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: T DefaultValue[T,TError](T, Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: T DefaultWith[T,TError](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,T], Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: TState FoldBack[T,TError,TState](Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.FSharpFunc`2[TState,TState]], Microsoft.FSharp.Core.FSharpResult`2[T,TError], TState) +Microsoft.FSharp.Core.ResultModule: TState Fold[T,TError,TState](Microsoft.FSharp.Core.FSharpFunc`2[TState,Microsoft.FSharp.Core.FSharpFunc`2[T,TState]], TState, Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: T[] ToArray[T,TError](Microsoft.FSharp.Core.FSharpResult`2[T,TError]) +Microsoft.FSharp.Core.ResultModule: Void Iterate[T,TError](Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.Unit], Microsoft.FSharp.Core.FSharpResult`2[T,TError]) Microsoft.FSharp.Core.SealedAttribute: Boolean Value Microsoft.FSharp.Core.SealedAttribute: Boolean get_Value() Microsoft.FSharp.Core.SealedAttribute: Void .ctor() diff --git a/tests/FSharp.Test.Utilities/Compiler.fs b/tests/FSharp.Test.Utilities/Compiler.fs index 6408f14dae0..54822b93d80 100644 --- a/tests/FSharp.Test.Utilities/Compiler.fs +++ b/tests/FSharp.Test.Utilities/Compiler.fs @@ -265,6 +265,11 @@ module rec Compiler = let CsSource source = SourceCodeFileKind.Cs({FileName="test.cs"; SourceText=Some source }) + let CsFromPath (path: string) : CompilationUnit = + csFromString (SourceFromPath path) + |> CS + |> withName (Path.GetFileNameWithoutExtension(path)) + let Fsx (source: string) : CompilationUnit = fsFromString (FsxSourceCode source) |> FS @@ -435,6 +440,18 @@ module rec Compiler = let withNoInterfaceData (cUnit: CompilationUnit) : CompilationUnit = withOptionsHelper [ "--nointerfacedata" ] "withNoInterfaceData is only supported for F#" cUnit + //--refonly[+|-] + let withRefOnly (cUnit: CompilationUnit) : CompilationUnit = + withOptionsHelper [ $"--refonly+" ] "withRefOnly is only supported for F#" cUnit + + //--refonly[+|-] + let withNoRefOnly (cUnit: CompilationUnit) : CompilationUnit = + withOptionsHelper [ $"--refonly-" ] "withRefOnly is only supported for F#" cUnit + + //--refout: Produce a reference assembly with the specified file path. + let withRefOut (name:string) (cUnit: CompilationUnit) : CompilationUnit = + withOptionsHelper [ $"--refout:{name}" ] "withNoInterfaceData is only supported for F#" cUnit + let asLibrary (cUnit: CompilationUnit) : CompilationUnit = match cUnit with | FS fs -> FS { fs with OutputType = CompileOutput.Library } @@ -467,6 +484,9 @@ module rec Compiler = | FS fs -> FS { fs with IgnoreWarnings = true } | _ -> failwith "TODO: Implement ignorewarnings for the rest." + let withCulture culture (cUnit: CompilationUnit) : CompilationUnit = + withOptionsHelper [ $"--preferreduilang:%s{culture}" ] "preferreduilang is only supported for F#" cUnit + let rec private asMetadataReference (cUnit: CompilationUnit) reference = match reference with | CompilationReference (cmpl, _) -> @@ -611,16 +631,27 @@ module rec Compiler = | _ -> failwith "Compilation has errors." - let compileGuid (cUnit: CompilationUnit) : Guid = - let bytes = - compile cUnit - |> shouldSucceed - |> getAssemblyInBytes + let getAssembly = getAssemblyInBytes >> Assembly.Load + + let withPeReader func compilationResult = + let bytes = getAssemblyInBytes compilationResult + use reader = new PEReader(bytes.ToImmutableArray()) + func reader - use reader1 = new PEReader(bytes.ToImmutableArray()) - let reader1 = reader1.GetMetadataReader() + let withMetadataReader func = + withPeReader (fun reader -> reader.GetMetadataReader() |> func) - reader1.GetModuleDefinition().Mvid |> reader1.GetGuid + let compileGuid cUnit = + cUnit + |> compile + |> shouldSucceed + |> withMetadataReader (fun reader -> reader.GetModuleDefinition().Mvid |> reader.GetGuid) + + let compileAssembly cUnit = + cUnit + |> compile + |> shouldSucceed + |> getAssembly let private parseFSharp (fsSource: FSharpCompilationSource) : CompilationResult = let source = fsSource.Source.GetSourceText |> Option.defaultValue "" diff --git a/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj b/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj index c9852f0fb8c..a20052b3f66 100644 --- a/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj +++ b/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj @@ -26,6 +26,7 @@ + diff --git a/tests/FSharp.Test.Utilities/ReflectionHelper.fs b/tests/FSharp.Test.Utilities/ReflectionHelper.fs new file mode 100644 index 00000000000..5759752c706 --- /dev/null +++ b/tests/FSharp.Test.Utilities/ReflectionHelper.fs @@ -0,0 +1,63 @@ +module FSharp.Test.ReflectionHelper + +open System +open System.Reflection + +/// Gets the given type from the assembly (otherwise throws) +let getType typeName (asm: Assembly) = + match asm.GetType(typeName, false) with + | null -> + let allTypes = + asm.GetTypes() + |> Array.map (fun ty -> ty.Name) + |> Array.reduce (fun x y -> $"%s{x}\r%s{y}") + + failwith $"Error: Assembly did not contain type %s{typeName}.\nAll types in asm:\n%s{allTypes}" + | ty -> ty + +/// Gets all anonymous types from the assembly +let getAnonymousTypes (asm: Assembly) = + [ for ty in asm.GetTypes() do + if ty.FullName.StartsWith "<>f__AnonymousType" then ty ] + +/// Gets the first anonymous type from the assembly +let getFirstAnonymousType asm = + match getAnonymousTypes asm with + | ty :: _ -> ty + | [] -> failwith "Error: No anonymous types found in the assembly" + +/// Gets a type's method +let getMethod methodName (ty: Type) = + match ty.GetMethod(methodName) with + | null -> failwith $"Error: Type did not contain member %s{methodName}" + | methodInfo -> methodInfo + +/// Assert that function f returns Ok for given input +let should f x y = + match f x y with + | Ok _ -> () + | Error message -> failwith $"%s{message} but it should" + +/// Assert that function f doesn't return Ok for given input +let shouldn't f x y = + match f x y with + | Ok message -> failwith $"%s{message} but it shouldn't" + | Error _ -> () + +/// Verify the object contains a custom attribute with the given name. E.g. "ObsoleteAttribute" +let haveAttribute attrName thingy = + let attrs = + match box thingy with + | :? Type as ty -> ty.GetCustomAttributes(false) + | :? MethodInfo as mi -> mi.GetCustomAttributes(false) + | :? PropertyInfo as pi -> pi.GetCustomAttributes(false) + | :? EventInfo as ei -> ei.GetCustomAttributes(false) + | _ -> failwith "Error: Unsupported primitive type, unable to get custom attributes." + + let hasAttribute = + attrs |> Array.exists (fun att -> att.GetType().Name = attrName) + + if hasAttribute then + Ok $"'{thingy}' has attribute '{attrName}'" + else + Error $"'{thingy}' doesn't have attribute '{attrName}'" diff --git a/tests/FSharp.Test.Utilities/TestFramework.fs b/tests/FSharp.Test.Utilities/TestFramework.fs index 936794b175b..f2d93c0513c 100644 --- a/tests/FSharp.Test.Utilities/TestFramework.fs +++ b/tests/FSharp.Test.Utilities/TestFramework.fs @@ -308,8 +308,8 @@ let config configurationName envVars = let coreClrRuntimePackageVersion = "5.0.0-preview.7.20364.11" let csc_flags = "/nologo" let vbc_flags = "/nologo" - let fsc_flags = "-r:System.Core.dll --nowarn:20 --define:COMPILED" - let fsi_flags = "-r:System.Core.dll --nowarn:20 --define:INTERACTIVE --maxerrors:1 --abortonerror" + let fsc_flags = "-r:System.Core.dll --nowarn:20 --define:COMPILED --preferreduilang:en-US" + let fsi_flags = "-r:System.Core.dll --nowarn:20 --define:INTERACTIVE --maxerrors:1 --abortonerror --preferreduilang:en-US" let operatingSystem = getOperatingSystem () let Is64BitOperatingSystem = DotnetPlatform.Is64BitOperatingSystem envVars let architectureMoniker = if Is64BitOperatingSystem then "x64" else "x86" diff --git a/tests/PEVerify/PEVerify.csproj b/tests/PEVerify/PEVerify.csproj index 961cbc66379..d8761bd252e 100644 --- a/tests/PEVerify/PEVerify.csproj +++ b/tests/PEVerify/PEVerify.csproj @@ -7,6 +7,13 @@ net6.0 win-x86;win-x64;linux-x64;osx-x64 $(AssetTargetFallback);portable-net45+win8+wp8+wpa81 + + $(NoWarn);NU1505 $(NoWarn);1591 diff --git a/tests/PEVerify/Program.cs b/tests/PEVerify/Program.cs index ecc24afee3e..f2a9a3f2caf 100644 --- a/tests/PEVerify/Program.cs +++ b/tests/PEVerify/Program.cs @@ -3,6 +3,7 @@ using System; using System.IO; using Roslyn.Test.Utilities.Desktop; +using System.Globalization; namespace PEVerify { @@ -10,6 +11,12 @@ class Program { static int Main(string[] args) { + // this version of PEVerify is only intended to run F# test suit + // force the en-US culture so that tests warning/error message comparision + // is not culture dependent + var culture = new CultureInfo("en-US"); + CultureInfo.CurrentCulture = culture; + CultureInfo.CurrentUICulture = culture; string assemblyPath = null; bool metadataOnly = false; foreach (var arg in args) diff --git a/tests/benchmarks/MicroPerf/Async.fs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Async.fs similarity index 100% rename from tests/benchmarks/MicroPerf/Async.fs rename to tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Async.fs diff --git a/tests/benchmarks/MicroPerf/Benchmarks.fs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Benchmarks.fs similarity index 100% rename from tests/benchmarks/MicroPerf/Benchmarks.fs rename to tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Benchmarks.fs diff --git a/tests/benchmarks/MicroPerf/CS/MicroPerfCSharp.cs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.cs similarity index 100% rename from tests/benchmarks/MicroPerf/CS/MicroPerfCSharp.cs rename to tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.cs diff --git a/tests/benchmarks/MicroPerf/CS/MicroPerfCSharp.csproj b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.csproj similarity index 100% rename from tests/benchmarks/MicroPerf/CS/MicroPerfCSharp.csproj rename to tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.csproj diff --git a/tests/benchmarks/MicroPerf/Collections.fs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Collections.fs similarity index 100% rename from tests/benchmarks/MicroPerf/Collections.fs rename to tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Collections.fs diff --git a/tests/benchmarks/MicroPerf/Conditions.fs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Conditions.fs similarity index 100% rename from tests/benchmarks/MicroPerf/Conditions.fs rename to tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Conditions.fs diff --git a/tests/benchmarks/MicroPerf/MicroPerf.fsproj b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/MicroPerf.fsproj similarity index 71% rename from tests/benchmarks/MicroPerf/MicroPerf.fsproj rename to tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/MicroPerf.fsproj index 796650d88a8..9b89d243beb 100644 --- a/tests/benchmarks/MicroPerf/MicroPerf.fsproj +++ b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/MicroPerf.fsproj @@ -2,6 +2,13 @@ net6.0 Exe + + $(NoWarn);NU1505 true $(OtherFlags) --nowarn:1204 @@ -22,7 +29,7 @@ - + diff --git a/tests/benchmarks/TaskPerf/TaskBuilder.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskBuilder.fs similarity index 100% rename from tests/benchmarks/TaskPerf/TaskBuilder.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskBuilder.fs diff --git a/tests/benchmarks/TaskPerf/TaskPerf.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fs similarity index 100% rename from tests/benchmarks/TaskPerf/TaskPerf.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fs diff --git a/tests/benchmarks/TaskPerf/TaskPerf.fsproj b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fsproj similarity index 76% rename from tests/benchmarks/TaskPerf/TaskPerf.fsproj rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fsproj index 3bd609d7fd5..4d04ba47cb4 100644 --- a/tests/benchmarks/TaskPerf/TaskPerf.fsproj +++ b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fsproj @@ -3,6 +3,13 @@ net6.0 Exe + + NU1505 true $(OtherFlags) --nowarn:1204 @@ -34,7 +41,7 @@ --> - + diff --git a/tests/benchmarks/TaskPerf/array.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/array.fs similarity index 100% rename from tests/benchmarks/TaskPerf/array.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/array.fs diff --git a/tests/benchmarks/TaskPerf/async2.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/async2.fs similarity index 100% rename from tests/benchmarks/TaskPerf/async2.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/async2.fs diff --git a/tests/benchmarks/TaskPerf/async2.fsi b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/async2.fsi similarity index 100% rename from tests/benchmarks/TaskPerf/async2.fsi rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/async2.fsi diff --git a/tests/benchmarks/TaskPerf/coroutine.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/coroutine.fs similarity index 100% rename from tests/benchmarks/TaskPerf/coroutine.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/coroutine.fs diff --git a/tests/benchmarks/TaskPerf/coroutineBasic.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/coroutineBasic.fs similarity index 100% rename from tests/benchmarks/TaskPerf/coroutineBasic.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/coroutineBasic.fs diff --git a/tests/benchmarks/TaskPerf/empty.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/empty.fs similarity index 100% rename from tests/benchmarks/TaskPerf/empty.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/empty.fs diff --git a/tests/benchmarks/TaskPerf/list.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/list.fs similarity index 100% rename from tests/benchmarks/TaskPerf/list.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/list.fs diff --git a/tests/benchmarks/TaskPerf/option.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/option.fs similarity index 100% rename from tests/benchmarks/TaskPerf/option.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/option.fs diff --git a/tests/benchmarks/TaskPerf/option2.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/option2.fs similarity index 100% rename from tests/benchmarks/TaskPerf/option2.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/option2.fs diff --git a/tests/benchmarks/TaskPerf/seq2.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/seq2.fs similarity index 100% rename from tests/benchmarks/TaskPerf/seq2.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/seq2.fs diff --git a/tests/benchmarks/TaskPerf/sync.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/sync.fs similarity index 100% rename from tests/benchmarks/TaskPerf/sync.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/sync.fs diff --git a/tests/benchmarks/TaskPerf/taskSeq.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/taskSeq.fs similarity index 100% rename from tests/benchmarks/TaskPerf/taskSeq.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/taskSeq.fs diff --git a/tests/benchmarks/TaskPerfCSharp/TaskPerfCSharp.cs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.cs similarity index 100% rename from tests/benchmarks/TaskPerfCSharp/TaskPerfCSharp.cs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.cs diff --git a/tests/benchmarks/TaskPerfCSharp/TaskPerfCSharp.csproj b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.csproj similarity index 100% rename from tests/benchmarks/TaskPerfCSharp/TaskPerfCSharp.csproj rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.csproj diff --git a/tests/benchmarks/TaskPerfPreviousCompiler/TaskPerfPreviousCompiler.fsproj b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/TaskPerfPreviousCompiler.fsproj similarity index 100% rename from tests/benchmarks/TaskPerfPreviousCompiler/TaskPerfPreviousCompiler.fsproj rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/TaskPerfPreviousCompiler.fsproj diff --git a/tests/benchmarks/TaskPerfPreviousCompiler/defs.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/defs.fs similarity index 100% rename from tests/benchmarks/TaskPerfPreviousCompiler/defs.fs rename to tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/defs.fs diff --git a/tests/benchmarks/BenchmarkComparison/BenchmarkComparison.fs b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/BenchmarkComparison.fs similarity index 100% rename from tests/benchmarks/BenchmarkComparison/BenchmarkComparison.fs rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/BenchmarkComparison.fs diff --git a/tests/benchmarks/BenchmarkComparison/Program.fs b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/Program.fs similarity index 100% rename from tests/benchmarks/BenchmarkComparison/Program.fs rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/Program.fs diff --git a/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/README.md b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/README.md new file mode 100644 index 00000000000..d24c6ad5216 --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/README.md @@ -0,0 +1,21 @@ +# BenchmarkComparison + +## What is it + +* A meta-benchmark that compares performance between versions of the FCS codebase for a single-file codebase. +* Notebook-based, see `runner.ipynb`. +* Specified versions of FCS are downloaded from GitHub, built and benchmarked. +* Individual runs involve running a BDN benchmark in a separate process. +* Each run tests `FSharpChecker.ParseAndCheckFileInProject` on a single file (see `decentlySizedStandAloneFile.fs`). + +## How to run it + +*TODO* + +## Sample results + +*TODO* + +## Other + +You can find this document under 'tests/benchmarks/FCSBenchmarks/BenchmarkComparison/README.md'. \ No newline at end of file diff --git a/tests/benchmarks/BenchmarkComparison/decentlySizedStandAloneFile.fs b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/decentlySizedStandAloneFile.fs similarity index 100% rename from tests/benchmarks/BenchmarkComparison/decentlySizedStandAloneFile.fs rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/decentlySizedStandAloneFile.fs diff --git a/tests/benchmarks/BenchmarkComparison/run.fsproj b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/run.fsproj similarity index 100% rename from tests/benchmarks/BenchmarkComparison/run.fsproj rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/run.fsproj diff --git a/tests/benchmarks/BenchmarkComparison/run_current.fsproj b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/run_current.fsproj similarity index 100% rename from tests/benchmarks/BenchmarkComparison/run_current.fsproj rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/run_current.fsproj diff --git a/tests/benchmarks/BenchmarkComparison/runner.ipynb b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/runner.ipynb similarity index 100% rename from tests/benchmarks/BenchmarkComparison/runner.ipynb rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/runner.ipynb diff --git a/tests/benchmarks/BenchmarkComparison/setup_commit_template.fsproj b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_commit_template.fsproj similarity index 90% rename from tests/benchmarks/BenchmarkComparison/setup_commit_template.fsproj rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_commit_template.fsproj index 9302071856f..c33b103f503 100644 --- a/tests/benchmarks/BenchmarkComparison/setup_commit_template.fsproj +++ b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_commit_template.fsproj @@ -18,7 +18,7 @@ - + {TEMPLATE_FCS_PATH} diff --git a/tests/benchmarks/BenchmarkComparison/setup_current.fsproj b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_current.fsproj similarity index 79% rename from tests/benchmarks/BenchmarkComparison/setup_current.fsproj rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_current.fsproj index ff0fda7ff64..8701aa0e715 100644 --- a/tests/benchmarks/BenchmarkComparison/setup_current.fsproj +++ b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_current.fsproj @@ -18,8 +18,8 @@ - - + + diff --git a/tests/benchmarks/BenchmarkComparison/setup_version_template.fsproj b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_version_template.fsproj similarity index 90% rename from tests/benchmarks/BenchmarkComparison/setup_version_template.fsproj rename to tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_version_template.fsproj index 96c706c19a7..300465c09f8 100644 --- a/tests/benchmarks/BenchmarkComparison/setup_version_template.fsproj +++ b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/setup_version_template.fsproj @@ -18,7 +18,7 @@ - + diff --git a/tests/benchmarks/CompilerServiceBenchmarks/Benchmarks.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Benchmarks.fs similarity index 100% rename from tests/benchmarks/CompilerServiceBenchmarks/Benchmarks.fs rename to tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Benchmarks.fs diff --git a/tests/benchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj similarity index 50% rename from tests/benchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj rename to tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj index 06f8d57b501..ce0203b33e8 100644 --- a/tests/benchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj @@ -4,6 +4,13 @@ Exe net6.0 true + + $(NoWarn);NU1505 @@ -19,8 +26,8 @@ - - + + diff --git a/tests/benchmarks/CompilerServiceBenchmarks/Helpers.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Helpers.fs similarity index 100% rename from tests/benchmarks/CompilerServiceBenchmarks/Helpers.fs rename to tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Helpers.fs diff --git a/tests/benchmarks/CompilerServiceBenchmarks/Program.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Program.fs similarity index 100% rename from tests/benchmarks/CompilerServiceBenchmarks/Program.fs rename to tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Program.fs diff --git a/tests/benchmarks/CompilerServiceBenchmarks/benchmarks.ipynb b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/benchmarks.ipynb similarity index 100% rename from tests/benchmarks/CompilerServiceBenchmarks/benchmarks.ipynb rename to tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/benchmarks.ipynb diff --git a/tests/benchmarks/CompilerServiceBenchmarks/decentlySizedStandAloneFile.fsx b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/decentlySizedStandAloneFile.fsx similarity index 100% rename from tests/benchmarks/CompilerServiceBenchmarks/decentlySizedStandAloneFile.fsx rename to tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/decentlySizedStandAloneFile.fsx diff --git a/tests/benchmarks/FCSSourceFiles/FCSSourceFiles.fsproj b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/FCSSourceFiles.fsproj similarity index 79% rename from tests/benchmarks/FCSSourceFiles/FCSSourceFiles.fsproj rename to tests/benchmarks/FCSBenchmarks/FCSSourceFiles/FCSSourceFiles.fsproj index 267013c6b41..71100a99af4 100644 --- a/tests/benchmarks/FCSSourceFiles/FCSSourceFiles.fsproj +++ b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/FCSSourceFiles.fsproj @@ -14,7 +14,7 @@ - + diff --git a/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/Program.fs b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/Program.fs new file mode 100644 index 00000000000..62cbb587e93 --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/Program.fs @@ -0,0 +1,934 @@ +open System +open System.Diagnostics +open System.IO +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Text +open BenchmarkDotNet.Attributes +open BenchmarkDotNet.Running + +module Project = + let nugetCache = + let ps = ProcessStartInfo("dotnet", "nuget locals global-packages -l") + ps.RedirectStandardOutput <- true + ps.RedirectStandardError <- true + let p = Process.Start ps + let stdout = p.StandardOutput.ReadToEnd().Trim() + p.WaitForExit() + stdout.Replace("global-packages:", "").Trim() + + let FSharpCore = + let projectOptions = + { ProjectFileName = __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\FSharp.Core.fsproj" + ProjectId = None + SourceFiles = + [| __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\prim-types-prelude.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\prim-types-prelude.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSCore.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSharp.Core.AssemblyInfo.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\prim-types.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\prim-types.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\local.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\local.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\array2.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\array2.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\option.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\option.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\result.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\result.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\collections.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\collections.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\seqcore.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\seqcore.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\seq.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\seq.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\string.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\string.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\list.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\list.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\array.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\array.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\array3.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\array3.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\map.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\map.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\set.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\set.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\reflect.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\reflect.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\math\z.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\math\z.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\sformat.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\sformat.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\printf.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\printf.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\quotations.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\quotations.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\nativeptr.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\nativeptr.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\event.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\event.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\resumable.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\resumable.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\async.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\async.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\tasks.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\tasks.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\eventmodule.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\eventmodule.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\observable.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\observable.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\mailbox.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\mailbox.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\Nullable.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\Nullable.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\Linq.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\Linq.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\MutableTuple.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\QueryExtensions.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\Query.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\Query.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\SI.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\fslib-extra-pervasives.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.Core\fslib-extra-pervasives.fs" |] + OtherOptions = + [| sprintf "-o:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSharp.Core.dll" + @"-g" + @"--debug:embedded" + @"--langversion:preview" + @"--noframework" + @"--define:TRACE" + @"--define:FSHARP_CORE" + @"--define:DEBUG" + @"--define:NETSTANDARD" + @"--define:FX_NO_APP_DOMAINS" + @"--define:FX_NO_CORHOST_SIGNER" + @"--define:FX_NO_PDB_READER" + @"--define:FX_NO_PDB_WRITER" + @"--define:FX_NO_SYMBOLSTORE" + @"--define:FX_NO_SYSTEM_CONFIGURATION" + @"--define:FX_NO_WIN_REGISTRY" + @"--define:FX_NO_WINFORMS" + @"--define:FX_RESHAPED_REFEMIT" + @"--define:NETSTANDARD" + @"--define:NETSTANDARD2_1" + @"--define:NETSTANDARD1_0_OR_GREATER" + @"--define:NETSTANDARD1_1_OR_GREATER" + @"--define:NETSTANDARD1_2_OR_GREATER" + @"--define:NETSTANDARD1_3_OR_GREATER" + @"--define:NETSTANDARD1_4_OR_GREATER" + @"--define:NETSTANDARD1_5_OR_GREATER" + @"--define:NETSTANDARD1_6_OR_GREATER" + @"--define:NETSTANDARD2_0_OR_GREATER" + @"--define:NETSTANDARD2_1_OR_GREATER" + sprintf "-doc:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSharp.Core.xml" + @"--publicsign+" + @"--optimize-" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\Microsoft.Win32.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\mscorlib.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\netstandard.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.AppContext.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Buffers.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.Concurrent.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.NonGeneric.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.Specialized.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.Composition.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.EventBasedAsync.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.TypeConverter.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Console.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Core.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Data.Common.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Data.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Contracts.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Debug.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.FileVersionInfo.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Process.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.StackTrace.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.TextWriterTraceListener.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Tools.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.TraceSource.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Tracing.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Drawing.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Drawing.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Dynamic.Runtime.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Globalization.Calendars.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Globalization.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Globalization.Extensions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Compression.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Compression.FileSystem.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Compression.ZipFile.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.DriveInfo.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.Watcher.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.IsolatedStorage.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.MemoryMappedFiles.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Pipes.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.UnmanagedMemoryStream.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.Expressions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.Parallel.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.Queryable.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Memory.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Http.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.NameResolution.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.NetworkInformation.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Ping.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Requests.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Security.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Sockets.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.WebHeaderCollection.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.WebSockets.Client.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.WebSockets.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Numerics.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Numerics.Vectors.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ObjectModel.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.DispatchProxy.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Emit.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Emit.ILGeneration.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Emit.Lightweight.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Extensions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Resources.Reader.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Resources.ResourceManager.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Resources.Writer.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.CompilerServices.VisualC.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Extensions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Handles.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.InteropServices.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.InteropServices.RuntimeInformation.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Numerics.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Formatters.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Json.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Xml.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Claims.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Algorithms.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Csp.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Encoding.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Primitives.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.X509Certificates.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Principal.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.SecureString.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ServiceModel.Web.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Text.Encoding.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Text.Encoding.Extensions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Text.RegularExpressions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Overlapped.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Tasks.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Tasks.Extensions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Tasks.Parallel.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Thread.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.ThreadPool.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Timer.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Transactions.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ValueTuple.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Web.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Windows.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.Linq.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.ReaderWriter.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.Serialization.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XDocument.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XmlDocument.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XmlSerializer.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XPath.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XPath.XDocument.dll" + @"--target:library" + @"--nowarn:FS2003,62,75,1204,NU5105" + @"--warn:3" + @"--warnaserror:3239,1182,0025" + @"--fullpaths" + @"--flaterrors" + @"--highentropyva+" + @"--targetprofile:netstandard" + @"--nocopyfsharpcore" + @"--deterministic+" + @"--simpleresolution" + @"--nowarn:3384" + @"--warnon:3218" + @"--warnon:1182" + @"--warnon:3390" + @"--warnon:3520" + @"--warnon:1182" + @"--warnon:3390" + @"--nowarn:57" + @"--nowarn:3511" + @"--nowarn:3513" + @"--compiling-fslib" + @"--compiling-fslib-40" + @"--maxerrors:100" + @"--extraoptimizationloops:1" + @"--simpleresolution" |] + ReferencedProjects = [||] + IsIncompleteTypeCheckEnvironment = false + UseScriptResolutionRules = false + LoadTime = DateTime.Now + UnresolvedReferences = None + OriginalLoadReferences = [] + Stamp = None } + + FSharpReferencedProject.CreateFSharp( + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\bin\FSharp.Core\Debug\netstandard2.1\FSharp.Core.dll", + projectOptions + ) + + let FSharpDependencyManagerNuget = + let projectOptions = + { ProjectFileName = __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.Nuget.fsproj" + ProjectId = None + SourceFiles = + [| __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSDependencyManager.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\UtilsStrings.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.InternalsVisibleTo.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.AssemblyInfo.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\CompilerLocation.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\CompilerLocation.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.ProjectFile.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.Utilities.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.fs" |] + OtherOptions = + [| sprintf "-o:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.dll" + @"-g" + @"--debug:embedded" + @"--noframework" + @"--define:TRACE" + @"--define:COMPILER" + @"--define:DEBUG" + @"--define:NETSTANDARD" + @"--define:FX_NO_APP_DOMAINS" + @"--define:FX_NO_CORHOST_SIGNER" + @"--define:FX_NO_PDB_READER" + @"--define:FX_NO_PDB_WRITER" + @"--define:FX_NO_SYMBOLSTORE" + @"--define:FX_NO_SYSTEM_CONFIGURATION" + @"--define:FX_NO_WIN_REGISTRY" + @"--define:FX_NO_WINFORMS" + @"--define:FX_RESHAPED_REFEMIT" + @"--define:NETSTANDARD" + @"--define:NETSTANDARD2_0" + @"--define:NETSTANDARD1_0_OR_GREATER" + @"--define:NETSTANDARD1_1_OR_GREATER" + @"--define:NETSTANDARD1_2_OR_GREATER" + @"--define:NETSTANDARD1_3_OR_GREATER" + @"--define:NETSTANDARD1_4_OR_GREATER" + @"--define:NETSTANDARD1_5_OR_GREATER" + @"--define:NETSTANDARD1_6_OR_GREATER" + @"--define:NETSTANDARD2_0_OR_GREATER" + sprintf "-doc:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.xml" + @"--publicsign+" + @"--optimize-" + sprintf "-r:%s%s" nugetCache @"fsharp.core\6.0.1\lib\netstandard2.0\FSharp.Core.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\Microsoft.Win32.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\mscorlib.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\netstandard.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.AppContext.dll" + sprintf "-r:%s%s" nugetCache @"system.buffers\4.5.1\ref\netstandard2.0\System.Buffers.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.Concurrent.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.dll" + sprintf "-r:%s%s" nugetCache @"system.collections.immutable\5.0.0\lib\netstandard2.0\System.Collections.Immutable.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.NonGeneric.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.Specialized.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.Composition.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.EventBasedAsync.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.TypeConverter.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Console.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Core.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Data.Common.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Data.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Contracts.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Debug.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.FileVersionInfo.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Process.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.StackTrace.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.TextWriterTraceListener.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Tools.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.TraceSource.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Tracing.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Drawing.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Drawing.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Dynamic.Runtime.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Globalization.Calendars.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Globalization.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Globalization.Extensions.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Compression.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Compression.FileSystem.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Compression.ZipFile.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.DriveInfo.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.Watcher.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.IsolatedStorage.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.MemoryMappedFiles.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Pipes.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.UnmanagedMemoryStream.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.Expressions.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.Parallel.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.Queryable.dll" + sprintf "-r:%s%s" nugetCache @"system.memory\4.5.4\lib\netstandard2.0\System.Memory.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Http.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.NameResolution.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.NetworkInformation.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Ping.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Requests.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Security.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Sockets.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.WebHeaderCollection.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.WebSockets.Client.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.WebSockets.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Numerics.dll" + sprintf "-r:%s%s" nugetCache @"system.numerics.vectors\4.4.0\ref\netstandard2.0\System.Numerics.Vectors.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ObjectModel.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Reflection.dll" + sprintf "-r:%s%s" nugetCache @"system.reflection.emit\4.3.0\ref\netstandard1.1\System.Reflection.Emit.dll" + sprintf "-r:%s%s" nugetCache @"system.reflection.emit.ilgeneration\4.3.0\ref\netstandard1.0\System.Reflection.Emit.ILGeneration.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Reflection.Extensions.dll" + sprintf "-r:%s%s" nugetCache @"system.reflection.metadata\5.0.0\lib\netstandard2.0\System.Reflection.Metadata.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Reflection.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"system.reflection.typeextensions\4.3.0\ref\netstandard1.5\System.Reflection.TypeExtensions.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Resources.Reader.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Resources.ResourceManager.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Resources.Writer.dll" + sprintf "-r:%s%s" nugetCache @"system.runtime.compilerservices.unsafe\6.0.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.CompilerServices.VisualC.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Extensions.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Handles.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.InteropServices.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.InteropServices.RuntimeInformation.dll" + sprintf "-r:%s%s" nugetCache @"system.runtime.loader\4.3.0\ref\netstandard1.5\System.Runtime.Loader.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Numerics.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Formatters.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Json.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Xml.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Claims.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Algorithms.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Csp.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Encoding.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Primitives.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.X509Certificates.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Principal.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.SecureString.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ServiceModel.Web.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Text.Encoding.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Text.Encoding.Extensions.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Text.RegularExpressions.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Overlapped.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Tasks.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Tasks.Parallel.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Thread.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.ThreadPool.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Timer.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Transactions.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ValueTuple.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Web.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Windows.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.Linq.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.ReaderWriter.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.Serialization.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XDocument.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XmlDocument.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XmlSerializer.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XPath.dll" + sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XPath.XDocument.dll" + @"--target:library" + @"--nowarn:FS2003,NU5105" + @"--warn:3" + @"--warnaserror:3239,1182,0025" + @"--fullpaths" + @"--flaterrors" + @"--highentropyva+" + @"--targetprofile:netstandard" + @"--nocopyfsharpcore" + @"--deterministic+" + @"--simpleresolution" + @"--nowarn:3384" + @"--warnon:1182" + @"--simpleresolution" |] + ReferencedProjects = [| FSharpCore |] + IsIncompleteTypeCheckEnvironment = false + UseScriptResolutionRules = false + LoadTime = DateTime.Now + UnresolvedReferences = None + OriginalLoadReferences = [] + Stamp = None } + + FSharpReferencedProject.CreateFSharp( + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\bin\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.dll", + projectOptions + ) + + let FSharpCompilerService = + { ProjectFileName = __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\FSharp.Compiler.Service.fsproj" + ProjectId = None + SourceFiles = + [| __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSComp.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSIstrings.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\UtilsStrings.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.InternalsVisibleTo.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.AssemblyInfo.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\sformat.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\sformat.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\sr.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\sr.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\ResizeArray.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\ResizeArray.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\HashMultiMap.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\HashMultiMap.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\EditDistance.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\EditDistance.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\TaggedCollections.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\TaggedCollections.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\illib.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\illib.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\FileSystem.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\FileSystem.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\ildiag.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\ildiag.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\zmap.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\zmap.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\zset.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\zset.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\XmlAdapters.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\XmlAdapters.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\InternalCollections.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\InternalCollections.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\QueueList.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\QueueList.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\lib.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\lib.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\ImmutableArray.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\ImmutableArray.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\rational.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\rational.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\PathMap.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\PathMap.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\RidHelpers.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\range.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Utilities\range.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\Logger.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\Logger.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\LanguageFeatures.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\LanguageFeatures.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\Diagnostics.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\Diagnostics.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\TextLayoutRender.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\TextLayoutRender.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\DiagnosticsLogger.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\DiagnosticsLogger.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\ErrorResolutionHints.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\ErrorResolutionHints.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\prim-lexing.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\prim-lexing.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\prim-parsing.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\prim-parsing.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\ReferenceResolver.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\ReferenceResolver.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\SimulatedMSBuildReferenceResolver.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\SimulatedMSBuildReferenceResolver.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\CompilerLocation.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Facilities\CompilerLocation.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\il.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\il.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilx.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilx.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilascii.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilascii.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\ilpars.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\illex.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilprint.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilprint.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilmorph.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilmorph.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilsign.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilsign.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilnativeres.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilnativeres.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilsupp.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilsupp.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilbinary.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilbinary.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilread.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilread.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilwritepdb.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilwritepdb.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilwrite.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilwrite.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilreflect.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\AbstractIL\ilreflect.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\PrettyNaming.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\PrettyNaming.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\CodeGen\EraseClosures.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\CodeGen\EraseClosures.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\UnicodeLexing.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\UnicodeLexing.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\XmlDoc.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\XmlDoc.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\SyntaxTrivia.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\SyntaxTrivia.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\SyntaxTree.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\SyntaxTree.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\SyntaxTreeOps.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\SyntaxTreeOps.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\ParseHelpers.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\ParseHelpers.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\pppars.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\pars.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\LexHelpers.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\LexHelpers.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\pplex.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\lex.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\LexFilter.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\SyntaxTree\LexFilter.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\tainted.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\tainted.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypeProviders.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypeProviders.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\QuotationPickler.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\QuotationPickler.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\CompilerGlobalState.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\CompilerGlobalState.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypedTree.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypedTreeBasics.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypedTreeBasics.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TcGlobals.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypedTreeOps.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypedTreeOps.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypedTreePickle.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\TypedTree\TypedTreePickle.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\import.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\import.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\TypeHierarchy.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\TypeHierarchy.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\infos.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\infos.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\AccessibilityLogic.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\AccessibilityLogic.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\AttributeChecking.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\AttributeChecking.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\TypeRelations.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\TypeRelations.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\InfoReader.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\InfoReader.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\NicePrint.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\NicePrint.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\AugmentWithHashCompare.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\AugmentWithHashCompare.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\NameResolution.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\NameResolution.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\SignatureConformance.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\SignatureConformance.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\MethodOverrides.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\MethodOverrides.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\MethodCalls.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\MethodCalls.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\PatternMatchCompilation.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\PatternMatchCompilation.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\ConstraintSolver.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\ConstraintSolver.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckFormatStrings.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckFormatStrings.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\FindUnsolved.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\FindUnsolved.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\QuotationTranslator.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\QuotationTranslator.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\PostInferenceChecks.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\PostInferenceChecks.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckExpressions.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckExpressions.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckComputationExpressions.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckComputationExpressions.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckDeclarations.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Checking\CheckDeclarations.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\Optimizer.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\Optimizer.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\DetupleArgs.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\DetupleArgs.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\InnerLambdasToTopLevelFuncs.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\InnerLambdasToTopLevelFuncs.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerCalls.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerCalls.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerSequences.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerSequences.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerComputedCollections.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerComputedCollections.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerStateMachines.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerStateMachines.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerLocalMutables.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Optimize\LowerLocalMutables.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\CodeGen\EraseUnions.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\CodeGen\EraseUnions.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\CodeGen\IlxGen.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\CodeGen\IlxGen.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\FxResolver.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\DependencyManager\AssemblyResolveHandler.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\DependencyManager\AssemblyResolveHandler.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\DependencyManager\NativeDllResolveHandler.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\DependencyManager\NativeDllResolveHandler.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\DependencyManager\DependencyProvider.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\DependencyManager\DependencyProvider.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\BuildGraph.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\BuildGraph.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerConfig.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerConfig.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerImports.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerImports.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerDiagnostics.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerDiagnostics.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\ParseAndCheckInputs.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\ParseAndCheckInputs.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\ScriptClosure.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\ScriptClosure.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerOptions.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CompilerOptions.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\OptimizeInputs.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\OptimizeInputs.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\XmlDocFileWriter.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\XmlDocFileWriter.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\BinaryResourceFormats.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\BinaryResourceFormats.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\StaticLinking.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\StaticLinking.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CreateILModule.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\CreateILModule.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\fsc.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Driver\fsc.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\FSharpDiagnostic.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\FSharpDiagnostic.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\SymbolHelpers.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\SymbolHelpers.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\Symbols.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\Symbols.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\Exprs.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\Exprs.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\SymbolPatterns.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Symbols\SymbolPatterns.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\SemanticClassification.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\SemanticClassification.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ItemKey.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ItemKey.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\SemanticClassificationKey.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\SemanticClassificationKey.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\FSharpSource.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\FSharpSource.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\IncrementalBuild.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\IncrementalBuild.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceCompilerDiagnostics.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceCompilerDiagnostics.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceConstants.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceDeclarationLists.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceDeclarationLists.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceLexing.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceLexing.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceParseTreeWalk.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceParseTreeWalk.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceNavigation.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceNavigation.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceParamInfoLocations.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceParamInfoLocations.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\FSharpParseFileResults.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\FSharpParseFileResults.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceParsedInputOps.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceParsedInputOps.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceAssemblyContent.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceAssemblyContent.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceXmlDocParser.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceXmlDocParser.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ExternalSymbol.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ExternalSymbol.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\QuickParse.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\QuickParse.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\FSharpCheckerResults.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\FSharpCheckerResults.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\service.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\service.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceInterfaceStubGenerator.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceInterfaceStubGenerator.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceStructure.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceStructure.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceAnalysis.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Service\ServiceAnalysis.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Interactive\fsi.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Interactive\fsi.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Legacy\LegacyMSBuildReferenceResolver.fsi" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Legacy\LegacyMSBuildReferenceResolver.fs" + __SOURCE_DIRECTORY__ + @"\..\..\..\..\src\Compiler\Legacy\LegacyHostedCompilerForTesting.fs" |] + OtherOptions = + [| sprintf "-o:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.dll" + @"-g" + @"--debug:embedded" + @"--noframework" + @"--define:TRACE" + @"--define:COMPILER" + @"--define:ENABLE_MONO_SUPPORT" + @"--define:DEBUG" + @"--define:ENABLE_MONO_SUPPORT" + @"--define:NETFRAMEWORK" + @"--define:NET472" + @"--define:NET20_OR_GREATER" + @"--define:NET30_OR_GREATER" + @"--define:NET35_OR_GREATER" + @"--define:NET40_OR_GREATER" + @"--define:NET45_OR_GREATER" + @"--define:NET451_OR_GREATER" + @"--define:NET452_OR_GREATER" + @"--define:NET46_OR_GREATER" + @"--define:NET461_OR_GREATER" + @"--define:NET462_OR_GREATER" + @"--define:NET47_OR_GREATER" + @"--define:NET471_OR_GREATER" + @"--define:NET472_OR_GREATER" + sprintf "-doc:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.xml" + @"--publicsign+" + @"--optimize-" + sprintf "-r:%s%s" nugetCache @"fsharp.core\6.0.1\lib\netstandard2.0\FSharp.Core.dll" + sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\..\artifacts\bin\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.dll" + sprintf "-r:%s%s" nugetCache @"microsoft.build.framework\17.0.0\lib\net472\Microsoft.Build.Framework.dll" + sprintf "-r:%s%s" nugetCache @"microsoft.build.tasks.core\17.0.0\lib\net472\Microsoft.Build.Tasks.Core.dll" + sprintf "-r:%s%s" nugetCache @"microsoft.build.utilities.core\17.0.0\lib\net472\Microsoft.Build.Utilities.Core.dll" + sprintf "-r:%s%s" nugetCache @"microsoft.net.stringtools\1.0.0\lib\net472\Microsoft.NET.StringTools.dll" + sprintf "-r:%s%s" nugetCache @"microsoft.visualstudio.setup.configuration.interop\1.16.30\lib\net35\Microsoft.VisualStudio.Setup.Configuration.Interop.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\mscorlib.dll" + sprintf "-r:%s%s" nugetCache @"system.buffers\4.5.1\ref\net45\System.Buffers.dll" + sprintf "-r:%s%s" nugetCache @"system.collections.immutable\5.0.0\lib\net461\System.Collections.Immutable.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.ComponentModel.Composition.dll" + sprintf "-r:%s%s" nugetCache @"system.configuration.configurationmanager\4.7.0\ref\net461\System.Configuration.ConfigurationManager.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Configuration.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Core.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Data.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Data.OracleClient.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Diagnostics.Process.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Diagnostics.TraceSource.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Drawing.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.IO.Compression.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.IO.Compression.FileSystem.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.IO.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Linq.Expressions.dll" + sprintf "-r:%s%s" nugetCache @"system.memory\4.5.4\lib\net461\System.Memory.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Net.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Net.Http.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Net.Security.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Numerics.dll" + sprintf "-r:%s%s" nugetCache @"system.numerics.vectors\4.5.0\ref\net46\System.Numerics.Vectors.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Reflection.dll" + sprintf "-r:%s%s" nugetCache @"system.reflection.metadata\5.0.0\lib\net461\System.Reflection.Metadata.dll" + sprintf "-r:%s%s" nugetCache @"system.reflection.typeextensions\4.3.0\ref\net462\System.Reflection.TypeExtensions.dll" + sprintf "-r:%s%s" nugetCache @"system.resources.extensions\4.6.0\ref\netstandard2.0\System.Resources.Extensions.dll" + sprintf "-r:%s%s" nugetCache @"system.runtime.compilerservices.unsafe\6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Runtime.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Runtime.InteropServices.dll" + sprintf "-r:%s%s" nugetCache @"system.runtime.loader\4.3.0\ref\netstandard1.5\System.Runtime.Loader.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Runtime.Serialization.dll" + sprintf "-r:%s%s" nugetCache @"system.security.accesscontrol\4.7.0\ref\net461\System.Security.AccessControl.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Claims.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.Algorithms.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.Encoding.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.Primitives.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.X509Certificates.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Security.dll" + sprintf "-r:%s%s" nugetCache @"system.security.permissions\4.7.0\ref\net461\System.Security.Permissions.dll" + sprintf "-r:%s%s" nugetCache @"system.security.principal.windows\4.7.0\ref\net461\System.Security.Principal.Windows.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.ServiceProcess.dll" + sprintf "-r:%s%s" nugetCache @"system.threading.tasks.dataflow\4.9.0\lib\netstandard2.0\System.Threading.Tasks.Dataflow.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Threading.Thread.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Threading.ThreadPool.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Transactions.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Windows.Forms.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Xaml.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Xml.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Xml.Linq.dll" + @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\WindowsBase.dll" + @"--target:library" + @"--nowarn:FS2003,44,57,75,1204,NU5125,NU5105" + @"--warn:3" + @"--warnaserror:3239,1182,0025" + @"--fullpaths" + @"--flaterrors" + @"--subsystemversion:6.00" + @"--highentropyva+" + @"--targetprofile:mscorlib" + @"--nocopyfsharpcore" + @"--deterministic+" + @"--simpleresolution" + @"--nowarn:3384" + @"--extraoptimizationloops:1" + @"--times" + @"--warnon:1182" + @"--warnon:3218" + @"--warnon:3390" |] + ReferencedProjects = + [| FSharpDependencyManagerNuget + FSharpCore |] + IsIncompleteTypeCheckEnvironment = false + UseScriptResolutionRules = false + LoadTime = DateTime.Now + UnresolvedReferences = None + OriginalLoadReferences = [] + Stamp = None } + +[] +type CompilerService() = + let mutable checkerOpt = None + let mutable sourceOpt : (string * ISourceText) array option = None + + let projectOptions = Project.FSharpCompilerService + + [] + member _.Setup() = + match checkerOpt with + | None -> checkerOpt <- Some(FSharpChecker.Create(projectCacheSize = 200)) + | _ -> () + + match sourceOpt with + | None -> + sourceOpt <- + projectOptions.SourceFiles + |> Array.filter (fun filePath -> filePath.EndsWith("CheckDeclarations.fs")) // || filePath.EndsWith("CheckExpressions.fs")) + // || filePath.EndsWith("lex.fs") || filePath.EndsWith("pars.fs")) + |> Array.map (fun filePath -> filePath, SourceText.ofString (File.ReadAllText(filePath))) + |> Some + | _ -> () + + [] + member _.ParseAndCheckFileInProject() = + match checkerOpt, sourceOpt with + | None, _ -> failwith "no checker" + | _, None -> failwith "no source" + | Some checker, Some sourceFiles -> + checker.InvalidateAll() + sourceFiles + |> Array.iter (fun (filePath, sourceText) -> + let _fileResult, _checkResult = + checker.ParseAndCheckFileInProject(filePath, 0, sourceText, projectOptions) + |> Async.RunSynchronously + + () + ) + +[] +let main _ = + BenchmarkRunner.Run() |> ignore + 0 diff --git a/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/README.md b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/README.md new file mode 100644 index 00000000000..534e2762961 --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/README.md @@ -0,0 +1,20 @@ +# FCSSourceFiles + +## What is it + +* A BDN-based benchmark +* Tests `FSharpChecker.ParseAndCheckFileInProject` on the `FSharp.Core` project. +* Uses locally available source code for both the code being type-checked (`FSharp.Core`) and the code being benchmarked (`FCS`). + +## How to run it + +1. Run `dotnet run -c release` +2. Output available on the commandline and in `BenchmarkDotNet.Artifacts/` + +## Sample results + +*TODO* + +## Other + +You can find this document under 'tests/benchmarks/FCSBenchmarks/FCSSourceFiles/README.md'. \ No newline at end of file diff --git a/tests/benchmarks/FCSBenchmarks/README.md b/tests/benchmarks/FCSBenchmarks/README.md new file mode 100644 index 00000000000..700e12fb890 --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/README.md @@ -0,0 +1,22 @@ +# FCSBenchmarks + +## What can be found here + +Benchmarks that exercise performance of `FSharp.Compiler.Service` + +## Testing performance of FSharp.Compiler.Service +Performance of the compiler service is crucial for having good developer experience. +This includes compilation, type checking and any other parts of the API used by IDEs. + +When making changes to the FCS source code, consider running some of these to assess impact of the changes on performance. + +## Benchmark list +* `BenchmarkComparison/` - a Notebook-based benchmark that analyses performance of `FSharpChecker.ParseAndCheckFileInProject` on a single-file F# project. Supports comparing different revisions of the FCS codebase and fetching the code automatically. +* `CompilerServiceBenchmarks/` - +* `FCSSourceFiles/` - analyses performance of `FSharpChecker.ParseAndCheckFileInProject` for the `FSharp.Core` project. Uses locally available source code. + +All the above benchmarks use BenchmarkDotNet. + +## Other + +You can find this document under 'tests/benchmarks/FCSBenchmarks/README.md'. \ No newline at end of file diff --git a/tests/benchmarks/FCSSourceFiles/Program.fs b/tests/benchmarks/FCSSourceFiles/Program.fs deleted file mode 100644 index a4d90bc2df7..00000000000 --- a/tests/benchmarks/FCSSourceFiles/Program.fs +++ /dev/null @@ -1,934 +0,0 @@ -open System -open System.Diagnostics -open System.IO -open FSharp.Compiler.CodeAnalysis -open FSharp.Compiler.Text -open BenchmarkDotNet.Attributes -open BenchmarkDotNet.Running - -module Project = - let nugetCache = - let ps = ProcessStartInfo("dotnet", "nuget locals global-packages -l") - ps.RedirectStandardOutput <- true - ps.RedirectStandardError <- true - let p = Process.Start ps - let stdout = p.StandardOutput.ReadToEnd().Trim() - p.WaitForExit() - stdout.Replace("global-packages:", "").Trim() - - let FSharpCore = - let projectOptions = - { ProjectFileName = __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\FSharp.Core.fsproj" - ProjectId = None - SourceFiles = - [| __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\prim-types-prelude.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\prim-types-prelude.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSCore.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSharp.Core.AssemblyInfo.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\prim-types.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\prim-types.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\local.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\local.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\array2.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\array2.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\option.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\option.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\result.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\result.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\collections.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\collections.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\seqcore.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\seqcore.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\seq.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\seq.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\string.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\string.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\list.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\list.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\array.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\array.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\array3.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\array3.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\map.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\map.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\set.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\set.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\reflect.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\reflect.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\math\z.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\math\z.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\sformat.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\sformat.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\printf.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\printf.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\quotations.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\quotations.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\nativeptr.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\nativeptr.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\event.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\event.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\resumable.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\resumable.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\async.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\async.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\tasks.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\tasks.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\eventmodule.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\eventmodule.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\observable.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\observable.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\mailbox.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\mailbox.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\Nullable.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\Nullable.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\Linq.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\Linq.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\MutableTuple.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\QueryExtensions.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\Query.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\Query.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\SI.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\fslib-extra-pervasives.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.Core\fslib-extra-pervasives.fs" |] - OtherOptions = - [| sprintf "-o:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSharp.Core.dll" - @"-g" - @"--debug:embedded" - @"--langversion:preview" - @"--noframework" - @"--define:TRACE" - @"--define:FSHARP_CORE" - @"--define:DEBUG" - @"--define:NETSTANDARD" - @"--define:FX_NO_APP_DOMAINS" - @"--define:FX_NO_CORHOST_SIGNER" - @"--define:FX_NO_PDB_READER" - @"--define:FX_NO_PDB_WRITER" - @"--define:FX_NO_SYMBOLSTORE" - @"--define:FX_NO_SYSTEM_CONFIGURATION" - @"--define:FX_NO_WIN_REGISTRY" - @"--define:FX_NO_WINFORMS" - @"--define:FX_RESHAPED_REFEMIT" - @"--define:NETSTANDARD" - @"--define:NETSTANDARD2_1" - @"--define:NETSTANDARD1_0_OR_GREATER" - @"--define:NETSTANDARD1_1_OR_GREATER" - @"--define:NETSTANDARD1_2_OR_GREATER" - @"--define:NETSTANDARD1_3_OR_GREATER" - @"--define:NETSTANDARD1_4_OR_GREATER" - @"--define:NETSTANDARD1_5_OR_GREATER" - @"--define:NETSTANDARD1_6_OR_GREATER" - @"--define:NETSTANDARD2_0_OR_GREATER" - @"--define:NETSTANDARD2_1_OR_GREATER" - sprintf "-doc:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\artifacts\obj\FSharp.Core\Debug\netstandard2.1\FSharp.Core.xml" - @"--publicsign+" - @"--optimize-" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\Microsoft.Win32.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\mscorlib.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\netstandard.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.AppContext.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Buffers.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.Concurrent.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.NonGeneric.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Collections.Specialized.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.Composition.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.EventBasedAsync.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ComponentModel.TypeConverter.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Console.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Core.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Data.Common.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Data.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Contracts.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Debug.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.FileVersionInfo.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Process.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.StackTrace.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.TextWriterTraceListener.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Tools.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.TraceSource.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Diagnostics.Tracing.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Drawing.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Drawing.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Dynamic.Runtime.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Globalization.Calendars.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Globalization.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Globalization.Extensions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Compression.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Compression.FileSystem.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Compression.ZipFile.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.DriveInfo.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.FileSystem.Watcher.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.IsolatedStorage.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.MemoryMappedFiles.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.Pipes.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.IO.UnmanagedMemoryStream.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.Expressions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.Parallel.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Linq.Queryable.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Memory.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Http.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.NameResolution.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.NetworkInformation.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Ping.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Requests.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Security.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.Sockets.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.WebHeaderCollection.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.WebSockets.Client.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Net.WebSockets.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Numerics.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Numerics.Vectors.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ObjectModel.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.DispatchProxy.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Emit.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Emit.ILGeneration.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Emit.Lightweight.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Extensions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Reflection.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Resources.Reader.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Resources.ResourceManager.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Resources.Writer.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.CompilerServices.VisualC.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Extensions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Handles.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.InteropServices.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.InteropServices.RuntimeInformation.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Numerics.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Formatters.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Json.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Runtime.Serialization.Xml.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Claims.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Algorithms.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Csp.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Encoding.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.Primitives.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Cryptography.X509Certificates.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.Principal.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Security.SecureString.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ServiceModel.Web.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Text.Encoding.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Text.Encoding.Extensions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Text.RegularExpressions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Overlapped.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Tasks.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Tasks.Extensions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Tasks.Parallel.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Thread.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.ThreadPool.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Threading.Timer.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Transactions.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.ValueTuple.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Web.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Windows.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.Linq.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.ReaderWriter.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.Serialization.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XDocument.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XmlDocument.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XmlSerializer.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XPath.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\.dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\System.Xml.XPath.XDocument.dll" - @"--target:library" - @"--nowarn:FS2003,62,75,1204,NU5105" - @"--warn:3" - @"--warnaserror:3239,1182,0025" - @"--fullpaths" - @"--flaterrors" - @"--highentropyva+" - @"--targetprofile:netstandard" - @"--nocopyfsharpcore" - @"--deterministic+" - @"--simpleresolution" - @"--nowarn:3384" - @"--warnon:3218" - @"--warnon:1182" - @"--warnon:3390" - @"--warnon:3520" - @"--warnon:1182" - @"--warnon:3390" - @"--nowarn:57" - @"--nowarn:3511" - @"--nowarn:3513" - @"--compiling-fslib" - @"--compiling-fslib-40" - @"--maxerrors:100" - @"--extraoptimizationloops:1" - @"--simpleresolution" |] - ReferencedProjects = [||] - IsIncompleteTypeCheckEnvironment = false - UseScriptResolutionRules = false - LoadTime = DateTime.Now - UnresolvedReferences = None - OriginalLoadReferences = [] - Stamp = None } - - FSharpReferencedProject.CreateFSharp( - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\bin\FSharp.Core\Debug\netstandard2.1\FSharp.Core.dll", - projectOptions - ) - - let FSharpDependencyManagerNuget = - let projectOptions = - { ProjectFileName = __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.Nuget.fsproj" - ProjectId = None - SourceFiles = - [| __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSDependencyManager.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\UtilsStrings.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.InternalsVisibleTo.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.AssemblyInfo.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\CompilerLocation.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\CompilerLocation.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.ProjectFile.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.Utilities.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.fs" |] - OtherOptions = - [| sprintf "-o:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.dll" - @"-g" - @"--debug:embedded" - @"--noframework" - @"--define:TRACE" - @"--define:COMPILER" - @"--define:DEBUG" - @"--define:NETSTANDARD" - @"--define:FX_NO_APP_DOMAINS" - @"--define:FX_NO_CORHOST_SIGNER" - @"--define:FX_NO_PDB_READER" - @"--define:FX_NO_PDB_WRITER" - @"--define:FX_NO_SYMBOLSTORE" - @"--define:FX_NO_SYSTEM_CONFIGURATION" - @"--define:FX_NO_WIN_REGISTRY" - @"--define:FX_NO_WINFORMS" - @"--define:FX_RESHAPED_REFEMIT" - @"--define:NETSTANDARD" - @"--define:NETSTANDARD2_0" - @"--define:NETSTANDARD1_0_OR_GREATER" - @"--define:NETSTANDARD1_1_OR_GREATER" - @"--define:NETSTANDARD1_2_OR_GREATER" - @"--define:NETSTANDARD1_3_OR_GREATER" - @"--define:NETSTANDARD1_4_OR_GREATER" - @"--define:NETSTANDARD1_5_OR_GREATER" - @"--define:NETSTANDARD1_6_OR_GREATER" - @"--define:NETSTANDARD2_0_OR_GREATER" - sprintf "-doc:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\artifacts\obj\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.xml" - @"--publicsign+" - @"--optimize-" - sprintf "-r:%s%s" nugetCache @"fsharp.core\6.0.1\lib\netstandard2.0\FSharp.Core.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\Microsoft.Win32.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\mscorlib.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\netstandard.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.AppContext.dll" - sprintf "-r:%s%s" nugetCache @"system.buffers\4.5.1\ref\netstandard2.0\System.Buffers.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.Concurrent.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.dll" - sprintf "-r:%s%s" nugetCache @"system.collections.immutable\5.0.0\lib\netstandard2.0\System.Collections.Immutable.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.NonGeneric.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.Specialized.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.Composition.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.EventBasedAsync.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ComponentModel.TypeConverter.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Console.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Core.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Data.Common.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Data.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Contracts.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Debug.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.FileVersionInfo.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Process.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.StackTrace.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.TextWriterTraceListener.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Tools.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.TraceSource.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Diagnostics.Tracing.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Drawing.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Drawing.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Dynamic.Runtime.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Globalization.Calendars.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Globalization.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Globalization.Extensions.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Compression.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Compression.FileSystem.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Compression.ZipFile.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.DriveInfo.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.FileSystem.Watcher.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.IsolatedStorage.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.MemoryMappedFiles.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.Pipes.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.IO.UnmanagedMemoryStream.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.Expressions.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.Parallel.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Linq.Queryable.dll" - sprintf "-r:%s%s" nugetCache @"system.memory\4.5.4\lib\netstandard2.0\System.Memory.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Http.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.NameResolution.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.NetworkInformation.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Ping.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Requests.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Security.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.Sockets.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.WebHeaderCollection.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.WebSockets.Client.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Net.WebSockets.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Numerics.dll" - sprintf "-r:%s%s" nugetCache @"system.numerics.vectors\4.4.0\ref\netstandard2.0\System.Numerics.Vectors.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ObjectModel.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Reflection.dll" - sprintf "-r:%s%s" nugetCache @"system.reflection.emit\4.3.0\ref\netstandard1.1\System.Reflection.Emit.dll" - sprintf "-r:%s%s" nugetCache @"system.reflection.emit.ilgeneration\4.3.0\ref\netstandard1.0\System.Reflection.Emit.ILGeneration.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Reflection.Extensions.dll" - sprintf "-r:%s%s" nugetCache @"system.reflection.metadata\5.0.0\lib\netstandard2.0\System.Reflection.Metadata.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Reflection.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"system.reflection.typeextensions\4.3.0\ref\netstandard1.5\System.Reflection.TypeExtensions.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Resources.Reader.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Resources.ResourceManager.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Resources.Writer.dll" - sprintf "-r:%s%s" nugetCache @"system.runtime.compilerservices.unsafe\6.0.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.CompilerServices.VisualC.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Extensions.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Handles.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.InteropServices.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.InteropServices.RuntimeInformation.dll" - sprintf "-r:%s%s" nugetCache @"system.runtime.loader\4.3.0\ref\netstandard1.5\System.Runtime.Loader.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Numerics.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Formatters.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Json.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Runtime.Serialization.Xml.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Claims.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Algorithms.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Csp.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Encoding.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.Primitives.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Cryptography.X509Certificates.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.Principal.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Security.SecureString.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ServiceModel.Web.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Text.Encoding.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Text.Encoding.Extensions.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Text.RegularExpressions.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Overlapped.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Tasks.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Tasks.Parallel.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Thread.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.ThreadPool.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Threading.Timer.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Transactions.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.ValueTuple.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Web.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Windows.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.Linq.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.ReaderWriter.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.Serialization.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XDocument.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XmlDocument.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XmlSerializer.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XPath.dll" - sprintf "-r:%s%s" nugetCache @"netstandard.library\2.0.3\build\netstandard2.0\ref\System.Xml.XPath.XDocument.dll" - @"--target:library" - @"--nowarn:FS2003,NU5105" - @"--warn:3" - @"--warnaserror:3239,1182,0025" - @"--fullpaths" - @"--flaterrors" - @"--highentropyva+" - @"--targetprofile:netstandard" - @"--nocopyfsharpcore" - @"--deterministic+" - @"--simpleresolution" - @"--nowarn:3384" - @"--warnon:1182" - @"--simpleresolution" |] - ReferencedProjects = [| FSharpCore |] - IsIncompleteTypeCheckEnvironment = false - UseScriptResolutionRules = false - LoadTime = DateTime.Now - UnresolvedReferences = None - OriginalLoadReferences = [] - Stamp = None } - - FSharpReferencedProject.CreateFSharp( - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\bin\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.dll", - projectOptions - ) - - let FSharpCompilerService = - { ProjectFileName = __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\FSharp.Compiler.Service.fsproj" - ProjectId = None - SourceFiles = - [| __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSComp.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSIstrings.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\UtilsStrings.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.InternalsVisibleTo.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.AssemblyInfo.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\sformat.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\sformat.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\sr.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\sr.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\ResizeArray.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\ResizeArray.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\HashMultiMap.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\HashMultiMap.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\EditDistance.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\EditDistance.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\TaggedCollections.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\TaggedCollections.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\illib.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\illib.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\FileSystem.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\FileSystem.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\ildiag.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\ildiag.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\zmap.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\zmap.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\zset.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\zset.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\XmlAdapters.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\XmlAdapters.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\InternalCollections.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\InternalCollections.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\QueueList.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\QueueList.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\lib.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\lib.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\ImmutableArray.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\ImmutableArray.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\rational.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\rational.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\PathMap.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\PathMap.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\RidHelpers.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\range.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Utilities\range.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\Logger.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\Logger.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\LanguageFeatures.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\LanguageFeatures.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\Diagnostics.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\Diagnostics.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\TextLayoutRender.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\TextLayoutRender.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\DiagnosticsLogger.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\DiagnosticsLogger.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\ErrorResolutionHints.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\ErrorResolutionHints.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\prim-lexing.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\prim-lexing.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\prim-parsing.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\prim-parsing.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\ReferenceResolver.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\ReferenceResolver.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\SimulatedMSBuildReferenceResolver.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\SimulatedMSBuildReferenceResolver.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\CompilerLocation.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Facilities\CompilerLocation.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\il.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\il.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilx.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilx.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilascii.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilascii.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\ilpars.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\illex.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilprint.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilprint.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilmorph.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilmorph.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilsign.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilsign.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilnativeres.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilnativeres.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilsupp.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilsupp.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilbinary.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilbinary.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilread.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilread.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilwritepdb.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilwritepdb.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilwrite.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilwrite.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilreflect.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\AbstractIL\ilreflect.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\PrettyNaming.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\PrettyNaming.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\CodeGen\EraseClosures.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\CodeGen\EraseClosures.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\UnicodeLexing.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\UnicodeLexing.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\XmlDoc.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\XmlDoc.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\SyntaxTrivia.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\SyntaxTrivia.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\SyntaxTree.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\SyntaxTree.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\SyntaxTreeOps.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\SyntaxTreeOps.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\ParseHelpers.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\ParseHelpers.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\pppars.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\pars.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\LexHelpers.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\LexHelpers.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\pplex.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\lex.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\LexFilter.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\SyntaxTree\LexFilter.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\tainted.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\tainted.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypeProviders.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypeProviders.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\QuotationPickler.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\QuotationPickler.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\CompilerGlobalState.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\CompilerGlobalState.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypedTree.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypedTreeBasics.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypedTreeBasics.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TcGlobals.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypedTreeOps.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypedTreeOps.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypedTreePickle.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\TypedTree\TypedTreePickle.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\import.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\import.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\TypeHierarchy.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\TypeHierarchy.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\infos.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\infos.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\AccessibilityLogic.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\AccessibilityLogic.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\AttributeChecking.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\AttributeChecking.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\TypeRelations.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\TypeRelations.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\InfoReader.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\InfoReader.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\NicePrint.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\NicePrint.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\AugmentWithHashCompare.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\AugmentWithHashCompare.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\NameResolution.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\NameResolution.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\SignatureConformance.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\SignatureConformance.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\MethodOverrides.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\MethodOverrides.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\MethodCalls.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\MethodCalls.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\PatternMatchCompilation.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\PatternMatchCompilation.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\ConstraintSolver.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\ConstraintSolver.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckFormatStrings.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckFormatStrings.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\FindUnsolved.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\FindUnsolved.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\QuotationTranslator.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\QuotationTranslator.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\PostInferenceChecks.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\PostInferenceChecks.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckExpressions.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckExpressions.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckComputationExpressions.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckComputationExpressions.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckDeclarations.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Checking\CheckDeclarations.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\Optimizer.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\Optimizer.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\DetupleArgs.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\DetupleArgs.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\InnerLambdasToTopLevelFuncs.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\InnerLambdasToTopLevelFuncs.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerCalls.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerCalls.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerSequences.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerSequences.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerComputedCollections.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerComputedCollections.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerStateMachines.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerStateMachines.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerLocalMutables.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Optimize\LowerLocalMutables.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\CodeGen\EraseUnions.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\CodeGen\EraseUnions.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\CodeGen\IlxGen.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\CodeGen\IlxGen.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\FxResolver.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\DependencyManager\AssemblyResolveHandler.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\DependencyManager\AssemblyResolveHandler.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\DependencyManager\NativeDllResolveHandler.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\DependencyManager\NativeDllResolveHandler.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\DependencyManager\DependencyProvider.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\DependencyManager\DependencyProvider.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\BuildGraph.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\BuildGraph.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerConfig.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerConfig.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerImports.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerImports.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerDiagnostics.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerDiagnostics.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\ParseAndCheckInputs.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\ParseAndCheckInputs.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\ScriptClosure.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\ScriptClosure.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerOptions.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CompilerOptions.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\OptimizeInputs.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\OptimizeInputs.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\XmlDocFileWriter.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\XmlDocFileWriter.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\BinaryResourceFormats.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\BinaryResourceFormats.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\StaticLinking.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\StaticLinking.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CreateILModule.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\CreateILModule.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\fsc.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Driver\fsc.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\FSharpDiagnostic.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\FSharpDiagnostic.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\SymbolHelpers.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\SymbolHelpers.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\Symbols.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\Symbols.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\Exprs.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\Exprs.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\SymbolPatterns.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Symbols\SymbolPatterns.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\SemanticClassification.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\SemanticClassification.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ItemKey.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ItemKey.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\SemanticClassificationKey.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\SemanticClassificationKey.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\FSharpSource.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\FSharpSource.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\IncrementalBuild.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\IncrementalBuild.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceCompilerDiagnostics.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceCompilerDiagnostics.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceConstants.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceDeclarationLists.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceDeclarationLists.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceLexing.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceLexing.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceParseTreeWalk.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceParseTreeWalk.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceNavigation.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceNavigation.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceParamInfoLocations.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceParamInfoLocations.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\FSharpParseFileResults.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\FSharpParseFileResults.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceParsedInputOps.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceParsedInputOps.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceAssemblyContent.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceAssemblyContent.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceXmlDocParser.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceXmlDocParser.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ExternalSymbol.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ExternalSymbol.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\QuickParse.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\QuickParse.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\FSharpCheckerResults.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\FSharpCheckerResults.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\service.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\service.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceInterfaceStubGenerator.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceInterfaceStubGenerator.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceStructure.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceStructure.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceAnalysis.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Service\ServiceAnalysis.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Interactive\fsi.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Interactive\fsi.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Legacy\LegacyMSBuildReferenceResolver.fsi" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Legacy\LegacyMSBuildReferenceResolver.fs" - __SOURCE_DIRECTORY__ + @"\..\..\..\src\Compiler\Legacy\LegacyHostedCompilerForTesting.fs" |] - OtherOptions = - [| sprintf "-o:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.dll" - @"-g" - @"--debug:embedded" - @"--noframework" - @"--define:TRACE" - @"--define:COMPILER" - @"--define:ENABLE_MONO_SUPPORT" - @"--define:DEBUG" - @"--define:ENABLE_MONO_SUPPORT" - @"--define:NETFRAMEWORK" - @"--define:NET472" - @"--define:NET20_OR_GREATER" - @"--define:NET30_OR_GREATER" - @"--define:NET35_OR_GREATER" - @"--define:NET40_OR_GREATER" - @"--define:NET45_OR_GREATER" - @"--define:NET451_OR_GREATER" - @"--define:NET452_OR_GREATER" - @"--define:NET46_OR_GREATER" - @"--define:NET461_OR_GREATER" - @"--define:NET462_OR_GREATER" - @"--define:NET47_OR_GREATER" - @"--define:NET471_OR_GREATER" - @"--define:NET472_OR_GREATER" - sprintf "-doc:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\artifacts\obj\FSharp.Compiler.Service\Debug\net472\FSharp.Compiler.Service.xml" - @"--publicsign+" - @"--optimize-" - sprintf "-r:%s%s" nugetCache @"fsharp.core\6.0.1\lib\netstandard2.0\FSharp.Core.dll" - sprintf "-r:%s%s" __SOURCE_DIRECTORY__ @"\..\..\..\artifacts\bin\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.dll" - sprintf "-r:%s%s" nugetCache @"microsoft.build.framework\17.0.0\lib\net472\Microsoft.Build.Framework.dll" - sprintf "-r:%s%s" nugetCache @"microsoft.build.tasks.core\17.0.0\lib\net472\Microsoft.Build.Tasks.Core.dll" - sprintf "-r:%s%s" nugetCache @"microsoft.build.utilities.core\17.0.0\lib\net472\Microsoft.Build.Utilities.Core.dll" - sprintf "-r:%s%s" nugetCache @"microsoft.net.stringtools\1.0.0\lib\net472\Microsoft.NET.StringTools.dll" - sprintf "-r:%s%s" nugetCache @"microsoft.visualstudio.setup.configuration.interop\1.16.30\lib\net35\Microsoft.VisualStudio.Setup.Configuration.Interop.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\mscorlib.dll" - sprintf "-r:%s%s" nugetCache @"system.buffers\4.5.1\ref\net45\System.Buffers.dll" - sprintf "-r:%s%s" nugetCache @"system.collections.immutable\5.0.0\lib\net461\System.Collections.Immutable.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.ComponentModel.Composition.dll" - sprintf "-r:%s%s" nugetCache @"system.configuration.configurationmanager\4.7.0\ref\net461\System.Configuration.ConfigurationManager.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Configuration.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Core.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Data.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Data.OracleClient.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Diagnostics.Process.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Diagnostics.TraceSource.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Drawing.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.IO.Compression.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.IO.Compression.FileSystem.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.IO.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Linq.Expressions.dll" - sprintf "-r:%s%s" nugetCache @"system.memory\4.5.4\lib\net461\System.Memory.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Net.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Net.Http.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Net.Security.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Numerics.dll" - sprintf "-r:%s%s" nugetCache @"system.numerics.vectors\4.5.0\ref\net46\System.Numerics.Vectors.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Reflection.dll" - sprintf "-r:%s%s" nugetCache @"system.reflection.metadata\5.0.0\lib\net461\System.Reflection.Metadata.dll" - sprintf "-r:%s%s" nugetCache @"system.reflection.typeextensions\4.3.0\ref\net462\System.Reflection.TypeExtensions.dll" - sprintf "-r:%s%s" nugetCache @"system.resources.extensions\4.6.0\ref\netstandard2.0\System.Resources.Extensions.dll" - sprintf "-r:%s%s" nugetCache @"system.runtime.compilerservices.unsafe\6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Runtime.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Runtime.InteropServices.dll" - sprintf "-r:%s%s" nugetCache @"system.runtime.loader\4.3.0\ref\netstandard1.5\System.Runtime.Loader.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Runtime.Serialization.dll" - sprintf "-r:%s%s" nugetCache @"system.security.accesscontrol\4.7.0\ref\net461\System.Security.AccessControl.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Claims.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.Algorithms.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.Encoding.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.Primitives.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Security.Cryptography.X509Certificates.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Security.dll" - sprintf "-r:%s%s" nugetCache @"system.security.permissions\4.7.0\ref\net461\System.Security.Permissions.dll" - sprintf "-r:%s%s" nugetCache @"system.security.principal.windows\4.7.0\ref\net461\System.Security.Principal.Windows.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.ServiceProcess.dll" - sprintf "-r:%s%s" nugetCache @"system.threading.tasks.dataflow\4.9.0\lib\netstandard2.0\System.Threading.Tasks.Dataflow.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Threading.Thread.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Threading.ThreadPool.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Transactions.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Windows.Forms.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Xaml.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Xml.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Xml.Linq.dll" - @"-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\WindowsBase.dll" - @"--target:library" - @"--nowarn:FS2003,44,57,75,1204,NU5125,NU5105" - @"--warn:3" - @"--warnaserror:3239,1182,0025" - @"--fullpaths" - @"--flaterrors" - @"--subsystemversion:6.00" - @"--highentropyva+" - @"--targetprofile:mscorlib" - @"--nocopyfsharpcore" - @"--deterministic+" - @"--simpleresolution" - @"--nowarn:3384" - @"--extraoptimizationloops:1" - @"--times" - @"--warnon:1182" - @"--warnon:3218" - @"--warnon:3390" |] - ReferencedProjects = - [| FSharpDependencyManagerNuget - FSharpCore |] - IsIncompleteTypeCheckEnvironment = false - UseScriptResolutionRules = false - LoadTime = DateTime.Now - UnresolvedReferences = None - OriginalLoadReferences = [] - Stamp = None } - -[] -type CompilerService() = - let mutable checkerOpt = None - let mutable sourceOpt : (string * ISourceText) array option = None - - let projectOptions = Project.FSharpCompilerService - - [] - member _.Setup() = - match checkerOpt with - | None -> checkerOpt <- Some(FSharpChecker.Create(projectCacheSize = 200)) - | _ -> () - - match sourceOpt with - | None -> - sourceOpt <- - projectOptions.SourceFiles - |> Array.filter (fun filePath -> filePath.EndsWith("CheckDeclarations.fs")) // || filePath.EndsWith("CheckExpressions.fs")) - // || filePath.EndsWith("lex.fs") || filePath.EndsWith("pars.fs")) - |> Array.map (fun filePath -> filePath, SourceText.ofString (File.ReadAllText(filePath))) - |> Some - | _ -> () - - [] - member _.ParseAndCheckFileInProject() = - match checkerOpt, sourceOpt with - | None, _ -> failwith "no checker" - | _, None -> failwith "no source" - | Some checker, Some sourceFiles -> - checker.InvalidateAll() - sourceFiles - |> Array.iter (fun (filePath, sourceText) -> - let _fileResult, _checkResult = - checker.ParseAndCheckFileInProject(filePath, 0, sourceText, projectOptions) - |> Async.RunSynchronously - - () - ) - -[] -let main _ = - BenchmarkRunner.Run() |> ignore - 0 diff --git a/tests/benchmarks/README.md b/tests/benchmarks/README.md new file mode 100644 index 00000000000..c3500eb8bb5 --- /dev/null +++ b/tests/benchmarks/README.md @@ -0,0 +1,59 @@ +# Benchmarks + +## What can be found here + +This folder contains code and scripts used for running a selection of performance benchmarks. + +### How the tests are used + +The existing benchmarks are designed for on-demand local runs, to guide developers in performance improvement efforts and provide limited information during code change discussions. +Each of them assesses a slightly different use case and is run in a different way. + +Since there is currently no dedicated hardware setup for running benchmarks in a highly accurate fashion, the results obtained by running them locally have to be treated carefully. +Specifically results obtained on different hardware or in different environments should be treated differently. + +Note that there are plans to update the performance testing infrastructure. More information can be found at the following links: +* https://github.com/dotnet/fsharp/discussions/12526 +* https://github.com/dotnet/performance/issues/2457 + +### Types of performance tests + +Performance tests in this codebase can be broadly put into two groups: +1. tests that measure runtime performance of code produced from F# source code, +2. tests that measure performance of the compilation process itself. This involves any computations required by IDEs, for example type checking. + +Group 1. affects end users of programs, while group 2. affects developer experience. + +### Directory structure + +Tests are structured as follows +* `CompiledCodeBenchmarks/` - benchmarks that test compiled code performance. +* `FCSBenchmarks/` - benchmarks of the compiler service itself. + +### Jupyter notebooks + +Some benchmarks are written using F# Notebooks that use the .NET Interactive kernel. +Those can be identified by the `.ipynb` extension. +For instruction on how to run them see https://fsharp.org/use/notebooks/. + +### BenchmarkDotNet + +Most of the benchmarks use [BenchmarkDotNet](https://benchmarkdotnet.org/) (BDN), a popular benchmarking library for .NET. +It helps avoid common benchmarking pitfalls and provide highly-accurate, repeatable results. + +A BDN benchmark is an executable. To run it, simply run `dotnet run %BenchmarkProject.fsproj%` in the benchmark's directory. + +### Writing a new benchmark + +When adding a benchmark, consider: +* choosing an appropriate subdirectory +* adding a README with the following details: +* * what is being measured +* * how to run the benchmark, including any environment requirements +* * an example of the results it produces + +For instructions on how to write a BDN benchmark see [DEVGUIDE](https://github.com/dotnet/fsharp/blob/main/DEVGUIDE.md). + +## Other + +You can find this document under 'tests/benchmarks/README.md'. diff --git a/tests/fsharp/.gitignore b/tests/fsharp/.gitignore index 97071d47988..56279379484 100644 --- a/tests/fsharp/.gitignore +++ b/tests/fsharp/.gitignore @@ -15,4 +15,6 @@ Library1.dll cd.tmp *.err *.vserr -*.pdb \ No newline at end of file +*.pdb +*.stderr.txt +*.stdout.txt \ No newline at end of file diff --git a/tests/fsharp/Compiler/Language/ComparisonOptimizationTest.fs b/tests/fsharp/Compiler/Language/ComparisonOptimizationTest.fs new file mode 100644 index 00000000000..4fad1c2faef --- /dev/null +++ b/tests/fsharp/Compiler/Language/ComparisonOptimizationTest.fs @@ -0,0 +1,401 @@ +namespace FSharp.Compiler.UnitTests + +open System +open NUnit.Framework +open FSharp.Test + +[] +module ComparisonOptimizationTests = + + [] + let Script_Compare_int() = + let script = + """ +module Test +open System + + +let f (x: int) (y: int) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + [] + let Script_Compare_uint() = + let script = + """ +module Test +open System + + +let f (x: uint) (y: uint) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt.un + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt.un + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + [] + let Script_Compare_int64() = + let script = + """ +module Test +open System + + +let f (x: int64) (y: int64) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + [] + let Script_Compare_uint64() = + let script = + """ +module Test +open System + + +let f (x: uint64) (y: uint64) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt.un + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt.un + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + + [] + let Script_Compare_int16() = + let script = + """ +module Test +open System + + +let f (x: int16) (y: int16) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + [] + let Script_Compare_uint16() = + let script = + """ +module Test +open System + + +let f (x: uint16) (y: uint16) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt.un + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt.un + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + [] + let Script_Compare_byte() = + let script = + """ +module Test +open System + + +let f (x: byte) (y: byte) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt.un + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt.un + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + + [] + let Script_Compare_sbyte() = + let script = + """ +module Test +open System + + +let f (x: sbyte) (y: sbyte) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + + [] + let Script_Compare_char() = + let script = + """ +module Test +open System + + +let f (x: char) (y: char) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: cgt + IL_0004: ldarg.0 + IL_0005: ldarg.1 + IL_0006: clt + IL_0008: sub + IL_0009: ret + """ + ] + ) + ) + + [] + let Script_Compare_bool() = + let script = + """ +module Test +open System + + +let f (x: bool) (y: bool) = compare x y + """ + + CompilerAssert.CompileLibraryAndVerifyILWithOptions([|"-g"; "--optimize+"|], script, + (fun verifier -> + verifier.VerifyIL + [ + """ + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: sub + IL_0003: ret + """ + ] + ) + ) + + + + + module Assert = + /// Checks that x and y have same sign. + /// Since compare and CompareTo are not restricted to returning 0,-1,1 + /// but can return any positive or negative values, tests use this function + /// to check that the behavior is the same without over specifying. + let areSameSign (x: int) (y: int) = + Math.Sign(x) |> Assert.areEqual (Math.Sign(y)) + + [] + let Check_equivalence_with_CompareTo() = + let rnd = Random() + for i in 0 .. 1000 do + let x = rnd.Next() + let y = rnd.Next() + + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + + + [] + let Check_limit_case_equivalence_with_CompareTo_int32() = + let values = [0; 1; -1; Int32.MinValue; Int32.MaxValue; Int32.MinValue+1; Int32.MaxValue-1] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_uint32() = + let values = [0u; 1u; UInt32.MaxValue; UInt32.MaxValue-1u] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_int64() = + let values = [0L; 1L; -1L; Int64.MinValue; Int64.MaxValue; Int64.MinValue+1L; Int64.MaxValue-1L] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_uint64() = + let values = [0UL; 1UL; UInt64.MaxValue; UInt64.MaxValue-1UL] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_int16() = + let values = [0s; 1s; -1s; Int16.MinValue; Int16.MaxValue; Int16.MinValue+1s; Int16.MaxValue-1s] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_uint16() = + let values = [0us; 1us; UInt16.MaxValue; UInt16.MaxValue-1us] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + + [] + let Check_limit_case_equivalence_with_CompareTo_sbyte() = + let values = [0y; 1y; -1y; SByte.MinValue; SByte.MaxValue; SByte.MinValue+1y; SByte.MaxValue-1y] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_byte() = + let values = [0uy; 1uy; Byte.MaxValue; Byte.MaxValue-1uy] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_char() = + let values = [Char.MinValue; Char.MinValue+char 1 ; Char.MaxValue; Char.MaxValue+char -1] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + + [] + let Check_limit_case_equivalence_with_CompareTo_bool() = + let values = [false; true] + + for x in values do + for y in values do + compare x y |> Assert.areSameSign (x.CompareTo(y)) + diff --git a/tests/fsharp/Compiler/Language/HatDesugaringTests.fs b/tests/fsharp/Compiler/Language/HatDesugaringTests.fs index f3a33897468..2210e3a9851 100644 --- a/tests/fsharp/Compiler/Language/HatDesugaringTests.fs +++ b/tests/fsharp/Compiler/Language/HatDesugaringTests.fs @@ -4,7 +4,7 @@ open NUnit.Framework open FSharp.Test open FSharp.Compiler.Diagnostics -[] +[] module HatDesugaringTests = [] diff --git a/tests/fsharp/Compiler/Language/StringInterpolation.fs b/tests/fsharp/Compiler/Language/StringInterpolation.fs index 708d9be5e3b..367f4997d85 100644 --- a/tests/fsharp/Compiler/Language/StringInterpolation.fs +++ b/tests/fsharp/Compiler/Language/StringInterpolation.fs @@ -688,9 +688,9 @@ let xb = $"{%5d{1:N3}}" // inner error that looks like format specifiers CompilerAssert.TypeCheckWithErrorsAndOptions [| "--langversion:5.0" |] code [|(FSharpDiagnosticSeverity.Error, 1156, (2, 14, 2, 16), - "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger)."); + "This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int/int32), 1u (uint/uint32), 1L (int64), 1UL (uint64), 1s (int16), 1us (uint16), 1y (int8/sbyte), 1uy (uint8/byte), 1.0 (float/double), 1.0f (float32/single), 1.0m (decimal), 1I (bigint).") (FSharpDiagnosticSeverity.Error, 10, (2, 18, 2, 19), - "Unexpected symbol ':' in expression. Expected '}' or other token."); + "Unexpected symbol ':' in expression. Expected '}' or other token.") (FSharpDiagnosticSeverity.Error, 604, (2, 16, 2, 17), "Unmatched '{'") |] diff --git a/tests/fsharp/FSharpSuite.Tests.fsproj b/tests/fsharp/FSharpSuite.Tests.fsproj index ea602624b69..6e1daff174e 100644 --- a/tests/fsharp/FSharpSuite.Tests.fsproj +++ b/tests/fsharp/FSharpSuite.Tests.fsproj @@ -67,6 +67,7 @@ + diff --git a/tests/fsharp/core/classStructInterface/test.fsx b/tests/fsharp/core/classStructInterface/test.fsx new file mode 100644 index 00000000000..824f484a021 --- /dev/null +++ b/tests/fsharp/core/classStructInterface/test.fsx @@ -0,0 +1,5 @@ +module Foo + +type C = class end +type S = struct end +type I = interface end \ No newline at end of file diff --git a/tests/fsharp/core/functionTypes/test.fs b/tests/fsharp/core/functionTypes/test.fs new file mode 100644 index 00000000000..b2c2cb53147 --- /dev/null +++ b/tests/fsharp/core/functionTypes/test.fs @@ -0,0 +1,43 @@ +namespace Fantomas.Core + +module Context = + type Context = { SourceCode: string } + +namespace FSharp.Compiler + +module Syntax = + + type SynExpr = + | IfThenElse + | While + +module Text = + type Range = + struct + val startLine: int + val startColumn: int + val endLine: int + val endColumn: int + end + +namespace Fantomas.Core + +module internal CodePrinter = + + open FSharp.Compiler + open FSharp.Compiler.Syntax + open FSharp.Compiler.Text + open Fantomas.Core.Context + + type ASTContext = + { Meh: bool } + static member Default = { Meh = false } + + let rec genExpr (e: SynExpr) (ctx: Context) = ctx + + and genLambdaArrowWithTrivia + (bodyExpr: SynExpr -> Context -> Context) + (body: SynExpr) + (arrowRange: Range option) + : Context -> Context = + id diff --git a/tests/fsharp/core/load-script/out.stdout.bsl b/tests/fsharp/core/load-script/out.stdout.bsl index 498a44690ba..0cbbd767c36 100644 --- a/tests/fsharp/core/load-script/out.stdout.bsl +++ b/tests/fsharp/core/load-script/out.stdout.bsl @@ -22,11 +22,11 @@ Test 3================================================= Hello World -the end -namespace FSI_0002 +module FSI_0002.1 -namespace FSI_0002 +module FSI_0002.2 -namespace FSI_0002 +module FSI_0002.3 > Test 4================================================= diff --git a/tests/fsharp/core/mixCurriedTupled/test.fsx b/tests/fsharp/core/mixCurriedTupled/test.fsx new file mode 100644 index 00000000000..2302cbc5057 --- /dev/null +++ b/tests/fsharp/core/mixCurriedTupled/test.fsx @@ -0,0 +1,81 @@ +module Foo + +type Context = { Name: string } + +let veryLongFunctionNameWithATupleAsArgumentThatWillReallyUseALotOfSpaceInTheGeneratedSignatureFile + (justAString: string, + suuuuuuuuuuuuuuuperLoooooooooooooooooooooooooooooooooooooooooooooooooongIntegerNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaame: int) + (ctx: Context) + : Context -> Context = + id + +type TType = obj + +let SampleFunctionTupledAllBreakA + ( + longLongLongArgName1: string, + longLongLongArgName2: TType, + longLongLongArgName3: TType, + longLongLongArgName4: TType + ) : TType list = + [] + +let SampleFunctionCurriedAllBreaksA + (longLongLongArgName1: string) + (longLongLongArgName2: TType) + (longLongLongArgName3: TType) + (longLongLongArgName4: TType) + : TType list = + [] + +let SampleFunctionMixedA + (longLongLongArgName1: string, longLongLongArgName2: string) + (longLongLongArgName3: string, longLongLongArgName4: string, longLongLongArgName5: TType) + (longLongLongArgName6: TType, longLongLongArgName7: TType) + (longLongLongArgName8: TType, longLongLongArgName9: TType, longLongLongArgName10: TType) + : TType list = + [] + +type Meh = + abstract member ResolveDependencies: + scriptDirectory1: string * + scriptDirectory2: string * + scriptDirectory3: string * + scriptDirectory4: string * + scriptName: string * + scriptExt: string * + timeout: int -> + obj + + abstract member SomethingElse: + int -> + string -> + string -> + System.DateTime -> + System.Action -> + int array -> + obj -> + System.Collections.Generic.Comparer + +type AlternativeMeh() = + member this.ResolveDependencies + (scriptDirectory: string, scriptName: string) + (otherDirectory1: string, otherDirectory2: string, otherDirectory3: string, otherDirectory4: string) + (nicerScriptName: string, scriptExt: string, timeout: int) + : obj = + null + +let somethingTupledReturingSomethingTupled + ( + a: int, + b: int, + c: int, + d: int, + e: int, + f: int, + g: int, + h: int, + j: int, + k: int + ) = + (a, b, c) diff --git a/tests/fsharp/core/nestedModule/test.fsx b/tests/fsharp/core/nestedModule/test.fsx new file mode 100644 index 00000000000..99c161a65a8 --- /dev/null +++ b/tests/fsharp/core/nestedModule/test.fsx @@ -0,0 +1,3 @@ +module Top.Square.Middle.Level + +let value = 10 \ No newline at end of file diff --git a/tests/fsharp/core/nestedModuleInNamespace/test.fsx b/tests/fsharp/core/nestedModuleInNamespace/test.fsx new file mode 100644 index 00000000000..136efbf7c27 --- /dev/null +++ b/tests/fsharp/core/nestedModuleInNamespace/test.fsx @@ -0,0 +1,4 @@ +namespace Very.Real.NamespaceName + +module Foo = + let i = 1 diff --git a/tests/fsharp/core/printing/output.1000.stdout.bsl b/tests/fsharp/core/printing/output.1000.stdout.bsl index 9c91290b3bd..cc3eaef035e 100644 --- a/tests/fsharp/core/printing/output.1000.stdout.bsl +++ b/tests/fsharp/core/printing/output.1000.stdout.bsl @@ -5,44 +5,44 @@ > val repeatId: string = "B" -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0006 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0006 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile2 = - new: unit -> ClassInFile2 +module FSI_0005.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0006.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0006.TestLoadFile2 +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile2 = + new: unit -> ClassInFile2 > val x1: seq val x2: seq @@ -1133,7 +1133,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = { x: int } -> type internal T3 +> type internal T3 = + class end > type internal T4 = new: unit -> T4 @@ -1166,7 +1167,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = private { x: int } -> type private T3 +> type private T3 = + class end > type private T4 = new: unit -> T4 @@ -1373,7 +1375,8 @@ val x1564_A3: int = 3 | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -1396,7 +1399,8 @@ val x1564_A3: int = 3 | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 module internal PrivateM = @@ -1411,7 +1415,8 @@ module internal PrivateM = | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -1434,7 +1439,8 @@ module internal PrivateM = | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 @@ -2615,37 +2621,37 @@ val x: optionRecord = { x = null } TwoFields2: obj } -> type Int32 with +> type System.Int32 with member ExtrinsicExtensionProperty: int -type Int32 with +type System.Int32 with member ExtrinsicExtensionMethod: unit -> int > val ``value with spaces in name`` : bool = true > val functionWhichTakesLongNameMixedParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameTupledParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int * ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameCurriedParameters: - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int - -> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int - -> dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int -> + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int -> + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesMixedLengthCurriedParametersA: - a: 'a -> b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd - -> int + a: 'a -> + b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd -> int > val functionWhichTakesMixedLengthCurriedParametersB: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 'a -> b: 'b -> c: 'c -> d: 'd -> int diff --git a/tests/fsharp/core/printing/output.200.stdout.bsl b/tests/fsharp/core/printing/output.200.stdout.bsl index d9a8f38aff2..6d1b4c6dfc9 100644 --- a/tests/fsharp/core/printing/output.200.stdout.bsl +++ b/tests/fsharp/core/printing/output.200.stdout.bsl @@ -5,44 +5,44 @@ > val repeatId: string = "B" -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0006 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0006 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile2 = - new: unit -> ClassInFile2 +module FSI_0005.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0006.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0006.TestLoadFile2 +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile2 = + new: unit -> ClassInFile2 > val x1: seq val x2: seq @@ -453,7 +453,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = { x: int } -> type internal T3 +> type internal T3 = + class end > type internal T4 = new: unit -> T4 @@ -486,7 +487,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = private { x: int } -> type private T3 +> type private T3 = + class end > type private T4 = new: unit -> T4 @@ -618,7 +620,8 @@ val x1564_A3: int = 3 | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -641,7 +644,8 @@ val x1564_A3: int = 3 | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 module internal PrivateM = @@ -656,7 +660,8 @@ module internal PrivateM = | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -679,7 +684,8 @@ module internal PrivateM = | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 @@ -1860,37 +1866,37 @@ val x: optionRecord = { x = null } TwoFields2: obj } -> type Int32 with +> type System.Int32 with member ExtrinsicExtensionProperty: int -type Int32 with +type System.Int32 with member ExtrinsicExtensionMethod: unit -> int > val ``value with spaces in name`` : bool = true > val functionWhichTakesLongNameMixedParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameTupledParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int * ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameCurriedParameters: - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int - -> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int - -> dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int -> + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int -> + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesMixedLengthCurriedParametersA: - a: 'a -> b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd - -> int + a: 'a -> + b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd -> int > val functionWhichTakesMixedLengthCurriedParametersB: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 'a -> b: 'b -> c: 'c -> d: 'd -> int diff --git a/tests/fsharp/core/printing/output.47.stdout.bsl b/tests/fsharp/core/printing/output.47.stdout.bsl index f62162360fa..af2d597eaad 100644 --- a/tests/fsharp/core/printing/output.47.stdout.bsl +++ b/tests/fsharp/core/printing/output.47.stdout.bsl @@ -3,44 +3,44 @@ > val repeatId: string = "B" -namespace FSI_0004 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile2 = - new: unit -> ClassInFile2 +module FSI_0004.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0005.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0005.TestLoadFile2 +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile2 = + new: unit -> ClassInFile2 > val x1: seq val x2: seq @@ -4090,7 +4090,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = { x: int } -> type internal T3 +> type internal T3 = + class end > type internal T4 = new: unit -> T4 @@ -4123,7 +4124,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = private { x: int } -> type private T3 +> type private T3 = + class end > type private T4 = new: unit -> T4 @@ -4918,7 +4920,8 @@ val x1564_A3: int = 3 | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -4941,7 +4944,8 @@ val x1564_A3: int = 3 | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 module internal PrivateM = @@ -4956,7 +4960,8 @@ module internal PrivateM = | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -4979,7 +4984,8 @@ module internal PrivateM = | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 @@ -6160,37 +6166,37 @@ val x: optionRecord = { x = null } TwoFields2: obj } -> type Int32 with +> type System.Int32 with member ExtrinsicExtensionProperty: int -type Int32 with +type System.Int32 with member ExtrinsicExtensionMethod: unit -> int > val ``value with spaces in name`` : bool = true > val functionWhichTakesLongNameMixedParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameTupledParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int * ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameCurriedParameters: - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int - -> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int - -> dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int -> + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int -> + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesMixedLengthCurriedParametersA: - a: 'a -> b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd - -> int + a: 'a -> + b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd -> int > val functionWhichTakesMixedLengthCurriedParametersB: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 'a -> b: 'b -> c: 'c -> d: 'd -> int diff --git a/tests/fsharp/core/printing/output.multiemit.stdout.bsl b/tests/fsharp/core/printing/output.multiemit.stdout.bsl index ea38da2de43..acdcf6c63d8 100644 --- a/tests/fsharp/core/printing/output.multiemit.stdout.bsl +++ b/tests/fsharp/core/printing/output.multiemit.stdout.bsl @@ -3,44 +3,44 @@ > val repeatId: string = "B" -namespace FSI_0004 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile2 = - new: unit -> ClassInFile2 +module FSI_0004.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0005.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0005.TestLoadFile2 +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile2 = + new: unit -> ClassInFile2 > val x1: seq val x2: seq @@ -4092,7 +4092,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = { x: int } -> type internal T3 +> type internal T3 = + class end > type internal T4 = new: unit -> T4 @@ -4125,7 +4126,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = private { x: int } -> type private T3 +> type private T3 = + class end > type private T4 = new: unit -> T4 @@ -4920,7 +4922,8 @@ val x1564_A3: int = 3 | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -4943,7 +4946,8 @@ val x1564_A3: int = 3 | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 module internal PrivateM = @@ -4958,7 +4962,8 @@ module internal PrivateM = | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -4981,7 +4986,8 @@ module internal PrivateM = | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 @@ -6162,37 +6168,37 @@ val x: optionRecord = { x = null } TwoFields2: obj } -> type Int32 with +> type System.Int32 with member ExtrinsicExtensionProperty: int -type Int32 with +type System.Int32 with member ExtrinsicExtensionMethod: unit -> int > val ``value with spaces in name`` : bool = true > val functionWhichTakesLongNameMixedParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameTupledParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int * ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameCurriedParameters: - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int - -> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int - -> dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int -> + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int -> + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesMixedLengthCurriedParametersA: - a: 'a -> b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd - -> int + a: 'a -> + b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd -> int > val functionWhichTakesMixedLengthCurriedParametersB: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 'a -> b: 'b -> c: 'c -> d: 'd -> int diff --git a/tests/fsharp/core/printing/output.off.stdout.bsl b/tests/fsharp/core/printing/output.off.stdout.bsl index 0ddfe7af9bd..2bd43f77f8f 100644 --- a/tests/fsharp/core/printing/output.off.stdout.bsl +++ b/tests/fsharp/core/printing/output.off.stdout.bsl @@ -5,44 +5,44 @@ > val repeatId: string -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0006 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0006 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile2 = - new: unit -> ClassInFile2 +module FSI_0005.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0006.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0006.TestLoadFile2 +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile2 = + new: unit -> ClassInFile2 > val x1: seq val x2: seq @@ -280,7 +280,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = { x: int } -> type internal T3 +> type internal T3 = + class end > type internal T4 = new: unit -> T4 @@ -313,7 +314,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = private { x: int } -> type private T3 +> type private T3 = + class end > type private T4 = new: unit -> T4 @@ -418,7 +420,8 @@ val x1564_A3: int | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -441,7 +444,8 @@ val x1564_A3: int | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 module internal PrivateM = @@ -456,7 +460,8 @@ module internal PrivateM = | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -479,7 +484,8 @@ module internal PrivateM = | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 @@ -1630,37 +1636,37 @@ val x: optionRecord TwoFields2: obj } -> type Int32 with +> type System.Int32 with member ExtrinsicExtensionProperty: int -type Int32 with +type System.Int32 with member ExtrinsicExtensionMethod: unit -> int > val ``value with spaces in name`` : bool > val functionWhichTakesLongNameMixedParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameTupledParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int * ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameCurriedParameters: - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int - -> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int - -> dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int -> + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int -> + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesMixedLengthCurriedParametersA: - a: 'a -> b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd - -> int + a: 'a -> + b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd -> int > val functionWhichTakesMixedLengthCurriedParametersB: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 'a -> b: 'b -> c: 'c -> d: 'd -> int diff --git a/tests/fsharp/core/printing/output.stdout.bsl b/tests/fsharp/core/printing/output.stdout.bsl index ea38da2de43..acdcf6c63d8 100644 --- a/tests/fsharp/core/printing/output.stdout.bsl +++ b/tests/fsharp/core/printing/output.stdout.bsl @@ -3,44 +3,44 @@ > val repeatId: string = "B" -namespace FSI_0004 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile1 = - new: unit -> ClassInFile1 - -namespace FSI_0005 - val x1: int - val x2: string - val x3: 'a option - val x4: int option - val x5: 'a list - val x6: int list - val x7: System.Windows.Forms.Form - val x8: int[,] - val x9: Lazy - type ClassInFile2 = - new: unit -> ClassInFile2 +module FSI_0004.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0005.TestLoadFile +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile1 = + new: unit -> ClassInFile1 + +module FSI_0005.TestLoadFile2 +val x1: int +val x2: string +val x3: 'a option +val x4: int option +val x5: 'a list +val x6: int list +val x7: System.Windows.Forms.Form +val x8: int[,] +val x9: Lazy +type ClassInFile2 = + new: unit -> ClassInFile2 > val x1: seq val x2: seq @@ -4092,7 +4092,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = { x: int } -> type internal T3 +> type internal T3 = + class end > type internal T4 = new: unit -> T4 @@ -4125,7 +4126,8 @@ type 'a T4063 = | AT4063 of 'a > type internal T2 = private { x: int } -> type private T3 +> type private T3 = + class end > type private T4 = new: unit -> T4 @@ -4920,7 +4922,8 @@ val x1564_A3: int = 3 | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -4943,7 +4946,8 @@ val x1564_A3: int = 3 | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 module internal PrivateM = @@ -4958,7 +4962,8 @@ module internal PrivateM = | B type T2 = { x: int } - type T3 + type T3 = + class end type T4 = new: unit -> T4 type T5 = @@ -4981,7 +4986,8 @@ module internal PrivateM = | B type T12 = private { x: int } - type private T13 + type private T13 = + class end type private T14 = new: unit -> T14 @@ -6162,37 +6168,37 @@ val x: optionRecord = { x = null } TwoFields2: obj } -> type Int32 with +> type System.Int32 with member ExtrinsicExtensionProperty: int -type Int32 with +type System.Int32 with member ExtrinsicExtensionMethod: unit -> int > val ``value with spaces in name`` : bool = true > val functionWhichTakesLongNameMixedParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameTupledParameters: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int * ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int * - ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesLongNameCurriedParameters: - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int - -> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int - -> cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int - -> dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int - -> int + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: int -> + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: int -> + cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: int -> + dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: int -> + int > val functionWhichTakesMixedLengthCurriedParametersA: - a: 'a -> b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd - -> int + a: 'a -> + b: 'b -> c: 'c -> ddddddddddddddddddddddddddddddddddddddddddddd: 'd -> int > val functionWhichTakesMixedLengthCurriedParametersB: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 'a -> b: 'b -> c: 'c -> d: 'd -> int diff --git a/tests/fsharp/core/recursiveNestedModule/test.fsx b/tests/fsharp/core/recursiveNestedModule/test.fsx new file mode 100644 index 00000000000..747c0f253fc --- /dev/null +++ b/tests/fsharp/core/recursiveNestedModule/test.fsx @@ -0,0 +1,11 @@ +module rec Top.Square.Middle.Level + +let value = 10 + +type Foo = + { Bar: Bar } + +type Bar = { Meh: string } + +module Nested = + let x = "" \ No newline at end of file diff --git a/tests/fsharp/core/typeAliasPrimitives/test.fsx b/tests/fsharp/core/typeAliasPrimitives/test.fsx new file mode 100644 index 00000000000..950a20fd61f --- /dev/null +++ b/tests/fsharp/core/typeAliasPrimitives/test.fsx @@ -0,0 +1,22 @@ +namespace Foo + +type A = bool +type B = sbyte +type C = byte +type D = int16 +type E = uint16 +type F = int +type G = uint +type H = nativeint +type I = unativeint +type J = int64 +type K = single +type L = float32 +type M = float +type N = double +type O = bigint +type P = decimal +type Q = System.Char +type R = System.String +type S = System.Byte +type T = unit \ No newline at end of file diff --git a/tests/fsharp/core/typeAugmentation/test.fsx b/tests/fsharp/core/typeAugmentation/test.fsx new file mode 100644 index 00000000000..cb46eb9f6e1 --- /dev/null +++ b/tests/fsharp/core/typeAugmentation/test.fsx @@ -0,0 +1,8 @@ +module Foo + +open System + +type Int32 with + member this.PlusPlus () = this + 1 + +let two = (1).PlusPlus() \ No newline at end of file diff --git a/tests/fsharp/core/unionWithFunctionType/test.fs b/tests/fsharp/core/unionWithFunctionType/test.fs new file mode 100644 index 00000000000..aa278e95dc8 --- /dev/null +++ b/tests/fsharp/core/unionWithFunctionType/test.fs @@ -0,0 +1,10 @@ +module Example.Context + +type Context = { Events: string list } + +type internal ColMultilineItem = + | ColMultilineItem of + // current expression + expr: (Context -> Context) * + // sepNln of current item + sepNln: (Context -> Context) \ No newline at end of file diff --git a/tests/fsharp/single-test.fs b/tests/fsharp/single-test.fs index aa8babe2e20..02548f16e56 100644 --- a/tests/fsharp/single-test.fs +++ b/tests/fsharp/single-test.fs @@ -378,8 +378,8 @@ let singleVersionedNegTest (cfg: TestConfig) version testname = let cfg = { cfg with - fsc_flags = sprintf "%s %s --define:NEGATIVE" cfg.fsc_flags (if not (String.IsNullOrEmpty(version)) then "--langversion:" + version else "") - fsi_flags = sprintf "%s %s" cfg.fsi_flags (if not (String.IsNullOrEmpty(version)) then "--langversion:" + version else "") + fsc_flags = sprintf "%s %s --preferreduilang:en-US --define:NEGATIVE" cfg.fsc_flags (if not (String.IsNullOrEmpty(version)) then "--langversion:" + version else "") + fsi_flags = sprintf "%s --preferreduilang:en-US %s" cfg.fsi_flags (if not (String.IsNullOrEmpty(version)) then "--langversion:" + version else "") } // REM == Set baseline (fsc vs vs, in case the vs baseline exists) diff --git a/tests/fsharp/tests.fs b/tests/fsharp/tests.fs index c8e909e1e8b..d8c4bd79cc2 100644 --- a/tests/fsharp/tests.fs +++ b/tests/fsharp/tests.fs @@ -32,7 +32,8 @@ let singleTestBuildAndRun = getTestsDirectory >> singleTestBuildAndRun let singleTestBuildAndRunVersion = getTestsDirectory >> singleTestBuildAndRunVersion let testConfig = getTestsDirectory >> testConfig -[] + +[] module CoreTests = // These tests are enabled for .NET Framework and .NET Core [] @@ -464,7 +465,7 @@ module CoreTests = let cfg = testConfig "core/span" - let cfg = { cfg with fsc_flags = sprintf "%s --test:StackSpan" cfg.fsc_flags} + let cfg = { cfg with fsc_flags = sprintf "%s --preferreduilang:en-US --test:StackSpan" cfg.fsc_flags} begin use testOkFile = fileguard cfg "test.ok" @@ -1057,7 +1058,7 @@ module CoreTests = let rawFileOut = tryCreateTemporaryFileName () let rawFileErr = tryCreateTemporaryFileName () - ``fsi b 2>c`` "%s --nologo %s" fsc_flags_errors_ok flag ("test.fsx", rawFileOut, rawFileErr) + ``fsi b 2>c`` "%s --nologo --preferreduilang:en-US %s" fsc_flags_errors_ok flag ("test.fsx", rawFileOut, rawFileErr) // REM REVIEW: want to normalise CWD paths, not suppress them. let ``findstr /v`` text = Seq.filter (fun (s: string) -> not <| s.Contains(text)) @@ -1113,7 +1114,7 @@ module CoreTests = runPrintingTest "--use:preludePrintSize1000.fsx" "output.1000" [] - let ``printing-width-200`` () = + let ``printing-width-200`` () = runPrintingTest "--use:preludePrintSize200.fsx" "output.200" [] @@ -2098,13 +2099,14 @@ module VersionTests = let ``nameof-fsi``() = singleTestBuildAndRunVersion "core/nameof/preview" FSI "preview" #if !NETCOREAPP -[] +[] module ToolsTests = // This test is disabled in coreclr builds dependent on fixing : https://github.com/dotnet/fsharp/issues/2600 [] let bundle () = - let cfg = testConfig "tools/bundle" + let cfg = + testConfig "tools/bundle" fsc cfg "%s --progress --standalone -o:test-one-fsharp-module.exe -g" cfg.fsc_flags ["test-one-fsharp-module.fs"] @@ -2228,7 +2230,9 @@ module RegressionTests = [] let ``SRTP doesn't handle calling member hiding hinherited members`` () = - let cfg = testConfig "regression/5531" + let cfg = + testConfig "regression/5531" + let outFile = "compilation.output.test.txt" let expectedFile = "compilation.output.test.bsl" @@ -3354,6 +3358,33 @@ module GeneratedSignatureTests = [] let ``measures-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/measures" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``nestedModule-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/nestedModule" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``recursiveNestedModule-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/recursiveNestedModule" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``nestedModuleInNamespace-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/nestedModuleInNamespace" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``classStructInterface-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/classStructInterface" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``typeAugmentation-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/typeAugmentation" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``typeAliasPrimitives-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/typeAliasPrimitives" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``functionTypes-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/functionTypes" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``unionWithFunctionType-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/unionWithFunctionType" FSC_NETFX_TEST_GENERATED_SIGNATURE + + [] + let ``mixCurriedTupled-FSC_NETFX_TEST_GENERATED_SIGNATURE`` () = singleTestBuildAndRun "core/mixCurriedTupled" FSC_NETFX_TEST_GENERATED_SIGNATURE #endif #if !NETCOREAPP diff --git a/tests/fsharp/typeProviders/fsharp41/net45/providerDesigner.dll b/tests/fsharp/typeProviders/fsharp41/net45/providerDesigner.dll deleted file mode 100644 index 6c1217f65c0..00000000000 Binary files a/tests/fsharp/typeProviders/fsharp41/net45/providerDesigner.dll and /dev/null differ diff --git a/tests/fsharp/typeProviders/fsharp41/net461/providerDesigner.dll b/tests/fsharp/typeProviders/fsharp41/net461/providerDesigner.dll deleted file mode 100644 index be66328ed47..00000000000 Binary files a/tests/fsharp/typeProviders/fsharp41/net461/providerDesigner.dll and /dev/null differ diff --git a/tests/fsharp/typeProviders/fsharp41/net472/providerDesigner.dll b/tests/fsharp/typeProviders/fsharp41/net472/providerDesigner.dll deleted file mode 100644 index 3fc00ffeff3..00000000000 Binary files a/tests/fsharp/typeProviders/fsharp41/net472/providerDesigner.dll and /dev/null differ diff --git a/tests/fsharp/typeProviders/fsharp41/net48/providerDesigner.dll b/tests/fsharp/typeProviders/fsharp41/net48/providerDesigner.dll deleted file mode 100644 index 8d9f90ef421..00000000000 Binary files a/tests/fsharp/typeProviders/fsharp41/net48/providerDesigner.dll and /dev/null differ diff --git a/tests/fsharp/typeProviders/fsharp41/netstandard2.0/providerDesigner.dll b/tests/fsharp/typeProviders/fsharp41/netstandard2.0/providerDesigner.dll deleted file mode 100644 index 873999d0e96..00000000000 Binary files a/tests/fsharp/typeProviders/fsharp41/netstandard2.0/providerDesigner.dll and /dev/null differ diff --git a/tests/fsharp/typecheck/sigs/neg06.fs b/tests/fsharp/typecheck/sigs/neg06.fs index a31bbbba21c..ee9ddce60dc 100644 --- a/tests/fsharp/typecheck/sigs/neg06.fs +++ b/tests/fsharp/typecheck/sigs/neg06.fs @@ -24,7 +24,7 @@ type BadSealedInterface = type BadSealedAbbreviatedType = System.Object [] -type UnnecessarilySealedDelegate() = delegate of int -> int +type UnnecessarilySealedDelegate = delegate of int -> int type BadExtensionOfSealedType() = class diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fs b/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fs index 324a05b273f..23432c4bb50 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fs +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fs @@ -48,10 +48,12 @@ //section='- ADVANCED - ' ! option=subsystemversion kind=OptionString //section='- ADVANCED - ' ! option=targetprofile kind=OptionString //section='- ADVANCED - ' ! option=quotations-debug kind=OptionSwitch -//section='NoSection ' ! option=stamps kind=OptionUnit -//section='NoSection ' ! option=ranges kind=OptionSet -//section='NoSection ' ! option=terms kind=OptionUnit -//section='NoSection ' ! option=termsfile kind=OptionUnit +//section='NoSection ' ! option=typedtree kind=OptionUnit +//section='NoSection ' ! option=typedtreefile kind=OptionUnit +//section='NoSection ' ! option=typedtreestamps kind=OptionUnit +//section='NoSection ' ! option=typedtreeranges kind=OptionUnit +//section='NoSection ' ! option=typedtreetypes kind=OptionUnit +//section='NoSection ' ! option=typedtreevalreprinfo kind=OptionUnit //section='NoSection ' ! option=pause kind=OptionUnit //section='NoSection ' ! option=detuple kind=OptionInt //section='NoSection ' ! option=simulateException kind=OptionString diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fsx b/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fsx index bfc350a2b86..7d9f0b0f5c0 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fsx +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/dumpAllCommandLineOptions/dummy.fsx @@ -31,10 +31,12 @@ //section='- ADVANCED - ' ! option=fullpaths kind=OptionUnit //section='- ADVANCED - ' ! option=lib kind=OptionStringList //section='- ADVANCED - ' ! option=noframework kind=OptionUnit -//section='NoSection ' ! option=ranges kind=OptionSet -//section='NoSection ' ! option=terms kind=OptionUnit -//section='NoSection ' ! option=termsfile kind=OptionUnit -//section='NoSection ' ! option=stamps kind=OptionUnit +//section='NoSection ' ! option=typedtree kind=OptionUnit +//section='NoSection ' ! option=typedtreefile kind=OptionUnit +//section='NoSection ' ! option=typedtreestamps kind=OptionUnit +//section='NoSection ' ! option=typedtreeranges kind=OptionUnit +//section='NoSection ' ! option=typedtreetypes kind=OptionUnit +//section='NoSection ' ! option=typedtreevalreprinfo kind=OptionUnit //section='NoSection ' ! option=pause kind=OptionUnit //section='NoSection ' ! option=detuple kind=OptionInt //section='NoSection ' ! option=simulateException kind=OptionString diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl index 166a579b88f..d916a6c2eba 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl @@ -92,6 +92,8 @@ Usage: fsharpi [script.fsx []] this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib +--clearResultsCache Clear the package manager results + cache --noframework Do not reference the default CLI assemblies by default --exec Exit fsi after loading the files or diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl index 06f0acdb1c4..906df1bcee4 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl @@ -92,6 +92,8 @@ Usage: fsiAnyCpu [script.fsx []] this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib +--clearResultsCache Clear the package manager results + cache --noframework Do not reference the default CLI assemblies by default --exec Exit fsi after loading the files or diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl index f2651c5c8a1..87541384a88 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl @@ -94,6 +94,8 @@ Usage: fsiAnyCpu [script.fsx []] this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib +--clearResultsCache Clear the package manager results + cache --noframework Do not reference the default CLI assemblies by default --exec Exit fsi after loading the files or diff --git a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/DelegateTypes/env.lst b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/DelegateTypes/env.lst index bb9e0f2ae1f..e805eea233c 100644 --- a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/DelegateTypes/env.lst +++ b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/DelegateTypes/env.lst @@ -1,10 +1,9 @@ SOURCE=ByrefArguments01.fs # ByrefArguments01.fs SOURCE=E_InvalidSignature01.fs # E_InvalidSignature01.fs SOURCE=E_InvalidSignature02.fs # E_InvalidSignature02.fs - SOURCE=ValidSignature_MultiArg01.fs # ValidSignature_MultiArg01.fs SOURCE=ValidSignature_ReturningValues01.fs # ValidSignature_ReturningValues01.fs # This test has a dependency on NetFx3.5 (i.e. CSC_PIPE must be 3.5 or better) # For this reason, we exclude it from MT -NoMT SOURCE=DelegateBindingInvoke01.fs PRECMD="\$CSC_PIPE /t:library IDelegateBinding.cs" SCFLAGS="-r:IDelegateBinding.dll" # DelegateBindingInvoke01.fs \ No newline at end of file +NoMT SOURCE=DelegateBindingInvoke01.fs PRECMD="\$CSC_PIPE /t:library IDelegateBinding.cs" SCFLAGS="-r:IDelegateBinding.dll" # DelegateBindingInvoke01.fs diff --git a/tests/scripts/identifierAnalysisByType.fsx b/tests/scripts/identifierAnalysisByType.fsx new file mode 100644 index 00000000000..d3b5c4e9415 --- /dev/null +++ b/tests/scripts/identifierAnalysisByType.fsx @@ -0,0 +1,153 @@ +// Print some stats about identifiers grouped by type +// + +#r "nuget: Ionide.ProjInfo" +#I @"..\..\artifacts\bin\fsc\Debug\net6.0\" +#r "FSharp.Compiler.Service.dll" + +open System +open System.IO +open Ionide.ProjInfo +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Symbols +open Ionide.ProjInfo.Types + +let argv = fsi.CommandLineArgs + +if argv.Length = 1 then + eprintfn "usage:" + eprintfn " dotnet fsi tests/scripts/identifierAnalysisByType.fsx " + eprintfn "" + eprintfn "examples:" + eprintfn " dotnet fsi tests/scripts/identifierAnalysisByType.fsx src/FSharp.Build/FSharp.Build.fsproj" + eprintfn " dotnet fsi tests/scripts/identifierAnalysisByType.fsx src/Compiler/FSharp.Compiler.Service.fsproj" + eprintfn "" + eprintfn "Sample output is at https://gist.github.com/dsyme/abfa11bebf0713251418906d55c08804" + +//let projectFile = Path.Combine(__SOURCE_DIRECTORY__, @"..\..\src\Compiler\FSharp.Compiler.Service.fsproj") +//let projectFile = Path.Combine(__SOURCE_DIRECTORY__, @"..\..\src\FSharp.Build\FSharp.Build.fsproj") +let projectFile = Path.GetFullPath(argv[1]) + +let cwd = System.Environment.CurrentDirectory |> System.IO.DirectoryInfo + +let _toolsPath = Init.init cwd None + +printfn "Cracking project options...." +let opts = + match ProjectLoader.getProjectInfo projectFile [] BinaryLogGeneration.Off [] with + | Result.Ok res -> res + | Result.Error err -> failwithf "%s" err + +let checker = FSharpChecker.Create() + +let checkerOpts = checker.GetProjectOptionsFromCommandLineArgs(projectFile, [| yield! opts.SourceFiles; yield! opts.OtherOptions |] ) + +printfn "Checking project...." +let results = checker.ParseAndCheckProject(checkerOpts) |> Async.RunSynchronously + +printfn "Grouping symbol uses...." +let symbols = results.GetAllUsesOfAllSymbols() + +let rec stripTy (ty: FSharpType) = + if ty.IsAbbreviation then stripTy ty.AbbreviatedType else ty + +let getTypeText (sym: FSharpMemberOrFunctionOrValue) = + let ty = stripTy sym.FullType + FSharpType.Prettify(ty).Format(FSharpDisplayContext.Empty) + +symbols +|> Array.choose (fun vUse -> match vUse.Symbol with :? FSharpMemberOrFunctionOrValue as v -> Some (v, vUse.Range) | _ -> None) +|> Array.filter (fun (v, _) -> v.GenericParameters.Count = 0) +|> Array.filter (fun (v, _) -> v.CurriedParameterGroups.Count = 0) +|> Array.filter (fun (v, _) -> not v.FullType.IsGenericParameter) +|> Array.map (fun (v, vUse) -> getTypeText v, v, vUse.ToString()) +|> Array.filter (fun (vTypeText, v, _) -> + match vTypeText with + | "System.String" -> false + | "System.Boolean" -> false + | "System.Int32" -> false + | "System.Int64" -> false + | "System.Object" -> false + | "Microsoft.FSharp.Collections.List" -> false + | "Microsoft.FSharp.Core.Option" -> false + | s when s.EndsWith(" Microsoft.FSharp.Core.[]") -> false // for now filter array types + | _ when v.DisplayName.StartsWith "_" -> false + | _ -> true) +|> Array.groupBy (fun (vTypeText, _, _) -> vTypeText) +|> Array.map (fun (key, g) -> + key, + (g + |> Array.distinctBy (fun (_, _, vUse) -> vUse) + |> Array.groupBy (fun (_, v, _) -> v.DisplayName) + |> Array.sortByDescending (snd >> Array.length))) +|> Array.filter (fun (_, g) -> g.Length > 1) +|> Array.sortByDescending (fun (key, g) -> Array.length g) +|> Array.iter (fun (key, g) -> + let key = key.Replace("Microsoft.FSharp", "FSharp").Replace("FSharp.Core.", "") + printfn "Type: %s" key + for (nm, entries) in g do + printfn " %s (%d times)" nm (Array.length entries) + for (_, _, vUse) in entries do + printfn " %s" vUse + printfn "") + +(* +let isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + +let dotnet = + if isWindows then + "dotnet.exe" + else + "dotnet" +let fileExists pathToFile = + try + File.Exists(pathToFile) + with _ -> + false +// Look for global install of dotnet sdk +let getDotnetGlobalHostPath () = + let pf = Environment.GetEnvironmentVariable("ProgramW6432") + + let pf = + if String.IsNullOrEmpty(pf) then + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + else + pf + + let candidate = Path.Combine(pf, "dotnet", dotnet) + + if fileExists candidate then + Some candidate + else + // Can't find it --- give up + None + +let getDotnetHostPath () = + let probePathForDotnetHost () = + let paths = + let p = Environment.GetEnvironmentVariable("PATH") + + if not (isNull p) then + p.Split(Path.PathSeparator) + else + [||] + + paths |> Array.tryFind (fun f -> fileExists (Path.Combine(f, dotnet))) + + match (Environment.GetEnvironmentVariable("DOTNET_HOST_PATH")) with + // Value set externally + | value when not (String.IsNullOrEmpty(value)) && fileExists value -> Some value + | _ -> + // Probe for netsdk install, dotnet. and dotnet.exe is a constant offset from the location of System.Int32 + let candidate = + let assemblyLocation = Path.GetDirectoryName(typeof.Assembly.Location) + Path.GetFullPath(Path.Combine(assemblyLocation, "..", "..", "..", dotnet)) + + if fileExists candidate then + Some candidate + else + match probePathForDotnetHost () with + | Some f -> Some(Path.Combine(f, dotnet)) + | None -> getDotnetGlobalHostPath () +let dotnetExe = getDotnetHostPath () |> Option.map System.IO.FileInfo +*) diff --git a/tests/service/Common.fs b/tests/service/Common.fs index efc7e115084..b683dd9dce1 100644 --- a/tests/service/Common.fs +++ b/tests/service/Common.fs @@ -226,6 +226,11 @@ let getSingleExprInModule (input: ParsedInput) = | SynModuleDecl.Expr (expr, _) -> expr | _ -> failwith "Unexpected expression" +let getSingleParenInnerExpr expr = + match expr with + | SynModuleDecl.Expr(SynExpr.Paren(expr, _, _, _), _) -> expr + | _ -> failwith "Unexpected tree" + let parseSourceCodeAndGetModule (source: string) = parseSourceCode ("test.fsx", source) |> getSingleModuleLikeDecl @@ -449,6 +454,8 @@ let coreLibAssemblyName = "mscorlib" #endif +let getRange (e: SynExpr) = e.Range + let assertRange (expectedStartLine: int, expectedStartColumn: int) (expectedEndLine: int, expectedEndColumn: int) diff --git a/tests/service/ParserTests.fs b/tests/service/ParserTests.fs index bbfb623aef9..b96083b77e7 100644 --- a/tests/service/ParserTests.fs +++ b/tests/service/ParserTests.fs @@ -3,6 +3,7 @@ open FSharp.Compiler.Service.Tests.Common open FSharp.Compiler.Syntax open FSharp.Compiler.Text +open FsUnit open NUnit.Framework [] @@ -187,3 +188,148 @@ let f (x, | SynPat.FromParseError (SynPat.Paren (SynPat.FromParseError (SynPat.Wild _, _), _), _) -> () | _ -> failwith "Unexpected tree" | _ -> failwith "Unexpected tree" + +let assertIsBefore (f: _ -> range) (a, b) = + let r1 = f a + let r2 = f b + Position.posGeq r2.Start r1.End |> shouldEqual true + +let checkExprOrder exprs = + exprs + |> List.pairwise + |> List.iter (assertIsBefore getRange) + +let checkRangeCountAndOrder commas = + commas + |> List.iter (fun (commas, length) -> + List.length commas |> shouldEqual length + + commas + |> List.pairwise + |> List.iter (assertIsBefore id)) + +[] +let ``Expr - Tuple 01`` () = + let parseResults = getParseResults """ +(,) +(,,) +(,,,) +""" + let exprs = getSingleModuleMemberDecls parseResults |> List.map getSingleParenInnerExpr + match exprs with + | [ SynExpr.Tuple(_, [SynExpr.ArbitraryAfterError _ as e11; SynExpr.ArbitraryAfterError _ as e12], c1, _) + SynExpr.Tuple(_, [SynExpr.ArbitraryAfterError _ as e21; SynExpr.ArbitraryAfterError _ as e22; SynExpr.ArbitraryAfterError _ as e23], c2, _) + SynExpr.Tuple(_, [SynExpr.ArbitraryAfterError _ as e31; SynExpr.ArbitraryAfterError _ as e32; SynExpr.ArbitraryAfterError _ as e33; SynExpr.ArbitraryAfterError _ as e34], c3, _) ] -> + [ e11; e12; e21; e22; e23; e31; e32; e33; e34 ] |> checkExprOrder + [ c1, 1; c2, 2; c3, 3 ] |> checkRangeCountAndOrder + + | _ -> failwith "Unexpected tree" + +[] +let ``Expr - Tuple 02`` () = + let parseResults = getParseResults """ +(1,) +(,1) +(1,1) +""" + let exprs = getSingleModuleMemberDecls parseResults |> List.map getSingleParenInnerExpr + match exprs with + | [ SynExpr.Tuple(_, [SynExpr.Const _ as e11; SynExpr.ArbitraryAfterError _ as e12], c1, _) + SynExpr.Tuple(_, [SynExpr.ArbitraryAfterError _ as e21; SynExpr.Const _ as e22], c2, _) + SynExpr.Tuple(_, [SynExpr.Const _ as e31; SynExpr.Const _ as e32], c3, _) ] -> + [ e11; e12; e21; e22; e31; e32 ] |> checkExprOrder + [ c1, 1; c2, 1; c3, 1 ] |> checkRangeCountAndOrder + + | _ -> failwith "Unexpected tree" + +[] +let ``Expr - Tuple 03`` () = + let parseResults = getParseResults """ +(1,,) +(,1,) +(,,1) + +(1,1,) +(,1,1) +(1,,1) + +(1,1,1) +""" + let exprs = getSingleModuleMemberDecls parseResults |> List.map getSingleParenInnerExpr + match exprs with + | [ SynExpr.Tuple(_, [SynExpr.Const _ as e11; SynExpr.ArbitraryAfterError _ as e12; SynExpr.ArbitraryAfterError _ as e13], c1, _) + SynExpr.Tuple(_, [SynExpr.ArbitraryAfterError _ as e21; SynExpr.Const _ as e22; SynExpr.ArbitraryAfterError _ as e23], c2, _) + SynExpr.Tuple(_, [SynExpr.ArbitraryAfterError _ as e31; SynExpr.ArbitraryAfterError _ as e32; SynExpr.Const _ as e33], c3, _) + + SynExpr.Tuple(_, [SynExpr.Const _ as e41; SynExpr.Const _ as e42; SynExpr.ArbitraryAfterError _ as e43], c4, _) + SynExpr.Tuple(_, [SynExpr.ArbitraryAfterError _ as e51; SynExpr.Const _ as e52; SynExpr.Const _ as e53], c5, _) + SynExpr.Tuple(_, [SynExpr.Const _ as e61; SynExpr.ArbitraryAfterError _ as e62; SynExpr.Const _ as e63], c6, _) + + SynExpr.Tuple(_, [SynExpr.Const _ as e71; SynExpr.Const _ as e72; SynExpr.Const _ as e73], c7, _) ] -> + [ e11; e12; e13; e21; e22; e23; e31; e32; e33 + e41; e42; e43; e51; e52; e53; e61; e62; e63 + e71; e72; e73 ] + |> checkExprOrder + + [ c1, 2; c2, 2; c3, 2 + c4, 2; c5, 2; c6, 2 + c7, 2 ] + |> checkRangeCountAndOrder + + | _ -> failwith "Unexpected tree" + + +[] +let ``Expr - Tuple 04`` () = + let parseResults = getParseResults """ +(,1,,2,3,,4,) +""" + let exprs = getSingleModuleMemberDecls parseResults |> List.map getSingleParenInnerExpr + match exprs with + | [ SynExpr.Tuple(_, [ SynExpr.ArbitraryAfterError _ as e1 + SynExpr.Const _ as e2 + SynExpr.ArbitraryAfterError _ as e3 + SynExpr.Const _ as e4 + SynExpr.Const _ as e5 + SynExpr.ArbitraryAfterError _ as e6 + SynExpr.Const _ as e7 + SynExpr.ArbitraryAfterError _ as e8 ], c, _) ] -> + [ e1; e2; e3; e4; e5; e6; e7; e8 ] + |> checkExprOrder + + [ c, 7 ] |> checkRangeCountAndOrder + + | _ -> failwith "Unexpected tree" + +[] +let ``Expr - Tuple 05`` () = + let parseResults = getParseResults """ +(1, +""" + match getSingleModuleMemberDecls parseResults |> List.map getSingleParenInnerExpr with + | [ SynExpr.FromParseError(SynExpr.Tuple(_, [SynExpr.Const _; SynExpr.ArbitraryAfterError _], _, _), _) ] -> () + | _ -> failwith "Unexpected tree" + +[] +let ``Expr - Tuple 06`` () = + let parseResults = getParseResults """ +(1,,,2) +""" + let synExprs = getSingleModuleMemberDecls parseResults |> List.map getSingleParenInnerExpr + match synExprs with + | [ SynExpr.Tuple(_, [ SynExpr.Const _ + SynExpr.ArbitraryAfterError _ + SynExpr.ArbitraryAfterError _ + SynExpr.Const _ ], _, _) ] -> () + | _ -> failwith "Unexpected tree" + +[] +let ``Expr - Tuple 07`` () = + let parseResults = getParseResults """ +let x = 1, +""" + match getSingleModuleMemberDecls parseResults with + | [ SynModuleDecl.Let(_, [ (SynBinding(expr = expr)) ], range) ] -> + shouldEqual expr.Range.StartLine expr.Range.EndLine + shouldEqual range.StartLine range.EndLine + | _ -> failwith "Unexpected tree" diff --git a/tests/service/ProjectAnalysisTests.fs b/tests/service/ProjectAnalysisTests.fs index 00ae15bc4e1..3318cf40cf4 100644 --- a/tests/service/ProjectAnalysisTests.fs +++ b/tests/service/ProjectAnalysisTests.fs @@ -95,7 +95,7 @@ let mmmm2 : M.CAbbrev = new M.CAbbrev() // note, these don't count as uses of C let parsingOptions, _ = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) let cleanFileName a = if a = fileName1 then "file1" else if a = fileName2 then "file2" else "??" -[] +[] let ``Test project1 whole project errors`` () = let wholeProjectResults = checker.ParseAndCheckProject(Project1.options) |> Async.RunImmediate diff --git a/tests/service/ServiceUntypedParseTests.fs b/tests/service/ServiceUntypedParseTests.fs index 5678ac00c91..9917ec23d27 100644 --- a/tests/service/ServiceUntypedParseTests.fs +++ b/tests/service/ServiceUntypedParseTests.fs @@ -152,7 +152,7 @@ let rec getParenTypes (synType: SynType): SynType list = yield synType yield! getParenTypes innerType - | SynType.Fun (argType, returnType, _) -> + | SynType.Fun (argType = argType; returnType = returnType) -> yield! getParenTypes argType yield! getParenTypes returnType @@ -256,8 +256,7 @@ type T = with get () = x and set (value) = x <- value """ - getTypeMemberRange source |> shouldEqual [ (3, 4), (5, 36) - (3, 4), (5, 36) ] + getTypeMemberRange source |> shouldEqual [ (3, 4), (5, 36) ] [] diff --git a/tests/service/Symbols.fs b/tests/service/Symbols.fs index 968f25f572e..b6af2161a86 100644 --- a/tests/service/Symbols.fs +++ b/tests/service/Symbols.fs @@ -70,12 +70,12 @@ extern int private c() let (SynModuleOrNamespace (decls = decls)) = getSingleModuleLikeDecl parseResults.ParseTree [ None - Some SynAccess.Public - Some SynAccess.Private ] + Some "Public" + Some "Private" ] |> List.zip decls |> List.iter (fun (actual, expected) -> match actual with - | SynModuleDecl.Let (_, [SynBinding (accessibility = access)], _) -> access |> should equal expected + | SynModuleDecl.Let (_, [SynBinding (accessibility = access)], _) -> Option.map string access |> should equal expected | decl -> Assert.Fail (sprintf "unexpected decl: %O" decl)) [ "a", (true, false, false, false) @@ -361,4270 +361,3 @@ let tester2: int Group = [] |> should equal expectedTypeFormat | _ -> Assert.Fail (sprintf "Couldn't get member: %s" entityName) ) - - [] - let ``Single SynEnumCase contains range of constant`` () = - let parseResults = - getParseResults - """ -type Foo = One = 0x00000001 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [ - SynTypeDefn.SynTypeDefn(typeRepr = - SynTypeDefnRepr.Simple(simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ SynEnumCase.SynEnumCase(valueRange = r) ])))]) - ]) ])) -> - assertRange (2, 17) (2, 27) r - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Multiple SynEnumCase contains range of constant`` () = - let parseResults = - getParseResults - """ -type Foo = - | One = 0x00000001 - | Two = 2 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [ - SynTypeDefn.SynTypeDefn(typeRepr = - SynTypeDefnRepr.Simple(simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ SynEnumCase.SynEnumCase(valueRange = r1) - SynEnumCase.SynEnumCase(valueRange = r2) ])))]) - ]) ])) -> - assertRange (3, 13) (3, 23) r1 - assertRange (4, 12) (4, 13) r2 - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in SynTypeDefn`` () = - let parseResults = - getParseResults - """ -[] -type Bar = - class - end""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [t]) as types - ]) ])) -> - assertRange (2, 0) (5, 7) types.Range - assertRange (2, 0) (5, 7) t.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attributes should be included in recursive types`` () = - let parseResults = - getParseResults - """ -[] -type Foo<'context, 'a> = - | Apply of ApplyCrate<'context, 'a> - -and [] Bar<'context, 'a> = - internal { - Hash : int - Foo : Foo<'a, 'b> - }""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [t1;t2]) as types - ]) ])) -> - assertRange (2, 0) (10, 5) types.Range - assertRange (2, 0) (4, 39) t1.Range - assertRange (6, 4) (10, 5) t2.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with ObjectModel Delegate contains the range of the equals sign`` () = - let parseResults = - getParseResults - """ -type X = delegate of string -> string -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(kind = SynTypeDefnKind.Delegate _) - trivia={ EqualsRange = Some mEquals }) ] - ) - ]) ])) -> - assertRange (2, 7) (2, 8) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with ObjectModel class contains the range of the equals sign`` () = - let parseResults = - getParseResults - """ -type Foobar () = - class - end -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(kind = SynTypeDefnKind.Class) - trivia={ EqualsRange = Some mEquals }) ] - ) - ]) ])) -> - assertRange (2, 15) (2, 16) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with Enum contains the range of the equals sign`` () = - let parseResults = - getParseResults - """ -type Bear = - | BlackBear = 1 - | PolarBear = 2 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(simpleRepr = - SynTypeDefnSimpleRepr.Enum(cases = [ - SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase1 }) - SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase2 }) - ])) - trivia={ EqualsRange = Some mEquals }) ] - ) - ]) ])) -> - assertRange (2, 10) (2, 11) mEquals - assertRange (3, 16) (3, 17) mEqualsEnumCase1 - assertRange (4, 16) (4, 17) mEqualsEnumCase2 - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with Union contains the range of the equals sign`` () = - let parseResults = - getParseResults - """ -type Shape = - | Square of int - | Rectangle of int * int -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(simpleRepr = SynTypeDefnSimpleRepr.Union _) - trivia={ EqualsRange = Some mEquals }) ] - ) - ]) ])) -> - assertRange (2, 11) (2, 12) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with AutoProperty contains the range of the equals sign`` () = - let parseResults = - getParseResults - """ -/// mutable class with auto-properties -type Person(name : string, age : int) = - /// Full name - member val Name = name with get, set -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [_ ; SynMemberDefn.AutoProperty(equalsRange = mEquals)])) ] - ) - ]) ])) -> - assertRange (5, 20) (5, 21) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with Record contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Foo = - { Bar : int } - with - member this.Meh (v:int) = this.Bar + v -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr=SynTypeDefnRepr.Simple(simpleRepr= SynTypeDefnSimpleRepr.Record _) - trivia={ WithKeyword = Some mWithKeyword }) ] - ) - ]) ])) -> - assertRange (4, 4) (4, 8) mWithKeyword - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with Augmentation contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Int32 with - member _.Zero = 0 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(kind=SynTypeDefnKind.Augmentation mWithKeyword)) ] - ) - ]) ])) -> - assertRange (2, 11) (2, 15) mWithKeyword - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynMemberDefn.Interface contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Foo() = - interface Bar with - member Meh () = () - interface Other -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members=[ SynMemberDefn.ImplicitCtor _ - SynMemberDefn.Interface(withKeyword=Some mWithKeyword) - SynMemberDefn.Interface(withKeyword=None) ])) ] - ) - ]) ])) -> - assertRange (3, 18) (3, 22) mWithKeyword - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with AutoProperty contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Foo() = - member val AutoProperty = autoProp with get, set - member val AutoProperty2 = autoProp -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [_ - SynMemberDefn.AutoProperty(withKeyword=Some mWith) - SynMemberDefn.AutoProperty(withKeyword=None)])) ] - ) - ]) ])) -> - assertRange (3, 39) (3, 43) mWith - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with AbstractSlot contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Foo() = - abstract member Bar : int with get,set -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [_ - SynMemberDefn.AbstractSlot(slotSig=SynValSig(trivia = { WithKeyword = Some mWith }))])) ] - ) - ]) ])) -> - assertRange (3, 30) (3, 34) mWith - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``read-only property in SynMemberDefn.Member contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Foo() = - // A read-only property. - member this.MyReadProperty with get () = myInternalValue -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = - SynTypeDefnRepr.ObjectModel(members=[ _ - SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(propertyKeyword=Some(PropertyKeyword.With mWith)))) ]) - ) ]) - ]) ])) -> - assertRange (4, 31) (4, 35) mWith - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``write-only property in SynMemberDefn.Member contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Foo() = - // A write-only property. - member this.MyWriteOnlyProperty with set (value) = myInternalValue <- value -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = - SynTypeDefnRepr.ObjectModel(members=[ _ - SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(propertyKeyword=Some(PropertyKeyword.With mWith)))) ]) - ) ]) - ]) ])) -> - assertRange (4, 36) (4, 40) mWith - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``read/write property in SynMemberDefn.Member contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -type Foo() = - // A read-write property. - member this.MyReadWriteProperty - with get () = myInternalValue - and set (value) = myInternalValue <- value -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(typeRepr = - SynTypeDefnRepr.ObjectModel(members=[ _ - SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(propertyKeyword=Some(PropertyKeyword.With mWith)))) - SynMemberDefn.Member(memberDefn=SynBinding(headPat=SynPat.LongIdent(propertyKeyword=Some(PropertyKeyword.And mAnd)))) ]) - ) ]) - ]) ])) -> - assertRange (5, 8) (5, 12) mWith - assertRange (6, 8) (6, 11) mAnd - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with XmlDoc contains the range of the type keyword`` () = - let parseResults = - getParseResults - """ -/// Doc -// noDoc -type A = B -and C = D -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(trivia={ TypeKeyword = Some mType }) - SynTypeDefn(trivia={ TypeKeyword = None }) ] - ) - ]) ])) -> - assertRange (4, 0) (4, 4) mType - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefn with attribute contains the range of the type keyword`` () = - let parseResults = - getParseResults - """ -[] -// noDoc -type A = B -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types( - typeDefns = [ SynTypeDefn(trivia={ TypeKeyword = Some mType }) ] - ) - ]) ])) -> - assertRange (4, 0) (4, 4) mType - | _ -> Assert.Fail "Could not get valid AST" - -module SyntaxExpressions = - [] - let ``SynExpr.Do contains the range of the do keyword`` () = - let ast = """let a = - do - foobar - do! - foobarBang -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [ - SynBinding(expr = SynExpr.Sequential(expr1 = SynExpr.Do(_, doRange) ; expr2 = SynExpr.DoBang(_, doBangRange))) - ]) - ]) - ])) -> - assertRange (2, 4) (3, 14) doRange - assertRange (4, 4) (5, 18) doBangRange - | _ -> - Assert.Fail "Could not find SynExpr.Do" - - [] - let ``SynExpr.LetOrUseBang contains the range of the equals sign`` () = - let ast = - """ -comp { - let! x = y - and! z = someFunction () - return () -} -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.App(argExpr = - SynExpr.ComputationExpr(expr = - SynExpr.LetOrUseBang(trivia = { EqualsRange = Some mLetBangEquals } - andBangs = [ SynExprAndBang(trivia= { EqualsRange = mAndBangEquals }) ])))) - ]) - ])) -> - assertRange (3, 11) (3, 12) mLetBangEquals - assertRange (4, 11) (4, 12) mAndBangEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.Record contains the range of the equals sign in SynExprRecordField`` () = - let ast = - """ -{ V = v - X = // some comment - someLongFunctionCall - a - b - c } -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Record(recordFields = [ - SynExprRecordField(equalsRange = Some mEqualsV) - SynExprRecordField(equalsRange = Some mEqualsX) - ])) - ]) - ])) -> - assertRange (2, 4) (2, 5) mEqualsV - assertRange (3, 9) (3, 10) mEqualsX - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``inherit SynExpr.Record contains the range of the equals sign in SynExprRecordField`` () = - let ast = - """ -{ inherit Exception(msg); X = 1; } -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Record(baseInfo = Some _ ; recordFields = [ - SynExprRecordField(equalsRange = Some mEquals) - ])) - ]) - ])) -> - assertRange (2, 28) (2, 29) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``copy SynExpr.Record contains the range of the equals sign in SynExprRecordField`` () = - let ast = - """ -{ foo with - X - = - 12 } -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Record(copyInfo = Some _ ; recordFields = [ - SynExprRecordField(equalsRange = Some mEquals) - ])) - ]) - ])) -> - assertRange (4, 12) (4, 13) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.AnonRecord contains the range of the equals sign in the fields`` () = - let ast = - """ -{| X = 5 - Y = 6 - Z = 7 |} -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.AnonRecd(recordFields = [ - (_, Some mEqualsX, _) - (_, Some mEqualsY, _) - (_, Some mEqualsZ, _) - ])) - ]) - ])) -> - assertRange (2, 5) (2, 6) mEqualsX - assertRange (3, 8) (3, 9) mEqualsY - assertRange (4, 12) (4, 13) mEqualsZ - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.For contains the range of the equals sign`` () = - let ast = - """ -for i = 1 to 10 do - printf "%d " i -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.For(equalsRange = Some mEquals)) - ]) - ])) -> - assertRange (2, 6) (2, 7) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.TryWith contains the range of the try and with keyword`` () = - let ast = - """ -try - x -with -| ex -> y -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.TryWith(trivia={ TryKeyword = mTry; WithKeyword = mWith })) - ]) - ])) -> - assertRange (2, 0) (2, 3) mTry - assertRange (4, 0) (4, 4) mWith - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.TryFinally contains the range of the try and with keyword`` () = - let ast = - """ -try - x -finally - () -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.TryFinally(trivia={ TryKeyword = mTry; FinallyKeyword = mFinally })) - ]) - ])) -> - assertRange (2, 0) (2, 3) mTry - assertRange (4, 0) (4, 7) mFinally - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.Match contains the range of the match and with keyword`` () = - let ast = - """ -match x with -| y -> z -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Match(trivia = { MatchKeyword = mMatch; WithKeyword = mWith })) - ]) - ])) -> - assertRange (2, 0) (2, 5) mMatch - assertRange (2, 8) (2, 12) mWith - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.MatchBang contains the range of the match and with keyword`` () = - let ast = - """ -match! x with -| y -> z -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.MatchBang(trivia = { MatchBangKeyword = mMatch; WithKeyword = mWith })) - ]) - ])) -> - assertRange (2, 0) (2, 6) mMatch - assertRange (2, 9) (2, 13) mWith - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.ObjExpr contains the range of with keyword`` () = - let ast = - """ -{ new obj() with - member x.ToString() = "INotifyEnumerableInternal" - interface INotifyEnumerableInternal<'T> - interface IEnumerable<_> with - member x.GetEnumerator() = null } -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.ObjExpr(withKeyword=Some mWithObjExpr; extraImpls=[ SynInterfaceImpl(withKeyword=None); SynInterfaceImpl(withKeyword=Some mWithSynInterfaceImpl) ])) - ]) - ])) -> - assertRange (2, 12) (2, 16) mWithObjExpr - assertRange (5, 27) (5, 31) mWithSynInterfaceImpl - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.LetOrUse contains the range of in keyword`` () = - let ast = - getParseResults "let x = 1 in ()" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.LetOrUse(trivia={ InKeyword = Some mIn })) - ]) - ])) -> - assertRange (1, 10) (1, 12) mIn - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.LetOrUse with recursive binding contains the range of in keyword`` () = - let ast = - getParseResults """ -do - let rec f = () - and g = () in - () -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Do(expr = SynExpr.LetOrUse(bindings=[_;_]; trivia={ InKeyword = Some mIn }))) - ]) - ])) -> - assertRange (4, 15) (4, 17) mIn - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``nested SynExpr.LetOrUse contains the range of in keyword`` () = - let ast = - getParseResults """ -let f () = - let x = 1 in // the "in" keyword is available in F# - let y = 2 in - x + y -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [ - SynBinding(expr = - SynExpr.LetOrUse(bindings=[_]; trivia={ InKeyword = Some mIn }; body=SynExpr.LetOrUse(trivia={ InKeyword = Some mInnerIn }))) - ]) - ]) - ])) -> - assertRange (3, 14) (3, 16) mIn - assertRange (4, 14) (4, 16) mInnerIn - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.LetOrUse does not contain the range of in keyword`` () = - let ast = - getParseResults """ -do - let x = 1 - () -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Do(expr = SynExpr.LetOrUse(trivia={ InKeyword = None }))) - ]) - ])) -> - Assert.Pass() - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.LetOrUse where body expr starts with token of two characters does not contain the range of in keyword`` () = - let ast = - getParseResults """ -do - let e1 = e :?> Collections.DictionaryEntry - e1.Key, e1.Value -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Do(expr = SynExpr.LetOrUse(trivia={ InKeyword = None }))) - ]) - ])) -> - Assert.Pass() - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``global keyword as SynExpr`` () = - let ast = - getParseResults """ -global -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.LongIdent(longDotId = SynLongIdent([mangledGlobal], [], [Some (IdentTrivia.OriginalNotation "global")])) - )]) - ])) -> - Assert.AreEqual("`global`", mangledGlobal.idText) - Assert.Pass() - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExprRecordFields contain correct amount of trivia`` () = - let ast = - getParseResults """ - { JobType = EsriBoundaryImport - FileToImport = filePath - State = state - DryRun = args.DryRun } -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Record(recordFields = [ - SynExprRecordField(fieldName = (synLongIdent, _)) - _; _; _ - ])) - ]) - ])) -> - match synLongIdent.IdentsWithTrivia with - | [ _ ] -> Assert.Pass() - | idents -> Assert.Fail $"Expected a single SynIdent, got {idents}" - | _ -> Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``SynExpr.Dynamic does contain ident`` () = - let ast = - getParseResults "x?k" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Dynamic (_, _, SynExpr.Ident(idK) ,mDynamicExpr)) - ]) - ])) -> - Assert.AreEqual("k", idK.idText) - assertRange (1,0) (1, 3) mDynamicExpr - | _ -> Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``SynExpr.Dynamic does contain parentheses`` () = - let ast = - getParseResults "x?(g)" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.Dynamic (_, _, SynExpr.Paren(SynExpr.Ident(idG), lpr, Some rpr, mParen) ,mDynamicExpr)) - ]) - ])) -> - Assert.AreEqual("g", idG.idText) - assertRange (1, 2) (1,3) lpr - assertRange (1, 4) (1,5) rpr - assertRange (1, 2) (1,5) mParen - assertRange (1,0) (1, 5) mDynamicExpr - | _ -> Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``SynExpr.Set with SynExpr.Dynamic`` () = - let ast = - getParseResults "x?v <- 2" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Set( - SynExpr.Dynamic (_, _, SynExpr.Ident(idV) ,mDynamicExpr), - SynExpr.Const _, - mSetExpr - )) - ]) - ])) -> - Assert.AreEqual("v", idV.idText) - assertRange (1,0) (1, 3) mDynamicExpr - assertRange (1,0) (1, 8) mSetExpr - | _ -> Assert.Fail $"Could not get valid AST, got {ast}" - -module Strings = - let getBindingExpressionValue (parseResults: ParsedInput) = - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = modules)) -> - modules |> List.tryPick (fun (SynModuleOrNamespace (decls = decls)) -> - decls |> List.tryPick (fun decl -> - match decl with - | SynModuleDecl.Let (bindings = bindings) -> - bindings |> List.tryPick (fun binding -> - match binding with - | SynBinding.SynBinding (headPat=(SynPat.Named _|SynPat.As(_,SynPat.Named _,_)); expr=e) -> Some e - | _ -> None) - | _ -> None)) - | _ -> None - - let getBindingConstValue parseResults = - match getBindingExpressionValue parseResults with - | Some (SynExpr.Const(c,_)) -> Some c - | _ -> None - - [] - let ``SynConst.String with SynStringKind.Regular`` () = - let parseResults = - getParseResults - """ - let s = "yo" - """ - - match getBindingConstValue parseResults with - | Some (SynConst.String (_, kind, _)) -> kind |> should equal SynStringKind.Regular - | _ -> Assert.Fail "Couldn't find const" - - [] - let ``SynConst.String with SynStringKind.Verbatim`` () = - let parseResults = - getParseResults - """ - let s = @"yo" - """ - - match getBindingConstValue parseResults with - | Some (SynConst.String (_, kind, _)) -> kind |> should equal SynStringKind.Verbatim - | _ -> Assert.Fail "Couldn't find const" - - [] - let ``SynConst.String with SynStringKind.TripleQuote`` () = - let parseResults = - getParseResults - " - let s = \"\"\"yo\"\"\" - " - - match getBindingConstValue parseResults with - | Some (SynConst.String (_, kind, _)) -> kind |> should equal SynStringKind.TripleQuote - | _ -> Assert.Fail "Couldn't find const" - - [] - let ``SynConst.Bytes with SynByteStringKind.Regular`` () = - let parseResults = - getParseResults - """ -let bytes = "yo"B - """ - - match getBindingConstValue parseResults with - | Some (SynConst.Bytes (_, kind, _)) -> kind |> should equal SynByteStringKind.Regular - | _ -> Assert.Fail "Couldn't find const" - - [] - let ``SynConst.Bytes with SynByteStringKind.Verbatim`` () = - let parseResults = - getParseResults - """ -let bytes = @"yo"B - """ - - match getBindingConstValue parseResults with - | Some (SynConst.Bytes (_, kind, _)) -> kind |> should equal SynByteStringKind.Verbatim - | _ -> Assert.Fail "Couldn't find const" - - [] - let ``SynExpr.InterpolatedString with SynStringKind.TripleQuote`` () = - let parseResults = - getParseResults - " - let s = $\"\"\"yo {42}\"\"\" - " - - match getBindingExpressionValue parseResults with - | Some (SynExpr.InterpolatedString(_, kind, _)) -> kind |> should equal SynStringKind.TripleQuote - | _ -> Assert.Fail "Couldn't find const" - - [] - let ``SynExpr.InterpolatedString with SynStringKind.Regular`` () = - let parseResults = - getParseResults - """ - let s = $"yo {42}" - """ - - match getBindingExpressionValue parseResults with - | Some (SynExpr.InterpolatedString(_, kind, _)) -> kind |> should equal SynStringKind.Regular - | _ -> Assert.Fail "Couldn't find const" - - [] - let ``SynExpr.InterpolatedString with SynStringKind.Verbatim`` () = - let parseResults = - getParseResults - """ - let s = $@"Migrate notes of file ""{oldId}"" to new file ""{newId}""." - """ - - match getBindingExpressionValue parseResults with - | Some (SynExpr.InterpolatedString(_, kind, _)) -> kind |> should equal SynStringKind.Verbatim - | _ -> Assert.Fail "Couldn't find const" - -module SynModuleOrNamespace = - [] - let ``DeclaredNamespace range should start at namespace keyword`` () = - let parseResults = - getParseResults - """namespace TypeEquality - -/// A type for witnessing type equality between 'a and 'b -type Teq<'a, 'b> -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; range = r) ])) -> - assertRange (1, 0) (4, 8) r - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Multiple DeclaredNamespaces should have a range that starts at the namespace keyword`` () = - let parseResults = - getParseResults - """namespace TypeEquality - -/// A type for witnessing type equality between 'a and 'b -type Teq = class end - -namespace Foobar - -let x = 42 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; range = r1) - SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; range = r2) ])) -> - assertRange (1, 0) (4, 20) r1 - assertRange (6, 0) (8, 10) r2 - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``GlobalNamespace should start at namespace keyword`` () = - let parseResults = - getParseResults - """// foo -// bar -namespace global - -type X = int -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.GlobalNamespace; range = r) ])) -> - assertRange (3, 0) (5, 12) r - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Module range should start at first attribute`` () = - let parseResults = - getParseResults - """ -[< Foo >] -module Bar - -let s : string = "s" -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.NamedModule; range = r) ])) -> - assertRange (2, 0) (5, 20) r - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Module should contain module keyword`` () = - let parseResults = - getParseResults - """ -/// this file contains patches to the F# Compiler Service that have not yet made it into -/// published nuget packages. We source-copy them here to have a consistent location for our to-be-removed extensions - -module FsAutoComplete.FCSPatches - -open FSharp.Compiler.Syntax -open FSharp.Compiler.Text -open FsAutoComplete.UntypedAstUtils -open FSharp.Compiler.CodeAnalysis - -module internal SynExprAppLocationsImpl = - let a = 42 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.NamedModule; trivia = { ModuleKeyword = Some mModule; NamespaceKeyword = None }) ])) -> - assertRange (5, 0) (5, 6) mModule - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Namespace should contain namespace keyword`` () = - let parseResults = - getParseResults - """ -namespace Foo -module Bar = - let a = 42 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; trivia = { ModuleKeyword = None; NamespaceKeyword = Some mNamespace }) ])) -> - assertRange (2, 0) (2, 9) mNamespace - | _ -> Assert.Fail "Could not get valid AST" - -module SynConsts = - [] - let ``Measure contains the range of the constant`` () = - let parseResults = - getParseResults - """ -let n = 1.0m -let m = 7.000 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [ SynBinding.SynBinding(expr = SynExpr.Const(SynConst.Measure(constantRange = r1), _)) ]) - SynModuleDecl.Let(bindings = [ SynBinding.SynBinding(expr = SynExpr.Const(SynConst.Measure(constantRange = r2), _)) ]) - ]) ])) -> - assertRange (2, 8) (2, 12) r1 - assertRange (3, 8) (3, 13) r2 - | _ -> Assert.Fail "Could not get valid AST" - -module SynModuleOrNamespaceSig = - [] - let ``Range member returns range of SynModuleOrNamespaceSig`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace Foobar - -type Bar = | Bar of string * int -""" - - match parseResults with - | ParsedInput.SigFile(ParsedSigFileInput(modules = [ - SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.DeclaredNamespace) as singleModule - ])) -> - assertRange (2,0) (4,32) singleModule.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``GlobalNamespace should start at namespace keyword`` () = - let parseResults = - getParseResultsOfSignatureFile - """// foo -// bar -namespace global - -type Bar = | Bar of string * int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.GlobalNamespace; range = r) ])) -> - assertRange (3, 0) (5, 32) r - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Module range should start at first attribute`` () = - let parseResults = - getParseResultsOfSignatureFile - """ - [< Foo >] -module Bar - -val s : string -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig.SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.NamedModule; range = r) ])) -> - assertRange (2, 1) (5, 14) r - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Module should contain module keyword`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -module Bar - -val a: int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.NamedModule; trivia = { ModuleKeyword = Some mModule; NamespaceKeyword = None }) ])) -> - assertRange (2, 0) (2, 6) mModule - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Namespace should contain namespace keyword`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace Foo -module Bar = - val a: int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.DeclaredNamespace; trivia = { ModuleKeyword = None; NamespaceKeyword = Some mNamespace }) ])) -> - assertRange (2, 0) (2, 9) mNamespace - | _ -> Assert.Fail "Could not get valid AST" - -module SignatureTypes = - [] - let ``Range of Type should end at end keyword`` () = - let parseResults = - getParseResultsOfSignatureFile - """namespace GreatProjectThing - -type Meh = - class - end - - -// foo""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types(range = r)]) ])) -> - assertRange (3, 0) (5,11) r - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of SynTypeDefnSig record should end at last member`` () = - let parseResults = - getParseResultsOfSignatureFile - """namespace X -type MyRecord = - { Level: int } - member Score : unit -> int""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes)]) ])) -> - assertRange (2, 0) (4, 30) mTypes - assertRange (2, 5) (4, 30) mSynTypeDefnSig - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of SynTypeDefnSig object model should end at last member`` () = - let parseResults = - getParseResultsOfSignatureFile - """namespace X -type MyRecord = - class - end - member Score : unit -> int""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes)]) ])) -> - assertRange (2, 0) (5, 30) mTypes - assertRange (2, 5) (5, 30) mSynTypeDefnSig - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of SynTypeDefnSig delegate of should start from name`` () = - let parseResults = - getParseResultsOfSignatureFile - """namespace Y -type MyFunction = - delegate of int -> string""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes) ]) ])) -> - assertRange (2, 0) (3, 29) mTypes - assertRange (2, 5) (3, 29) mSynTypeDefnSig - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of SynTypeDefnSig simple should end at last val`` () = - let parseResults = - getParseResultsOfSignatureFile - """namespace Z -type SomeCollection with - val LastIndex : int - val SomeThingElse : int -> string""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes)]) ])) -> - assertRange (2, 0) (4, 37) mTypes - assertRange (2, 5) (4, 37) mSynTypeDefnSig - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in SynTypeDefnSig`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace SomeNamespace - -[] -type MyType = - class - end -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types(types = [SynTypeDefnSig.SynTypeDefnSig(range = r)]) as t]) ])) -> - assertRange (4, 0) (7, 7) r - assertRange (4, 0) (7, 7) t.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attributes should be included in recursive types`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace SomeNamespace - -type Foo = - | Bar - -and [] Bang = - internal - { - LongNameBarBarBarBarBarBarBar: int - } - override GetHashCode : unit -> int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([ - SynTypeDefnSig.SynTypeDefnSig(range = r1) - SynTypeDefnSig.SynTypeDefnSig(range = r2) - ], mTypes)]) ])) -> - assertRange (4, 5) (5, 9) r1 - assertRange (7, 4) (12, 42) r2 - assertRange (4, 0) (12, 42) mTypes - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in SynValSpfn and Member`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace SomeNamespace - -type FooType = - [] // ValSpfn - abstract x : int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ - SynModuleOrNamespaceSig(decls = - [ SynModuleSigDecl.Types(types = [ - SynTypeDefnSig.SynTypeDefnSig(typeRepr = - SynTypeDefnSigRepr.ObjectModel(memberSigs = [ - SynMemberSig.Member(range = mr; memberSig = SynValSig(range = mv)) ])) - ]) ]) ])) -> - assertRange (5, 4) (6, 20) mr - assertRange (5, 4) (6, 20) mv - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefnSig with ObjectModel Delegate contains the range of the equals sign`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace Foo - -type X = delegate of string -> string -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Types( - types = [ SynTypeDefnSig(equalsRange = Some mEquals - typeRepr = SynTypeDefnSigRepr.ObjectModel(kind = SynTypeDefnKind.Delegate _)) ] - ) - ]) ])) -> - assertRange (4, 7) (4, 8) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefnSig with ObjectModel class contains the range of the equals sign`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace SomeNamespace - -type Foobar = - class - end -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Types( - types = [ SynTypeDefnSig(equalsRange = Some mEquals - typeRepr = SynTypeDefnSigRepr.ObjectModel(kind = SynTypeDefnKind.Class)) ] - ) - ]) ])) -> - assertRange (4, 12) (4, 13) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefnSig with Enum contains the range of the equals sign`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace SomeNamespace - -type Bear = - | BlackBear = 1 - | PolarBear = 2 -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Types( - types = [ SynTypeDefnSig(equalsRange = Some mEquals - typeRepr = SynTypeDefnSigRepr.Simple(repr = - SynTypeDefnSimpleRepr.Enum(cases = [ - SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase1 }) - SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase2 }) - ]) )) ] - ) - ]) ])) -> - assertRange (4, 10) (4, 11) mEquals - assertRange (5, 16) (5, 17) mEqualsEnumCase1 - assertRange (6, 16) (6, 17) mEqualsEnumCase2 - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefnSig with Union contains the range of the equals sign`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace SomeNamespace - -type Shape = - | Square of int - | Rectangle of int * int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Types( - types = [ SynTypeDefnSig(equalsRange = Some mEquals - typeRepr = SynTypeDefnSigRepr.Simple(repr = SynTypeDefnSimpleRepr.Union _)) ] - ) - ]) ])) -> - assertRange (4, 11) (4, 12) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynTypeDefnSig should contains the range of the with keyword`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace X - -type Foo with - member Meh : unit -> unit -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules =[ SynModuleOrNamespaceSig(decls =[ - SynModuleSigDecl.Types( - types=[ SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.Simple _ - withKeyword=Some mWithKeyword) ] - ) - ]) ])) -> - assertRange (4, 9) (4, 13) mWithKeyword - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynExceptionSig should contains the range of the with keyword`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace X - -exception Foo with - member Meh : unit -> unit -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Exception( - exnSig=SynExceptionSig(withKeyword = Some mWithKeyword) - ) - ]) ])) -> - assertRange (4, 14) (4, 18) mWithKeyword - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``memberSig of SynMemberSig.Member should contains the range of the with keyword`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace X - -type Foo = - abstract member Bar : int with get,set -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Types( - types=[ SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.ObjectModel(memberSigs=[SynMemberSig.Member(memberSig=SynValSig(trivia = { WithKeyword = Some mWithKeyword }))])) ] - ) - ]) ])) -> - assertRange (5, 30) (5, 34) mWithKeyword - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in SynExceptionDefnRepr and SynExceptionSig`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -module internal FSharp.Compiler.ParseHelpers - -// The error raised by the parse_error_rich function, which is called by the parser engine -[] -exception SyntaxError of obj * range: range - - -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules=[ - SynModuleOrNamespaceSig(decls=[ - SynModuleSigDecl.Exception( - SynExceptionSig(exnRepr=SynExceptionDefnRepr(range=mSynExceptionDefnRepr); range=mSynExceptionSig), mException) - ] ) ])) -> - assertRange (5, 0) (6, 43) mSynExceptionDefnRepr - assertRange (5, 0) (6, 43) mSynExceptionSig - assertRange (5, 0) (6, 43) mException - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of members should be included in SynExceptionSig and SynModuleSigDecl.Exception`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -module internal FSharp.Compiler.ParseHelpers - -exception SyntaxError of obj * range: range with - member Meh : string -> int - -open Foo -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules=[ - SynModuleOrNamespaceSig(decls=[ - SynModuleSigDecl.Exception( - SynExceptionSig(exnRepr=SynExceptionDefnRepr(range=mSynExceptionDefnRepr); range=mSynExceptionSig), mException) - SynModuleSigDecl.Open _ - ] ) ])) -> - assertRange (4, 0) (4, 43) mSynExceptionDefnRepr - assertRange (4, 0) (5, 30) mSynExceptionSig - assertRange (4, 0) (5, 30) mException - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Val keyword is present in SynValSig`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -module Meh - -[] -// meh -val a : int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules=[ - SynModuleOrNamespaceSig(decls=[ - SynModuleSigDecl.Val(valSig = SynValSig(trivia = { ValKeyword = Some mVal })) - ] ) ])) -> - assertRange (6, 0) (6, 3) mVal - | _ -> Assert.Fail "Could not get valid AST" - -module SynMatchClause = - [] - let ``Range of single SynMatchClause`` () = - let parseResults = - getParseResults - """ -try - let content = tryDownloadFile url - Some content -with ex -> - Infrastructure.ReportWarning ex - None""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) - ]) ])) -> - assertRange (5, 5) (7, 8) range - assertRange (5, 5) (7, 8) clause.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of multiple SynMatchClause`` () = - let parseResults = - getParseResults - """ -try - let content = tryDownloadFile url - Some content -with -| ex -> - Infrastructure.ReportWarning ex - None -| exx -> - None""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = r1) as clause1 - SynMatchClause(range = r2) as clause2 ])) - ]) ])) -> - assertRange (6, 2) (8, 8) r1 - assertRange (6, 2) (8, 8) clause1.Range - - assertRange (9, 2) (10, 8) r2 - assertRange (9, 2) (10, 8) clause2.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of single SynMatchClause followed by bar`` () = - let parseResults = - getParseResults - """ -try - let content = tryDownloadFile url - Some content -with -| ex -> - () -| """ - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) - ]) ])) -> - assertRange (6, 2) (7, 6) range - assertRange (6, 2) (7, 6) clause.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of single SynMatchClause with missing body`` () = - let parseResults = - getParseResults - """ -try - let content = tryDownloadFile url - Some content -with -| ex ->""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) - ]) ])) -> - assertRange (6, 2) (6, 4) range - assertRange (6, 2) (6, 4) clause.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of single SynMatchClause with missing body and when expr`` () = - let parseResults = - getParseResults - """ -try - let content = tryDownloadFile url - Some content -with -| ex when (isNull ex) ->""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) - ]) ])) -> - assertRange (6, 2) (6, 21) range - assertRange (6, 2) (6, 21) clause.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of arrow in SynMatchClause`` () = - let parseResults = - getParseResults - """ -match foo with -| Bar bar -> ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ ArrowRange = Some mArrow }) ])) - ]) ])) -> - assertRange (3, 10) (3, 12) mArrow - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of arrow in SynMatchClause with when clause`` () = - let parseResults = - getParseResults - """ -match foo with -| Bar bar when (someCheck bar) -> ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ ArrowRange = Some mArrow }) ])) - ]) ])) -> - assertRange (3, 31) (3, 33) mArrow - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of bar in a single SynMatchClause in SynExpr.Match`` () = - let parseResults = - getParseResults - """ -match foo with -| Bar bar when (someCheck bar) -> ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ BarRange = Some mBar }) ])) - ]) ])) -> - assertRange (3, 0) (3, 1) mBar - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of bar in multiple SynMatchClauses in SynExpr.Match`` () = - let parseResults = - getParseResults - """ -match foo with -| Bar bar when (someCheck bar) -> () -| Far too -> near ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ BarRange = Some mBar1 }) - SynMatchClause(trivia={ BarRange = Some mBar2 }) ])) - ]) ])) -> - assertRange (3, 0) (3, 1) mBar1 - assertRange (4, 0) (4, 1) mBar2 - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of bar in a single SynMatchClause in SynExpr.TryWith`` () = - let parseResults = - getParseResults - """ -try - foo () -with -| exn -> ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(trivia={ BarRange = Some mBar }) ])) - ]) ])) -> - assertRange (5, 0) (5, 1) mBar - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``No range of bar in a single SynMatchClause in SynExpr.TryWith`` () = - let parseResults = - getParseResults - """ -try - foo () -with exn -> - // some comment - ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(trivia={ BarRange = None }) ])) - ]) ])) -> - Assert.Pass() - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of bar in a multiple SynMatchClauses in SynExpr.TryWith`` () = - let parseResults = - getParseResults - """ -try - foo () -with -| IOException as ioex -> - // some comment - () -| ex -> ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(trivia={ BarRange = Some mBar1 }) - SynMatchClause(trivia={ BarRange = Some mBar2 }) ])) - ]) ])) -> - assertRange (5, 0) (5, 1) mBar1 - assertRange (8, 0) (8, 1) mBar2 - | _ -> Assert.Fail "Could not get valid AST" - -module SourceIdentifiers = - [] - let ``__LINE__`` () = - let parseResults = - getParseResults - """ -__LINE__""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Const(SynConst.SourceIdentifier("__LINE__", "2", range), _)) - ]) ])) -> - assertRange (2, 0) (2, 8) range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``__SOURCE_DIRECTORY__`` () = - let parseResults = - getParseResults - """ -__SOURCE_DIRECTORY__""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Const(SynConst.SourceIdentifier("__SOURCE_DIRECTORY__", _, range), _)) - ]) ])) -> - assertRange (2, 0) (2, 20) range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``__SOURCE_FILE__`` () = - let parseResults = - getParseResults - """ -__SOURCE_FILE__""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Const(SynConst.SourceIdentifier("__SOURCE_FILE__", _, range), _)) - ]) ])) -> - assertRange (2, 0) (2, 15) range - | _ -> Assert.Fail "Could not get valid AST" - -module NestedModules = - - [] - let ``Range of attribute should be included in SynModuleSigDecl.NestedModule`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace SomeNamespace - -[] -module Nested = - val x : int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.NestedModule _ as nm - ]) as sigModule ])) -> - assertRange (4, 0) (6, 15) nm.Range - assertRange (2, 0) (6, 15) sigModule.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in SynModuleDecl.NestedModule`` () = - let parseResults = - getParseResults - """ -module TopLevel - -[] -module Nested = - ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.NestedModule _ as nm - ]) ])) -> - assertRange (4, 0) (6, 6) nm.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present`` () = - let parseResults = - getParseResults - """ -module X = - () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.NestedModule(trivia = { ModuleKeyword = Some mModule; EqualsRange = Some mEquals }) - ]) ])) -> - assertRange (2, 0) (2, 6) mModule - assertRange (2, 9) (2, 10) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present, signature file`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace Foo - -module X = - val bar : int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.NestedModule(trivia = { ModuleKeyword = Some mModule; EqualsRange = Some mEquals }) - ]) ])) -> - assertRange (4, 0) (4, 6) mModule - assertRange (4, 9) (4, 10) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of nested module in signature file should end at the last SynModuleSigDecl`` () = - let parseResults = - getParseResultsOfSignatureFile - """namespace Microsoft.FSharp.Core - -open System -open System.Collections.Generic -open Microsoft.FSharp.Core -open Microsoft.FSharp.Collections -open System.Collections - - -module Tuple = - - type Tuple<'T1,'T2,'T3,'T4> = - interface IStructuralEquatable - interface IStructuralComparable - interface IComparable - new : 'T1 * 'T2 * 'T3 * 'T4 -> Tuple<'T1,'T2,'T3,'T4> - member Item1 : 'T1 with get - member Item2 : 'T2 with get - member Item3 : 'T3 with get - member Item4 : 'T4 with get - - -module Choice = - - /// Helper types for active patterns with 6 choices. - [] - [] - type Choice<'T1,'T2,'T3,'T4,'T5,'T6> = - /// Choice 1 of 6 choices - | Choice1Of6 of 'T1 - /// Choice 2 of 6 choices - | Choice2Of6 of 'T2 - /// Choice 3 of 6 choices - | Choice3Of6 of 'T3 - /// Choice 4 of 6 choices - | Choice4Of6 of 'T4 - /// Choice 5 of 6 choices - | Choice5Of6 of 'T5 - /// Choice 6 of 6 choices - | Choice6Of6 of 'T6 - - - -/// Basic F# Operators. This module is automatically opened in all F# code. -[] -module Operators = - - type ``[,]``<'T> with - [] - /// Get the length of an array in the first dimension - member Length1 : int - [] - /// Get the length of the array in the second dimension - member Length2 : int - [] - /// Get the lower bound of the array in the first dimension - member Base1 : int - [] - /// Get the lower bound of the array in the second dimension - member Base2 : int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Open _ - SynModuleSigDecl.Open _ - SynModuleSigDecl.Open _ - SynModuleSigDecl.Open _ - SynModuleSigDecl.Open _ - SynModuleSigDecl.NestedModule(range=mTupleModule; moduleDecls=[ SynModuleSigDecl.Types([ - SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.ObjectModel(range=mTupleObjectModel); range=mTupleType) - ], mTupleTypes) ]) - SynModuleSigDecl.NestedModule(range=mChoiceModule) - SynModuleSigDecl.NestedModule(range=mOperatorsModule; moduleDecls=[ SynModuleSigDecl.Types([ - SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.Simple(range=mAugmentationSimple); range=mAugmentation) - ], mOperatorsTypes) ]) - ]) ])) -> - assertRange (10, 0) (20, 35) mTupleModule - assertRange (12, 4) (20, 35) mTupleTypes - assertRange (12, 9) (20, 35) mTupleType - assertRange (13, 8) (20, 35) mTupleObjectModel - assertRange (23, 0) (40, 25) mChoiceModule - assertRange (44, 0) (60, 26) mOperatorsModule - assertRange (48, 4) (60, 26) mOperatorsTypes - assertRange (48, 9) (60, 26) mAugmentation - assertRange (48, 9) (60, 26) mAugmentationSimple - | _ -> Assert.Fail "Could not get valid AST" - -module SynBindings = - [] - let ``Range of attribute should be included in SynModuleDecl.Let`` () = - let parseResults = - getParseResults - """ -[] -let a = 0""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(range = mb)]) as lt - ]) ])) -> - assertRange (2, 0) (3, 5) mb - assertRange (2, 0) (3, 9) lt.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute between let keyword and pattern should be included in SynModuleDecl.Let`` () = - let parseResults = - getParseResults - """ -let [] (A x) = 1""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(range = mb)]) as lt - ]) ])) -> - assertRange (2, 4) (2, 21) mb - assertRange (2, 0) (2, 25) lt.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in SynMemberDefn.LetBindings`` () = - let parseResults = - getParseResults - """ -type Bar = - [] - let x = 8""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.LetBindings(bindings = [SynBinding(range = mb)]) as m]))]) - ]) ])) -> - assertRange (3, 4) (4, 9) mb - assertRange (3, 4) (4, 13) m.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in SynMemberDefn.Member`` () = - let parseResults = - getParseResults - """ -type Bar = - [] - member this.Something () = ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.Member(memberDefn = SynBinding(range = mb)) as m]))]) - ]) ])) -> - assertRange (3, 4) (4, 28) mb - assertRange (3, 4) (4, 33) m.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in binding of SynExpr.ObjExpr`` () = - let parseResults = - getParseResults - """ -{ new System.Object() with - [] - member x.ToString() = "F#" }""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.ObjExpr(members = [SynMemberDefn.Member(memberDefn=SynBinding(range = mb))])) - ]) ])) -> - assertRange (3, 4) (4, 23) mb - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in constructor SynMemberDefn.Member`` () = - let parseResults = - getParseResults - """ -type Tiger = - [] - new () = ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.Member(memberDefn = SynBinding(range = mb)) as m]))]) - ]) ])) -> - assertRange (3, 4) (4, 10) mb - assertRange (3, 4) (4, 15) m.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in constructor SynMemberDefn.Member, optAsSpec`` () = - let parseResults = - getParseResults - """ -type Tiger = - [] - new () as tony = ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.Member(memberDefn = SynBinding(range = mb)) as m]))]) - ]) ])) -> - assertRange (3, 4) (4, 18) mb - assertRange (3, 4) (4, 23) m.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in secondary constructor`` () = - let parseResults = - getParseResults - """ -type T() = - new () = - T () - - internal new () = - T () - - [] - new () = - T ()""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ - SynMemberDefn.ImplicitCtor _ - SynMemberDefn.Member(memberDefn = SynBinding(range = mb1)) as m1 - SynMemberDefn.Member(memberDefn = SynBinding(range = mb2)) as m2 - SynMemberDefn.Member(memberDefn = SynBinding(range = mb3)) as m3 - ]))]) - ]) ])) -> - assertRange (3, 4) (3, 10) mb1 - assertRange (3, 4) (4, 12) m1.Range - assertRange (6, 4) (6, 19) mb2 - assertRange (6, 4) (7, 12) m2.Range - assertRange (9, 4) (10, 10) mb3 - assertRange (9, 4) (11, 12) m3.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in write only SynMemberDefn.Member property`` () = - let parseResults = - getParseResults - """ -type Crane = - [] - member this.MyWriteOnlyProperty with set (value) = myInternalValue <- value""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.Member(memberDefn = SynBinding(range = mb)) as m]))]) - ]) ])) -> - assertRange (3, 4) (4, 52) mb - assertRange (3, 4) (4, 79) m.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of attribute should be included in full SynMemberDefn.Member property`` () = - let parseResults = - getParseResults - """ -type Bird = - [] - member this.TheWord - with get () = myInternalValue - and set (value) = myInternalValue <- value""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ - SynMemberDefn.Member(memberDefn = SynBinding(range = mb1)) as getter - SynMemberDefn.Member(memberDefn = SynBinding(range = mb2)) as setter - ]))]) - ]) ])) -> - assertRange (3, 4) (5, 19) mb1 - assertRange (3, 4) (6, 50) getter.Range - assertRange (3, 4) (6, 23) mb2 - assertRange (3, 4) (6, 50) setter.Range - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in SynModuleDecl.Let binding`` () = - let parseResults = - getParseResults "let v = 12" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]) - ]) ])) -> - assertRange (1, 6) (1, 7) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in SynModuleDecl.Let binding, typed`` () = - let parseResults = - getParseResults "let v : int = 12" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]) - ]) ])) -> - assertRange (1, 12) (1, 13) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in local Let binding`` () = - let parseResults = - getParseResults - """ -do - let z = 2 - () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Do(expr = SynExpr.LetOrUse(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]))) - ]) ])) -> - assertRange (3, 10) (3, 11) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in local Let binding, typed`` () = - let parseResults = - getParseResults - """ -do - let z: int = 2 - () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.Do(expr = SynExpr.LetOrUse(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]))) - ]) ])) -> - assertRange (3, 15) (3, 16) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in member binding`` () = - let parseResults = - getParseResults - """ -type X() = - member this.Y = z -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ _; SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some mEquals }))]))]) - ]) ])) -> - assertRange (3, 18) (3, 19) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in member binding, with parameters`` () = - let parseResults = - getParseResults - """ -type X() = - member this.Y () = z -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ _; SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some mEquals }))]))]) - ]) ])) -> - assertRange (3, 21) (3, 22) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in member binding, with return type`` () = - let parseResults = - getParseResults - """ -type X() = - member this.Y () : string = z -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ _; SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some mEquals }))]))]) - ]) ])) -> - assertRange (3, 30) (3, 31) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of equal sign should be present in property`` () = - let parseResults = - getParseResults - """ -type Y() = - member this.MyReadWriteProperty - with get () = myInternalValue - and set (value) = myInternalValue <- value -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ - _ - SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some eqGetM })) - SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some eqSetM })) - ]))]) - ]) ])) -> - assertRange (4, 20) (4, 21) eqGetM - assertRange (5, 24) (5, 25) eqSetM - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of let keyword should be present in SynModuleDecl.Let binding`` () = - let parseResults = - getParseResults "let v = 12" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(trivia={ LetKeyword = Some mLet })]) - ]) ])) -> - assertRange (1, 0) (1, 3) mLet - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of let keyword should be present in SynModuleDecl.Let binding with attributes`` () = - let parseResults = - getParseResults """ -/// XmlDoc -[] -// some comment -let v = 12 -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(trivia={ LetKeyword = Some mLet })]) - ]) ])) -> - assertRange (5, 0) (5, 3) mLet - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Range of let keyword should be present in SynExpr.LetOrUse binding`` () = - let parseResults = - getParseResults """ -let a = - let b c = d - () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(expr=SynExpr.LetOrUse(bindings=[SynBinding(trivia={ LetKeyword = Some mLet })]))]) - ]) ])) -> - assertRange (3, 4) (3, 7) mLet - | _ -> Assert.Fail "Could not get valid AST" - -module ParsedHashDirective = - [] - let ``SourceIdentifier as ParsedHashDirectiveArgument`` () = - let parseResults = - getParseResults - "#I __SOURCE_DIRECTORY__" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.HashDirective(ParsedHashDirective("I", [ ParsedHashDirectiveArgument.SourceIdentifier(c,_,m) ] , _), _) - ]) ])) -> - Assert.AreEqual("__SOURCE_DIRECTORY__", c) - assertRange (1, 3) (1, 23) m - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Regular String as ParsedHashDirectiveArgument`` () = - let parseResults = - getParseResults - "#I \"/tmp\"" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.HashDirective(ParsedHashDirective("I", [ ParsedHashDirectiveArgument.String(v, SynStringKind.Regular, m) ] , _), _) - ]) ])) -> - Assert.AreEqual("/tmp", v) - assertRange (1, 3) (1, 9) m - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Verbatim String as ParsedHashDirectiveArgument`` () = - let parseResults = - getParseResults - "#I @\"C:\\Temp\"" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.HashDirective(ParsedHashDirective("I", [ ParsedHashDirectiveArgument.String(v, SynStringKind.Verbatim, m) ] , _), _) - ]) ])) -> - Assert.AreEqual("C:\\Temp", v) - assertRange (1, 3) (1, 13) m - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Triple quote String as ParsedHashDirectiveArgument`` () = - let parseResults = - getParseResults - "#nowarn \"\"\"40\"\"\"" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.HashDirective(ParsedHashDirective("nowarn", [ ParsedHashDirectiveArgument.String(v, SynStringKind.TripleQuote, m) ] , _), _) - ]) ])) -> - Assert.AreEqual("40", v) - assertRange (1, 8) (1, 16) m - | _ -> Assert.Fail "Could not get valid AST" - -module Lambdas = - [] - let ``Lambda with two parameters gives correct body`` () = - let parseResults = - getParseResults - "fun a b -> x" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(parsedData = Some([SynPat.Named _; SynPat.Named _], SynExpr.Ident ident)) - ) - ]) ])) -> - Assert.AreEqual("x", ident.idText) - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Lambda with wild card parameter gives correct body`` () = - let parseResults = - getParseResults - "fun a _ b -> x" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(parsedData = Some([SynPat.Named _; SynPat.Wild _; SynPat.Named _], SynExpr.Ident ident)) - ) - ]) ])) -> - Assert.AreEqual("x", ident.idText) - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Lambda with tuple parameter with wild card gives correct body`` () = - let parseResults = - getParseResults - "fun a (b, _) c -> x" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(parsedData = Some([SynPat.Named _; SynPat.Paren(SynPat.Tuple _,_); SynPat.Named _], SynExpr.Ident ident)) - ) - ]) ])) -> - Assert.AreEqual("x", ident.idText) - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Lambda with wild card that returns a lambda gives correct body`` () = - let parseResults = - getParseResults - "fun _ -> fun _ -> x" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(parsedData = Some([SynPat.Wild _], SynExpr.Lambda(parsedData = Some([SynPat.Wild _], SynExpr.Ident ident)))) - ) - ]) ])) -> - Assert.AreEqual("x", ident.idText) - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Simple lambda has arrow range`` () = - let parseResults = - getParseResults - "fun x -> x" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) - ) - ]) ])) -> - assertRange (1, 6) (1, 8) mArrow - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Multiline lambda has arrow range`` () = - let parseResults = - getParseResults - "fun x y z - -> - x * y * z" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) - ) - ]) ])) -> - assertRange (2, 28) (2, 30) mArrow - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Destructed lambda has arrow range`` () = - let parseResults = - getParseResults - "fun { X = x } -> x * 2" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) - ) - ]) ])) -> - assertRange (1, 14) (1, 16) mArrow - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Tuple in lambda has arrow range`` () = - let parseResults = - getParseResults - "fun (x, _) -> x * 3" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) - ) - ]) ])) -> - assertRange (1, 11) (1, 13) mArrow - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Complex arguments lambda has arrow range`` () = - let parseResults = - getParseResults - "fun (x, _) - ({ Y = h::_ }) - (SomePattern(z)) - -> - x * y + z" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) - ) - ]) ])) -> - assertRange (4, 4) (4, 6) mArrow - | _ -> Assert.Fail "Could not get valid AST" - -module IfThenElse = - [] - let ``If keyword in IfThenElse`` () = - let parseResults = - getParseResults - "if a then b" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = None }) - ) - ]) ])) -> - assertRange (1, 0) (1, 2) mIfKw - assertRange (1, 5) (1, 9) mThenKw - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Else keyword in simple IfThenElse`` () = - let parseResults = - getParseResults - "if a then b else c" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr =SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = Some mElse }) - ) - ]) ])) -> - assertRange (1, 0) (1, 2) mIfKw - assertRange (1, 5) (1, 9) mThenKw - assertRange (1, 12) (1, 16) mElse - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``If, Then and Else keyword on separate lines`` () = - let parseResults = - getParseResults - """ -if a -then b -else c""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = Some mElse }) - ) - ]) ])) -> - assertRange (2, 0) (2, 2) mIfKw - assertRange (3, 0) (3, 4) mThenKw - assertRange (4, 0) (4, 4) mElse - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Nested elif in IfThenElse`` () = - let parseResults = - getParseResults - """ -if a then - b -elif c then d""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif=false; ThenKeyword = mThenKw; ElseKeyword = None } - elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElif; IsElif = true }))) - ) - ]) ])) -> - assertRange (2, 0) (2, 2) mIfKw - assertRange (2, 5) (2, 9) mThenKw - assertRange (4, 0) (4, 4) mElif - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Nested else if in IfThenElse`` () = - let parseResults = - getParseResults - """ -if a then - b -else - if c then d""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = Some mElse } - elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElseIf; IsElif = false }))) - ) - ]) ])) -> - assertRange (2, 0) (2, 2) mIfKw - assertRange (2, 5) (2, 9) mThenKw - assertRange (4, 0) (4, 4) mElse - assertRange (5, 4) (5, 6) mElseIf - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Nested else if on the same line in IfThenElse`` () = - let parseResults = - getParseResults - """ -if a then - b -else if c then - d""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif=false; ThenKeyword = mThenKw; ElseKeyword = Some mElse } - elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElseIf; IsElif = false }))) - ) - ]) ])) -> - assertRange (2, 0) (2, 2) mIfKw - assertRange (2, 5) (2, 9) mThenKw - assertRange (4, 0) (4, 4) mElse - assertRange (4, 5) (4, 7) mElseIf - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Deeply nested IfThenElse`` () = - let parseResults = - getParseResults - """ -if a then - b -elif c then - d -else - if e then - f - else - g""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIf1; IsElif = false; ElseKeyword = None } - elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElif; IsElif = true; ElseKeyword = Some mElse1 } - elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mIf2; IsElif = false; ElseKeyword = Some mElse2 })))))) - ]) ])) -> - assertRange (2, 0) (2, 2) mIf1 - assertRange (4, 0) (4, 4) mElif - assertRange (6, 0) (6, 4) mElse1 - assertRange (7, 8) (7, 10) mIf2 - assertRange (9, 8) (9, 12) mElse2 - - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``Comment between else and if`` () = - let parseResults = - getParseResults - """ -if a then - b -else (* some long comment here *) if c then - d""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIf1; IsElif = false; ElseKeyword = Some mElse } - elseExpr = Some (SynExpr.IfThenElse(trivia = { IfKeyword = mIf2; IsElif = false })))) - ]) ])) -> - assertRange (2, 0) (2, 2) mIf1 - assertRange (4, 0) (4, 4) mElse - assertRange (4, 34) (4, 36) mIf2 - - | _ -> Assert.Fail "Could not get valid AST" - -module UnionCases = - [] - let ``Union Case fields can have comments`` () = - let ast = """ -type Foo = -/// docs for Thing -| Thing of - /// docs for first - first: string * - /// docs for anon field - bool -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ - SynUnionCase.SynUnionCase (caseType = SynUnionCaseKind.Fields [ - SynField.SynField(xmlDoc = firstXml) - SynField.SynField(xmlDoc = anonXml) - ]) - ]))) - ], _) - ]) - ])) -> - let firstDocs = firstXml.ToXmlDoc(false, None).GetXmlText() - let anonDocs = anonXml.ToXmlDoc(false, None).GetXmlText() - - let nl = Environment.NewLine - - Assert.AreEqual($"{nl} docs for first{nl}", firstDocs) - Assert.AreEqual($"{nl} docs for anon field{nl}", anonDocs) - - | _ -> - failwith "Could not find SynExpr.Do" - - [] - let ``single SynUnionCase has bar range`` () = - let ast = """ -type Foo = | Bar of string -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ - SynUnionCase.SynUnionCase (trivia = { BarRange = Some mBar }) - ]))) - ], _) - ]) - ])) -> - assertRange (2, 11) (2, 12) mBar - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``multiple SynUnionCases have bar range`` () = - let ast = """ -type Foo = - | Bar of string - | Bear of int -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ - SynUnionCase.SynUnionCase (trivia = { BarRange = Some mBar1 }) - SynUnionCase.SynUnionCase (trivia = { BarRange = Some mBar2 }) - ]))) - ], _) - ]) - ])) -> - assertRange (3, 4) (3, 5) mBar1 - assertRange (4, 4) (4, 5) mBar2 - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``single SynUnionCase without bar`` () = - let ast = """ -type Foo = Bar of string -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ - SynUnionCase.SynUnionCase (trivia = { BarRange = None }) - ]))) - ], _) - ]) - ])) -> - Assert.Pass() - | _ -> - Assert.Fail "Could not get valid AST" - -module EnumCases = - [] - let ``single SynEnumCase has bar range`` () = - let ast = """ -type Foo = | Bar = 1 -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ - SynEnumCase.SynEnumCase (trivia = { BarRange = Some mBar; EqualsRange = mEquals }) - ]))) - ], _) - ]) - ])) -> - assertRange (2, 11) (2, 12) mBar - assertRange (2, 17) (2, 18) mEquals - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``multiple SynEnumCases have bar range`` () = - let ast = """ -type Foo = - | Bar = 1 - | Bear = 2 -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ - SynEnumCase.SynEnumCase (trivia = { BarRange = Some mBar1; EqualsRange = mEquals1 }) - SynEnumCase.SynEnumCase (trivia = { BarRange = Some mBar2; EqualsRange = mEquals2 }) - ]))) - ], _) - ]) - ])) -> - assertRange (3, 4) (3, 5) mBar1 - assertRange (3, 10) (3, 11) mEquals1 - assertRange (4, 4) (4, 5) mBar2 - assertRange (4, 11) (4, 12) mEquals2 - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``single SynEnumCase without bar`` () = - let ast = """ -type Foo = Bar = 1 -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ - SynEnumCase.SynEnumCase (trivia = { BarRange = None; EqualsRange = mEquals }) - ]))) - ], _) - ]) - ])) -> - assertRange (2, 15) (2, 16) mEquals - | _ -> - Assert.Fail "Could not get valid AST" - -module Patterns = - [] - let ``SynPat.Record contains the range of the equals sign`` () = - let parseResults = - getParseResults - """ -match x with -| { Foo = bar } -> () -| _ -> () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Match(clauses = [ SynMatchClause(pat = SynPat.Record(fieldPats = [ (_, mEquals, _) ])) ; _ ]) - ) - ]) ])) -> - assertRange (3, 8) (3, 9) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynArgPats.NamePatPairs contains the range of the equals sign`` () = - let parseResults = - getParseResults - """ -match x with -| X(Y = y) -> y -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Match(clauses = [ SynMatchClause(pat = SynPat.LongIdent(argPats = SynArgPats.NamePatPairs(pats = [ _, mEquals ,_ ])))]) - ) - ]) ])) -> - assertRange (3, 7) (3, 8) mEquals - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynPat.Or contains the range of the bar`` () = - let parseResults = - getParseResults - """ -match x with -| A -| B -> () -| _ -> () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Match(clauses = [ SynMatchClause(pat = SynPat.Or(trivia={ BarRange = mBar })) ; _ ]) - ) - ]) ])) -> - assertRange (4, 0) (4, 1) mBar - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``:: operator in SynPat.LongIdent`` () = - let parseResults = - getParseResults - """ -let (head::tail) = [ 1;2;4] -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let( - bindings = [ SynBinding(headPat = SynPat.Paren(SynPat.LongIdent(longDotId = SynLongIdent([ opColonColonIdent ], _, [ Some (IdentTrivia.OriginalNotation "::") ])), _)) ] - ) - ]) ])) -> - Assert.AreEqual("op_ColonColon", opColonColonIdent.idText) - | _ -> Assert.Fail $"Could not get valid AST, got {parseResults}" - - [] - let ``:: operator in match pattern`` () = - let parseResults = - getParseResults - """ -match x with -| (head) :: (tail) -> () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Match(clauses = [ - SynMatchClause(pat = SynPat.LongIdent(longDotId = SynLongIdent([ opColonColonIdent ], _, [ Some (IdentTrivia.OriginalNotation "::") ]))) - ]) - ) - ]) ])) -> - Assert.AreEqual("op_ColonColon", opColonColonIdent.idText) - | _ -> Assert.Fail $"Could not get valid AST, got {parseResults}" - -module Exceptions = - [] - let ``SynExceptionDefn should contains the range of the with keyword`` () = - let parseResults = - getParseResults - """ -namespace X - -exception Foo with - member Meh () = () -""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace(decls = [ - SynModuleDecl.Exception( - exnDefn=SynExceptionDefn(withKeyword = Some mWithKeyword) - ) - ]) ])) -> - assertRange (4, 14) (4, 18) mWithKeyword - | _ -> Assert.Fail "Could not get valid AST" - -module SynMemberFlags = - [] - let ``SynMemberSig.Member has correct keywords`` () = - let parseResults = - getParseResultsOfSignatureFile - """ -namespace X - -type Y = - abstract A : int - abstract member B : double - static member C : string - member D : int - override E : int - default F : int -""" - - match parseResults with - | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Types(types =[ - SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.ObjectModel(memberSigs=[ - SynMemberSig.Member(flags={ Trivia= { AbstractRange = Some mAbstract1 } }) - SynMemberSig.Member(flags={ Trivia= { AbstractRange = Some mAbstract2 - MemberRange = Some mMember1 } }) - SynMemberSig.Member(flags={ Trivia= { StaticRange = Some mStatic3 - MemberRange = Some mMember3 } }) - SynMemberSig.Member(flags={ Trivia= { MemberRange = Some mMember4 } }) - SynMemberSig.Member(flags={ Trivia= { OverrideRange = Some mOverride5 } }) - SynMemberSig.Member(flags={ Trivia= { DefaultRange = Some mDefault6 } }) - ])) - ]) - ]) ])) -> - assertRange (5, 4) (5, 12) mAbstract1 - assertRange (6, 4) (6, 12) mAbstract2 - assertRange (6, 13) (6, 19) mMember1 - assertRange (7, 4) (7, 10) mStatic3 - assertRange (7, 11) (7, 17) mMember3 - assertRange (8, 4) (8, 10) mMember4 - assertRange (9, 4) (9, 12) mOverride5 - assertRange (10, 4) (10, 11) mDefault6 - | _ -> Assert.Fail "Could not get valid AST" - - [] - let ``SynMemberDefn.AbstractSlot has correct keyword`` () = - let ast = """ -type Foo = - abstract X : int - abstract member Y: int -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.ObjectModel (members=[ - SynMemberDefn.AbstractSlot(flags={ Trivia = { AbstractRange = Some mAbstract1 } }) - SynMemberDefn.AbstractSlot(flags={ Trivia = { AbstractRange = Some mAbstract2 - MemberRange = Some mMember2 } }) - ])) - ], _) - ]) - ])) -> - assertRange (3, 4) (3, 12) mAbstract1 - assertRange (4, 4) (4, 12) mAbstract2 - assertRange (4, 13) (4, 19) mMember2 - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``SynMemberDefn.AutoProperty has correct keyword`` () = - let ast = """ -type Foo = - static member val W : int = 1 - member val X : int = 1 - override val Y : int = 2 - default val Z : int = 1 -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.ObjectModel (members=[ - SynMemberDefn.AutoProperty(memberFlags= mkFlags1) - SynMemberDefn.AutoProperty(memberFlags= mkFlags2) - SynMemberDefn.AutoProperty(memberFlags= mkFlags3) - SynMemberDefn.AutoProperty(memberFlags= mkFlags4) - ])) - ], _) - ]) - ])) -> - let ({ Trivia = flagsTrivia1 } : SynMemberFlags) = mkFlags1 SynMemberKind.Member - assertRange (3, 4) (3, 10) flagsTrivia1.StaticRange.Value - assertRange (3, 11) (3, 17) flagsTrivia1.MemberRange.Value - - let ({ Trivia = flagsTrivia2 } : SynMemberFlags) = mkFlags2 SynMemberKind.Member - assertRange (4, 4) (4, 10) flagsTrivia2.MemberRange.Value - - let ({ Trivia = flagsTrivia3 } : SynMemberFlags) = mkFlags3 SynMemberKind.Member - assertRange (5, 4) (5, 12) flagsTrivia3.OverrideRange.Value - - let ({ Trivia = flagsTrivia4 } : SynMemberFlags) = mkFlags4 SynMemberKind.Member - assertRange (6, 4) (6, 11) flagsTrivia4.DefaultRange.Value - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``SynMemberDefn.Member SynValData has correct keyword`` () = - let ast = """ -type Foo = - static member this.B() = () - member this.A() = () - override this.C() = () - default this.D() = () -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types ([ - SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.ObjectModel (members=[ - SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { StaticRange = Some mStatic1 - MemberRange = Some mMember1 } }))) - SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { MemberRange = Some mMember2 } }))) - SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { OverrideRange = Some mOverride3 } }))) - SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { DefaultRange = Some mDefaultRange4 } }))) - ])) - ], _) - ]) - ])) -> - assertRange (3, 4) (3, 10) mStatic1 - assertRange (3, 11) (3, 17) mMember1 - assertRange (4, 4) (4, 10) mMember2 - assertRange (5, 4) (5, 12) mOverride3 - assertRange (6, 4) (6, 11) mDefaultRange4 - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``SynExpr.Obj members have correct keywords`` () = - let ast = """ -let meh = - { new Interface with - override this.Foo () = () - member this.Bar () = () - interface SomethingElse with - member this.Blah () = () } -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let (bindings = [ - SynBinding(expr=SynExpr.ObjExpr( - members=[ - SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { OverrideRange = Some mOverride1 } }))) - SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { MemberRange = Some mMember2 } }))) - ] - extraImpls=[ SynInterfaceImpl(members=[ - SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { MemberRange = Some mMember3 } }))) - ]) ])) - ]) - ]) ])) -> - assertRange (4, 8) (4, 16) mOverride1 - assertRange (5, 8) (5, 14) mMember2 - assertRange (7, 8) (7, 14) mMember3 - | _ -> - Assert.Fail "Could not get valid AST" - -module ComputationExpressions = - [] - let ``SynExprAndBang range starts at and! and ends after expression`` () = - let ast = - getParseResults """ -async { - let! bar = getBar () - - and! foo = getFoo () - - return bar -} -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr (expr = SynExpr.App(argExpr = SynExpr.ComputationExpr(expr = SynExpr.LetOrUseBang(andBangs = [ - SynExprAndBang(range = mAndBang) - ])))) - ]) - ])) -> - assertRange (5, 4) (5, 24) mAndBang - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``multiple SynExprAndBang have range that starts at and! and ends after expression`` () = - let ast = - getParseResults """ -async { - let! bar = getBar () - and! foo = getFoo () in - and! meh = getMeh () - return bar -} -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr (expr = SynExpr.App(argExpr = SynExpr.ComputationExpr(expr = SynExpr.LetOrUseBang(andBangs = [ - SynExprAndBang(range = mAndBang1; trivia={ InKeyword = Some mIn }) - SynExprAndBang(range = mAndBang2) - ])))) - ]) - ])) -> - assertRange (4, 4) (4, 24) mAndBang1 - assertRange (4, 25) (4, 27) mIn - assertRange (5, 4) (5, 24) mAndBang2 - | _ -> - Assert.Fail "Could not get valid AST" - -module ConditionalDirectives = - let private getDirectiveTrivia isSignatureFile source = - let ast = (if isSignatureFile then getParseResultsOfSignatureFile else getParseResults) source - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(trivia = { ConditionalDirectives = trivia })) - | ParsedInput.SigFile(ParsedSigFileInput(trivia = { ConditionalDirectives = trivia })) -> trivia - - [] - let ``single #if / #endif`` () = - let trivia = - getDirectiveTrivia false """ -let v = - #if DEBUG - () - #endif - 42 -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr, mIf) - ConditionalDirectiveTrivia.EndIf mEndif ] -> - assertRange (3, 4) (3, 13) mIf - assertRange (5, 4) (5, 10) mEndif - - match expr with - | IfDirectiveExpression.Ident "DEBUG" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``single #if / #else / #endif`` () = - let trivia = - getDirectiveTrivia false """ -let v = - #if DEBUG - 30 - #else - 42 - #endif -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr, mIf) - ConditionalDirectiveTrivia.Else mElse - ConditionalDirectiveTrivia.EndIf mEndif ] -> - assertRange (3, 4) (3, 13) mIf - assertRange (5, 4) (5, 9) mElse - assertRange (7, 4) (7, 10) mEndif - - match expr with - | IfDirectiveExpression.Ident "DEBUG" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``nested #if / #else / #endif`` () = - let trivia = - getDirectiveTrivia false """ -let v = - #if FOO - #if MEH - 1 - #else - 2 - #endif - #else - 3 - #endif -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr1, mIf1) - ConditionalDirectiveTrivia.If(expr2, mIf2) - ConditionalDirectiveTrivia.Else mElse1 - ConditionalDirectiveTrivia.EndIf mEndif1 - ConditionalDirectiveTrivia.Else mElse2 - ConditionalDirectiveTrivia.EndIf mEndif2 ] -> - assertRange (3, 4) (3, 11) mIf1 - assertRange (4, 8) (4, 15) mIf2 - assertRange (6, 8) (6, 13) mElse1 - assertRange (8, 8) (8, 14) mEndif1 - assertRange (9, 4) (9, 9) mElse2 - assertRange (11, 4) (11, 10) mEndif2 - - match expr1 with - | IfDirectiveExpression.Ident "FOO" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr1}" - - match expr2 with - | IfDirectiveExpression.Ident "MEH" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr2}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``nested #if / #endif with complex expressions`` () = - let trivia = - getDirectiveTrivia false """ -let v = - #if !DEBUG - #if FOO && BAR - #if MEH || HMM - printfn "oh some logging" - #endif - #endif - #endif -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr1, mIf1) - ConditionalDirectiveTrivia.If(expr2, mIf2) - ConditionalDirectiveTrivia.If(expr3, mIf3) - ConditionalDirectiveTrivia.EndIf mEndif1 - ConditionalDirectiveTrivia.EndIf mEndif2 - ConditionalDirectiveTrivia.EndIf mEndif3 ] -> - assertRange (3, 4) (3, 14) mIf1 - assertRange (4, 8) (4, 22) mIf2 - assertRange (5, 12) (5, 26) mIf3 - assertRange (7, 12) (7, 18) mEndif1 - assertRange (8, 8) (8, 14) mEndif2 - assertRange (9, 4) (9, 10) mEndif3 - - match expr1 with - | IfDirectiveExpression.Not (IfDirectiveExpression.Ident "DEBUG") -> () - | _ -> Assert.Fail $"Expected different expression, got {expr1}" - - match expr2 with - | IfDirectiveExpression.And(IfDirectiveExpression.Ident "FOO", IfDirectiveExpression.Ident "BAR") -> () - | _ -> Assert.Fail $"Expected different expression, got {expr2}" - - match expr3 with - | IfDirectiveExpression.Or(IfDirectiveExpression.Ident "MEH", IfDirectiveExpression.Ident "HMM") -> () - | _ -> Assert.Fail $"Expected different expression, got {expr3}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``directives in multiline comment are not reported as trivia`` () = - let trivia = - getDirectiveTrivia false """ -let v = -(* - #if DEBUG - () - #endif -*) - 42 -""" - - match trivia with - | [] -> Assert.Pass() - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``directives in multiline string are not reported as trivia`` () = - let trivia = - getDirectiveTrivia false " -let v = \"\"\" - #if DEBUG - () - #endif - 42 -\"\"\" -" - - match trivia with - | [] -> Assert.Pass() - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``single #if / #endif, signature file`` () = - let trivia = - getDirectiveTrivia true """ -namespace Foobar - -val v: int = - #if DEBUG - 1 - #endif - 42 -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr, mIf) - ConditionalDirectiveTrivia.EndIf mEndif ] -> - assertRange (5, 4) (5, 13) mIf - assertRange (7, 4) (7, 10) mEndif - - match expr with - | IfDirectiveExpression.Ident "DEBUG" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``single #if / #else / #endif, signature file`` () = - let trivia = - getDirectiveTrivia true """ -namespace Foobar - -val v : int = - #if DEBUG - 30 - #else - 42 - #endif -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr, mIf) - ConditionalDirectiveTrivia.Else mElse - ConditionalDirectiveTrivia.EndIf mEndif ] -> - assertRange (5, 4) (5, 13) mIf - assertRange (7, 4) (7, 9) mElse - assertRange (9, 4) (9, 10) mEndif - - match expr with - | IfDirectiveExpression.Ident "DEBUG" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``nested #if / #else / #endif, signature file`` () = - let trivia = - getDirectiveTrivia true """ -namespace Foobar - -val v : int = - #if FOO - #if MEH - 1 - #else - 2 - #endif - #else - 3 - #endif -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr1, mIf1) - ConditionalDirectiveTrivia.If(expr2, mIf2) - ConditionalDirectiveTrivia.Else mElse1 - ConditionalDirectiveTrivia.EndIf mEndif1 - ConditionalDirectiveTrivia.Else mElse2 - ConditionalDirectiveTrivia.EndIf mEndif2 ] -> - assertRange (5, 4) (5, 11) mIf1 - assertRange (6, 8) (6, 15) mIf2 - assertRange (8, 8) (8, 13) mElse1 - assertRange (10, 8) (10, 14) mEndif1 - assertRange (11, 4) (11, 9) mElse2 - assertRange (13, 4) (13, 10) mEndif2 - - match expr1 with - | IfDirectiveExpression.Ident "FOO" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr1}" - - match expr2 with - | IfDirectiveExpression.Ident "MEH" -> () - | _ -> Assert.Fail $"Expected different expression, got {expr2}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``nested #if / #endif with complex expressions, signature file`` () = - let trivia = - getDirectiveTrivia true """ -namespace Foobar - -val v : int = - #if !DEBUG - #if FOO && BAR - #if MEH || HMM - 9 - #endif - #endif - #endif - 10 -""" - - match trivia with - | [ ConditionalDirectiveTrivia.If(expr1, mIf1) - ConditionalDirectiveTrivia.If(expr2, mIf2) - ConditionalDirectiveTrivia.If(expr3, mIf3) - ConditionalDirectiveTrivia.EndIf mEndif1 - ConditionalDirectiveTrivia.EndIf mEndif2 - ConditionalDirectiveTrivia.EndIf mEndif3 ] -> - assertRange (5, 4) (5, 14) mIf1 - assertRange (6, 8) (6, 22) mIf2 - assertRange (7, 12) (7, 26) mIf3 - assertRange (9, 12) (9, 18) mEndif1 - assertRange (10, 8) (10, 14) mEndif2 - assertRange (11, 4) (11, 10) mEndif3 - - match expr1 with - | IfDirectiveExpression.Not (IfDirectiveExpression.Ident "DEBUG") -> () - | _ -> Assert.Fail $"Expected different expression, got {expr1}" - - match expr2 with - | IfDirectiveExpression.And(IfDirectiveExpression.Ident "FOO", IfDirectiveExpression.Ident "BAR") -> () - | _ -> Assert.Fail $"Expected different expression, got {expr2}" - - match expr3 with - | IfDirectiveExpression.Or(IfDirectiveExpression.Ident "MEH", IfDirectiveExpression.Ident "HMM") -> () - | _ -> Assert.Fail $"Expected different expression, got {expr3}" - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``directives in multiline comment are not reported as trivia, signature file`` () = - let trivia = - getDirectiveTrivia true """ -namespace Foobar - -val v : int = -(* - #if DEBUG - () - #endif -*) - 42 -""" - - match trivia with - | [] -> Assert.Pass() - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - - [] - let ``directives in multiline string are not reported as trivia, signature file`` () = - let trivia = - getDirectiveTrivia true " -namespace Foobar - -let v : string = \"\"\" - #if DEBUG - () - #endif - 42 -\"\"\" -" - - match trivia with - | [] -> Assert.Pass() - | _ -> - Assert.Fail $"Unexpected trivia, got {trivia}" - -module CodeComments = - let private getCommentTrivia isSignatureFile source = - let ast = (if isSignatureFile then getParseResultsOfSignatureFile else getParseResults) source - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(trivia = { CodeComments = trivia })) - | ParsedInput.SigFile(ParsedSigFileInput(trivia = { CodeComments = trivia })) -> trivia - - [] - let ``comment on single line`` () = - let trivia = - getCommentTrivia false """ -// comment! -foo() -""" - - match trivia with - | [ CommentTrivia.LineComment mComment ] -> - assertRange (2, 0) (2, 11) mComment - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``comment on single line, signature file`` () = - let trivia = - getCommentTrivia true """ -namespace Meh -// comment! -foo() -""" - - match trivia with - | [ CommentTrivia.LineComment mComment ] -> - assertRange (3, 0) (3, 11) mComment - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``comment after source code`` () = - let trivia = - getCommentTrivia false """ -foo() // comment! -""" - - match trivia with - | [ CommentTrivia.LineComment mComment ] -> - assertRange (2, 6) (2, 17) mComment - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``comment after source code, signature file`` () = - let trivia = - getCommentTrivia true """ -namespace Meh - -val foo : int // comment! -""" - - match trivia with - | [ CommentTrivia.LineComment mComment ] -> - assertRange (4, 14) (4, 25) mComment - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``block comment in source code`` () = - let trivia = - getCommentTrivia false """ -let a (* b *) c = c + 42 -""" - - match trivia with - | [ CommentTrivia.BlockComment mComment ] -> - assertRange (2, 6) (2, 13) mComment - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``block comment in source code, signature file`` () = - let trivia = - getCommentTrivia true """ -namespace Meh - -val a (* b *) : int -""" - - match trivia with - | [ CommentTrivia.BlockComment mComment ] -> - assertRange (4, 6) (4, 13) mComment - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``comment at end of file`` () = - let trivia = - getCommentTrivia false "x // y" - - match trivia with - | [ CommentTrivia.LineComment mComment ] -> - assertRange (1, 2) (1, 6) mComment - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``triple slash comment should not be captured`` () = - let trivia = - getCommentTrivia false """ -/// Some great documentation comment -let x = 0 -""" - - match trivia with - | [] -> - Assert.Pass() - | _ -> - Assert.Fail "Could not get valid AST" - - [] - let ``triple slash comment should be captured, if used in an invalid location`` () = - let trivia = - getCommentTrivia false """ -/// Valid xml doc -let x = - /// Some great documentation comment - - /// With a blank line in between - /// but on a while loop - while true do () - a + 1 -""" - - match trivia with - | [ CommentTrivia.LineComment m1 - CommentTrivia.LineComment m2 - CommentTrivia.LineComment m3 ] -> - assertRange (4, 4) (4, 40) m1 - assertRange (6, 4) (6, 36) m2 - assertRange (7, 4) (7, 27) m3 - | _ -> - Assert.Fail "Could not get valid AST" - -module OperatorName = - [] - let ``operator as function`` () = - let ast = """ -(+) 3 4 -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr (expr = SynExpr.App(funcExpr = SynExpr.App(funcExpr = - SynExpr.Paren(SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "+")])), lpr, Some rpr, pr)))) - ]) - ])) -> - assertRange (2, 0) (2, 1) lpr - Assert.AreEqual("op_Addition", ident.idText) - assertRange (2, 2) (2, 3) rpr - assertRange (2, 0) (2, 3) pr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``active pattern as function `` () = - let ast = """ -(|Odd|Even|) 4 -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr (expr = SynExpr.App(funcExpr = - SynExpr.Paren(SynExpr.Ident ident, lpr, Some rpr, pr))) - ]) - ])) -> - assertRange (2, 0) (2, 1) lpr - Assert.AreEqual("|Odd|Even|", ident.idText) - assertRange (2, 11) (2, 12) rpr - assertRange (2, 0) (2, 12) pr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``partial active pattern as function `` () = - let ast = """ -(|Odd|_|) 4 -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr (expr = SynExpr.App(funcExpr = - SynExpr.Paren(SynExpr.Ident ident, lpr, Some rpr, pr))) - ]) - ])) -> - assertRange (2, 0) (2, 1) lpr - Assert.AreEqual("|Odd|_|", ident.idText) - assertRange (2, 8) (2, 9) rpr - assertRange (2, 0) (2, 9) pr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``custom operator definition`` () = - let ast = """ -let (+) a b = a + b -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(headPat= - SynPat.LongIdent(longDotId = SynLongIdent([ ident ],_, [ Some (IdentTrivia.OriginalNotationWithParen(lpr, "+", rpr)) ]))) - ]) - ])])) -> - assertRange (2, 4) (2,5) lpr - Assert.AreEqual("op_Addition", ident.idText) - assertRange (2, 6) (2, 7) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``active pattern definition`` () = - let ast = """ -let (|Odd|Even|) (a: int) = if a % 2 = 0 then Even else Odd -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(headPat= - SynPat.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.HasParenthesis(lpr, rpr))]))) - ]) - ])])) -> - assertRange (2, 4) (2, 5) lpr - Assert.AreEqual("|Odd|Even|", ident.idText) - assertRange (2, 15) (2, 16) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``partial active pattern definition`` () = - let ast = """ -let (|Int32Const|_|) (a: SynConst) = match a with SynConst.Int32 _ -> Some a | _ -> None -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(headPat= - SynPat.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.HasParenthesis(lpr, rpr))]))) - ]) - ])])) -> - assertRange (2, 4) (2, 5) lpr - Assert.AreEqual("|Int32Const|_|", ident.idText) - assertRange (2, 19) (2, 20) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``partial active pattern definition without parameters`` () = - let ast = """ -let (|Boolean|_|) = Boolean.parse -""" - |> getParseResults - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [SynBinding(headPat= - SynPat.Named(ident = SynIdent(ident, Some (IdentTrivia.HasParenthesis(lpr, rpr))))) - ]) - ])])) -> - assertRange (2, 4) (2, 5) lpr - Assert.AreEqual("|Boolean|_|", ident.idText) - assertRange (2, 16) (2, 17) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - - [] - let ``operator name in SynValSig`` () = - let ast = """ -module IntrinsicOperators -val (&): e1: bool -> e2: bool -> bool -""" - |> getParseResultsOfSignatureFile - - match ast with - | ParsedInput.SigFile(ParsedSigFileInput(modules = [ - SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Val(valSig = SynValSig(ident = SynIdent(ident, Some (IdentTrivia.OriginalNotationWithParen(lpr, "&", rpr))) - ))]) - ])) -> - assertRange (3, 4) (3, 5) lpr - Assert.AreEqual("op_Amp", ident.idText) - assertRange (3, 6) (3, 7) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``operator name in val constraint`` () = - let ast = - getParseResultsOfSignatureFile """ - [] - module Operators - /// Overloaded unary negation. - /// - /// The value to negate. - /// - /// The result of the operation. - /// - /// - /// - val inline (~-): n: ^T -> ^T when ^T: (static member ( ~- ): ^T -> ^T) and default ^T: int -""" - - match ast with - | ParsedInput.SigFile(ParsedSigFileInput(modules = [ - SynModuleOrNamespaceSig(decls = [ - SynModuleSigDecl.Val(valSig = SynValSig(synType=SynType.WithGlobalConstraints(constraints=[ - SynTypeConstraint.WhereTyparSupportsMember(memberSig=SynMemberSig.Member(memberSig=SynValSig(ident = - SynIdent(ident, Some (IdentTrivia.OriginalNotationWithParen(lpr, "~-", rpr)))))) - SynTypeConstraint.WhereTyparDefaultsToType _ - ]))) - ]) - ])) -> - assertRange (12, 57) (12, 58) lpr - Assert.AreEqual("op_UnaryNegation", ident.idText) - assertRange (12, 62) (12, 63) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``named parameter`` () = - let ast = getParseResults """ -f(x=4) -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = SynExpr.App(argExpr = SynExpr.Paren(expr = SynExpr.App(funcExpr= - SynExpr.App(funcExpr= SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "=")]))))))) - ]) - ])) -> - Assert.AreEqual("op_Equality", ident.idText) - assertRange (2,3) (2,4) ident.idRange - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``infix operation`` () = - let ast = getParseResults """ -1 + 1 -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.App(funcExpr = SynExpr.App(isInfix = true - funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "+")])) - argExpr = SynExpr.Const(SynConst.Int32(1), _)) - argExpr = SynExpr.Const(SynConst.Int32(1), _))) - ]) - ])) -> - Assert.AreEqual("op_Addition", ident.idText) - assertRange (2,2) (2,3) ident.idRange - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``prefix operation`` () = - let ast = getParseResults """ -+ -86 -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.App(isInfix = false - funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "+")])) - argExpr = SynExpr.Const(SynConst.Int32(-86), _))) - ]) - ])) -> - Assert.AreEqual("op_UnaryPlus", ident.idText) - assertRange (2,0) (2,1) ident.idRange - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``prefix operation with two characters`` () = - let ast = getParseResults """ -%%arg -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.App(isInfix = false - funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "%%")])) - argExpr = SynExpr.Ident argIdent)) - ]) - ])) -> - Assert.AreEqual("op_SpliceUntyped", ident.idText) - assertRange (2,0) (2,2) ident.idRange - Assert.AreEqual("arg", argIdent.idText) - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``detect difference between compiled operators`` () = - let ast = getParseResults """ -(+) a b -op_Addition a b -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.App(funcExpr = SynExpr.App(isInfix = false - funcExpr = SynExpr.Paren(SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "+")])), lpr, Some rpr, pr) - argExpr = SynExpr.Ident a1) - argExpr = SynExpr.Ident b1)) - SynModuleDecl.Expr(expr = - SynExpr.App(funcExpr = SynExpr.App(isInfix = false - funcExpr = SynExpr.Ident op_Addition - argExpr = SynExpr.Ident a2) - argExpr = SynExpr.Ident b2) - ) - ]) - ])) -> - assertRange (2,0) (2,1) lpr - Assert.AreEqual("op_Addition", ident.idText) - assertRange (2,2) (2,3) rpr - assertRange (2,0) (2,3) pr - Assert.AreEqual("a", a1.idText) - Assert.AreEqual("b", b1.idText) - - Assert.AreEqual("op_Addition", op_Addition.idText) - Assert.AreEqual("a", a2.idText) - Assert.AreEqual("b", b2.idText) - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``operator in member definition`` () = - let ast = getParseResults """ -type X with - member _.(+) a b = a + b -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [ - SynTypeDefn(members = [ - SynMemberDefn.Member(memberDefn = SynBinding(headPat = SynPat.LongIdent(longDotId = - SynLongIdent([ _; operatorIdent ], [ mDot ], [ None; Some (IdentTrivia.OriginalNotationWithParen(lpr, "+", rpr)) ]) as lid))) - ]) - ] - ) - ]) - ])) -> - assertRange (3,12) (3,13) mDot - assertRange (3,13) (3,14) lpr - Assert.AreEqual("op_Addition", operatorIdent.idText) - assertRange (3,15) (3,16) rpr - assertRange (3,11) (3,15) lid.Range - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``nameof operator`` () = - let ast = getParseResults """ -nameof(+) -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.App(isInfix = false - funcExpr = SynExpr.Ident nameofIdent - argExpr = SynExpr.Paren( - SynExpr.LongIdent(longDotId = SynLongIdent([operatorIdent], _, [Some (IdentTrivia.OriginalNotation "+")])), - lpr, - Some rpr, - pr - ) - ) - ) - ]) - ])) -> - Assert.AreEqual("nameof", nameofIdent.idText) - assertRange (2,6) (2,7) lpr - Assert.AreEqual("op_Addition", operatorIdent.idText) - assertRange (2,8) (2,9) rpr - assertRange (2,6) (2,9) pr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``optional expression`` () = - let ast = getParseResults """ -f(?x = 7) -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr(expr = - SynExpr.App(isInfix = false - funcExpr = SynExpr.Ident f - argExpr = SynExpr.Paren( - SynExpr.App(funcExpr = SynExpr.App( - isInfix = true - funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([eqIdent], _, [Some (IdentTrivia.OriginalNotation "=")])) - argExpr = SynExpr.LongIdent(true, SynLongIdent([x], [], [None]), _, mOptional) - ) - argExpr = SynExpr.Const(SynConst.Int32 7, _)), lpr, Some rpr, pr))) - ]) - ])) -> - Assert.AreEqual("f", f.idText) - assertRange (2,1) (2,2) lpr - Assert.AreEqual("x", x.idText) - assertRange (2,3) (2, 4) mOptional - Assert.AreEqual("op_Equality", eqIdent.idText) - assertRange (2,8) (2,9) rpr - assertRange (2,1) (2,9) pr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``object model with two members`` () = - let ast = getParseResults """ -type X() = - let mutable allowInto = 0 - member _.AllowIntoPattern with get() = allowInto and set v = allowInto <- v -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [ - SynTypeDefn.SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members =[ - SynMemberDefn.ImplicitCtor _ - SynMemberDefn.LetBindings _ - SynMemberDefn.Member(memberDefn = SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = [ _ ; allowIntoPatternGet ]) - propertyKeyword = Some (PropertyKeyword.With mWith)))) - SynMemberDefn.Member(memberDefn = SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = [ _ ; allowIntoPatternSet ]) - propertyKeyword = Some (PropertyKeyword.And mAnd)))) - ])) - ]) - ]) - ])) -> - Assert.AreEqual("AllowIntoPattern", allowIntoPatternGet.idText) - assertRange (4, 30) (4, 34) mWith - Assert.AreEqual("AllowIntoPattern", allowIntoPatternSet.idText) - assertRange (4, 53) (4, 56) mAnd - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``qualified operator expression`` () = - let ast = getParseResults """ -let PowByte (x:byte) n = Checked.( * ) x -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Let(bindings = [ - SynBinding(expr = SynExpr.App(funcExpr = - SynExpr.LongIdent(longDotId = SynLongIdent([checkedIdent; operatorIdent], [mDot], [None; Some (IdentTrivia.OriginalNotationWithParen(lpr, "*", rpr))])))) - ]) - ]) - ])) -> - Assert.AreEqual("Checked", checkedIdent.idText) - assertRange (2, 32) (2, 33) mDot - assertRange (2, 33) (2, 34) lpr - Assert.AreEqual("op_Multiply", operatorIdent.idText) - assertRange (2, 37) (2, 38) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - - [] - let ``active pattern identifier in private member`` () = - let ast = getParseResults """ -type A() = - member private _.(| - A' - |) = (| - Lazy - |) -""" - - match ast with - | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ - SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Types(typeDefns = [ - SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ - SynMemberDefn.ImplicitCtor _ - SynMemberDefn.Member(memberDefn = SynBinding( - headPat = SynPat.LongIdent(longDotId = SynLongIdent([underscoreIdent; aQuoteIdent], [ mDot ], [ None; Some (IdentTrivia.HasParenthesis(lpr, rpr)) ])) - )) - ])) - ]) - ]) - ])) -> - () - Assert.AreEqual("_", underscoreIdent.idText) - Assert.AreEqual("|A'|", aQuoteIdent.idText) - assertRange (3, 21) (3, 22) lpr - assertRange (5, 5) (5, 6) rpr - | _ -> - Assert.Fail $"Could not get valid AST, got {ast}" - -module Measures = - [] - let ``SynMeasure.Paren has correct range`` () = - let parseResults = - getParseResults - """ -40u
-""" - - match parseResults with - | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ - SynModuleDecl.Expr( - expr = SynExpr.Const(SynConst.Measure(SynConst.UInt32 _, _, SynMeasure.Divide( - SynMeasure.Seq([ SynMeasure.Named([ hrIdent ], _) ], _), - SynMeasure.Seq([ SynMeasure.Paren(SynMeasure.Seq([ - SynMeasure.Named([ staffIdent ], _) - SynMeasure.Named([ weeksIdent ], _) - ], _) , mParen) ], _), - _) - ), _)) - ]) ])) -> - Assert.AreEqual("hr", hrIdent.idText) - Assert.AreEqual("staff", staffIdent.idText) - Assert.AreEqual("weeks", weeksIdent.idText) - assertRange (2, 9) (2, 22) mParen - | _ -> Assert.Fail $"Could not get valid AST, got {parseResults}" diff --git a/tests/service/SyntaxTreeTests/BindingTests.fs b/tests/service/SyntaxTreeTests/BindingTests.fs new file mode 100644 index 00000000000..b8f8ed54bfd --- /dev/null +++ b/tests/service/SyntaxTreeTests/BindingTests.fs @@ -0,0 +1,368 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.BindingTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``Range of attribute should be included in SynModuleDecl.Let`` () = + let parseResults = + getParseResults + """ +[] +let a = 0""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(range = mb)]) as lt + ]) ])) -> + assertRange (2, 0) (3, 5) mb + assertRange (2, 0) (3, 9) lt.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute between let keyword and pattern should be included in SynModuleDecl.Let`` () = + let parseResults = + getParseResults + """ +let [] (A x) = 1""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(range = mb)]) as lt + ]) ])) -> + assertRange (2, 4) (2, 21) mb + assertRange (2, 0) (2, 25) lt.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in SynMemberDefn.LetBindings`` () = + let parseResults = + getParseResults + """ +type Bar = + [] + let x = 8""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.LetBindings(bindings = [SynBinding(range = mb)]) as m]))]) + ]) ])) -> + assertRange (3, 4) (4, 9) mb + assertRange (3, 4) (4, 13) m.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in SynMemberDefn.Member`` () = + let parseResults = + getParseResults + """ +type Bar = + [] + member this.Something () = ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.Member(memberDefn = SynBinding(range = mb)) as m]))]) + ]) ])) -> + assertRange (3, 4) (4, 28) mb + assertRange (3, 4) (4, 33) m.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in binding of SynExpr.ObjExpr`` () = + let parseResults = + getParseResults + """ +{ new System.Object() with + [] + member x.ToString() = "F#" }""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.ObjExpr(members = [SynMemberDefn.Member(memberDefn=SynBinding(range = mb))])) + ]) ])) -> + assertRange (3, 4) (4, 23) mb + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in constructor SynMemberDefn.Member`` () = + let parseResults = + getParseResults + """ +type Tiger = + [] + new () = ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.Member(memberDefn = SynBinding(range = mb)) as m]))]) + ]) ])) -> + assertRange (3, 4) (4, 10) mb + assertRange (3, 4) (4, 15) m.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in constructor SynMemberDefn.Member, optAsSpec`` () = + let parseResults = + getParseResults + """ +type Tiger = + [] + new () as tony = ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [SynMemberDefn.Member(memberDefn = SynBinding(range = mb)) as m]))]) + ]) ])) -> + assertRange (3, 4) (4, 18) mb + assertRange (3, 4) (4, 23) m.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in secondary constructor`` () = + let parseResults = + getParseResults + """ +type T() = + new () = + T () + + internal new () = + T () + + [] + new () = + T ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ + SynMemberDefn.ImplicitCtor _ + SynMemberDefn.Member(memberDefn = SynBinding(range = mb1)) as m1 + SynMemberDefn.Member(memberDefn = SynBinding(range = mb2)) as m2 + SynMemberDefn.Member(memberDefn = SynBinding(range = mb3)) as m3 + ]))]) + ]) ])) -> + assertRange (3, 4) (3, 10) mb1 + assertRange (3, 4) (4, 12) m1.Range + assertRange (6, 4) (6, 19) mb2 + assertRange (6, 4) (7, 12) m2.Range + assertRange (9, 4) (10, 10) mb3 + assertRange (9, 4) (11, 12) m3.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in write only SynMemberDefn.Member property`` () = + let parseResults = + getParseResults + """ +type Crane = + [] + member this.MyWriteOnlyProperty with set (value) = myInternalValue <- value""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = + [SynMemberDefn.GetSetMember(memberDefnForSet = Some (SynBinding(range = mb))) as m]))]) + ]) ])) -> + assertRange (3, 4) (4, 52) mb + assertRange (3, 4) (4, 79) m.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in full SynMemberDefn.Member property`` () = + let parseResults = + getParseResults + """ +type Bird = + [] + member this.TheWord + with get () = myInternalValue + and set (value) = myInternalValue <- value""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ + SynMemberDefn.GetSetMember(Some (SynBinding(range = mb1)), Some (SynBinding(range = mb2)), m, _) + ]))]) + ]) ])) -> + assertRange (3, 4) (5, 19) mb1 + assertRange (3, 4) (6, 23) mb2 + assertRange (3, 4) (6, 50) m + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in SynModuleDecl.Let binding`` () = + let parseResults = + getParseResults "let v = 12" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]) + ]) ])) -> + assertRange (1, 6) (1, 7) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in SynModuleDecl.Let binding, typed`` () = + let parseResults = + getParseResults "let v : int = 12" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]) + ]) ])) -> + assertRange (1, 12) (1, 13) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in local Let binding`` () = + let parseResults = + getParseResults + """ +do + let z = 2 + () +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Do(expr = SynExpr.LetOrUse(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]))) + ]) ])) -> + assertRange (3, 10) (3, 11) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in local Let binding, typed`` () = + let parseResults = + getParseResults + """ +do + let z: int = 2 + () +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Do(expr = SynExpr.LetOrUse(bindings = [SynBinding(trivia={ EqualsRange = Some mEquals })]))) + ]) ])) -> + assertRange (3, 15) (3, 16) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in member binding`` () = + let parseResults = + getParseResults + """ +type X() = + member this.Y = z +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ _; SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some mEquals }))]))]) + ]) ])) -> + assertRange (3, 18) (3, 19) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in member binding, with parameters`` () = + let parseResults = + getParseResults + """ +type X() = + member this.Y () = z +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ _; SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some mEquals }))]))]) + ]) ])) -> + assertRange (3, 21) (3, 22) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in member binding, with return type`` () = + let parseResults = + getParseResults + """ +type X() = + member this.Y () : string = z +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ _; SynMemberDefn.Member(memberDefn = SynBinding(trivia={ EqualsRange = Some mEquals }))]))]) + ]) ])) -> + assertRange (3, 30) (3, 31) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present in property`` () = + let parseResults = + getParseResults + """ +type Y() = + member this.MyReadWriteProperty + with get () = myInternalValue + and set (value) = myInternalValue <- value +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ + _ + SynMemberDefn.GetSetMember( + Some(SynBinding(trivia={ EqualsRange = Some eqGetM })), + Some(SynBinding(trivia={ EqualsRange = Some eqSetM })), _, _) + ]))]) + ]) ])) -> + assertRange (4, 20) (4, 21) eqGetM + assertRange (5, 24) (5, 25) eqSetM + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of let keyword should be present in SynModuleDecl.Let binding`` () = + let parseResults = + getParseResults "let v = 12" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(trivia={ LetKeyword = Some mLet })]) + ]) ])) -> + assertRange (1, 0) (1, 3) mLet + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of let keyword should be present in SynModuleDecl.Let binding with attributes`` () = + let parseResults = + getParseResults """ +/// XmlDoc +[] +// some comment +let v = 12 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(trivia={ LetKeyword = Some mLet })]) + ]) ])) -> + assertRange (5, 0) (5, 3) mLet + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of let keyword should be present in SynExpr.LetOrUse binding`` () = + let parseResults = + getParseResults """ +let a = + let b c = d + () +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(expr=SynExpr.LetOrUse(bindings=[SynBinding(trivia={ LetKeyword = Some mLet })]))]) + ]) ])) -> + assertRange (3, 4) (3, 7) mLet + | _ -> Assert.Fail "Could not get valid AST" diff --git a/tests/service/SyntaxTreeTests/CodeCommentTests.fs b/tests/service/SyntaxTreeTests/CodeCommentTests.fs new file mode 100644 index 00000000000..ce25783eecf --- /dev/null +++ b/tests/service/SyntaxTreeTests/CodeCommentTests.fs @@ -0,0 +1,146 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.CodeCommentTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.SyntaxTrivia +open NUnit.Framework + +let private getCommentTrivia isSignatureFile source = + let ast = (if isSignatureFile then getParseResultsOfSignatureFile else getParseResults) source + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(trivia = { CodeComments = trivia })) + | ParsedInput.SigFile(ParsedSigFileInput(trivia = { CodeComments = trivia })) -> trivia + +[] +let ``comment on single line`` () = + let trivia = + getCommentTrivia false """ +// comment! +foo() +""" + + match trivia with + | [ CommentTrivia.LineComment mComment ] -> + assertRange (2, 0) (2, 11) mComment + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``comment on single line, signature file`` () = + let trivia = + getCommentTrivia true """ +namespace Meh +// comment! +foo() +""" + + match trivia with + | [ CommentTrivia.LineComment mComment ] -> + assertRange (3, 0) (3, 11) mComment + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``comment after source code`` () = + let trivia = + getCommentTrivia false """ +foo() // comment! +""" + + match trivia with + | [ CommentTrivia.LineComment mComment ] -> + assertRange (2, 6) (2, 17) mComment + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``comment after source code, signature file`` () = + let trivia = + getCommentTrivia true """ +namespace Meh + +val foo : int // comment! +""" + + match trivia with + | [ CommentTrivia.LineComment mComment ] -> + assertRange (4, 14) (4, 25) mComment + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``block comment in source code`` () = + let trivia = + getCommentTrivia false """ +let a (* b *) c = c + 42 +""" + + match trivia with + | [ CommentTrivia.BlockComment mComment ] -> + assertRange (2, 6) (2, 13) mComment + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``block comment in source code, signature file`` () = + let trivia = + getCommentTrivia true """ +namespace Meh + +val a (* b *) : int +""" + + match trivia with + | [ CommentTrivia.BlockComment mComment ] -> + assertRange (4, 6) (4, 13) mComment + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``comment at end of file`` () = + let trivia = + getCommentTrivia false "x // y" + + match trivia with + | [ CommentTrivia.LineComment mComment ] -> + assertRange (1, 2) (1, 6) mComment + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``triple slash comment should not be captured`` () = + let trivia = + getCommentTrivia false """ +/// Some great documentation comment +let x = 0 +""" + + match trivia with + | [] -> + Assert.Pass() + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``triple slash comment should be captured, if used in an invalid location`` () = + let trivia = + getCommentTrivia false """ +/// Valid xml doc +let x = + /// Some great documentation comment + + /// With a blank line in between + /// but on a while loop + while true do () + a + 1 +""" + + match trivia with + | [ CommentTrivia.LineComment m1 + CommentTrivia.LineComment m2 + CommentTrivia.LineComment m3 ] -> + assertRange (4, 4) (4, 40) m1 + assertRange (6, 4) (6, 36) m2 + assertRange (7, 4) (7, 27) m3 + | _ -> + Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/ComputationExpressionTests.fs b/tests/service/SyntaxTreeTests/ComputationExpressionTests.fs new file mode 100644 index 00000000000..5a1de7621bd --- /dev/null +++ b/tests/service/SyntaxTreeTests/ComputationExpressionTests.fs @@ -0,0 +1,57 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.ComputationExpressionTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``SynExprAndBang range starts at and! and ends after expression`` () = + let ast = + getParseResults """ +async { + let! bar = getBar () + + and! foo = getFoo () + + return bar +} +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr (expr = SynExpr.App(argExpr = SynExpr.ComputationExpr(expr = SynExpr.LetOrUseBang(andBangs = [ + SynExprAndBang(range = mAndBang) + ])))) + ]) + ])) -> + assertRange (5, 4) (5, 24) mAndBang + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``multiple SynExprAndBang have range that starts at and! and ends after expression`` () = + let ast = + getParseResults """ +async { + let! bar = getBar () + and! foo = getFoo () in + and! meh = getMeh () + return bar +} +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr (expr = SynExpr.App(argExpr = SynExpr.ComputationExpr(expr = SynExpr.LetOrUseBang(andBangs = [ + SynExprAndBang(range = mAndBang1; trivia={ InKeyword = Some mIn }) + SynExprAndBang(range = mAndBang2) + ])))) + ]) + ])) -> + assertRange (4, 4) (4, 24) mAndBang1 + assertRange (4, 25) (4, 27) mIn + assertRange (5, 4) (5, 24) mAndBang2 + | _ -> + Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/ConditionalDirectiveTests.fs b/tests/service/SyntaxTreeTests/ConditionalDirectiveTests.fs new file mode 100644 index 00000000000..b48262d370b --- /dev/null +++ b/tests/service/SyntaxTreeTests/ConditionalDirectiveTests.fs @@ -0,0 +1,357 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.ConditionalDirectiveTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.SyntaxTrivia +open NUnit.Framework + +let private getDirectiveTrivia isSignatureFile source = + let ast = (if isSignatureFile then getParseResultsOfSignatureFile else getParseResults) source + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(trivia = { ConditionalDirectives = trivia })) + | ParsedInput.SigFile(ParsedSigFileInput(trivia = { ConditionalDirectives = trivia })) -> trivia + +[] +let ``single #if / #endif`` () = + let trivia = + getDirectiveTrivia false """ +let v = + #if DEBUG + () + #endif + 42 +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr, mIf) + ConditionalDirectiveTrivia.EndIf mEndif ] -> + assertRange (3, 4) (3, 13) mIf + assertRange (5, 4) (5, 10) mEndif + + match expr with + | IfDirectiveExpression.Ident "DEBUG" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``single #if / #else / #endif`` () = + let trivia = + getDirectiveTrivia false """ +let v = + #if DEBUG + 30 + #else + 42 + #endif +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr, mIf) + ConditionalDirectiveTrivia.Else mElse + ConditionalDirectiveTrivia.EndIf mEndif ] -> + assertRange (3, 4) (3, 13) mIf + assertRange (5, 4) (5, 9) mElse + assertRange (7, 4) (7, 10) mEndif + + match expr with + | IfDirectiveExpression.Ident "DEBUG" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``nested #if / #else / #endif`` () = + let trivia = + getDirectiveTrivia false """ +let v = + #if FOO + #if MEH + 1 + #else + 2 + #endif + #else + 3 + #endif +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr1, mIf1) + ConditionalDirectiveTrivia.If(expr2, mIf2) + ConditionalDirectiveTrivia.Else mElse1 + ConditionalDirectiveTrivia.EndIf mEndif1 + ConditionalDirectiveTrivia.Else mElse2 + ConditionalDirectiveTrivia.EndIf mEndif2 ] -> + assertRange (3, 4) (3, 11) mIf1 + assertRange (4, 8) (4, 15) mIf2 + assertRange (6, 8) (6, 13) mElse1 + assertRange (8, 8) (8, 14) mEndif1 + assertRange (9, 4) (9, 9) mElse2 + assertRange (11, 4) (11, 10) mEndif2 + + match expr1 with + | IfDirectiveExpression.Ident "FOO" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr1}" + + match expr2 with + | IfDirectiveExpression.Ident "MEH" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr2}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``nested #if / #endif with complex expressions`` () = + let trivia = + getDirectiveTrivia false """ +let v = + #if !DEBUG + #if FOO && BAR + #if MEH || HMM + printfn "oh some logging" + #endif + #endif + #endif +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr1, mIf1) + ConditionalDirectiveTrivia.If(expr2, mIf2) + ConditionalDirectiveTrivia.If(expr3, mIf3) + ConditionalDirectiveTrivia.EndIf mEndif1 + ConditionalDirectiveTrivia.EndIf mEndif2 + ConditionalDirectiveTrivia.EndIf mEndif3 ] -> + assertRange (3, 4) (3, 14) mIf1 + assertRange (4, 8) (4, 22) mIf2 + assertRange (5, 12) (5, 26) mIf3 + assertRange (7, 12) (7, 18) mEndif1 + assertRange (8, 8) (8, 14) mEndif2 + assertRange (9, 4) (9, 10) mEndif3 + + match expr1 with + | IfDirectiveExpression.Not (IfDirectiveExpression.Ident "DEBUG") -> () + | _ -> Assert.Fail $"Expected different expression, got {expr1}" + + match expr2 with + | IfDirectiveExpression.And(IfDirectiveExpression.Ident "FOO", IfDirectiveExpression.Ident "BAR") -> () + | _ -> Assert.Fail $"Expected different expression, got {expr2}" + + match expr3 with + | IfDirectiveExpression.Or(IfDirectiveExpression.Ident "MEH", IfDirectiveExpression.Ident "HMM") -> () + | _ -> Assert.Fail $"Expected different expression, got {expr3}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``directives in multiline comment are not reported as trivia`` () = + let trivia = + getDirectiveTrivia false """ +let v = +(* +#if DEBUG +() +#endif +*) +42 +""" + + match trivia with + | [] -> Assert.Pass() + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``directives in multiline string are not reported as trivia`` () = + let trivia = + getDirectiveTrivia false " +let v = \"\"\" +#if DEBUG +() +#endif +42 +\"\"\" +" + + match trivia with + | [] -> Assert.Pass() + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``single #if / #endif, signature file`` () = + let trivia = + getDirectiveTrivia true """ +namespace Foobar + +val v: int = + #if DEBUG + 1 + #endif + 42 +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr, mIf) + ConditionalDirectiveTrivia.EndIf mEndif ] -> + assertRange (5, 4) (5, 13) mIf + assertRange (7, 4) (7, 10) mEndif + + match expr with + | IfDirectiveExpression.Ident "DEBUG" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``single #if / #else / #endif, signature file`` () = + let trivia = + getDirectiveTrivia true """ +namespace Foobar + +val v : int = + #if DEBUG + 30 + #else + 42 + #endif +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr, mIf) + ConditionalDirectiveTrivia.Else mElse + ConditionalDirectiveTrivia.EndIf mEndif ] -> + assertRange (5, 4) (5, 13) mIf + assertRange (7, 4) (7, 9) mElse + assertRange (9, 4) (9, 10) mEndif + + match expr with + | IfDirectiveExpression.Ident "DEBUG" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``nested #if / #else / #endif, signature file`` () = + let trivia = + getDirectiveTrivia true """ +namespace Foobar + +val v : int = + #if FOO + #if MEH + 1 + #else + 2 + #endif + #else + 3 + #endif +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr1, mIf1) + ConditionalDirectiveTrivia.If(expr2, mIf2) + ConditionalDirectiveTrivia.Else mElse1 + ConditionalDirectiveTrivia.EndIf mEndif1 + ConditionalDirectiveTrivia.Else mElse2 + ConditionalDirectiveTrivia.EndIf mEndif2 ] -> + assertRange (5, 4) (5, 11) mIf1 + assertRange (6, 8) (6, 15) mIf2 + assertRange (8, 8) (8, 13) mElse1 + assertRange (10, 8) (10, 14) mEndif1 + assertRange (11, 4) (11, 9) mElse2 + assertRange (13, 4) (13, 10) mEndif2 + + match expr1 with + | IfDirectiveExpression.Ident "FOO" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr1}" + + match expr2 with + | IfDirectiveExpression.Ident "MEH" -> () + | _ -> Assert.Fail $"Expected different expression, got {expr2}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``nested #if / #endif with complex expressions, signature file`` () = + let trivia = + getDirectiveTrivia true """ +namespace Foobar + +val v : int = + #if !DEBUG + #if FOO && BAR + #if MEH || HMM + 9 + #endif + #endif + #endif + 10 +""" + + match trivia with + | [ ConditionalDirectiveTrivia.If(expr1, mIf1) + ConditionalDirectiveTrivia.If(expr2, mIf2) + ConditionalDirectiveTrivia.If(expr3, mIf3) + ConditionalDirectiveTrivia.EndIf mEndif1 + ConditionalDirectiveTrivia.EndIf mEndif2 + ConditionalDirectiveTrivia.EndIf mEndif3 ] -> + assertRange (5, 4) (5, 14) mIf1 + assertRange (6, 8) (6, 22) mIf2 + assertRange (7, 12) (7, 26) mIf3 + assertRange (9, 12) (9, 18) mEndif1 + assertRange (10, 8) (10, 14) mEndif2 + assertRange (11, 4) (11, 10) mEndif3 + + match expr1 with + | IfDirectiveExpression.Not (IfDirectiveExpression.Ident "DEBUG") -> () + | _ -> Assert.Fail $"Expected different expression, got {expr1}" + + match expr2 with + | IfDirectiveExpression.And(IfDirectiveExpression.Ident "FOO", IfDirectiveExpression.Ident "BAR") -> () + | _ -> Assert.Fail $"Expected different expression, got {expr2}" + + match expr3 with + | IfDirectiveExpression.Or(IfDirectiveExpression.Ident "MEH", IfDirectiveExpression.Ident "HMM") -> () + | _ -> Assert.Fail $"Expected different expression, got {expr3}" + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``directives in multiline comment are not reported as trivia, signature file`` () = + let trivia = + getDirectiveTrivia true """ +namespace Foobar + +val v : int = +(* +#if DEBUG +() +#endif +*) +42 +""" + + match trivia with + | [] -> Assert.Pass() + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" + +[] +let ``directives in multiline string are not reported as trivia, signature file`` () = + let trivia = + getDirectiveTrivia true " +namespace Foobar + +let v : string = \"\"\" +#if DEBUG +() +#endif +42 +\"\"\" +" + + match trivia with + | [] -> Assert.Pass() + | _ -> + Assert.Fail $"Unexpected trivia, got {trivia}" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/EnumCaseTests.fs b/tests/service/SyntaxTreeTests/EnumCaseTests.fs new file mode 100644 index 00000000000..60dd4a1e6eb --- /dev/null +++ b/tests/service/SyntaxTreeTests/EnumCaseTests.fs @@ -0,0 +1,75 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.EnumCaseTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``single SynEnumCase has bar range`` () = + let ast = """ +type Foo = | Bar = 1 +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ + SynEnumCase.SynEnumCase (trivia = { BarRange = Some mBar; EqualsRange = mEquals }) + ]))) + ], _) + ]) + ])) -> + assertRange (2, 11) (2, 12) mBar + assertRange (2, 17) (2, 18) mEquals + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``multiple SynEnumCases have bar range`` () = + let ast = """ +type Foo = + | Bar = 1 + | Bear = 2 +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ + SynEnumCase.SynEnumCase (trivia = { BarRange = Some mBar1; EqualsRange = mEquals1 }) + SynEnumCase.SynEnumCase (trivia = { BarRange = Some mBar2; EqualsRange = mEquals2 }) + ]))) + ], _) + ]) + ])) -> + assertRange (3, 4) (3, 5) mBar1 + assertRange (3, 10) (3, 11) mEquals1 + assertRange (4, 4) (4, 5) mBar2 + assertRange (4, 11) (4, 12) mEquals2 + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``single SynEnumCase without bar`` () = + let ast = """ +type Foo = Bar = 1 +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ + SynEnumCase.SynEnumCase (trivia = { BarRange = None; EqualsRange = mEquals }) + ]))) + ], _) + ]) + ])) -> + assertRange (2, 15) (2, 16) mEquals + | _ -> + Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/ExceptionTests.fs b/tests/service/SyntaxTreeTests/ExceptionTests.fs new file mode 100644 index 00000000000..cd0ccef1cd1 --- /dev/null +++ b/tests/service/SyntaxTreeTests/ExceptionTests.fs @@ -0,0 +1,25 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.ExceptionTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``SynExceptionDefn should contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +namespace X + +exception Foo with + member Meh () = () +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace(decls = [ + SynModuleDecl.Exception( + exnDefn=SynExceptionDefn(withKeyword = Some mWithKeyword) + ) + ]) ])) -> + assertRange (4, 14) (4, 18) mWithKeyword + | _ -> Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/ExpressionTests.fs b/tests/service/SyntaxTreeTests/ExpressionTests.fs new file mode 100644 index 00000000000..eb18d053d6a --- /dev/null +++ b/tests/service/SyntaxTreeTests/ExpressionTests.fs @@ -0,0 +1,496 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.ExpressionTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.SyntaxTrivia +open NUnit.Framework + +[] +let ``SynExpr.Do contains the range of the do keyword`` () = + let ast = """let a = + do + foobar + do! + foobarBang +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [ + SynBinding(expr = SynExpr.Sequential(expr1 = SynExpr.Do(_, doRange) ; expr2 = SynExpr.DoBang(_, doBangRange))) + ]) + ]) + ])) -> + assertRange (2, 4) (3, 14) doRange + assertRange (4, 4) (5, 18) doBangRange + | _ -> + Assert.Fail "Could not find SynExpr.Do" + +[] +let ``SynExpr.LetOrUseBang contains the range of the equals sign`` () = + let ast = + """ +comp { + let! x = y + and! z = someFunction () + return () +} +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.App(argExpr = + SynExpr.ComputationExpr(expr = + SynExpr.LetOrUseBang(trivia = { EqualsRange = Some mLetBangEquals } + andBangs = [ SynExprAndBang(trivia= { EqualsRange = mAndBangEquals }) ])))) + ]) + ])) -> + assertRange (3, 11) (3, 12) mLetBangEquals + assertRange (4, 11) (4, 12) mAndBangEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.Record contains the range of the equals sign in SynExprRecordField`` () = + let ast = + """ +{ V = v + X = // some comment + someLongFunctionCall + a + b + c } +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Record(recordFields = [ + SynExprRecordField(equalsRange = Some mEqualsV) + SynExprRecordField(equalsRange = Some mEqualsX) + ])) + ]) + ])) -> + assertRange (2, 4) (2, 5) mEqualsV + assertRange (3, 9) (3, 10) mEqualsX + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``inherit SynExpr.Record contains the range of the equals sign in SynExprRecordField`` () = + let ast = + """ +{ inherit Exception(msg); X = 1; } +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Record(baseInfo = Some _ ; recordFields = [ + SynExprRecordField(equalsRange = Some mEquals) + ])) + ]) + ])) -> + assertRange (2, 28) (2, 29) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``copy SynExpr.Record contains the range of the equals sign in SynExprRecordField`` () = + let ast = + """ +{ foo with + X + = + 12 } +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Record(copyInfo = Some _ ; recordFields = [ + SynExprRecordField(equalsRange = Some mEquals) + ])) + ]) + ])) -> + assertRange (4, 12) (4, 13) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.AnonRecord contains the range of the equals sign in the fields`` () = + let ast = + """ +{| X = 5 + Y = 6 + Z = 7 |} +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.AnonRecd(recordFields = [ + (_, Some mEqualsX, _) + (_, Some mEqualsY, _) + (_, Some mEqualsZ, _) + ])) + ]) + ])) -> + assertRange (2, 5) (2, 6) mEqualsX + assertRange (3, 8) (3, 9) mEqualsY + assertRange (4, 12) (4, 13) mEqualsZ + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.For contains the range of the equals sign`` () = + let ast = + """ +for i = 1 to 10 do +printf "%d " i +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.For(equalsRange = Some mEquals)) + ]) + ])) -> + assertRange (2, 6) (2, 7) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.TryWith contains the range of the try and with keyword`` () = + let ast = + """ +try +x +with +| ex -> y +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.TryWith(trivia={ TryKeyword = mTry; WithKeyword = mWith })) + ]) + ])) -> + assertRange (2, 0) (2, 3) mTry + assertRange (4, 0) (4, 4) mWith + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.TryFinally contains the range of the try and with keyword`` () = + let ast = + """ +try +x +finally +() +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.TryFinally(trivia={ TryKeyword = mTry; FinallyKeyword = mFinally })) + ]) + ])) -> + assertRange (2, 0) (2, 3) mTry + assertRange (4, 0) (4, 7) mFinally + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.Match contains the range of the match and with keyword`` () = + let ast = + """ +match x with +| y -> z +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Match(trivia = { MatchKeyword = mMatch; WithKeyword = mWith })) + ]) + ])) -> + assertRange (2, 0) (2, 5) mMatch + assertRange (2, 8) (2, 12) mWith + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.MatchBang contains the range of the match and with keyword`` () = + let ast = + """ +match! x with +| y -> z +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.MatchBang(trivia = { MatchBangKeyword = mMatch; WithKeyword = mWith })) + ]) + ])) -> + assertRange (2, 0) (2, 6) mMatch + assertRange (2, 9) (2, 13) mWith + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.ObjExpr contains the range of with keyword`` () = + let ast = + """ +{ new obj() with + member x.ToString() = "INotifyEnumerableInternal" + interface INotifyEnumerableInternal<'T> + interface IEnumerable<_> with + member x.GetEnumerator() = null } +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.ObjExpr(withKeyword=Some mWithObjExpr; extraImpls=[ SynInterfaceImpl(withKeyword=None); SynInterfaceImpl(withKeyword=Some mWithSynInterfaceImpl) ])) + ]) + ])) -> + assertRange (2, 12) (2, 16) mWithObjExpr + assertRange (5, 27) (5, 31) mWithSynInterfaceImpl + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.LetOrUse contains the range of in keyword`` () = + let ast = + getParseResults "let x = 1 in ()" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.LetOrUse(trivia={ InKeyword = Some mIn })) + ]) + ])) -> + assertRange (1, 10) (1, 12) mIn + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.LetOrUse with recursive binding contains the range of in keyword`` () = + let ast = + getParseResults """ +do + let rec f = () + and g = () in + () +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Do(expr = SynExpr.LetOrUse(bindings=[_;_]; trivia={ InKeyword = Some mIn }))) + ]) + ])) -> + assertRange (4, 15) (4, 17) mIn + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``nested SynExpr.LetOrUse contains the range of in keyword`` () = + let ast = + getParseResults """ +let f () = + let x = 1 in // the "in" keyword is available in F# + let y = 2 in + x + y +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [ + SynBinding(expr = + SynExpr.LetOrUse(bindings=[_]; trivia={ InKeyword = Some mIn }; body=SynExpr.LetOrUse(trivia={ InKeyword = Some mInnerIn }))) + ]) + ]) + ])) -> + assertRange (3, 14) (3, 16) mIn + assertRange (4, 14) (4, 16) mInnerIn + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.LetOrUse does not contain the range of in keyword`` () = + let ast = + getParseResults """ +do +let x = 1 +() +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Do(expr = SynExpr.LetOrUse(trivia={ InKeyword = None }))) + ]) + ])) -> + Assert.Pass() + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.LetOrUse where body expr starts with token of two characters does not contain the range of in keyword`` () = + let ast = + getParseResults """ +do +let e1 = e :?> Collections.DictionaryEntry +e1.Key, e1.Value +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Do(expr = SynExpr.LetOrUse(trivia={ InKeyword = None }))) + ]) + ])) -> + Assert.Pass() + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``global keyword as SynExpr`` () = + let ast = + getParseResults """ +global +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.LongIdent(longDotId = SynLongIdent([mangledGlobal], [], [Some (IdentTrivia.OriginalNotation "global")])) + )]) + ])) -> + Assert.AreEqual("`global`", mangledGlobal.idText) + Assert.Pass() + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExprRecordFields contain correct amount of trivia`` () = + let ast = + getParseResults """ + { JobType = EsriBoundaryImport + FileToImport = filePath + State = state + DryRun = args.DryRun } +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Record(recordFields = [ + SynExprRecordField(fieldName = (synLongIdent, _)) + _; _; _ + ])) + ]) + ])) -> + match synLongIdent.IdentsWithTrivia with + | [ _ ] -> Assert.Pass() + | idents -> Assert.Fail $"Expected a single SynIdent, got {idents}" + | _ -> Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``SynExpr.Dynamic does contain ident`` () = + let ast = + getParseResults "x?k" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Dynamic (_, _, SynExpr.Ident(idK) ,mDynamicExpr)) + ]) + ])) -> + Assert.AreEqual("k", idK.idText) + assertRange (1,0) (1, 3) mDynamicExpr + | _ -> Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``SynExpr.Dynamic does contain parentheses`` () = + let ast = + getParseResults "x?(g)" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.Dynamic (_, _, SynExpr.Paren(SynExpr.Ident(idG), lpr, Some rpr, mParen) ,mDynamicExpr)) + ]) + ])) -> + Assert.AreEqual("g", idG.idText) + assertRange (1, 2) (1,3) lpr + assertRange (1, 4) (1,5) rpr + assertRange (1, 2) (1,5) mParen + assertRange (1,0) (1, 5) mDynamicExpr + | _ -> Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``SynExpr.Set with SynExpr.Dynamic`` () = + let ast = + getParseResults "x?v <- 2" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Set( + SynExpr.Dynamic (_, _, SynExpr.Ident(idV) ,mDynamicExpr), + SynExpr.Const _, + mSetExpr + )) + ]) + ])) -> + Assert.AreEqual("v", idV.idText) + assertRange (1,0) (1, 3) mDynamicExpr + assertRange (1,0) (1, 8) mSetExpr + | _ -> Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``SynExpr.Obj with setter`` () = + let ast = + getParseResults """ +[] +type CFoo() = + abstract AbstractClassPropertySet: string with set + +{ new CFoo() with + override this.AbstractClassPropertySet with set (v:string) = () } +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types _ + SynModuleDecl.Expr(expr = SynExpr.ObjExpr(members = [ + SynMemberDefn.GetSetMember(None, Some _, m, { WithKeyword = mWith; SetKeyword = Some mSet }) + ])) + ]) + ])) -> + assertRange (7, 43) (7, 47) mWith + assertRange (7, 48) (7, 51) mSet + assertRange (7,4) (7, 67) m + | _ -> Assert.Fail $"Could not get valid AST, got {ast}" + diff --git a/tests/service/SyntaxTreeTests/IfThenElseTests.fs b/tests/service/SyntaxTreeTests/IfThenElseTests.fs new file mode 100644 index 00000000000..7db54e4dfef --- /dev/null +++ b/tests/service/SyntaxTreeTests/IfThenElseTests.fs @@ -0,0 +1,177 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.IfThenElseTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``If keyword in IfThenElse`` () = + let parseResults = + getParseResults + "if a then b" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = None }) + ) + ]) ])) -> + assertRange (1, 0) (1, 2) mIfKw + assertRange (1, 5) (1, 9) mThenKw + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Else keyword in simple IfThenElse`` () = + let parseResults = + getParseResults + "if a then b else c" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr =SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = Some mElse }) + ) + ]) ])) -> + assertRange (1, 0) (1, 2) mIfKw + assertRange (1, 5) (1, 9) mThenKw + assertRange (1, 12) (1, 16) mElse + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``If, Then and Else keyword on separate lines`` () = + let parseResults = + getParseResults + """ +if a +then b +else c""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = Some mElse }) + ) + ]) ])) -> + assertRange (2, 0) (2, 2) mIfKw + assertRange (3, 0) (3, 4) mThenKw + assertRange (4, 0) (4, 4) mElse + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Nested elif in IfThenElse`` () = + let parseResults = + getParseResults + """ +if a then +b +elif c then d""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif=false; ThenKeyword = mThenKw; ElseKeyword = None } + elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElif; IsElif = true }))) + ) + ]) ])) -> + assertRange (2, 0) (2, 2) mIfKw + assertRange (2, 5) (2, 9) mThenKw + assertRange (4, 0) (4, 4) mElif + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Nested else if in IfThenElse`` () = + let parseResults = + getParseResults + """ +if a then + b +else + if c then d""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif = false; ThenKeyword = mThenKw; ElseKeyword = Some mElse } + elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElseIf; IsElif = false }))) + ) + ]) ])) -> + assertRange (2, 0) (2, 2) mIfKw + assertRange (2, 5) (2, 9) mThenKw + assertRange (4, 0) (4, 4) mElse + assertRange (5, 4) (5, 6) mElseIf + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Nested else if on the same line in IfThenElse`` () = + let parseResults = + getParseResults + """ +if a then +b +else if c then +d""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIfKw; IsElif=false; ThenKeyword = mThenKw; ElseKeyword = Some mElse } + elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElseIf; IsElif = false }))) + ) + ]) ])) -> + assertRange (2, 0) (2, 2) mIfKw + assertRange (2, 5) (2, 9) mThenKw + assertRange (4, 0) (4, 4) mElse + assertRange (4, 5) (4, 7) mElseIf + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Deeply nested IfThenElse`` () = + let parseResults = + getParseResults + """ +if a then + b +elif c then + d +else + if e then + f + else + g""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIf1; IsElif = false; ElseKeyword = None } + elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mElif; IsElif = true; ElseKeyword = Some mElse1 } + elseExpr = Some (SynExpr.IfThenElse(trivia={ IfKeyword = mIf2; IsElif = false; ElseKeyword = Some mElse2 })))))) + ]) ])) -> + assertRange (2, 0) (2, 2) mIf1 + assertRange (4, 0) (4, 4) mElif + assertRange (6, 0) (6, 4) mElse1 + assertRange (7, 8) (7, 10) mIf2 + assertRange (9, 8) (9, 12) mElse2 + + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Comment between else and if`` () = + let parseResults = + getParseResults + """ +if a then +b +else (* some long comment here *) if c then +d""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.IfThenElse(trivia={ IfKeyword = mIf1; IsElif = false; ElseKeyword = Some mElse } + elseExpr = Some (SynExpr.IfThenElse(trivia = { IfKeyword = mIf2; IsElif = false })))) + ]) ])) -> + assertRange (2, 0) (2, 2) mIf1 + assertRange (4, 0) (4, 4) mElse + assertRange (4, 34) (4, 36) mIf2 + + | _ -> Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/LambdaTests.fs b/tests/service/SyntaxTreeTests/LambdaTests.fs new file mode 100644 index 00000000000..788279f8e76 --- /dev/null +++ b/tests/service/SyntaxTreeTests/LambdaTests.fs @@ -0,0 +1,146 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.LambdaTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``Lambda with two parameters gives correct body`` () = + let parseResults = + getParseResults + "fun a b -> x" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(parsedData = Some([SynPat.Named _; SynPat.Named _], SynExpr.Ident ident)) + ) + ]) ])) -> + Assert.AreEqual("x", ident.idText) + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Lambda with wild card parameter gives correct body`` () = + let parseResults = + getParseResults + "fun a _ b -> x" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(parsedData = Some([SynPat.Named _; SynPat.Wild _; SynPat.Named _], SynExpr.Ident ident)) + ) + ]) ])) -> + Assert.AreEqual("x", ident.idText) + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Lambda with tuple parameter with wild card gives correct body`` () = + let parseResults = + getParseResults + "fun a (b, _) c -> x" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(parsedData = Some([SynPat.Named _; SynPat.Paren(SynPat.Tuple _,_); SynPat.Named _], SynExpr.Ident ident)) + ) + ]) ])) -> + Assert.AreEqual("x", ident.idText) + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Lambda with wild card that returns a lambda gives correct body`` () = + let parseResults = + getParseResults + "fun _ -> fun _ -> x" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(parsedData = Some([SynPat.Wild _], SynExpr.Lambda(parsedData = Some([SynPat.Wild _], SynExpr.Ident ident)))) + ) + ]) ])) -> + Assert.AreEqual("x", ident.idText) + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Simple lambda has arrow range`` () = + let parseResults = + getParseResults + "fun x -> x" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) + ) + ]) ])) -> + assertRange (1, 6) (1, 8) mArrow + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Multiline lambda has arrow range`` () = + let parseResults = + getParseResults + "fun x y z + -> + x * y * z" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) + ) + ]) ])) -> + assertRange (2, 28) (2, 30) mArrow + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Destructed lambda has arrow range`` () = + let parseResults = + getParseResults + "fun { X = x } -> x * 2" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) + ) + ]) ])) -> + assertRange (1, 14) (1, 16) mArrow + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Tuple in lambda has arrow range`` () = + let parseResults = + getParseResults + "fun (x, _) -> x * 3" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) + ) + ]) ])) -> + assertRange (1, 11) (1, 13) mArrow + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Complex arguments lambda has arrow range`` () = + let parseResults = + getParseResults + "fun (x, _) + ({ Y = h::_ }) + (SomePattern(z)) + -> + x * y + z" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Lambda(trivia={ ArrowRange = Some mArrow }) + ) + ]) ])) -> + assertRange (4, 4) (4, 6) mArrow + | _ -> Assert.Fail "Could not get valid AST" diff --git a/tests/service/SyntaxTreeTests/MatchClauseTests.fs b/tests/service/SyntaxTreeTests/MatchClauseTests.fs new file mode 100644 index 00000000000..caa6c5d6da5 --- /dev/null +++ b/tests/service/SyntaxTreeTests/MatchClauseTests.fs @@ -0,0 +1,231 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.MatchClauseTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``Range of single SynMatchClause`` () = + let parseResults = + getParseResults + """ +try + let content = tryDownloadFile url + Some content +with ex -> + Infrastructure.ReportWarning ex + None""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) + ]) ])) -> + assertRange (5, 5) (7, 8) range + assertRange (5, 5) (7, 8) clause.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of multiple SynMatchClause`` () = + let parseResults = + getParseResults + """ +try + let content = tryDownloadFile url + Some content +with +| ex -> + Infrastructure.ReportWarning ex + None +| exx -> + None""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = r1) as clause1 + SynMatchClause(range = r2) as clause2 ])) + ]) ])) -> + assertRange (6, 2) (8, 8) r1 + assertRange (6, 2) (8, 8) clause1.Range + + assertRange (9, 2) (10, 8) r2 + assertRange (9, 2) (10, 8) clause2.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of single SynMatchClause followed by bar`` () = + let parseResults = + getParseResults + """ +try + let content = tryDownloadFile url + Some content +with +| ex -> + () +| """ + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) + ]) ])) -> + assertRange (6, 2) (7, 6) range + assertRange (6, 2) (7, 6) clause.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of single SynMatchClause with missing body`` () = + let parseResults = + getParseResults + """ +try + let content = tryDownloadFile url + Some content +with +| ex ->""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) + ]) ])) -> + assertRange (6, 2) (6, 4) range + assertRange (6, 2) (6, 4) clause.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of single SynMatchClause with missing body and when expr`` () = + let parseResults = + getParseResults + """ +try + let content = tryDownloadFile url + Some content +with +| ex when (isNull ex) ->""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(range = range) as clause ])) + ]) ])) -> + assertRange (6, 2) (6, 21) range + assertRange (6, 2) (6, 21) clause.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of arrow in SynMatchClause`` () = + let parseResults = + getParseResults + """ +match foo with +| Bar bar -> ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ ArrowRange = Some mArrow }) ])) + ]) ])) -> + assertRange (3, 10) (3, 12) mArrow + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of arrow in SynMatchClause with when clause`` () = + let parseResults = + getParseResults + """ +match foo with +| Bar bar when (someCheck bar) -> ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ ArrowRange = Some mArrow }) ])) + ]) ])) -> + assertRange (3, 31) (3, 33) mArrow + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of bar in a single SynMatchClause in SynExpr.Match`` () = + let parseResults = + getParseResults + """ +match foo with +| Bar bar when (someCheck bar) -> ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ BarRange = Some mBar }) ])) + ]) ])) -> + assertRange (3, 0) (3, 1) mBar + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of bar in multiple SynMatchClauses in SynExpr.Match`` () = + let parseResults = + getParseResults + """ +match foo with +| Bar bar when (someCheck bar) -> () +| Far too -> near ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Match(clauses = [ SynMatchClause(trivia={ BarRange = Some mBar1 }) + SynMatchClause(trivia={ BarRange = Some mBar2 }) ])) + ]) ])) -> + assertRange (3, 0) (3, 1) mBar1 + assertRange (4, 0) (4, 1) mBar2 + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of bar in a single SynMatchClause in SynExpr.TryWith`` () = + let parseResults = + getParseResults + """ +try + foo () +with +| exn -> ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(trivia={ BarRange = Some mBar }) ])) + ]) ])) -> + assertRange (5, 0) (5, 1) mBar + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``No range of bar in a single SynMatchClause in SynExpr.TryWith`` () = + let parseResults = + getParseResults + """ +try + foo () +with exn -> + // some comment + ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(trivia={ BarRange = None }) ])) + ]) ])) -> + Assert.Pass() + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of bar in a multiple SynMatchClauses in SynExpr.TryWith`` () = + let parseResults = + getParseResults + """ +try + foo () +with +| IOException as ioex -> + // some comment + () +| ex -> ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.TryWith(withCases = [ SynMatchClause(trivia={ BarRange = Some mBar1 }) + SynMatchClause(trivia={ BarRange = Some mBar2 }) ])) + ]) ])) -> + assertRange (5, 0) (5, 1) mBar1 + assertRange (8, 0) (8, 1) mBar2 + | _ -> Assert.Fail "Could not get valid AST" diff --git a/tests/service/SyntaxTreeTests/MeasureTests.fs b/tests/service/SyntaxTreeTests/MeasureTests.fs new file mode 100644 index 00000000000..0ccbf5a6d5d --- /dev/null +++ b/tests/service/SyntaxTreeTests/MeasureTests.fs @@ -0,0 +1,49 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.MeasureTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``Measure contains the range of the constant`` () = + let parseResults = + getParseResults + """ +let n = 1.0m +let m = 7.000 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [ SynBinding.SynBinding(expr = SynExpr.Const(SynConst.Measure(constantRange = r1), _)) ]) + SynModuleDecl.Let(bindings = [ SynBinding.SynBinding(expr = SynExpr.Const(SynConst.Measure(constantRange = r2), _)) ]) + ]) ])) -> + assertRange (2, 8) (2, 12) r1 + assertRange (3, 8) (3, 13) r2 + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynMeasure.Paren has correct range`` () = + let parseResults = + getParseResults + """ +40u
+""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Const(SynConst.Measure(SynConst.UInt32 _, _, SynMeasure.Divide( + SynMeasure.Seq([ SynMeasure.Named([ hrIdent ], _) ], _), + SynMeasure.Seq([ SynMeasure.Paren(SynMeasure.Seq([ + SynMeasure.Named([ staffIdent ], _) + SynMeasure.Named([ weeksIdent ], _) + ], _) , mParen) ], _), + _) + ), _)) + ]) ])) -> + Assert.AreEqual("hr", hrIdent.idText) + Assert.AreEqual("staff", staffIdent.idText) + Assert.AreEqual("weeks", weeksIdent.idText) + assertRange (2, 9) (2, 22) mParen + | _ -> Assert.Fail $"Could not get valid AST, got {parseResults}" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/MemberFlagTests.fs b/tests/service/SyntaxTreeTests/MemberFlagTests.fs new file mode 100644 index 00000000000..464884ae055 --- /dev/null +++ b/tests/service/SyntaxTreeTests/MemberFlagTests.fs @@ -0,0 +1,178 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.MemberFlagTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + + +[] +let ``SynMemberSig.Member has correct keywords`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace X + +type Y = + abstract A : int + abstract member B : double + static member C : string + member D : int + override E : int + default F : int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Types(types =[ + SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.ObjectModel(memberSigs=[ + SynMemberSig.Member(flags={ Trivia= { AbstractRange = Some mAbstract1 } }) + SynMemberSig.Member(flags={ Trivia= { AbstractRange = Some mAbstract2 + MemberRange = Some mMember1 } }) + SynMemberSig.Member(flags={ Trivia= { StaticRange = Some mStatic3 + MemberRange = Some mMember3 } }) + SynMemberSig.Member(flags={ Trivia= { MemberRange = Some mMember4 } }) + SynMemberSig.Member(flags={ Trivia= { OverrideRange = Some mOverride5 } }) + SynMemberSig.Member(flags={ Trivia= { DefaultRange = Some mDefault6 } }) + ])) + ]) + ]) ])) -> + assertRange (5, 4) (5, 12) mAbstract1 + assertRange (6, 4) (6, 12) mAbstract2 + assertRange (6, 13) (6, 19) mMember1 + assertRange (7, 4) (7, 10) mStatic3 + assertRange (7, 11) (7, 17) mMember3 + assertRange (8, 4) (8, 10) mMember4 + assertRange (9, 4) (9, 12) mOverride5 + assertRange (10, 4) (10, 11) mDefault6 + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynMemberDefn.AbstractSlot has correct keyword`` () = + let ast = """ +type Foo = + abstract X : int + abstract member Y: int +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.ObjectModel (members=[ + SynMemberDefn.AbstractSlot(flags={ Trivia = { AbstractRange = Some mAbstract1 } }) + SynMemberDefn.AbstractSlot(flags={ Trivia = { AbstractRange = Some mAbstract2 + MemberRange = Some mMember2 } }) + ])) + ], _) + ]) + ])) -> + assertRange (3, 4) (3, 12) mAbstract1 + assertRange (4, 4) (4, 12) mAbstract2 + assertRange (4, 13) (4, 19) mMember2 + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``SynMemberDefn.AutoProperty has correct keyword`` () = + let ast = """ +type Foo = + static member val W : int = 1 + member val X : int = 1 + override val Y : int = 2 + default val Z : int = 1 +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.ObjectModel (members=[ + SynMemberDefn.AutoProperty(memberFlags= mkFlags1) + SynMemberDefn.AutoProperty(memberFlags= mkFlags2) + SynMemberDefn.AutoProperty(memberFlags= mkFlags3) + SynMemberDefn.AutoProperty(memberFlags= mkFlags4) + ])) + ], _) + ]) + ])) -> + let ({ Trivia = flagsTrivia1 } : SynMemberFlags) = mkFlags1 SynMemberKind.Member + assertRange (3, 4) (3, 10) flagsTrivia1.StaticRange.Value + assertRange (3, 11) (3, 17) flagsTrivia1.MemberRange.Value + + let ({ Trivia = flagsTrivia2 } : SynMemberFlags) = mkFlags2 SynMemberKind.Member + assertRange (4, 4) (4, 10) flagsTrivia2.MemberRange.Value + + let ({ Trivia = flagsTrivia3 } : SynMemberFlags) = mkFlags3 SynMemberKind.Member + assertRange (5, 4) (5, 12) flagsTrivia3.OverrideRange.Value + + let ({ Trivia = flagsTrivia4 } : SynMemberFlags) = mkFlags4 SynMemberKind.Member + assertRange (6, 4) (6, 11) flagsTrivia4.DefaultRange.Value + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``SynMemberDefn.Member SynValData has correct keyword`` () = + let ast = """ +type Foo = + static member this.B() = () + member this.A() = () + override this.C() = () + default this.D() = () +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.ObjectModel (members=[ + SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { StaticRange = Some mStatic1 + MemberRange = Some mMember1 } }))) + SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { MemberRange = Some mMember2 } }))) + SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { OverrideRange = Some mOverride3 } }))) + SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { DefaultRange = Some mDefaultRange4 } }))) + ])) + ], _) + ]) + ])) -> + assertRange (3, 4) (3, 10) mStatic1 + assertRange (3, 11) (3, 17) mMember1 + assertRange (4, 4) (4, 10) mMember2 + assertRange (5, 4) (5, 12) mOverride3 + assertRange (6, 4) (6, 11) mDefaultRange4 + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``SynExpr.Obj members have correct keywords`` () = + let ast = """ +let meh = + { new Interface with + override this.Foo () = () + member this.Bar () = () + interface SomethingElse with + member this.Blah () = () } +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let (bindings = [ + SynBinding(expr=SynExpr.ObjExpr( + members=[ + SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { OverrideRange = Some mOverride1 } }))) + SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { MemberRange = Some mMember2 } }))) + ] + extraImpls=[ SynInterfaceImpl(members=[ + SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some { Trivia = { MemberRange = Some mMember3 } }))) + ]) ])) + ]) + ]) ])) -> + assertRange (4, 8) (4, 16) mOverride1 + assertRange (5, 8) (5, 14) mMember2 + assertRange (7, 8) (7, 14) mMember3 + | _ -> + Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/ModuleOrNamespaceSigTests.fs b/tests/service/SyntaxTreeTests/ModuleOrNamespaceSigTests.fs new file mode 100644 index 00000000000..bf9c025c36a --- /dev/null +++ b/tests/service/SyntaxTreeTests/ModuleOrNamespaceSigTests.fs @@ -0,0 +1,88 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.ModuleOrNamespaceSigTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``Range member returns range of SynModuleOrNamespaceSig`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace Foobar + +type Bar = | Bar of string * int +""" + + match parseResults with + | ParsedInput.SigFile(ParsedSigFileInput(modules = [ + SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.DeclaredNamespace) as singleModule + ])) -> + assertRange (2,0) (4,32) singleModule.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``GlobalNamespace should start at namespace keyword`` () = + let parseResults = + getParseResultsOfSignatureFile + """// foo +// bar +namespace global + +type Bar = | Bar of string * int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.GlobalNamespace; range = r) ])) -> + assertRange (3, 0) (5, 32) r + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Module range should start at first attribute`` () = + let parseResults = + getParseResultsOfSignatureFile + """ + [< Foo >] +module Bar + +val s : string +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig.SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.NamedModule; range = r) ])) -> + assertRange (2, 1) (5, 14) r + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Module should contain module keyword`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +module Bar + +val a: int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.NamedModule; trivia = { ModuleKeyword = Some mModule; NamespaceKeyword = None }) ])) -> + assertRange (2, 0) (2, 6) mModule + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Namespace should contain namespace keyword`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace Foo +module Bar = +val a: int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(kind = SynModuleOrNamespaceKind.DeclaredNamespace; trivia = { ModuleKeyword = None; NamespaceKeyword = Some mNamespace }) ])) -> + assertRange (2, 0) (2, 9) mNamespace + | _ -> Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/ModuleOrNamespaceTests.fs b/tests/service/SyntaxTreeTests/ModuleOrNamespaceTests.fs new file mode 100644 index 00000000000..2dbd30d673a --- /dev/null +++ b/tests/service/SyntaxTreeTests/ModuleOrNamespaceTests.fs @@ -0,0 +1,117 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.ModuleOrNamespaceTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``DeclaredNamespace range should start at namespace keyword`` () = + let parseResults = + getParseResults + """namespace TypeEquality + +/// A type for witnessing type equality between 'a and 'b +type Teq<'a, 'b> +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; range = r) ])) -> + assertRange (1, 0) (4, 8) r + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Multiple DeclaredNamespaces should have a range that starts at the namespace keyword`` () = + let parseResults = + getParseResults + """namespace TypeEquality + +/// A type for witnessing type equality between 'a and 'b +type Teq = class end + +namespace Foobar + +let x = 42 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; range = r1) + SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; range = r2) ])) -> + assertRange (1, 0) (4, 20) r1 + assertRange (6, 0) (8, 10) r2 + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``GlobalNamespace should start at namespace keyword`` () = + let parseResults = + getParseResults + """// foo +// bar +namespace global + +type X = int +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.GlobalNamespace; range = r) ])) -> + assertRange (3, 0) (5, 12) r + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Module range should start at first attribute`` () = + let parseResults = + getParseResults + """ +[< Foo >] +module Bar + +let s : string = "s" +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.NamedModule; range = r) ])) -> + assertRange (2, 0) (5, 20) r + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Module should contain module keyword`` () = + let parseResults = + getParseResults + """ +/// this file contains patches to the F# Compiler Service that have not yet made it into +/// published nuget packages. We source-copy them here to have a consistent location for our to-be-removed extensions + +module FsAutoComplete.FCSPatches + +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text +open FsAutoComplete.UntypedAstUtils +open FSharp.Compiler.CodeAnalysis + +module internal SynExprAppLocationsImpl = +let a = 42 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.NamedModule; trivia = { ModuleKeyword = Some mModule; NamespaceKeyword = None }) ])) -> + assertRange (5, 0) (5, 6) mModule + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Namespace should contain namespace keyword`` () = + let parseResults = + getParseResults + """ +namespace Foo +module Bar = +let a = 42 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(kind = SynModuleOrNamespaceKind.DeclaredNamespace; trivia = { ModuleKeyword = None; NamespaceKeyword = Some mNamespace }) ])) -> + assertRange (2, 0) (2, 9) mNamespace + | _ -> Assert.Fail "Could not get valid AST" diff --git a/tests/service/SyntaxTreeTests/NestedModuleTests.fs b/tests/service/SyntaxTreeTests/NestedModuleTests.fs new file mode 100644 index 00000000000..d6dcac70f76 --- /dev/null +++ b/tests/service/SyntaxTreeTests/NestedModuleTests.fs @@ -0,0 +1,172 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.NestedModuleTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + + +[] +let ``Range of attribute should be included in SynModuleSigDecl.NestedModule`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace SomeNamespace + +[] +module Nested = + val x : int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.NestedModule _ as nm + ]) as sigModule ])) -> + assertRange (4, 0) (6, 15) nm.Range + assertRange (2, 0) (6, 15) sigModule.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in SynModuleDecl.NestedModule`` () = + let parseResults = + getParseResults + """ +module TopLevel + +[] +module Nested = + ()""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.NestedModule _ as nm + ]) ])) -> + assertRange (4, 0) (6, 6) nm.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present`` () = + let parseResults = + getParseResults + """ +module X = +() +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.NestedModule(trivia = { ModuleKeyword = Some mModule; EqualsRange = Some mEquals }) + ]) ])) -> + assertRange (2, 0) (2, 6) mModule + assertRange (2, 9) (2, 10) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of equal sign should be present, signature file`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace Foo + +module X = +val bar : int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.NestedModule(trivia = { ModuleKeyword = Some mModule; EqualsRange = Some mEquals }) + ]) ])) -> + assertRange (4, 0) (4, 6) mModule + assertRange (4, 9) (4, 10) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of nested module in signature file should end at the last SynModuleSigDecl`` () = + let parseResults = + getParseResultsOfSignatureFile + """namespace Microsoft.FSharp.Core + +open System +open System.Collections.Generic +open Microsoft.FSharp.Core +open Microsoft.FSharp.Collections +open System.Collections + + +module Tuple = + + type Tuple<'T1,'T2,'T3,'T4> = + interface IStructuralEquatable + interface IStructuralComparable + interface IComparable + new : 'T1 * 'T2 * 'T3 * 'T4 -> Tuple<'T1,'T2,'T3,'T4> + member Item1 : 'T1 with get + member Item2 : 'T2 with get + member Item3 : 'T3 with get + member Item4 : 'T4 with get + + +module Choice = + + /// Helper types for active patterns with 6 choices. + [] + [] + type Choice<'T1,'T2,'T3,'T4,'T5,'T6> = + /// Choice 1 of 6 choices + | Choice1Of6 of 'T1 + /// Choice 2 of 6 choices + | Choice2Of6 of 'T2 + /// Choice 3 of 6 choices + | Choice3Of6 of 'T3 + /// Choice 4 of 6 choices + | Choice4Of6 of 'T4 + /// Choice 5 of 6 choices + | Choice5Of6 of 'T5 + /// Choice 6 of 6 choices + | Choice6Of6 of 'T6 + + + +/// Basic F# Operators. This module is automatically opened in all F# code. +[] +module Operators = + + type ``[,]``<'T> with + [] + /// Get the length of an array in the first dimension + member Length1 : int + [] + /// Get the length of the array in the second dimension + member Length2 : int + [] + /// Get the lower bound of the array in the first dimension + member Base1 : int + [] + /// Get the lower bound of the array in the second dimension + member Base2 : int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Open _ + SynModuleSigDecl.Open _ + SynModuleSigDecl.Open _ + SynModuleSigDecl.Open _ + SynModuleSigDecl.Open _ + SynModuleSigDecl.NestedModule(range=mTupleModule; moduleDecls=[ SynModuleSigDecl.Types([ + SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.ObjectModel(range=mTupleObjectModel); range=mTupleType) + ], mTupleTypes) ]) + SynModuleSigDecl.NestedModule(range=mChoiceModule) + SynModuleSigDecl.NestedModule(range=mOperatorsModule; moduleDecls=[ SynModuleSigDecl.Types([ + SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.Simple(range=mAugmentationSimple); range=mAugmentation) + ], mOperatorsTypes) ]) + ]) ])) -> + assertRange (10, 0) (20, 35) mTupleModule + assertRange (12, 4) (20, 35) mTupleTypes + assertRange (12, 9) (20, 35) mTupleType + assertRange (13, 8) (20, 35) mTupleObjectModel + assertRange (23, 0) (40, 25) mChoiceModule + assertRange (44, 0) (60, 26) mOperatorsModule + assertRange (48, 4) (60, 26) mOperatorsTypes + assertRange (48, 9) (60, 26) mAugmentation + assertRange (48, 9) (60, 26) mAugmentationSimple + | _ -> Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/OperatorNameTests.fs b/tests/service/SyntaxTreeTests/OperatorNameTests.fs new file mode 100644 index 00000000000..ce64e19b85e --- /dev/null +++ b/tests/service/SyntaxTreeTests/OperatorNameTests.fs @@ -0,0 +1,486 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.OperatorNameTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.SyntaxTrivia +open NUnit.Framework + +[] +let ``operator as function`` () = + let ast = """ +(+) 3 4 +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr (expr = SynExpr.App(funcExpr = SynExpr.App(funcExpr = + SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotationWithParen(lpr, "+", rpr))]))))) + ]) + ])) -> + assertRange (2, 0) (2, 1) lpr + Assert.AreEqual("op_Addition", ident.idText) + assertRange (2, 2) (2, 3) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``active pattern as function `` () = + let ast = """ +(|Odd|Even|) 4 +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr (expr = SynExpr.App(funcExpr = + SynExpr.LongIdent(false, SynLongIdent([ ident ], _, [ Some(IdentTrivia.HasParenthesis(lpr, rpr)) ]), None, pr))) + ]) + ])) -> + assertRange (2, 0) (2, 1) lpr + Assert.AreEqual("|Odd|Even|", ident.idText) + assertRange (2, 11) (2, 12) rpr + assertRange (2, 0) (2, 12) pr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``partial active pattern as function `` () = + let ast = """ +(|Odd|_|) 4 +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr (expr = SynExpr.App(funcExpr = + SynExpr.LongIdent(false, SynLongIdent([ ident ], _, [ Some(IdentTrivia.HasParenthesis(lpr, rpr)) ]), None, pr))) + ]) + ])) -> + assertRange (2, 0) (2, 1) lpr + Assert.AreEqual("|Odd|_|", ident.idText) + assertRange (2, 8) (2, 9) rpr + assertRange (2, 0) (2, 9) pr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``custom operator definition`` () = + let ast = """ +let (+) a b = a + b +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(headPat= + SynPat.LongIdent(longDotId = SynLongIdent([ ident ],_, [ Some (IdentTrivia.OriginalNotationWithParen(lpr, "+", rpr)) ]))) + ]) + ])])) -> + assertRange (2, 4) (2,5) lpr + Assert.AreEqual("op_Addition", ident.idText) + assertRange (2, 6) (2, 7) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``active pattern definition`` () = + let ast = """ +let (|Odd|Even|) (a: int) = if a % 2 = 0 then Even else Odd +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(headPat= + SynPat.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.HasParenthesis(lpr, rpr))]))) + ]) + ])])) -> + assertRange (2, 4) (2, 5) lpr + Assert.AreEqual("|Odd|Even|", ident.idText) + assertRange (2, 15) (2, 16) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``partial active pattern definition`` () = + let ast = """ +let (|Int32Const|_|) (a: SynConst) = match a with SynConst.Int32 _ -> Some a | _ -> None +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(headPat= + SynPat.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.HasParenthesis(lpr, rpr))]))) + ]) + ])])) -> + assertRange (2, 4) (2, 5) lpr + Assert.AreEqual("|Int32Const|_|", ident.idText) + assertRange (2, 19) (2, 20) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``partial active pattern definition without parameters`` () = + let ast = """ +let (|Boolean|_|) = Boolean.parse +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [SynBinding(headPat= + SynPat.Named(ident = SynIdent(ident, Some (IdentTrivia.HasParenthesis(lpr, rpr))))) + ]) + ])])) -> + assertRange (2, 4) (2, 5) lpr + Assert.AreEqual("|Boolean|_|", ident.idText) + assertRange (2, 16) (2, 17) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + + +[] +let ``operator name in SynValSig`` () = + let ast = """ +module IntrinsicOperators +val (&): e1: bool -> e2: bool -> bool +""" + |> getParseResultsOfSignatureFile + + match ast with + | ParsedInput.SigFile(ParsedSigFileInput(modules = [ + SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Val(valSig = SynValSig(ident = SynIdent(ident, Some (IdentTrivia.OriginalNotationWithParen(lpr, "&", rpr))) + ))]) + ])) -> + assertRange (3, 4) (3, 5) lpr + Assert.AreEqual("op_Amp", ident.idText) + assertRange (3, 6) (3, 7) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``operator name in val constraint`` () = + let ast = + getParseResultsOfSignatureFile """ + [] + module Operators + /// Overloaded unary negation. + /// + /// The value to negate. + /// + /// The result of the operation. + /// + /// + /// + val inline (~-): n: ^T -> ^T when ^T: (static member ( ~- ): ^T -> ^T) and default ^T: int +""" + + match ast with + | ParsedInput.SigFile(ParsedSigFileInput(modules = [ + SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Val(valSig = SynValSig(synType=SynType.WithGlobalConstraints(constraints=[ + SynTypeConstraint.WhereTyparSupportsMember(memberSig=SynMemberSig.Member(memberSig=SynValSig(ident = + SynIdent(ident, Some (IdentTrivia.OriginalNotationWithParen(lpr, "~-", rpr)))))) + SynTypeConstraint.WhereTyparDefaultsToType _ + ]))) + ]) + ])) -> + assertRange (12, 57) (12, 58) lpr + Assert.AreEqual("op_UnaryNegation", ident.idText) + assertRange (12, 62) (12, 63) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``named parameter`` () = + let ast = getParseResults """ +f(x=4) +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.App(argExpr = SynExpr.Paren(expr = SynExpr.App(funcExpr= + SynExpr.App(funcExpr= SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "=")]))))))) + ]) + ])) -> + Assert.AreEqual("op_Equality", ident.idText) + assertRange (2,3) (2,4) ident.idRange + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``infix operation`` () = + let ast = getParseResults """ +1 + 1 +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.App(funcExpr = SynExpr.App(isInfix = true + funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "+")])) + argExpr = SynExpr.Const(SynConst.Int32(1), _)) + argExpr = SynExpr.Const(SynConst.Int32(1), _))) + ]) + ])) -> + Assert.AreEqual("op_Addition", ident.idText) + assertRange (2,2) (2,3) ident.idRange + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``prefix operation`` () = + let ast = getParseResults """ ++ -86 +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.App(isInfix = false + funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "+")])) + argExpr = SynExpr.Const(SynConst.Int32(-86), _))) + ]) + ])) -> + Assert.AreEqual("op_UnaryPlus", ident.idText) + assertRange (2,0) (2,1) ident.idRange + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``prefix operation with two characters`` () = + let ast = getParseResults """ +%%arg +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.App(isInfix = false + funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotation "%%")])) + argExpr = SynExpr.Ident argIdent)) + ]) + ])) -> + Assert.AreEqual("op_SpliceUntyped", ident.idText) + assertRange (2,0) (2,2) ident.idRange + Assert.AreEqual("arg", argIdent.idText) + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``detect difference between compiled operators`` () = + let ast = getParseResults """ +(+) a b +op_Addition a b +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.App(funcExpr = SynExpr.App(isInfix = false + funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([ident], _, [Some (IdentTrivia.OriginalNotationWithParen(lpr, "+", rpr))])) + argExpr = SynExpr.Ident a1) + argExpr = SynExpr.Ident b1)) + SynModuleDecl.Expr(expr = + SynExpr.App(funcExpr = SynExpr.App(isInfix = false + funcExpr = SynExpr.Ident op_Addition + argExpr = SynExpr.Ident a2) + argExpr = SynExpr.Ident b2) + ) + ]) + ])) -> + assertRange (2,0) (2,1) lpr + Assert.AreEqual("op_Addition", ident.idText) + assertRange (2,2) (2,3) rpr + Assert.AreEqual("a", a1.idText) + Assert.AreEqual("b", b1.idText) + + Assert.AreEqual("op_Addition", op_Addition.idText) + Assert.AreEqual("a", a2.idText) + Assert.AreEqual("b", b2.idText) + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``operator in member definition`` () = + let ast = getParseResults """ +type X with + member _.(+) a b = a + b +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [ + SynTypeDefn(members = [ + SynMemberDefn.Member(memberDefn = SynBinding(headPat = SynPat.LongIdent(longDotId = + SynLongIdent([ _; operatorIdent ], [ mDot ], [ None; Some (IdentTrivia.OriginalNotationWithParen(lpr, "+", rpr)) ]) as lid))) + ]) + ] + ) + ]) + ])) -> + assertRange (3,12) (3,13) mDot + assertRange (3,13) (3,14) lpr + Assert.AreEqual("op_Addition", operatorIdent.idText) + assertRange (3,15) (3,16) rpr + assertRange (3,11) (3,15) lid.Range + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``nameof operator`` () = + let ast = getParseResults """ +nameof(+) +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.App(isInfix = false + funcExpr = SynExpr.Ident nameofIdent + argExpr = + SynExpr.LongIdent(longDotId = SynLongIdent([operatorIdent], _, [Some (IdentTrivia.OriginalNotationWithParen(lpr, "+", rpr))])) + ) + ) + ]) + ])) -> + Assert.AreEqual("nameof", nameofIdent.idText) + assertRange (2,6) (2,7) lpr + Assert.AreEqual("op_Addition", operatorIdent.idText) + assertRange (2,8) (2,9) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``optional expression`` () = + let ast = getParseResults """ +f(?x = 7) +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = + SynExpr.App(isInfix = false + funcExpr = SynExpr.Ident f + argExpr = SynExpr.Paren( + SynExpr.App(funcExpr = SynExpr.App( + isInfix = true + funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent([eqIdent], _, [Some (IdentTrivia.OriginalNotation "=")])) + argExpr = SynExpr.LongIdent(true, SynLongIdent([x], [], [None]), _, mOptional) + ) + argExpr = SynExpr.Const(SynConst.Int32 7, _)), lpr, Some rpr, pr))) + ]) + ])) -> + Assert.AreEqual("f", f.idText) + assertRange (2,1) (2,2) lpr + Assert.AreEqual("x", x.idText) + assertRange (2,3) (2, 4) mOptional + Assert.AreEqual("op_Equality", eqIdent.idText) + assertRange (2,8) (2,9) rpr + assertRange (2,1) (2,9) pr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``object model with two members`` () = + let ast = getParseResults """ +type X() = + let mutable allowInto = 0 + member _.AllowIntoPattern with get() = allowInto and set v = allowInto <- v +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [ + SynTypeDefn.SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members =[ + SynMemberDefn.ImplicitCtor _ + SynMemberDefn.LetBindings _ + SynMemberDefn.GetSetMember( + Some (SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = [ _ ; allowIntoPatternGet ])))), + Some (SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = [ _ ; allowIntoPatternSet ])))), + _, + { WithKeyword = mWith; AndKeyword = Some mAnd }) + ])) + ]) + ]) + ])) -> + Assert.AreEqual("AllowIntoPattern", allowIntoPatternGet.idText) + assertRange (4, 30) (4, 34) mWith + Assert.AreEqual("AllowIntoPattern", allowIntoPatternSet.idText) + assertRange (4, 53) (4, 56) mAnd + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``qualified operator expression`` () = + let ast = getParseResults """ +let PowByte (x:byte) n = Checked.( * ) x +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let(bindings = [ + SynBinding(expr = SynExpr.App(funcExpr = + SynExpr.LongIdent(longDotId = SynLongIdent([checkedIdent; operatorIdent], [mDot], [None; Some (IdentTrivia.OriginalNotationWithParen(lpr, "*", rpr))])))) + ]) + ]) + ])) -> + Assert.AreEqual("Checked", checkedIdent.idText) + assertRange (2, 32) (2, 33) mDot + assertRange (2, 33) (2, 34) lpr + Assert.AreEqual("op_Multiply", operatorIdent.idText) + assertRange (2, 37) (2, 38) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" + +[] +let ``active pattern identifier in private member`` () = + let ast = getParseResults """ +type A() = + member private _.(| + A' + |) = (| + Lazy + |) +""" + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [ + SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ + SynMemberDefn.ImplicitCtor _ + SynMemberDefn.Member(memberDefn = SynBinding( + headPat = SynPat.LongIdent(longDotId = SynLongIdent([underscoreIdent; aQuoteIdent], [ _ ], [ None; Some (IdentTrivia.HasParenthesis(lpr, rpr)) ])) + )) + ])) + ]) + ]) + ])) -> + () + Assert.AreEqual("_", underscoreIdent.idText) + Assert.AreEqual("|A'|", aQuoteIdent.idText) + assertRange (3, 21) (3, 22) lpr + assertRange (5, 5) (5, 6) rpr + | _ -> + Assert.Fail $"Could not get valid AST, got {ast}" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/ParsedHashDirectiveTests.fs b/tests/service/SyntaxTreeTests/ParsedHashDirectiveTests.fs new file mode 100644 index 00000000000..d59587c6b36 --- /dev/null +++ b/tests/service/SyntaxTreeTests/ParsedHashDirectiveTests.fs @@ -0,0 +1,61 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.ParsedHashDirectiveTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``SourceIdentifier as ParsedHashDirectiveArgument`` () = + let parseResults = + getParseResults + "#I __SOURCE_DIRECTORY__" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.HashDirective(ParsedHashDirective("I", [ ParsedHashDirectiveArgument.SourceIdentifier(c,_,m) ] , _), _) + ]) ])) -> + Assert.AreEqual("__SOURCE_DIRECTORY__", c) + assertRange (1, 3) (1, 23) m + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Regular String as ParsedHashDirectiveArgument`` () = + let parseResults = + getParseResults + "#I \"/tmp\"" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.HashDirective(ParsedHashDirective("I", [ ParsedHashDirectiveArgument.String(v, SynStringKind.Regular, m) ] , _), _) + ]) ])) -> + Assert.AreEqual("/tmp", v) + assertRange (1, 3) (1, 9) m + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Verbatim String as ParsedHashDirectiveArgument`` () = + let parseResults = + getParseResults + "#I @\"C:\\Temp\"" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.HashDirective(ParsedHashDirective("I", [ ParsedHashDirectiveArgument.String(v, SynStringKind.Verbatim, m) ] , _), _) + ]) ])) -> + Assert.AreEqual("C:\\Temp", v) + assertRange (1, 3) (1, 13) m + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Triple quote String as ParsedHashDirectiveArgument`` () = + let parseResults = + getParseResults + "#nowarn \"\"\"40\"\"\"" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.HashDirective(ParsedHashDirective("nowarn", [ ParsedHashDirectiveArgument.String(v, SynStringKind.TripleQuote, m) ] , _), _) + ]) ])) -> + Assert.AreEqual("40", v) + assertRange (1, 8) (1, 16) m + | _ -> Assert.Fail "Could not get valid AST" diff --git a/tests/service/SyntaxTreeTests/PatternTests.fs b/tests/service/SyntaxTreeTests/PatternTests.fs new file mode 100644 index 00000000000..42905ec976f --- /dev/null +++ b/tests/service/SyntaxTreeTests/PatternTests.fs @@ -0,0 +1,100 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.PatternTestsTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.SyntaxTrivia +open NUnit.Framework + +[] +let ``SynPat.Record contains the range of the equals sign`` () = + let parseResults = + getParseResults + """ +match x with +| { Foo = bar } -> () +| _ -> () +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Match(clauses = [ SynMatchClause(pat = SynPat.Record(fieldPats = [ (_, mEquals, _) ])) ; _ ]) + ) + ]) ])) -> + assertRange (3, 8) (3, 9) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynArgPats.NamePatPairs contains the range of the equals sign`` () = + let parseResults = + getParseResults + """ +match x with +| X(Y = y) -> y +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Match(clauses = [ SynMatchClause(pat = SynPat.LongIdent(argPats = SynArgPats.NamePatPairs(pats = [ _, mEquals ,_ ])))]) + ) + ]) ])) -> + assertRange (3, 7) (3, 8) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynPat.Or contains the range of the bar`` () = + let parseResults = + getParseResults + """ +match x with +| A +| B -> () +| _ -> () +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Match(clauses = [ SynMatchClause(pat = SynPat.Or(trivia={ BarRange = mBar })) ; _ ]) + ) + ]) ])) -> + assertRange (4, 0) (4, 1) mBar + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``:: operator in SynPat.LongIdent`` () = + let parseResults = + getParseResults + """ +let (head::tail) = [ 1;2;4] +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Let( + bindings = [ SynBinding(headPat = SynPat.Paren(SynPat.LongIdent(longDotId = SynLongIdent([ opColonColonIdent ], _, [ Some (IdentTrivia.OriginalNotation "::") ])), _)) ] + ) + ]) ])) -> + Assert.AreEqual("op_ColonColon", opColonColonIdent.idText) + | _ -> Assert.Fail $"Could not get valid AST, got {parseResults}" + +[] +let ``:: operator in match pattern`` () = + let parseResults = + getParseResults + """ +match x with +| (head) :: (tail) -> () +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr( + expr = SynExpr.Match(clauses = [ + SynMatchClause(pat = SynPat.LongIdent(longDotId = SynLongIdent([ opColonColonIdent ], _, [ Some (IdentTrivia.OriginalNotation "::") ]))) + ]) + ) + ]) ])) -> + Assert.AreEqual("op_ColonColon", opColonColonIdent.idText) + | _ -> Assert.Fail $"Could not get valid AST, got {parseResults}" \ No newline at end of file diff --git a/tests/service/SyntaxTreeTests/SignatureTypeTests.fs b/tests/service/SyntaxTreeTests/SignatureTypeTests.fs new file mode 100644 index 00000000000..acc789e1075 --- /dev/null +++ b/tests/service/SyntaxTreeTests/SignatureTypeTests.fs @@ -0,0 +1,427 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.SignatureTypeTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``Range of Type should end at end keyword`` () = + let parseResults = + getParseResultsOfSignatureFile + """namespace GreatProjectThing + +type Meh = + class + end + + +// foo""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types(range = r)]) ])) -> + assertRange (3, 0) (5,11) r + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of SynTypeDefnSig record should end at last member`` () = + let parseResults = + getParseResultsOfSignatureFile + """namespace X +type MyRecord = + { Level: int } + member Score : unit -> int""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes)]) ])) -> + assertRange (2, 0) (4, 30) mTypes + assertRange (2, 5) (4, 30) mSynTypeDefnSig + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of SynTypeDefnSig object model should end at last member`` () = + let parseResults = + getParseResultsOfSignatureFile + """namespace X +type MyRecord = + class + end + member Score : unit -> int""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes)]) ])) -> + assertRange (2, 0) (5, 30) mTypes + assertRange (2, 5) (5, 30) mSynTypeDefnSig + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of SynTypeDefnSig delegate of should start from name`` () = + let parseResults = + getParseResultsOfSignatureFile + """namespace Y +type MyFunction = + delegate of int -> string""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes) ]) ])) -> + assertRange (2, 0) (3, 29) mTypes + assertRange (2, 5) (3, 29) mSynTypeDefnSig + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of SynTypeDefnSig simple should end at last val`` () = + let parseResults = + getParseResultsOfSignatureFile + """namespace Z +type SomeCollection with + val LastIndex : int + val SomeThingElse : int -> string""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([SynTypeDefnSig.SynTypeDefnSig(range=mSynTypeDefnSig)], mTypes)]) ])) -> + assertRange (2, 0) (4, 37) mTypes + assertRange (2, 5) (4, 37) mSynTypeDefnSig + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in SynTypeDefnSig`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace SomeNamespace + +[] +type MyType = + class + end +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types(types = [SynTypeDefnSig.SynTypeDefnSig(range = r)]) as t]) ])) -> + assertRange (4, 0) (7, 7) r + assertRange (4, 0) (7, 7) t.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attributes should be included in recursive types`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace SomeNamespace + +type Foo = + | Bar + +and [] Bang = + internal + { + LongNameBarBarBarBarBarBarBar: int + } + override GetHashCode : unit -> int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = [SynModuleSigDecl.Types([ + SynTypeDefnSig.SynTypeDefnSig(range = r1) + SynTypeDefnSig.SynTypeDefnSig(range = r2) + ], mTypes)]) ])) -> + assertRange (4, 5) (5, 9) r1 + assertRange (7, 4) (12, 42) r2 + assertRange (4, 0) (12, 42) mTypes + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in SynValSpfn and Member`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace SomeNamespace + +type FooType = + [] // ValSpfn + abstract x : int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ + SynModuleOrNamespaceSig(decls = + [ SynModuleSigDecl.Types(types = [ + SynTypeDefnSig.SynTypeDefnSig(typeRepr = + SynTypeDefnSigRepr.ObjectModel(memberSigs = [ + SynMemberSig.Member(range = mr; memberSig = SynValSig(range = mv)) ])) + ]) ]) ])) -> + assertRange (5, 4) (6, 20) mr + assertRange (5, 4) (6, 20) mv + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefnSig with ObjectModel Delegate contains the range of the equals sign`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace Foo + +type X = delegate of string -> string +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Types( + types = [ SynTypeDefnSig(equalsRange = Some mEquals + typeRepr = SynTypeDefnSigRepr.ObjectModel(kind = SynTypeDefnKind.Delegate _)) ] + ) + ]) ])) -> + assertRange (4, 7) (4, 8) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefnSig with ObjectModel class contains the range of the equals sign`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace SomeNamespace + +type Foobar = + class + end +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Types( + types = [ SynTypeDefnSig(equalsRange = Some mEquals + typeRepr = SynTypeDefnSigRepr.ObjectModel(kind = SynTypeDefnKind.Class)) ] + ) + ]) ])) -> + assertRange (4, 12) (4, 13) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefnSig with Enum contains the range of the equals sign`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace SomeNamespace + +type Bear = + | BlackBear = 1 + | PolarBear = 2 +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Types( + types = [ SynTypeDefnSig(equalsRange = Some mEquals + typeRepr = SynTypeDefnSigRepr.Simple(repr = + SynTypeDefnSimpleRepr.Enum(cases = [ + SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase1 }) + SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase2 }) + ]) )) ] + ) + ]) ])) -> + assertRange (4, 10) (4, 11) mEquals + assertRange (5, 16) (5, 17) mEqualsEnumCase1 + assertRange (6, 16) (6, 17) mEqualsEnumCase2 + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefnSig with Union contains the range of the equals sign`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace SomeNamespace + +type Shape = +| Square of int +| Rectangle of int * int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Types( + types = [ SynTypeDefnSig(equalsRange = Some mEquals + typeRepr = SynTypeDefnSigRepr.Simple(repr = SynTypeDefnSimpleRepr.Union _)) ] + ) + ]) ])) -> + assertRange (4, 11) (4, 12) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefnSig should contains the range of the with keyword`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace X + +type Foo with +member Meh : unit -> unit +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules =[ SynModuleOrNamespaceSig(decls =[ + SynModuleSigDecl.Types( + types=[ SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.Simple _ + withKeyword=Some mWithKeyword) ] + ) + ]) ])) -> + assertRange (4, 9) (4, 13) mWithKeyword + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynExceptionSig should contains the range of the with keyword`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace X + +exception Foo with +member Meh : unit -> unit +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Exception( + exnSig=SynExceptionSig(withKeyword = Some mWithKeyword) + ) + ]) ])) -> + assertRange (4, 14) (4, 18) mWithKeyword + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``memberSig of SynMemberSig.Member should contains the range of the with keyword`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +namespace X + +type Foo = + abstract member Bar : int with get,set +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules = [ SynModuleOrNamespaceSig(decls = [ + SynModuleSigDecl.Types( + types=[ SynTypeDefnSig(typeRepr=SynTypeDefnSigRepr.ObjectModel(memberSigs=[SynMemberSig.Member(memberSig=SynValSig(trivia = { WithKeyword = Some mWithKeyword }))])) ] + ) + ]) ])) -> + assertRange (5, 30) (5, 34) mWithKeyword + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in SynExceptionDefnRepr and SynExceptionSig`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +module internal FSharp.Compiler.ParseHelpers + +// The error raised by the parse_error_rich function, which is called by the parser engine +[] +exception SyntaxError of obj * range: range + + +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules=[ + SynModuleOrNamespaceSig(decls=[ + SynModuleSigDecl.Exception( + SynExceptionSig(exnRepr=SynExceptionDefnRepr(range=mSynExceptionDefnRepr); range=mSynExceptionSig), mException) + ] ) ])) -> + assertRange (5, 0) (6, 43) mSynExceptionDefnRepr + assertRange (5, 0) (6, 43) mSynExceptionSig + assertRange (5, 0) (6, 43) mException + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of members should be included in SynExceptionSig and SynModuleSigDecl.Exception`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +module internal FSharp.Compiler.ParseHelpers + +exception SyntaxError of obj * range: range with + member Meh : string -> int + +open Foo +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules=[ + SynModuleOrNamespaceSig(decls=[ + SynModuleSigDecl.Exception( + SynExceptionSig(exnRepr=SynExceptionDefnRepr(range=mSynExceptionDefnRepr); range=mSynExceptionSig), mException) + SynModuleSigDecl.Open _ + ] ) ])) -> + assertRange (4, 0) (4, 43) mSynExceptionDefnRepr + assertRange (4, 0) (5, 30) mSynExceptionSig + assertRange (4, 0) (5, 30) mException + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Val keyword is present in SynValSig`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +module Meh + +[] +// meh +val a : int +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules=[ + SynModuleOrNamespaceSig(decls=[ + SynModuleSigDecl.Val(valSig = SynValSig(trivia = { ValKeyword = Some mVal })) + ] ) ])) -> + assertRange (6, 0) (6, 3) mVal + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Equals token is present in SynValSig value`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +module Meh + +val a : int = 9 +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules=[ + SynModuleOrNamespaceSig(decls=[ + SynModuleSigDecl.Val(valSig = SynValSig(trivia = { EqualsRange = Some mEquals }); range = mVal) + ] ) ])) -> + assertRange (4, 12) (4, 13) mEquals + assertRange (4, 0) (4, 15) mVal + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Equals token is present in SynValSig member`` () = + let parseResults = + getParseResultsOfSignatureFile + """ +module Meh + +type X = + member a : int = 10 +""" + + match parseResults with + | ParsedInput.SigFile (ParsedSigFileInput (modules=[ + SynModuleOrNamespaceSig(decls=[ + SynModuleSigDecl.Types(types = [ + SynTypeDefnSig(typeRepr = SynTypeDefnSigRepr.ObjectModel(memberSigs = [ + SynMemberSig.Member(memberSig = SynValSig(trivia = { EqualsRange = Some mEquals }); range = mMember) + ])) + ]) + ] ) ])) -> + assertRange (5, 19) (5, 20) mEquals + assertRange (5, 4) (5, 23) mMember + | _ -> Assert.Fail "Could not get valid AST" diff --git a/tests/service/SyntaxTreeTests/SourceIdentifierTests.fs b/tests/service/SyntaxTreeTests/SourceIdentifierTests.fs new file mode 100644 index 00000000000..190f2664574 --- /dev/null +++ b/tests/service/SyntaxTreeTests/SourceIdentifierTests.fs @@ -0,0 +1,48 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.SourceIdentifierTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + + +[] +let ``__LINE__`` () = + let parseResults = + getParseResults + """ +__LINE__""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Const(SynConst.SourceIdentifier("__LINE__", "2", range), _)) + ]) ])) -> + assertRange (2, 0) (2, 8) range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``__SOURCE_DIRECTORY__`` () = + let parseResults = + getParseResults + """ +__SOURCE_DIRECTORY__""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Const(SynConst.SourceIdentifier("__SOURCE_DIRECTORY__", _, range), _)) + ]) ])) -> + assertRange (2, 0) (2, 20) range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``__SOURCE_FILE__`` () = + let parseResults = + getParseResults + """ +__SOURCE_FILE__""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Expr(expr = SynExpr.Const(SynConst.SourceIdentifier("__SOURCE_FILE__", _, range), _)) + ]) ])) -> + assertRange (2, 0) (2, 15) range + | _ -> Assert.Fail "Could not get valid AST" diff --git a/tests/service/SyntaxTreeTests/StringTests.fs b/tests/service/SyntaxTreeTests/StringTests.fs new file mode 100644 index 00000000000..d75384d8f60 --- /dev/null +++ b/tests/service/SyntaxTreeTests/StringTests.fs @@ -0,0 +1,121 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.StringTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework +open FsUnit + +let private getBindingExpressionValue (parseResults: ParsedInput) = + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = modules)) -> + modules |> List.tryPick (fun (SynModuleOrNamespace (decls = decls)) -> + decls |> List.tryPick (fun decl -> + match decl with + | SynModuleDecl.Let (bindings = bindings) -> + bindings |> List.tryPick (fun binding -> + match binding with + | SynBinding.SynBinding (headPat=(SynPat.Named _|SynPat.As(_,SynPat.Named _,_)); expr=e) -> Some e + | _ -> None) + | _ -> None)) + | _ -> None + +let private getBindingConstValue parseResults = + match getBindingExpressionValue parseResults with + | Some (SynExpr.Const(c,_)) -> Some c + | _ -> None + +[] +let ``SynConst.String with SynStringKind.Regular`` () = + let parseResults = + getParseResults + """ +let s = "yo" +""" + + match getBindingConstValue parseResults with + | Some (SynConst.String (_, kind, _)) -> kind |> should equal SynStringKind.Regular + | _ -> Assert.Fail "Couldn't find const" + +[] +let ``SynConst.String with SynStringKind.Verbatim`` () = + let parseResults = + getParseResults + """ +let s = @"yo" +""" + + match getBindingConstValue parseResults with + | Some (SynConst.String (_, kind, _)) -> kind |> should equal SynStringKind.Verbatim + | _ -> Assert.Fail "Couldn't find const" + +[] +let ``SynConst.String with SynStringKind.TripleQuote`` () = + let parseResults = + getParseResults + " +let s = \"\"\"yo\"\"\" +" + + match getBindingConstValue parseResults with + | Some (SynConst.String (_, kind, _)) -> kind |> should equal SynStringKind.TripleQuote + | _ -> Assert.Fail "Couldn't find const" + +[] +let ``SynConst.Bytes with SynByteStringKind.Regular`` () = + let parseResults = + getParseResults + """ +let bytes = "yo"B +""" + + match getBindingConstValue parseResults with + | Some (SynConst.Bytes (_, kind, _)) -> kind |> should equal SynByteStringKind.Regular + | _ -> Assert.Fail "Couldn't find const" + +[] +let ``SynConst.Bytes with SynByteStringKind.Verbatim`` () = + let parseResults = + getParseResults + """ +let bytes = @"yo"B +""" + + match getBindingConstValue parseResults with + | Some (SynConst.Bytes (_, kind, _)) -> kind |> should equal SynByteStringKind.Verbatim + | _ -> Assert.Fail "Couldn't find const" + +[] +let ``SynExpr.InterpolatedString with SynStringKind.TripleQuote`` () = + let parseResults = + getParseResults + " +let s = $\"\"\"yo {42}\"\"\" +" + + match getBindingExpressionValue parseResults with + | Some (SynExpr.InterpolatedString(_, kind, _)) -> kind |> should equal SynStringKind.TripleQuote + | _ -> Assert.Fail "Couldn't find const" + +[] +let ``SynExpr.InterpolatedString with SynStringKind.Regular`` () = + let parseResults = + getParseResults + """ +let s = $"yo {42}" +""" + + match getBindingExpressionValue parseResults with + | Some (SynExpr.InterpolatedString(_, kind, _)) -> kind |> should equal SynStringKind.Regular + | _ -> Assert.Fail "Couldn't find const" + +[] +let ``SynExpr.InterpolatedString with SynStringKind.Verbatim`` () = + let parseResults = + getParseResults + """ +let s = $@"Migrate notes of file ""{oldId}"" to new file ""{newId}""." +""" + + match getBindingExpressionValue parseResults with + | Some (SynExpr.InterpolatedString(_, kind, _)) -> kind |> should equal SynStringKind.Verbatim + | _ -> Assert.Fail "Couldn't find const" diff --git a/tests/service/SyntaxTreeTests/TypeTests.fs b/tests/service/SyntaxTreeTests/TypeTests.fs new file mode 100644 index 00000000000..b965d7e929e --- /dev/null +++ b/tests/service/SyntaxTreeTests/TypeTests.fs @@ -0,0 +1,486 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.TypeTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.SyntaxTrivia +open NUnit.Framework + +[] +let ``Single SynEnumCase contains range of constant`` () = + let parseResults = + getParseResults + """ +type Foo = One = 0x00000001 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [ + SynTypeDefn.SynTypeDefn(typeRepr = + SynTypeDefnRepr.Simple(simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ SynEnumCase.SynEnumCase(valueRange = r) ])))]) + ]) ])) -> + assertRange (2, 17) (2, 27) r + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Multiple SynEnumCase contains range of constant`` () = + let parseResults = + getParseResults + """ +type Foo = + | One = 0x00000001 + | Two = 2 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [ + SynTypeDefn.SynTypeDefn(typeRepr = + SynTypeDefnRepr.Simple(simpleRepr = SynTypeDefnSimpleRepr.Enum(cases = [ SynEnumCase.SynEnumCase(valueRange = r1) + SynEnumCase.SynEnumCase(valueRange = r2) ])))]) + ]) ])) -> + assertRange (3, 13) (3, 23) r1 + assertRange (4, 12) (4, 13) r2 + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attribute should be included in SynTypeDefn`` () = + let parseResults = + getParseResults + """ +[] +type Bar = + class + end""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [t]) as types + ]) ])) -> + assertRange (2, 0) (5, 7) types.Range + assertRange (2, 0) (5, 7) t.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``Range of attributes should be included in recursive types`` () = + let parseResults = + getParseResults + """ +[] +type Foo<'context, 'a> = + | Apply of ApplyCrate<'context, 'a> + +and [] Bar<'context, 'a> = + internal { + Hash : int + Foo : Foo<'a, 'b> + }""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [t1;t2]) as types + ]) ])) -> + assertRange (2, 0) (10, 5) types.Range + assertRange (2, 0) (4, 39) t1.Range + assertRange (6, 4) (10, 5) t2.Range + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with ObjectModel Delegate contains the range of the equals sign`` () = + let parseResults = + getParseResults + """ +type X = delegate of string -> string +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(kind = SynTypeDefnKind.Delegate _) + trivia={ EqualsRange = Some mEquals }) ] + ) + ]) ])) -> + assertRange (2, 7) (2, 8) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with ObjectModel class contains the range of the equals sign`` () = + let parseResults = + getParseResults + """ +type Foobar () = + class + end +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(kind = SynTypeDefnKind.Class) + trivia={ EqualsRange = Some mEquals }) ] + ) + ]) ])) -> + assertRange (2, 15) (2, 16) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with Enum contains the range of the equals sign`` () = + let parseResults = + getParseResults + """ +type Bear = + | BlackBear = 1 + | PolarBear = 2 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(simpleRepr = + SynTypeDefnSimpleRepr.Enum(cases = [ + SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase1 }) + SynEnumCase(trivia={ EqualsRange = mEqualsEnumCase2 }) + ])) + trivia={ EqualsRange = Some mEquals }) ] + ) + ]) ])) -> + assertRange (2, 10) (2, 11) mEquals + assertRange (3, 16) (3, 17) mEqualsEnumCase1 + assertRange (4, 16) (4, 17) mEqualsEnumCase2 + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with Union contains the range of the equals sign`` () = + let parseResults = + getParseResults + """ +type Shape = + | Square of int + | Rectangle of int * int +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(simpleRepr = SynTypeDefnSimpleRepr.Union _) + trivia={ EqualsRange = Some mEquals }) ] + ) + ]) ])) -> + assertRange (2, 11) (2, 12) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with AutoProperty contains the range of the equals sign`` () = + let parseResults = + getParseResults + """ +/// mutable class with auto-properties +type Person(name : string, age : int) = + /// Full name + member val Name = name with get, set +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [_ ; SynMemberDefn.AutoProperty(equalsRange = mEquals)])) ] + ) + ]) ])) -> + assertRange (5, 20) (5, 21) mEquals + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with Record contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Foo = + { Bar : int } + with + member this.Meh (v:int) = this.Bar + v +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr=SynTypeDefnRepr.Simple(simpleRepr= SynTypeDefnSimpleRepr.Record _) + trivia={ WithKeyword = Some mWithKeyword }) ] + ) + ]) ])) -> + assertRange (4, 4) (4, 8) mWithKeyword + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with Augmentation contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Int32 with + member _.Zero = 0 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(kind=SynTypeDefnKind.Augmentation mWithKeyword)) ] + ) + ]) ])) -> + assertRange (2, 11) (2, 15) mWithKeyword + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynMemberDefn.Interface contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Foo() = + interface Bar with + member Meh () = () + interface Other +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members=[ SynMemberDefn.ImplicitCtor _ + SynMemberDefn.Interface(withKeyword=Some mWithKeyword) + SynMemberDefn.Interface(withKeyword=None) ])) ] + ) + ]) ])) -> + assertRange (3, 18) (3, 22) mWithKeyword + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with AutoProperty contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Foo() = + member val AutoProperty = autoProp with get, set + member val AutoProperty2 = autoProp +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [_ + SynMemberDefn.AutoProperty(withKeyword=Some mWith) + SynMemberDefn.AutoProperty(withKeyword=None)])) ] + ) + ]) ])) -> + assertRange (3, 39) (3, 43) mWith + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with AbstractSlot contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Foo() = + abstract member Bar : int with get,set +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [_ + SynMemberDefn.AbstractSlot(slotSig=SynValSig(trivia = { WithKeyword = Some mWith }))])) ] + ) + ]) ])) -> + assertRange (3, 30) (3, 34) mWith + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``read-only property in SynMemberDefn.Member contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Foo() = + // A read-only property. + member this.MyReadProperty with get () = myInternalValue +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = + SynTypeDefnRepr.ObjectModel(members=[ + _ + SynMemberDefn.GetSetMember(Some(SynBinding _), None, _, { WithKeyword = mWith }) ]) + ) ]) + ]) ])) -> + assertRange (4, 31) (4, 35) mWith + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``write-only property in SynMemberDefn.Member contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Foo() = + // A write-only property. + member this.MyWriteOnlyProperty with set (value) = myInternalValue <- value +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = + SynTypeDefnRepr.ObjectModel(members=[ + _ + SynMemberDefn.GetSetMember(None, Some(SynBinding _), _, { WithKeyword = mWith }) ]) + ) ]) + ]) ])) -> + assertRange (4, 36) (4, 40) mWith + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``read/write property in SynMemberDefn.Member contains the range of the with keyword`` () = + let parseResults = + getParseResults + """ +type Foo() = + // A read-write property. + member this.MyReadWriteProperty + with get () = myInternalValue + and set (value) = myInternalValue <- value +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = + SynTypeDefnRepr.ObjectModel(members=[ + _ + SynMemberDefn.GetSetMember(Some _, Some _, _, { WithKeyword = mWith; AndKeyword = Some mAnd }) ]) + ) ]) + ]) ])) -> + assertRange (5, 8) (5, 12) mWith + assertRange (6, 8) (6, 11) mAnd + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with XmlDoc contains the range of the type keyword`` () = + let parseResults = + getParseResults + """ +/// Doc +// noDoc +type A = B +and C = D +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(trivia={ TypeKeyword = Some mType }) + SynTypeDefn(trivia={ TypeKeyword = None }) ] + ) + ]) ])) -> + assertRange (4, 0) (4, 4) mType + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with attribute contains the range of the type keyword`` () = + let parseResults = + getParseResults + """ +[] +// noDoc +type A = B +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(trivia={ TypeKeyword = Some mType }) ] + ) + ]) ])) -> + assertRange (4, 0) (4, 4) mType + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with static member with get/set`` () = + let parseResults = + getParseResults + """ +type Foo = + static member ReadWrite2 + with set x = lastUsed <- ("ReadWrite2", x) + and get () = lastUsed <- ("ReadWrite2", 0); 4 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ + SynMemberDefn.GetSetMember(Some _, Some _, m, { WithKeyword = mWith + GetKeyword = Some mGet + AndKeyword = Some mAnd + SetKeyword = Some mSet }) + ])) ] + ) + ]) ])) -> + assertRange (4, 8) (4, 12) mWith + assertRange (4, 13) (4, 16) mSet + assertRange (5, 8) (5, 11) mAnd + assertRange (5, 13) (5, 16) mGet + assertRange (3, 4) (5, 54) m + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynTypeDefn with member with set/get`` () = + let parseResults = + getParseResults + """ +type A() = + member this.Z with set (_:int):unit = () and get():int = 1 +""" + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput (modules = [ SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types( + typeDefns = [ SynTypeDefn(typeRepr = SynTypeDefnRepr.ObjectModel(members = [ + SynMemberDefn.ImplicitCtor _ + SynMemberDefn.GetSetMember(Some (SynBinding(headPat = SynPat.LongIdent(extraId = Some getIdent))), + Some (SynBinding(headPat = SynPat.LongIdent(extraId = Some setIdent))), + m, + { WithKeyword = mWith + GetKeyword = Some mGet + AndKeyword = Some mAnd + SetKeyword = Some mSet }) + ])) ] + ) + ]) ])) -> + Assert.AreEqual("get", getIdent.idText) + Assert.AreEqual("set", setIdent.idText) + assertRange (3, 18) (3, 22) mWith + assertRange (3, 23) (3, 26) mSet + assertRange (3, 23) (3, 26) setIdent.idRange + assertRange (3, 45) (3, 48) mAnd + assertRange (3, 49) (3, 52) mGet + assertRange (3, 49) (3, 52) getIdent.idRange + assertRange (3, 4) (3, 62) m + | _ -> Assert.Fail "Could not get valid AST" + +[] +let ``SynType.Fun has range of arrow`` () = + let parseResults = + getParseResults + """ + type X = string -> // after a tuple, mixed needs an indent + int + """ + + match parseResults with + | ParsedInput.ImplFile (ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types(typeDefns = [ + SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(simpleRepr = + SynTypeDefnSimpleRepr.TypeAbbrev(rhsType = + SynType.Fun(trivia = { ArrowRange = mArrow })))) + ]) + ]) + ])) -> + assertRange (2, 21) (2, 23) mArrow + | _ -> Assert.Fail $"Could not get valid AST, got {parseResults}" diff --git a/tests/service/SyntaxTreeTests/UnionCaseTests.fs b/tests/service/SyntaxTreeTests/UnionCaseTests.fs new file mode 100644 index 00000000000..2cb1f80b730 --- /dev/null +++ b/tests/service/SyntaxTreeTests/UnionCaseTests.fs @@ -0,0 +1,138 @@ +module FSharp.Compiler.Service.Tests.SyntaxTreeTests.UnionCaseTestsTests + +open System +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +[] +let ``Union Case fields can have comments`` () = + let ast = """ +type Foo = +/// docs for Thing +| Thing of + /// docs for first + first: string * + /// docs for anon field + bool +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ + SynUnionCase.SynUnionCase (caseType = SynUnionCaseKind.Fields [ + SynField.SynField(xmlDoc = firstXml) + SynField.SynField(xmlDoc = anonXml) + ]) + ]))) + ], _) + ]) + ])) -> + let firstDocs = firstXml.ToXmlDoc(false, None).GetXmlText() + let anonDocs = anonXml.ToXmlDoc(false, None).GetXmlText() + + let nl = Environment.NewLine + + Assert.AreEqual($"{nl} docs for first{nl}", firstDocs) + Assert.AreEqual($"{nl} docs for anon field{nl}", anonDocs) + + | _ -> + failwith "Could not find SynExpr.Do" + +[] +let ``single SynUnionCase has bar range`` () = + let ast = """ +type Foo = | Bar of string +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ + SynUnionCase.SynUnionCase (trivia = { BarRange = Some mBar }) + ]))) + ], _) + ]) + ])) -> + assertRange (2, 11) (2, 12) mBar + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``multiple SynUnionCases have bar range`` () = + let ast = """ +type Foo = + | Bar of string + | Bear of int +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ + SynUnionCase.SynUnionCase (trivia = { BarRange = Some mBar1 }) + SynUnionCase.SynUnionCase (trivia = { BarRange = Some mBar2 }) + ]))) + ], _) + ]) + ])) -> + assertRange (3, 4) (3, 5) mBar1 + assertRange (4, 4) (4, 5) mBar2 + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``single SynUnionCase without bar`` () = + let ast = """ +type Foo = Bar of string +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union(unionCases = [ + SynUnionCase.SynUnionCase (trivia = { BarRange = None }) + ]))) + ], _) + ]) + ])) -> + Assert.Pass() + | _ -> + Assert.Fail "Could not get valid AST" + +[] +let ``private keyword has range`` () = + let ast = """ +type Currency = + // Temporary fix until a new Thoth.Json.Net package is released + // See https://github.com/MangelMaxime/Thoth/pull/70 + +#if !FABLE_COMPILER + private +#endif + | Code of string +""" + |> getParseResults + + match ast with + | ParsedInput.ImplFile(ParsedImplFileInput(modules = [ + SynModuleOrNamespace.SynModuleOrNamespace(decls = [ + SynModuleDecl.Types ([ + SynTypeDefn.SynTypeDefn (typeRepr = SynTypeDefnRepr.Simple (simpleRepr = SynTypeDefnSimpleRepr.Union( + accessibility = Some (SynAccess.Private mPrivate) + unionCases = [ SynUnionCase.SynUnionCase _ ]))) + ], _) + ]) + ])) -> + assertRange (7, 4) (7, 11) mPrivate + | _ -> + Assert.Fail "Could not get valid AST" \ No newline at end of file diff --git a/tests/service/XmlDocTests.fs b/tests/service/XmlDocTests.fs index 2822ab041e2..76bce785065 100644 --- a/tests/service/XmlDocTests.fs +++ b/tests/service/XmlDocTests.fs @@ -4,6 +4,7 @@ #load "FsUnit.fs" #load "Common.fs" #else +[] module Tests.Service.XmlDocTests.XmlDoc #endif @@ -896,7 +897,7 @@ type B = |] match parseResults.ParseTree with - | Members(SynMemberDefn.Member(range = range; memberDefn = SynBinding(xmlDoc = xmlDoc) as binding) :: _) -> + | Members([ SynMemberDefn.GetSetMember(Some (SynBinding(xmlDoc = xmlDoc) as binding), _, range, _); _ ]) -> assertRange (3, 4) (10, 37) range assertRange (3, 4) (8, 37) binding.RangeOfBindingWithRhs assertRange (3, 4) (4, 9) xmlDoc.Range diff --git a/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest b/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest index 5151aa32db6..fb2764e3d58 100644 --- a/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest +++ b/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest @@ -15,8 +15,10 @@ + + @@ -47,7 +49,6 @@ - diff --git a/vsintegration/Vsix/VisualFSharpFull/VisualFSharp.Core.targets b/vsintegration/Vsix/VisualFSharpFull/VisualFSharp.Core.targets index 36205c72766..8205ac783f3 100644 --- a/vsintegration/Vsix/VisualFSharpFull/VisualFSharp.Core.targets +++ b/vsintegration/Vsix/VisualFSharpFull/VisualFSharp.Core.targets @@ -33,7 +33,7 @@ All 2 True - TargetFramework=$(DependencyTargetFramework) + TargetFramework=netstandard2.0 @@ -84,22 +84,40 @@ TargetFramework=netstandard2.0 - + + false + False + + + + false + False + true + Arm64 + 2 + TargetFramework=$(DependencyTargetFramework) + + + false False - + false False - + false False + true + Arm64 + 2 + TargetFramework=$(DependencyTargetFramework) - + false False @@ -170,7 +188,7 @@ {FCFB214C-462E-42B3-91CA-FC557EFEE74F} FSharp.PropertiesPages - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All diff --git a/vsintegration/Vsix/VisualFSharpFull/VisualFSharpDebug.csproj b/vsintegration/Vsix/VisualFSharpFull/VisualFSharpDebug.csproj index 23564372ab8..96fd6dc836d 100644 --- a/vsintegration/Vsix/VisualFSharpFull/VisualFSharpDebug.csproj +++ b/vsintegration/Vsix/VisualFSharpFull/VisualFSharpDebug.csproj @@ -41,6 +41,16 @@ true + + Tools/%(_XlfLanguages.Identity) + true + + + + Tools/%(_XlfLanguages.Identity) + true + + Tools true @@ -51,6 +61,11 @@ true + + Tools + true + + Tools true @@ -60,6 +75,11 @@ Tools true + + + Tools + true + diff --git a/vsintegration/shims/Microsoft.FSharp.ShimHelpers.props b/vsintegration/shims/Microsoft.FSharp.ShimHelpers.props index f98483ba441..defb925296d 100644 --- a/vsintegration/shims/Microsoft.FSharp.ShimHelpers.props +++ b/vsintegration/shims/Microsoft.FSharp.ShimHelpers.props @@ -14,7 +14,8 @@ --> true - fsc.exe + fsc.exe + fscArm64.exe fscAnyCpu.exe $(NetCoreRoot)sdk/$(NETCoreSdkVersion)/FSharp/ @@ -34,7 +35,7 @@ <_FSCorePackageVersionSet>true - 6.0.3 + 6.0.4 diff --git a/vsintegration/src/FSharp.Editor/Common/Extensions.fs b/vsintegration/src/FSharp.Editor/Common/Extensions.fs index 60eb69bc288..fd9b80fff00 100644 --- a/vsintegration/src/FSharp.Editor/Common/Extensions.fs +++ b/vsintegration/src/FSharp.Editor/Common/Extensions.fs @@ -157,68 +157,68 @@ type NavigationItem with | FSharpGlyph.Type | FSharpGlyph.Exception -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.ClassPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.ClassInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.ClassPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.ClassInternal | _ -> FSharpRoslynGlyph.ClassPublic | FSharpGlyph.Constant -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.ConstantPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.ConstantInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.ConstantPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.ConstantInternal | _ -> FSharpRoslynGlyph.ConstantPublic | FSharpGlyph.Delegate -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.DelegatePrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.DelegateInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.DelegatePrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.DelegateInternal | _ -> FSharpRoslynGlyph.DelegatePublic | FSharpGlyph.Union | FSharpGlyph.Enum -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.EnumPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.EnumInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.EnumPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.EnumInternal | _ -> FSharpRoslynGlyph.EnumPublic | FSharpGlyph.EnumMember | FSharpGlyph.Variable | FSharpGlyph.Field -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.FieldPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.FieldInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.FieldPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.FieldInternal | _ -> FSharpRoslynGlyph.FieldPublic | FSharpGlyph.Event -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.EventPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.EventInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.EventPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.EventInternal | _ -> FSharpRoslynGlyph.EventPublic | FSharpGlyph.Interface -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.InterfacePrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.InterfaceInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.InterfacePrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.InterfaceInternal | _ -> FSharpRoslynGlyph.InterfacePublic | FSharpGlyph.Method | FSharpGlyph.OverridenMethod -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.MethodPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.MethodInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.MethodPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.MethodInternal | _ -> FSharpRoslynGlyph.MethodPublic | FSharpGlyph.Module -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.ModulePrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.ModuleInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.ModulePrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.ModuleInternal | _ -> FSharpRoslynGlyph.ModulePublic | FSharpGlyph.NameSpace -> FSharpRoslynGlyph.Namespace | FSharpGlyph.Property -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.PropertyPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.PropertyInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.PropertyPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.PropertyInternal | _ -> FSharpRoslynGlyph.PropertyPublic | FSharpGlyph.Struct -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.StructurePrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.StructureInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.StructurePrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.StructureInternal | _ -> FSharpRoslynGlyph.StructurePublic | FSharpGlyph.ExtensionMethod -> match x.Access with - | Some SynAccess.Private -> FSharpRoslynGlyph.ExtensionMethodPrivate - | Some SynAccess.Internal -> FSharpRoslynGlyph.ExtensionMethodInternal + | Some (SynAccess.Private _) -> FSharpRoslynGlyph.ExtensionMethodPrivate + | Some (SynAccess.Internal _) -> FSharpRoslynGlyph.ExtensionMethodInternal | _ -> FSharpRoslynGlyph.ExtensionMethodPublic | FSharpGlyph.Error -> FSharpRoslynGlyph.Error | FSharpGlyph.TypeParameter -> FSharpRoslynGlyph.TypeParameter diff --git a/vsintegration/src/FSharp.Editor/Formatting/EditorFormattingService.fs b/vsintegration/src/FSharp.Editor/Formatting/EditorFormattingService.fs index 778dc22b0dd..a21a230d617 100644 --- a/vsintegration/src/FSharp.Editor/Formatting/EditorFormattingService.fs +++ b/vsintegration/src/FSharp.Editor/Formatting/EditorFormattingService.fs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. namespace Microsoft.VisualStudio.FSharp.Editor @@ -167,14 +167,17 @@ type internal FSharpEditorFormattingService return textChanges |> Option.defaultValue Seq.empty |> toIList } - interface IFSharpEditorFormattingService with + interface IFSharpEditorFormattingServiceWithOptions with member val SupportsFormatDocument = false member val SupportsFormatSelection = false member val SupportsFormatOnPaste = true member val SupportsFormatOnReturn = true - override _.SupportsFormattingOnTypedCharacter (document, ch) = - if FSharpIndentationService.IsSmartIndentEnabled document.Project.Solution.Workspace.Options then + override _.SupportsFormattingOnTypedCharacter (_document, _ch) = + false + + override _.SupportsFormattingOnTypedCharacter (_document, options, ch) = + if options.IndentStyle = FormattingOptions.IndentStyle.Smart then match ch with | ')' | ']' | '}' -> true | _ -> false diff --git a/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs b/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs index ec73168c1f7..c0c4ce2b294 100644 --- a/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs +++ b/vsintegration/src/FSharp.Editor/Formatting/IndentationService.fs @@ -23,9 +23,6 @@ type internal FSharpIndentationService [] () = - static member IsSmartIndentEnabled (options: Microsoft.CodeAnalysis.Options.OptionSet) = - options.GetOption(FormattingOptions.SmartIndent, FSharpConstants.FSharpLanguageName) = FormattingOptions.IndentStyle.Smart - static member IndentShouldFollow (documentId: DocumentId, sourceText: SourceText, filePath: string, position: int, parsingOptions: FSharpParsingOptions) = let lastTokenOpt = let defines = CompilerEnvironment.GetConditionalDefinesForEditing parsingOptions diff --git a/vsintegration/src/FSharp.Editor/InlineRename/InlineRenameService.fs b/vsintegration/src/FSharp.Editor/InlineRename/InlineRenameService.fs index 51a9efe9951..dfc56faa5f4 100644 --- a/vsintegration/src/FSharp.Editor/InlineRename/InlineRenameService.fs +++ b/vsintegration/src/FSharp.Editor/InlineRename/InlineRenameService.fs @@ -3,6 +3,8 @@ namespace Microsoft.VisualStudio.FSharp.Editor open System +open System.Collections.Generic +open System.Collections.Immutable open System.Composition open System.Linq open System.Threading @@ -20,54 +22,42 @@ open FSharp.Compiler.Text open FSharp.Compiler.Tokenization open Symbols -type internal FailureInlineRenameInfo private () = - interface IFSharpInlineRenameInfo with - member _.CanRename = false - member _.LocalizedErrorMessage = FSharpEditorFeaturesResources.You_cannot_rename_this_element - member _.TriggerSpan = Unchecked.defaultof<_> - member _.HasOverloads = false - member _.ForceRenameOverloads = true - member _.DisplayName = "" - member _.FullDisplayName = "" - member _.Glyph = Glyph.MethodPublic - member _.GetFinalSymbolName _ = "" - member _.GetReferenceEditSpan(_, _) = Unchecked.defaultof<_> - member _.GetConflictEditSpan(_, _, _) = Nullable() - member _.FindRenameLocationsAsync(_, _) = Task.FromResult null - member _.TryOnBeforeGlobalSymbolRenamed(_, _, _) = false - member _.TryOnAfterGlobalSymbolRenamed(_, _, _) = false - static member Instance = FailureInlineRenameInfo() :> IFSharpInlineRenameInfo +type internal InlineRenameReplacementInfo(newSolution: Solution, replacementTextValid: bool, documentIds: IEnumerable) = + inherit FSharpInlineRenameReplacementInfo() + + override _.NewSolution = newSolution + override _.ReplacementTextValid = replacementTextValid + override _.DocumentIds = documentIds + override _.GetReplacements _ = Seq.empty type internal InlineRenameLocationSet(locations: FSharpInlineRenameLocation [], originalSolution: Solution, symbolKind: LexerSymbolKind, symbol: FSharpSymbol) = - interface IFSharpInlineRenameLocationSet with - member _.Locations = upcast locations.ToList() - - member _.GetReplacementsAsync(replacementText, _optionSet, cancellationToken) : Task = - let rec applyChanges (solution: Solution) (locationsByDocument: (Document * FSharpInlineRenameLocation list) list) = - async { - match locationsByDocument with - | [] -> return solution - | (document, locations) :: rest -> - let! oldSource = document.GetTextAsync(cancellationToken) |> Async.AwaitTask - let newSource = oldSource.WithChanges(locations |> List.map (fun l -> TextChange(l.TextSpan, replacementText))) - return! applyChanges (solution.WithDocumentText(document.Id, newSource)) rest - } + inherit FSharpInlineRenameLocationSet() + + override _.Locations = upcast locations.ToList() + override _.GetReplacementsAsync(replacementText, cancellationToken) : Task = + let rec applyChanges (solution: Solution) (locationsByDocument: (Document * FSharpInlineRenameLocation list) list) = async { - let! newSolution = applyChanges originalSolution (locations |> Array.toList |> List.groupBy (fun x -> x.Document)) - let replacementText = - match symbolKind with - | LexerSymbolKind.GenericTypeParameter - | LexerSymbolKind.StaticallyResolvedTypeParameter -> replacementText - | _ -> FSharpKeywords.NormalizeIdentifierBackticks replacementText - return - { new IFSharpInlineRenameReplacementInfo with - member _.NewSolution = newSolution - member _.ReplacementTextValid = Tokenizer.isValidNameForSymbol(symbolKind, symbol, replacementText) - member _.DocumentIds = locations |> Seq.map (fun doc -> doc.Document.Id) |> Seq.distinct - member _.GetReplacements _ = Seq.empty } + match locationsByDocument with + | [] -> return solution + | (document, locations) :: rest -> + let! oldSource = document.GetTextAsync(cancellationToken) |> Async.AwaitTask + let newSource = oldSource.WithChanges(locations |> List.map (fun l -> TextChange(l.TextSpan, replacementText))) + return! applyChanges (solution.WithDocumentText(document.Id, newSource)) rest } - |> RoslynHelpers.StartAsyncAsTask(cancellationToken) + + async { + let! newSolution = applyChanges originalSolution (locations |> Array.toList |> List.groupBy (fun x -> x.Document)) + let replacementText = + match symbolKind with + | LexerSymbolKind.GenericTypeParameter + | LexerSymbolKind.StaticallyResolvedTypeParameter -> replacementText + | _ -> FSharpKeywords.NormalizeIdentifierBackticks replacementText + let replacementTextValid = Tokenizer.isValidNameForSymbol(symbolKind, symbol, replacementText) + let documentIds = locations |> Seq.map (fun doc -> doc.Document.Id) |> Seq.distinct + return new InlineRenameReplacementInfo(newSolution, replacementTextValid, documentIds) :> FSharpInlineRenameReplacementInfo + } + |> RoslynHelpers.StartAsyncAsTask(cancellationToken) type internal InlineRenameInfo ( @@ -79,6 +69,8 @@ type internal InlineRenameInfo checkFileResults: FSharpCheckFileResults ) = + inherit FSharpInlineRenameInfo() + let getDocumentText (document: Document) cancellationToken = match document.TryGetText() with | true, text -> text @@ -88,61 +80,60 @@ type internal InlineRenameInfo SymbolHelpers.getSymbolUsesInSolution(symbolUse.Symbol, declLoc, checkFileResults, document.Project.Solution) |> Async.cache - interface IFSharpInlineRenameInfo with - member _.CanRename = true - member _.LocalizedErrorMessage = null - member _.TriggerSpan = triggerSpan - member _.HasOverloads = false - member _.ForceRenameOverloads = false - member _.DisplayName = symbolUse.Symbol.DisplayName - member _.FullDisplayName = try symbolUse.Symbol.FullName with _ -> symbolUse.Symbol.DisplayName - member _.Glyph = Glyph.MethodPublic - member _.GetFinalSymbolName replacementText = replacementText - - member _.GetReferenceEditSpan(location, cancellationToken) = - let text = getDocumentText location.Document cancellationToken - Tokenizer.fixupSpan(text, location.TextSpan) + override _.CanRename = true + override _.LocalizedErrorMessage = null + override _.TriggerSpan = triggerSpan + override _.HasOverloads = false + override _.ForceRenameOverloads = false + override _.DisplayName = symbolUse.Symbol.DisplayName + override _.FullDisplayName = try symbolUse.Symbol.FullName with _ -> symbolUse.Symbol.DisplayName + override _.Glyph = Glyph.MethodPublic + override _.GetFinalSymbolName replacementText = replacementText + override _.DefinitionLocations = ImmutableArray.Create(new FSharpInlineRenameLocation(document, triggerSpan)) + + override _.GetReferenceEditSpan(location, cancellationToken) = + let text = getDocumentText location.Document cancellationToken + Tokenizer.fixupSpan(text, location.TextSpan) - member _.GetConflictEditSpan(location, replacementText, cancellationToken) = - let text = getDocumentText location.Document cancellationToken - let spanText = text.ToString(location.TextSpan) - let position = spanText.LastIndexOf(replacementText, StringComparison.Ordinal) - if position < 0 then Nullable() - else Nullable(TextSpan(location.TextSpan.Start + position, replacementText.Length)) + override _.GetConflictEditSpan(location, replacementText, cancellationToken) = + let text = getDocumentText location.Document cancellationToken + let spanText = text.ToString(location.TextSpan) + let position = spanText.LastIndexOf(replacementText, StringComparison.Ordinal) + if position < 0 then Nullable() + else Nullable(TextSpan(location.TextSpan.Start + position, replacementText.Length)) - member _.FindRenameLocationsAsync(_optionSet, cancellationToken) = - async { - let! symbolUsesByDocumentId = symbolUses - let! locations = - symbolUsesByDocumentId - |> Seq.map (fun (KeyValue(documentId, symbolUses)) -> - async { - let document = document.Project.Solution.GetDocument(documentId) - let! sourceText = document.GetTextAsync(cancellationToken) |> Async.AwaitTask - return - [| for symbolUse in symbolUses do - match RoslynHelpers.TryFSharpRangeToTextSpan(sourceText, symbolUse) with - | Some span -> - let textSpan = Tokenizer.fixupSpan(sourceText, span) - yield FSharpInlineRenameLocation(document, textSpan) - | None -> () |] - }) - |> Async.Parallel - |> Async.map Array.concat - - return InlineRenameLocationSet(locations, document.Project.Solution, lexerSymbol.Kind, symbolUse.Symbol) :> IFSharpInlineRenameLocationSet - } |> RoslynHelpers.StartAsyncAsTask(cancellationToken) - - member _.TryOnBeforeGlobalSymbolRenamed(_workspace, _changedDocumentIDs, _replacementText) = true - member _.TryOnAfterGlobalSymbolRenamed(_workspace, _changedDocumentIDs, _replacementText) = true - -[); Shared>] + override _.FindRenameLocationsAsync(_, _, cancellationToken) = + async { + let! symbolUsesByDocumentId = symbolUses + let! locations = + symbolUsesByDocumentId + |> Seq.map (fun (KeyValue(documentId, symbolUses)) -> + async { + let document = document.Project.Solution.GetDocument(documentId) + let! sourceText = document.GetTextAsync(cancellationToken) |> Async.AwaitTask + return + [| for symbolUse in symbolUses do + match RoslynHelpers.TryFSharpRangeToTextSpan(sourceText, symbolUse) with + | Some span -> + let textSpan = Tokenizer.fixupSpan(sourceText, span) + yield FSharpInlineRenameLocation(document, textSpan) + | None -> () |] + }) + |> Async.Parallel + |> Async.map Array.concat + + return InlineRenameLocationSet(locations, document.Project.Solution, lexerSymbol.Kind, symbolUse.Symbol) :> FSharpInlineRenameLocationSet + } |> RoslynHelpers.StartAsyncAsTask(cancellationToken) + +[); Shared>] type internal InlineRenameService [] ( ) = - static member GetInlineRenameInfo(document: Document, position: int) : Async = + inherit FSharpInlineRenameServiceImplementation() + + static member GetInlineRenameInfo(document: Document, position: int) : Async = asyncMaybe { let! ct = Async.CancellationToken |> liftAsync let! sourceText = document.GetTextAsync(ct) @@ -158,13 +149,12 @@ type internal InlineRenameService let! span = RoslynHelpers.TryFSharpRangeToTextSpan(sourceText, symbolUse.Range) let triggerSpan = Tokenizer.fixupSpan(sourceText, span) - return InlineRenameInfo(document, triggerSpan, symbol, symbolUse, declLoc, checkFileResults) :> IFSharpInlineRenameInfo + return InlineRenameInfo(document, triggerSpan, symbol, symbolUse, declLoc, checkFileResults) :> FSharpInlineRenameInfo } - interface IFSharpEditorInlineRenameService with - member _.GetRenameInfoAsync(document: Document, position: int, cancellationToken: CancellationToken) : Task = - asyncMaybe { - return! InlineRenameService.GetInlineRenameInfo(document, position) - } - |> Async.map (Option.defaultValue FailureInlineRenameInfo.Instance) - |> RoslynHelpers.StartAsyncAsTask(cancellationToken) + override _.GetRenameInfoAsync(document: Document, position: int, cancellationToken: CancellationToken) : Task = + asyncMaybe { + return! InlineRenameService.GetInlineRenameInfo(document, position) + } + |> Async.map (Option.defaultValue null) + |> RoslynHelpers.StartAsyncAsTask(cancellationToken) diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 1a3f54dbc9b..b50277c019b 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -300,7 +300,9 @@ type internal FSharpLanguageService(package : FSharpPackage) = override this.Initialize() = base.Initialize() - this.Workspace.Options <- this.Workspace.Options.WithChangedOption(Shared.Options.FSharpServiceFeatureOnOffOptions.ClosedFileDiagnostic, FSharpConstants.FSharpLanguageName, Nullable false) + let globalOptions = package.ComponentModel.DefaultExportProvider.GetExport().Value + globalOptions.BlockForCompletionItems <- false + globalOptions.SetBackgroundAnalysisScope(openFilesOnly=true) let globalOptions = package.ComponentModel.DefaultExportProvider.GetExport().Value globalOptions.BlockForCompletionItems <- false @@ -344,7 +346,7 @@ type internal HackCpsCommandLineChanges /// This handles commandline change notifications from the Dotnet Project-system /// Prior to VS 15.7 path contained path to project file, post 15.7 contains target binpath /// binpath is more accurate because a project file can have multiple in memory projects based on configuration - member _.HandleCommandLineChanges(path:string, sources:ImmutableArray, _references:ImmutableArray, options:ImmutableArray) = + member _.HandleCommandLineChanges(path:string, sources:ImmutableArray, references:ImmutableArray, options:ImmutableArray) = use _logBlock = Logger.LogBlock(LogEditorFunctionId.LanguageService_HandleCommandLineArgs) let projectId = @@ -361,5 +363,11 @@ type internal HackCpsCommandLineChanges let sourcePaths = sources |> Seq.map(fun s -> getFullPath s.Path) |> Seq.toArray - let workspaceService = workspace.Services.GetRequiredService() - workspaceService.FSharpProjectOptionsManager.SetCommandLineOptions(projectId, sourcePaths, options) + /// Due to an issue in project system, when we close and reopen solution, it sends the CommandLineChanges twice for every project. + /// First time it sends a correct path, sources, references and options. + /// Second time it sends a correct path, empty sources, empty references and empty options, and we rewrite our cache, and fail to colourize the document later. + /// As a workaround, until we have a fix from PS or will move to Roslyn as a source of truth, we will not overwrite the cache in case of empty lists. + + if not (sources.IsEmpty && references.IsEmpty && options.IsEmpty) then + let workspaceService = workspace.Services.GetRequiredService() + workspaceService.FSharpProjectOptionsManager.SetCommandLineOptions(projectId, sourcePaths, options) diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/FSharp.ProjectSystem.FSharp.fsproj b/vsintegration/src/FSharp.ProjectSystem.FSharp/FSharp.ProjectSystem.FSharp.fsproj index 20c03b24ed9..aab721f9de1 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/FSharp.ProjectSystem.FSharp.fsproj +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/FSharp.ProjectSystem.FSharp.fsproj @@ -66,16 +66,6 @@ $(VSAssemblyVersion) - - FSharp.Core - $(FSCoreVersion) - $PackageFolder$\FSharp.Core.dll - - - FSharp.ProjectSystem.FSharp - $(VSAssemblyVersion) - $PackageFolder$\FSharp.ProjectSystem.FSharp.dll - FSharp.Compiler.Service $(FSharpCompilerServiceVersion) diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/AssemblyInfo.vb b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/AssemblyInfo.vb deleted file mode 100644 index a852e3a3399..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/AssemblyInfo.vb +++ /dev/null @@ -1,5 +0,0 @@ -' Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -Imports Microsoft.VisualStudio.Shell - - diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.ProjectSystem.PropertyPages.vbproj b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.ProjectSystem.PropertyPages.vbproj index 799603e1c35..a6b16f955b3 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.ProjectSystem.PropertyPages.vbproj +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.ProjectSystem.PropertyPages.vbproj @@ -16,6 +16,7 @@ win true false + false false true false @@ -61,7 +62,6 @@ - diff --git a/vsintegration/src/FSharp.VS.FSI/Properties.resx b/vsintegration/src/FSharp.VS.FSI/Properties.resx index ca594efbb3e..6a0e1964b77 100644 --- a/vsintegration/src/FSharp.VS.FSI/Properties.resx +++ b/vsintegration/src/FSharp.VS.FSI/Properties.resx @@ -1,5 +1,4 @@  - Roslyn\DocumentHighlightsServiceTests.fs @@ -122,7 +120,7 @@ - +