diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 506d284412a..4dbfc605554 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -1,12 +1,48 @@ { - "version": 1, "isRoot": true, "tools": { + "dotnet-counters": { + "commands": [ + "dotnet-counters" + ], + "version": "8.0.460601" + }, + "dotnet-dump": { + "commands": [ + "dotnet-dump" + ], + "version": "8.0.460601" + }, + "dotnet-gcdump": { + "commands": [ + "dotnet-gcdump" + ], + "version": "8.0.460601" + }, + "dotnet-sos": { + "commands": [ + "dotnet-sos" + ], + "version": "8.0.460601" + }, + "dotnet-symbol": { + "commands": [ + "dotnet-symbol" + ], + "version": "1.0.460401" + }, + "dotnet-trace": { + "commands": [ + "dotnet-trace" + ], + "version": "8.0.460601" + }, "fantomas": { - "version": "6.2.3", "commands": [ "fantomas" - ] + ], + "version": "6.2.3" } - } + }, + "version": 1 } diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 5cf08aea407..44cf398c407 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,7 +1,7 @@ // For format details, see https://aka.ms/vscode-remote/devcontainer.json or this file's README at: { "name": "F#", - "image": "mcr.microsoft.com/dotnet/sdk:8.0.100-rc.1", + "image": "mcr.microsoft.com/dotnet/sdk:8.0", "features": { "ghcr.io/devcontainers/features/common-utils:2": {}, "ghcr.io/devcontainers/features/git:1": {}, diff --git a/.fantomasignore b/.fantomasignore index a22c6c9249d..6b568034be7 100644 --- a/.fantomasignore +++ b/.fantomasignore @@ -20,7 +20,6 @@ src/Compiler/Checking/AccessibilityLogic.fs src/Compiler/Checking/AttributeChecking.fs src/Compiler/Checking/AugmentWithHashCompare.fs src/Compiler/Checking/CheckBasics.fs -src/Compiler/Checking/CheckComputationExpressions.fs src/Compiler/Checking/CheckDeclarations.fs src/Compiler/Checking/CheckExpressions.fs src/Compiler/Checking/CheckFormatStrings.fs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000000..d8110ac0ace --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Format src/Compiler/Checking/CheckComputationExpressions.fs, https://github.com/dotnet/fsharp/pull/16512 +603a310cdfd9902ec1d29b399377dcc9ac56235b diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 6642e4b7df6..f3fc39c1ec7 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -9,17 +9,17 @@ Fixes # (issue, if applicable) - [ ] Test cases added - [ ] Performance benchmarks added in case of performance changes - [ ] Release notes entry updated: - > Please make sure to add an entry with short succint description of the change as well as link to this pull request to the respective release notes file, if applicable. + > Please make sure to add an entry with short succinct description of the change as well as link to this pull request to the respective release notes file, if applicable. > > Release notes files: - > - If anything under `src/Compiler` has been changed, please make sure to make an entry in `docs/release-notes/FSharp.Compiler.Service/.md`, where `` is usually "highest" one, e.g. `42.8.200` - > - If language feature was added (i.e. `LanguageFeatures.fsi` was changed), please add it to `docs/releae-notes/Language/preview.md` - > - If a change to `FSharp.Core` was made, please make sure to edit `docs/release-notes/FSharp.Core/.md` where version is "highest" one, e.g. `8.0.200`. + > - If anything under `src/Compiler` has been changed, please make sure to make an entry in `docs/release-notes/.FSharp.Compiler.Service/.md`, where `` is usually "highest" one, e.g. `42.8.200` + > - If language feature was added (i.e. `LanguageFeatures.fsi` was changed), please add it to `docs/releae-notes/.Language/preview.md` + > - If a change to `FSharp.Core` was made, please make sure to edit `docs/release-notes/.FSharp.Core/.md` where version is "highest" one, e.g. `8.0.200`. - > Examples of release notes entries: - > - Respect line limit in quick info popup - https://github.com/dotnet/fsharp/pull/16208 - > - More inlines for Result module - https://github.com/dotnet/fsharp/pull/16106 - > - Miscellaneous fixes to parens analysis - https://github.com/dotnet/fsharp/pull/16262 - > + > Information about the release notes entries format can be found in the [documentation](https://fsharp.github.io/fsharp-compiler-docs/release-notes/About.html). + > Example: + > * More inlines for Result module. ([PR #16106](https://github.com/dotnet/fsharp/pull/16106)) + > * Correctly handle assembly imports with public key token of 0 length. ([Issue #16359](https://github.com/dotnet/fsharp/issues/16359), [PR #16363](https://github.com/dotnet/fsharp/pull/16363)) + > *`while!` ([Language suggestion #1038](https://github.com/fsharp/fslang-suggestions/issues/1038), [PR #14238](https://github.com/dotnet/fsharp/pull/14238)) > **If you believe that release notes are not necessary for this PR, please add `NO_RELEASE_NOTES` label to the pull request.** \ No newline at end of file diff --git a/.github/workflows/check_release_notes.yml b/.github/workflows/check_release_notes.yml index 14b3c85ca51..359046abcde 100644 --- a/.github/workflows/check_release_notes.yml +++ b/.github/workflows/check_release_notes.yml @@ -1,6 +1,6 @@ name: Check release notes on: - pull_request: + pull_request_target: types: [opened, synchronize, reopened, labeled, unlabeled] branches: - 'main' @@ -85,10 +85,10 @@ jobs: [[ "$VISUAL_STUDIO_VERSION" =~ ^[0-9]+\.[0-9]+$ ]] || (echo " Invalid Visual Studio Version parsed"; exit 1) _release_notes_base_path='docs/release-notes' - _fsharp_core_release_notes_path="${_release_notes_base_path}/FSharp.Core/${FSHARP_CORE_VERSION}.md" - _fsharp_compiler_release_notes_path="${_release_notes_base_path}/FSharp.Compiler.Service/${FSHARP_CORE_VERSION}.md" - _fsharp_language_release_notes_path="${_release_notes_base_path}/Language/preview.md" - _fsharp_vs_release_notes_path="${_release_notes_base_path}/VisualStudio/${VISUAL_STUDIO_VERSION}.md" + _fsharp_core_release_notes_path="${_release_notes_base_path}/.FSharp.Core/${FSHARP_CORE_VERSION}.md" + _fsharp_compiler_release_notes_path="${_release_notes_base_path}/.FSharp.Compiler.Service/${FSHARP_CORE_VERSION}.md" + _fsharp_language_release_notes_path="${_release_notes_base_path}/.Language/preview.md" + _fsharp_vs_release_notes_path="${_release_notes_base_path}/.VisualStudio/${VISUAL_STUDIO_VERSION}.md" readonly paths=( "src/FSharp.Core|${_fsharp_core_release_notes_path}" @@ -133,19 +133,19 @@ jobs: if [[ ${_pr_link_occurences} -eq 1 ]]; then echo " Found pull request URL in $release_notes once" - RELEASE_NOTES_FOUND+="> | \\\`$path\\\` | [$release_notes](${FSHARP_REPO_URL}/$release_notes) | |" + RELEASE_NOTES_FOUND+="> | \\\`$path\\\` | [$release_notes](${FSHARP_REPO_URL}/tree/main/$release_notes) | |" RELEASE_NOTES_FOUND+=$'\n' elif [[ ${_pr_link_occurences} -eq 0 ]]; then echo " Did not find pull request URL in $release_notes" DESCRIPTION="**No current pull request URL (${PR_URL}) found, please consider adding it**" - RELEASE_NOTES_FOUND+="> | \\\`$path\\\` | [$release_notes](${FSHARP_REPO_URL}/$release_notes) | ${DESCRIPTION} |" + RELEASE_NOTES_FOUND+="> | \\\`$path\\\` | [$release_notes](${FSHARP_REPO_URL}/tree/main/$release_notes) | ${DESCRIPTION} |" RELEASE_NOTES_FOUND+=$'\n' PULL_REQUEST_FOUND=false fi else echo " Did not find $release_notes in modified files" DESCRIPTION="**No release notes found or release notes format is not correct**" - RELEASE_NOTES_NOT_FOUND+="| \\\`$path\\\` | [$release_notes](${FSHARP_REPO_URL}/$release_notes) | ${DESCRIPTION} |" + RELEASE_NOTES_NOT_FOUND+="| \\\`$path\\\` | [$release_notes](${FSHARP_REPO_URL}/tree/main/$release_notes) | ${DESCRIPTION} |" RELEASE_NOTES_NOT_FOUND+=$'\n' fi else @@ -161,24 +161,29 @@ jobs: RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' RELEASE_NOTES_MESSAGE_DETAILS+=$"> [!CAUTION]" RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' - RELEASE_NOTES_MESSAGE_DETAILS+=$"> **No release notes found for the following paths.**" + RELEASE_NOTES_MESSAGE_DETAILS+=$"> **No release notes found for the changed paths (see table below).**" RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' RELEASE_NOTES_MESSAGE_DETAILS+=$">" RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' - RELEASE_NOTES_MESSAGE_DETAILS+=$"> Please make sure to add an entry with short succint description of the change as well as link to this pull request." + RELEASE_NOTES_MESSAGE_DETAILS+=$"> Please make sure to add an entry with an informative description of the change as well as link to this pull request, issue and language suggestion if applicable. Release notes for this repository are based on [Keep A Changelog](https://keepachangelog.com/en/1.1.0/) format." RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' RELEASE_NOTES_MESSAGE_DETAILS+=$">" RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' - RELEASE_NOTES_MESSAGE_DETAILS+=$"> Examples: " + RELEASE_NOTES_MESSAGE_DETAILS+=$"> **The following format is recommended for this repository:**" RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' - RELEASE_NOTES_MESSAGE_DETAILS+=$"> \\\`- Respect line limit in quick info popup - https://github.com/dotnet/fsharp/pull/16208\\\`" + RELEASE_NOTES_MESSAGE_DETAILS+=$">" + RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' + RELEASE_NOTES_MESSAGE_DETAILS+=$">" RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' - RELEASE_NOTES_MESSAGE_DETAILS+=$"> \\\`- More inlines for Result module - https://github.com/dotnet/fsharp/pull/16106\\\`" + RELEASE_NOTES_MESSAGE_DETAILS+=$"> \\\`* . ([PR #XXXXX](https://github.com/dotnet/fsharp/pull/XXXXX))\\\`" RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' - RELEASE_NOTES_MESSAGE_DETAILS+=$"> \\\`- Miscellaneous fixes to parens analysis - https://github.com/dotnet/fsharp/pull/16262\\\`" + RELEASE_NOTES_MESSAGE_DETAILS+=$">" + RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' + RELEASE_NOTES_MESSAGE_DETAILS+=$">" + RELEASE_NOTES_MESSAGE_DETAILS+=$"> See examples in the files, listed in the table below or in th full documentation at https://fsharp.github.io/fsharp-compiler-docs/release-notes/About.html." RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' - RELEASE_NOTES_MESSAGE_DETAILS+=$'**If you believe that release notes are not necessary for this PR, please add "NO_RELEASE_NOTES" label to the pull request.**' + RELEASE_NOTES_MESSAGE_DETAILS+=$'**If you believe that release notes are not necessary for this PR, please add NO_RELEASE_NOTES label to the pull request.**' RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' RELEASE_NOTES_MESSAGE_DETAILS+=$'\n' RELEASE_NOTES_MESSAGE_DETAILS+=$"**You can open this PR in browser to add release notes: [open in github.dev](https://github.dev/dotnet/fsharp/pull/${PR_NUMBER})**" diff --git a/.vscode/launch.json b/.vscode/launch.json index 965a1b47fc3..1c0af1d324e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,7 +6,7 @@ "id": "fscArgsPrompt", "description": "Enter arguments for fsc", "default": "", - "type": "promptString", + "type": "promptString" }, { "id": "fsiArgsPrompt", @@ -17,17 +17,17 @@ ], "configurations": [ { - "name": "Launch FSI (Debug, .NET 7.0)", + "name": "Launch FSI (Debug)", "type": "coreclr", "request": "launch", // TODO: Shall we assume that it's already been built, or build it every time we debug? - "preLaunchTask": "Build (Debug)", + "preLaunchTask": "${defaultBuildTask}", // If you have changed target frameworks, make sure to update the program p "program": "${workspaceFolder}/artifacts/bin/fsi/Debug/net8.0/fsi.dll", "args": [ "${input:fsiArgsPrompt}" ], - "cwd": "${workspaceFolder}/src", + "cwd": "${workspaceFolder}", "console": "integratedTerminal", // This is the default to be able to run in Codespaces. "internalConsoleOptions": "neverOpen", "suppressJITOptimizations": true, @@ -44,16 +44,19 @@ "enabled": true } }, + "allowFastEvaluate": true }, { - "name": "Launch FSC (Debug, .NET 7.0)", + "name": "Launch FSC (Debug)", "type": "coreclr", "request": "launch", // TODO: Shall we assume that it's already been built, or build it every time we debug? - "preLaunchTask": "Build (Debug)", + "preLaunchTask": "${defaultBuildTask}", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/artifacts/bin/fsc/Debug/net8.0/fsc.dll", "args": [ + "--targetprofile:netstandard", + "--simpleresolution", "${input:fscArgsPrompt}" ], "cwd": "${workspaceFolder}", @@ -73,9 +76,10 @@ "enabled": true } }, + "allowFastEvaluate": true }, { - "name": "Attach to a .NET process", + "name": "Attach to a .NET process with debugger", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}", @@ -86,7 +90,8 @@ }, "justMyCode": true, "enableStepFiltering": false, - "requireExactSource": false + "requireExactSource": false, + "allowFastEvaluate": true } ] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 1728f4efc97..c80b85f366a 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -2,6 +2,25 @@ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", + "inputs": [ + { + "id": "fscArgsPrompt", + "description": "Enter arguments for fsc", + "default": "", + "type": "promptString", + }, + { + "id": "fsiArgsPrompt", + "description": "Enter arguments for fsi", + "default": "", + "type": "promptString", + }, + { + "id": "PickProcess", + "description": "Enter process id", + "type": "promptString" + } + ], "windows": { "options": { "shell": { @@ -71,18 +90,98 @@ "problemMatcher": "$msCompile", "group": "build" }, + { + "label": "Run FSI with dotnet-trace", + "command": "dotnet", + "type": "shell", + "args": [ + "dotnet-trace", + "collect", + "--format", + "Speedscope", + "--", + "dotnet", + "${workspaceFolder}/artifacts/bin/fsi/Debug/net8.0/fsi.dll", + "${input:fsiArgsPrompt}" + ], + "problemMatcher": "$msCompile", + "group": "none" + }, + { + "label": "Run FSC with dotnet-trace", + "command": "dotnet", + "type": "shell", + "args": [ + "dotnet-trace", + "collect", + "--format", + "Speedscope", + "--", + "dotnet", + "${workspaceFolder}/artifacts/bin/fsc/Debug/net8.0/fsc.dll", + "--targetprofile:netstandard", + "--simpleresolution", + "${input:fscArgsPrompt}" + ], + "problemMatcher": "$msCompile", + "group": "none" + }, + { + "label": "Create a process dump with dotnet-dump", + "command": "dotnet", + "type": "shell", + "args": [ + "dotnet-dump", + "collect", + "--diag", + "--crashreport", + "--type", + "Full", + "--process-id", + "${input:PickProcess}", + ], + "problemMatcher": "$msCompile", + "group": "none" + }, + { + "label": "Create a process GC dump with dotnet-gcdump", + "command": "dotnet", + "type": "shell", + "args": [ + "dotnet-gcdump", + "collect", + "--process-id", + "${input:PickProcess}", + ], + "problemMatcher": "$msCompile", + "group": "none" + }, + { + "label": "Collect process counters with dotnet-counters", + "command": "dotnet", + "type": "shell", + "args": [ + "dotnet-counters", + "collect", + "--process-id", + "${input:PickProcess}", + ], + "problemMatcher": "$msCompile", + "group": "none" + }, { "label": "Update xlf files", - "command": "./build.sh", + "command": "dotnet", + "type": "shell", + "args": ["build", "-t:UpdateXlf", "src/Compiler/FSharp.Compiler.Service.fsproj"], + "problemMatcher": "$msCompile", + "group": "build" + }, + { + "label": "Run Fantomas", + "command": "dotnet", + "args": ["fantomas", "."], "type": "shell", - "windows": { - "command": "${workspaceFolder}/Build.cmd" - }, - "options": { - "env": { - "UpdateXlfOnBuild": "true" - } - }, "problemMatcher": "$msCompile", "group": "build" } diff --git a/BenchmarkDotNet.Artifacts/results/TaskPerf.Benchmarks-report-github.md b/BenchmarkDotNet.Artifacts/results/TaskPerf.Benchmarks-report-github.md deleted file mode 100644 index 6cce7d6b240..00000000000 --- a/BenchmarkDotNet.Artifacts/results/TaskPerf.Benchmarks-report-github.md +++ /dev/null @@ -1,67 +0,0 @@ -``` ini - -BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042 -Intel Xeon CPU E5-1620 0 3.60GHz, 1 CPU, 8 logical and 4 physical cores -.NET Core SDK=5.0.104 - [Host] : .NET Core 5.0.6 (CoreCLR 5.0.621.22011, CoreFX 5.0.621.22011), X64 RyuJIT DEBUG - DefaultJob : .NET Core 5.0.6 (CoreCLR 5.0.621.22011, CoreFX 5.0.621.22011), X64 RyuJIT - - -``` -| Method | Categories | Mean | Error | StdDev | Median | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | -|-------------------------------------------- |----------------------- |---------------:|--------------:|--------------:|---------------:|-------:|--------:|-----------:|--------:|------:|------------:| -| ManyWriteFile_CSharpTasks | ManyWriteFile | 4,186.6 μs | 81.32 μs | 201.00 μs | 4,187.4 μs | 1.00 | 0.00 | 15.6250 | - | - | 117288 B | -| ManyWriteFile_taskBuilder | ManyWriteFile | 5,744.5 μs | 124.34 μs | 356.76 μs | 5,712.3 μs | 1.38 | 0.11 | 62.5000 | - | - | 444882 B | -| ManyWriteFile_async | ManyWriteFile | 6,108.8 μs | 121.27 μs | 271.23 μs | 6,132.1 μs | 1.46 | 0.10 | 132.8125 | - | - | 704991 B | -| ManyWriteFile_task | ManyWriteFile | 5,014.3 μs | 100.18 μs | 204.65 μs | 4,973.0 μs | 1.19 | 0.07 | 15.6250 | - | - | 116996 B | -| ManyWriteFile_async2 | ManyWriteFile | 5,358.4 μs | 106.05 μs | 211.79 μs | 5,374.1 μs | 1.27 | 0.07 | 15.6250 | - | - | 117140 B | -| | | | | | | | | | | | | -| NonAsyncBinds_CSharpTasks | NonAsyncBinds | 17,444.8 μs | 374.32 μs | 1,097.80 μs | 17,030.4 μs | 1.00 | 0.00 | 15125.0000 | - | - | 79200000 B | -| NonAsyncBinds_taskBuilder | NonAsyncBinds | 26,000.1 μs | 440.68 μs | 880.09 μs | 25,621.3 μs | 1.47 | 0.09 | 22187.5000 | - | - | 116000000 B | -| NonAsyncBinds_async | NonAsyncBinds | 1,303,920.2 μs | 63,453.67 μs | 177,930.90 μs | 1,269,891.9 μs | 74.52 | 10.59 | 52000.0000 | - | - | 276000000 B | -| NonAsyncBinds_async2 | NonAsyncBinds | 24,213.0 μs | 191.23 μs | 178.88 μs | 24,168.6 μs | 1.38 | 0.09 | 18812.5000 | 62.5000 | - | 98400000 B | -| NonAsyncBinds_task | NonAsyncBinds | 16,693.5 μs | 302.84 μs | 759.75 μs | 16,586.1 μs | 0.95 | 0.07 | 15125.0000 | - | - | 79200000 B | -| | | | | | | | | | | | | -| AsyncBinds_CSharpTasks | AsyncBinds | 8,335.4 μs | 190.47 μs | 558.61 μs | 8,197.5 μs | 1.00 | 0.00 | 15.6250 | - | - | 112119 B | -| AsyncBinds_taskBuilder | AsyncBinds | 11,567.6 μs | 229.28 μs | 522.18 μs | 11,360.0 μs | 1.39 | 0.12 | 296.8750 | - | - | 1559252 B | -| AsyncBinds_async | AsyncBinds | 127,872.2 μs | 3,090.27 μs | 8,866.56 μs | 127,900.8 μs | 15.38 | 1.47 | 1333.3333 | - | - | 8312000 B | -| AsyncBinds_task | AsyncBinds | 9,897.9 μs | 314.55 μs | 927.46 μs | 10,058.4 μs | 1.19 | 0.15 | 31.2500 | - | - | 192096 B | -| AsyncBinds_async2 | AsyncBinds | 8,165.2 μs | 156.64 μs | 347.09 μs | 8,051.9 μs | 0.98 | 0.07 | 62.5000 | - | - | 352218 B | -| | | | | | | | | | | | | -| SingleSyncTask_CSharpTasks | SingleSyncTask | 8,668.5 μs | 170.65 μs | 233.59 μs | 8,595.4 μs | 1.00 | 0.00 | - | - | - | - | -| SingleSyncTask_taskBuilder | SingleSyncTask | 12,402.4 μs | 103.89 μs | 92.10 μs | 12,366.7 μs | 1.43 | 0.04 | 9171.8750 | - | - | 48000000 B | -| SingleSyncTask_async | SingleSyncTask | 3,659,569.1 μs | 109,062.88 μs | 298,557.86 μs | 3,576,228.4 μs | 409.11 | 38.68 | 91000.0000 | - | - | 475999216 B | -| SingleSyncTask_task | SingleSyncTask | 10,642.1 μs | 90.05 μs | 84.23 μs | 10,622.2 μs | 1.23 | 0.04 | - | - | - | - | -| SingleSyncTask_async2 | SingleSyncTask | 28,177.5 μs | 263.90 μs | 220.37 μs | 28,134.6 μs | 3.25 | 0.08 | 7625.0000 | - | - | 40000000 B | -| | | | | | | | | | | | | -| SyncBuilderLoop_NormalCode | sync | 81,206.3 μs | 1,598.95 μs | 1,570.38 μs | 80,813.7 μs | 1.00 | 0.00 | 36714.2857 | - | - | 192176000 B | -| SyncBuilderLoop_WorkflowCode | sync | 81,811.3 μs | 1,610.38 μs | 3,140.93 μs | 80,621.9 μs | 1.02 | 0.05 | 36714.2857 | - | - | 192176000 B | -| | | | | | | | | | | | | -| TinyVariableSizedList_Builtin | TinyVariableSizedList | 57,762.3 μs | 1,721.40 μs | 4,827.00 μs | 56,313.5 μs | 1.00 | 0.00 | 20375.0000 | - | - | 106666656 B | -| TinyVariableSizedList_NewBuilder | TinyVariableSizedList | 17,122.1 μs | 341.76 μs | 650.23 μs | 17,233.0 μs | 0.29 | 0.03 | 2031.2500 | - | - | 10666656 B | -| | | | | | | | | | | | | -| VariableSizedList_Builtin | VariableSizedList | 330,273.8 μs | 6,534.98 μs | 13,051.05 μs | 328,659.3 μs | 1.00 | 0.00 | 63000.0000 | - | - | 330666624 B | -| VariableSizedList_NewBuilder | VariableSizedList | 167,451.6 μs | 2,840.89 μs | 2,217.98 μs | 167,326.7 μs | 0.51 | 0.02 | 44750.0000 | - | - | 234666934 B | -| | | | | | | | | | | | | -| FixedSizeList_Builtin | FixedSizedList | 100,128.5 μs | 1,968.29 μs | 3,885.21 μs | 100,084.8 μs | 1.00 | 0.00 | 61166.6667 | - | - | 320000000 B | -| FixedSizeList_NewBuilder | FixedSizedList | 229,639.0 μs | 4,589.37 μs | 11,846.63 μs | 227,278.1 μs | 2.30 | 0.13 | 61000.0000 | - | - | 320000000 B | -| | | | | | | | | | | | | -| TinyVariableSizedArray_Builtin | TinyVariableSizedArray | 100,414.3 μs | 1,995.07 μs | 4,462.26 μs | 100,631.3 μs | 1.00 | 0.00 | 30000.0000 | - | - | 157333304 B | -| TinyVariableSizedArray_NewBuilder | TinyVariableSizedArray | 28,538.5 μs | 632.86 μs | 1,825.93 μs | 28,426.7 μs | 0.29 | 0.02 | 10687.5000 | - | - | 55999968 B | -| | | | | | | | | | | | | -| VariableSizedArray_Builtin | VariableSizedArray | 356,489.5 μs | 3,061.89 μs | 2,714.29 μs | 356,174.5 μs | 1.00 | 0.00 | 77000.0000 | - | - | 405333840 B | -| VariableSizedArray_NewBuilder | VariableSizedArray | 161,909.3 μs | 861.02 μs | 672.23 μs | 161,860.8 μs | 0.45 | 0.00 | 59000.0000 | - | - | 309333476 B | -| | | | | | | | | | | | | -| FixedSizeArray_Builtin | FixedSizedArray | 32,944.8 μs | 777.85 μs | 2,293.52 μs | 32,391.8 μs | 1.00 | 0.00 | 19875.0000 | - | - | 104000000 B | -| FixedSizeArray_NewBuilder | FixedSizedArray | 219,352.6 μs | 4,288.40 μs | 10,837.34 μs | 217,830.4 μs | 6.65 | 0.60 | 82333.3333 | - | - | 432000000 B | -| | | | | | | | | | | | | -| MultiStepOption_OldBuilder | MultiStepOption | 63,360.5 μs | 1,199.04 μs | 1,062.92 μs | 63,133.5 μs | 1.00 | 0.00 | 38750.0000 | - | - | 202666703 B | -| MultiStepOption_NewBuilder | MultiStepOption | 20,179.8 μs | 622.44 μs | 1,775.86 μs | 19,705.5 μs | 0.29 | 0.02 | 13437.5000 | - | - | 70399968 B | -| MultiStepOption_NoBuilder | MultiStepOption | 19,727.8 μs | 469.72 μs | 1,362.75 μs | 19,395.3 μs | 0.32 | 0.02 | 13437.5000 | - | - | 70399968 B | -| | | | | | | | | | | | | -| MultiStepValueOption_OldBuilder | MultiStepValueOption | 47,237.3 μs | 909.93 μs | 759.83 μs | 47,211.0 μs | 1.00 | 0.00 | 19090.9091 | - | - | 100266664 B | -| MultiStepValueOption_NewBuilder | MultiStepValueOption | 4,144.6 μs | 46.31 μs | 43.32 μs | 4,146.1 μs | 0.09 | 0.00 | - | - | - | - | -| MultiStepValueOption_NoBuilder | MultiStepValueOption | 3,824.0 μs | 75.26 μs | 73.92 μs | 3,806.3 μs | 0.08 | 0.00 | - | - | - | - | -| | | | | | | | | | | | | -| NestedForLoops_taskSeqUsingRawResumableCode | taskSeq | 983.7 μs | 18.23 μs | 17.90 μs | 984.7 μs | 1.61 | 0.04 | 54.6875 | - | - | 295641 B | -| NestedForLoops_CSharpAsyncEnumerable | taskSeq | 612.9 μs | 10.04 μs | 8.90 μs | 615.5 μs | 1.00 | 0.00 | 24.4141 | - | - | 131280 B | diff --git a/Directory.Build.props b/Directory.Build.props index 879bd89410f..10c53909035 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -16,6 +16,10 @@ true + + true + + true diff --git a/Directory.Build.targets b/Directory.Build.targets index 5952e0ed670..079e0e68fd4 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -13,7 +13,4 @@ - - - diff --git a/FSharp.Benchmarks.sln b/FSharp.Benchmarks.sln new file mode 100644 index 00000000000..2ace22c1515 --- /dev/null +++ b/FSharp.Benchmarks.sln @@ -0,0 +1,119 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.1.32113.165 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicroPerfCSharp", "tests\benchmarks\CompiledCodeBenchmarks\MicroPerf\CS\MicroPerfCSharp.csproj", "{CA98804B-E371-45AB-814F-AC4996579B6F}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Service", "src\Compiler\FSharp.Compiler.Service.fsproj", "{9B4528F6-8883-475C-AAF0-4F646233D30A}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Core", "src\FSharp.Core\FSharp.Core.fsproj", "{ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.DependencyManager.Nuget", "src\FSharp.DependencyManager.Nuget\FSharp.DependencyManager.Nuget.fsproj", "{9B98A267-BE47-4711-A1B6-98F3F321E3DD}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "MicroPerf", "tests\benchmarks\CompiledCodeBenchmarks\MicroPerf\MicroPerf.fsproj", "{ED766F38-BD2B-436B-AF73-7BE6FAE061DD}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "TaskPerf", "tests\benchmarks\CompiledCodeBenchmarks\TaskPerf\TaskPerf\TaskPerf.fsproj", "{4779C245-9B85-4491-85EB-B0AF6D818E81}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TaskPerfCSharp", "tests\benchmarks\CompiledCodeBenchmarks\TaskPerf\TaskPerfCSharp\TaskPerfCSharp.csproj", "{38CAA9B6-E4B8-42CB-B4E3-C2DC7D481913}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "HistoricalBenchmark", "tests\benchmarks\FCSBenchmarks\BenchmarkComparison\HistoricalBenchmark.fsproj", "{66E23120-5E94-49AE-A263-24583007F5F5}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "HistoricalBenchmark.Runner", "tests\benchmarks\FCSBenchmarks\BenchmarkComparison\HistoricalBenchmark.Runner\HistoricalBenchmark.Runner.fsproj", "{2A1289B1-1539-48CB-BE03-807FE4BC0387}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Benchmarks", "tests\benchmarks\FCSBenchmarks\CompilerServiceBenchmarks\FSharp.Compiler.Benchmarks.fsproj", "{50D1ECF3-DF38-4A8E-AC3B-2AF1E63263B8}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FCSSourceFiles", "tests\benchmarks\FCSBenchmarks\FCSSourceFiles\FCSSourceFiles.fsproj", "{0E2A7B27-3AD3-4C1D-BA0D-008A1200946F}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Test.Utilities", "tests\FSharp.Test.Utilities\FSharp.Test.Utilities.fsproj", "{0B149238-0912-493E-8877-F831AE01B942}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + ReleaseCompressed|Any CPU = ReleaseCompressed|Any CPU + Proto|Any CPU = Proto|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CA98804B-E371-45AB-814F-AC4996579B6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA98804B-E371-45AB-814F-AC4996579B6F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA98804B-E371-45AB-814F-AC4996579B6F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA98804B-E371-45AB-814F-AC4996579B6F}.Release|Any CPU.Build.0 = Release|Any CPU + {CA98804B-E371-45AB-814F-AC4996579B6F}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {CA98804B-E371-45AB-814F-AC4996579B6F}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {9B4528F6-8883-475C-AAF0-4F646233D30A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B4528F6-8883-475C-AAF0-4F646233D30A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B4528F6-8883-475C-AAF0-4F646233D30A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B4528F6-8883-475C-AAF0-4F646233D30A}.Release|Any CPU.Build.0 = Release|Any CPU + {9B4528F6-8883-475C-AAF0-4F646233D30A}.ReleaseCompressed|Any CPU.ActiveCfg = ReleaseCompressed|Any CPU + {9B4528F6-8883-475C-AAF0-4F646233D30A}.ReleaseCompressed|Any CPU.Build.0 = ReleaseCompressed|Any CPU + {9B4528F6-8883-475C-AAF0-4F646233D30A}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.Release|Any CPU.Build.0 = Release|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.ReleaseCompressed|Any CPU.ActiveCfg = ReleaseCompressed|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.ReleaseCompressed|Any CPU.Build.0 = ReleaseCompressed|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {ADB51E6C-2D63-4AB1-9F2C-8E869FEFD170}.Proto|Any CPU.Build.0 = Proto|Any CPU + {9B98A267-BE47-4711-A1B6-98F3F321E3DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B98A267-BE47-4711-A1B6-98F3F321E3DD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B98A267-BE47-4711-A1B6-98F3F321E3DD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B98A267-BE47-4711-A1B6-98F3F321E3DD}.Release|Any CPU.Build.0 = Release|Any CPU + {9B98A267-BE47-4711-A1B6-98F3F321E3DD}.ReleaseCompressed|Any CPU.ActiveCfg = ReleaseCompressed|Any CPU + {9B98A267-BE47-4711-A1B6-98F3F321E3DD}.ReleaseCompressed|Any CPU.Build.0 = ReleaseCompressed|Any CPU + {9B98A267-BE47-4711-A1B6-98F3F321E3DD}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {ED766F38-BD2B-436B-AF73-7BE6FAE061DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ED766F38-BD2B-436B-AF73-7BE6FAE061DD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ED766F38-BD2B-436B-AF73-7BE6FAE061DD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ED766F38-BD2B-436B-AF73-7BE6FAE061DD}.Release|Any CPU.Build.0 = Release|Any CPU + {ED766F38-BD2B-436B-AF73-7BE6FAE061DD}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {ED766F38-BD2B-436B-AF73-7BE6FAE061DD}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {4779C245-9B85-4491-85EB-B0AF6D818E81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4779C245-9B85-4491-85EB-B0AF6D818E81}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4779C245-9B85-4491-85EB-B0AF6D818E81}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4779C245-9B85-4491-85EB-B0AF6D818E81}.Release|Any CPU.Build.0 = Release|Any CPU + {4779C245-9B85-4491-85EB-B0AF6D818E81}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {4779C245-9B85-4491-85EB-B0AF6D818E81}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {38CAA9B6-E4B8-42CB-B4E3-C2DC7D481913}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {38CAA9B6-E4B8-42CB-B4E3-C2DC7D481913}.Debug|Any CPU.Build.0 = Debug|Any CPU + {38CAA9B6-E4B8-42CB-B4E3-C2DC7D481913}.Release|Any CPU.ActiveCfg = Release|Any CPU + {38CAA9B6-E4B8-42CB-B4E3-C2DC7D481913}.Release|Any CPU.Build.0 = Release|Any CPU + {38CAA9B6-E4B8-42CB-B4E3-C2DC7D481913}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {38CAA9B6-E4B8-42CB-B4E3-C2DC7D481913}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {66E23120-5E94-49AE-A263-24583007F5F5}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {66E23120-5E94-49AE-A263-24583007F5F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {66E23120-5E94-49AE-A263-24583007F5F5}.Release|Any CPU.Build.0 = Release|Any CPU + {66E23120-5E94-49AE-A263-24583007F5F5}.ReleaseCompressed|Any CPU.ActiveCfg = Release|Any CPU + {66E23120-5E94-49AE-A263-24583007F5F5}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {2A1289B1-1539-48CB-BE03-807FE4BC0387}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2A1289B1-1539-48CB-BE03-807FE4BC0387}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2A1289B1-1539-48CB-BE03-807FE4BC0387}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2A1289B1-1539-48CB-BE03-807FE4BC0387}.Release|Any CPU.Build.0 = Release|Any CPU + {2A1289B1-1539-48CB-BE03-807FE4BC0387}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {2A1289B1-1539-48CB-BE03-807FE4BC0387}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {50D1ECF3-DF38-4A8E-AC3B-2AF1E63263B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {50D1ECF3-DF38-4A8E-AC3B-2AF1E63263B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {50D1ECF3-DF38-4A8E-AC3B-2AF1E63263B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {50D1ECF3-DF38-4A8E-AC3B-2AF1E63263B8}.Release|Any CPU.Build.0 = Release|Any CPU + {50D1ECF3-DF38-4A8E-AC3B-2AF1E63263B8}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {50D1ECF3-DF38-4A8E-AC3B-2AF1E63263B8}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {0E2A7B27-3AD3-4C1D-BA0D-008A1200946F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0E2A7B27-3AD3-4C1D-BA0D-008A1200946F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0E2A7B27-3AD3-4C1D-BA0D-008A1200946F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0E2A7B27-3AD3-4C1D-BA0D-008A1200946F}.Release|Any CPU.Build.0 = Release|Any CPU + {0E2A7B27-3AD3-4C1D-BA0D-008A1200946F}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {0E2A7B27-3AD3-4C1D-BA0D-008A1200946F}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {0B149238-0912-493E-8877-F831AE01B942}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0B149238-0912-493E-8877-F831AE01B942}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0B149238-0912-493E-8877-F831AE01B942}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0B149238-0912-493E-8877-F831AE01B942}.Release|Any CPU.Build.0 = Release|Any CPU + {0B149238-0912-493E-8877-F831AE01B942}.ReleaseCompressed|Any CPU.ActiveCfg = Debug|Any CPU + {0B149238-0912-493E-8877-F831AE01B942}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6D8EE73F-B214-462F-8774-84EF625EA6E4} + EndGlobalSection +EndGlobal diff --git a/VisualFSharp.sln b/VisualFSharp.sln index 94d3cef1d10..bedba19a485 100644 --- a/VisualFSharp.sln +++ b/VisualFSharp.sln @@ -189,8 +189,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "FCSBenchmarks", "FCSBenchma tests\benchmarks\FCSBenchmarks\SmokeTestAllBenchmarks.ps1 = tests\benchmarks\FCSBenchmarks\SmokeTestAllBenchmarks.ps1 EndProjectSection EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "Fsharp.ProfilingStartpointProject", "tests\benchmarks\Fsharp.ProfilingStartpointProject\Fsharp.ProfilingStartpointProject.fsproj", "{FE23BB65-276A-4E41-8CC7-F7752241DEBA}" -EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Editor.Tests", "vsintegration\tests\FSharp.Editor.Tests\FSharp.Editor.Tests.fsproj", "{CBC96CC7-65AB-46EA-A82E-F6A788DABF80}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FSharp.Editor.IntegrationTests", "vsintegration\tests\FSharp.Editor.IntegrationTests\FSharp.Editor.IntegrationTests.csproj", "{E31F9B59-FCF1-4D04-8762-C7BB60285A7B}" @@ -999,18 +997,6 @@ Global {583182E1-3484-4A8F-AC06-7C0D232C0CA4}.Release|Any CPU.Build.0 = Release|Any CPU {583182E1-3484-4A8F-AC06-7C0D232C0CA4}.Release|x86.ActiveCfg = Release|Any CPU {583182E1-3484-4A8F-AC06-7C0D232C0CA4}.Release|x86.Build.0 = Release|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Debug|x86.ActiveCfg = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Debug|x86.Build.0 = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Proto|Any CPU.ActiveCfg = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Proto|Any CPU.Build.0 = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Proto|x86.ActiveCfg = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Proto|x86.Build.0 = Debug|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Release|Any CPU.Build.0 = Release|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Release|x86.ActiveCfg = Release|Any CPU - {FE23BB65-276A-4E41-8CC7-F7752241DEBA}.Release|x86.Build.0 = Release|Any CPU {CBC96CC7-65AB-46EA-A82E-F6A788DABF80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CBC96CC7-65AB-46EA-A82E-F6A788DABF80}.Debug|Any CPU.Build.0 = Debug|Any CPU {CBC96CC7-65AB-46EA-A82E-F6A788DABF80}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -1125,7 +1111,6 @@ Global {EB015235-1E07-4CDA-9CC6-3FBCC27910D1} = {B8DDA694-7939-42E3-95E5-265C2217C142} {583182E1-3484-4A8F-AC06-7C0D232C0CA4} = {39CDF34B-FB23-49AE-AB27-0975DA379BB5} {39CDF34B-FB23-49AE-AB27-0975DA379BB5} = {DFB6ADD7-3149-43D9-AFA0-FC4A818B472B} - {FE23BB65-276A-4E41-8CC7-F7752241DEBA} = {39CDF34B-FB23-49AE-AB27-0975DA379BB5} {CBC96CC7-65AB-46EA-A82E-F6A788DABF80} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} {E31F9B59-FCF1-4D04-8762-C7BB60285A7B} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} {6992D926-AB1C-4CD4-94D5-0319D14DB54B} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 8ee494eeed1..1de2f4309f8 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -86,11 +86,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.8') }}: + - ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/release/dev17.9') }}: - template: /eng/common/templates/job/onelocbuild.yml parameters: MirrorRepo: fsharp - MirrorBranch: release/dev17.8 + MirrorBranch: release/dev17.9 LclSource: lclFilesfromPackage LclPackageId: 'LCL-JUNO-PROD-FSHARP' - template: /eng/common/templates/jobs/jobs.yml @@ -713,6 +713,33 @@ stages: continueOnError: true condition: always() + # Build benchmarks + - job: Plain_Build_Benchmarks + pool: + name: $(DncEngPublicBuildPool) + demands: ImageOverride -equals $(WindowsMachineQueueName) + variables: + - name: _BuildConfig + value: Debug + 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 build .\FSharp.Benchmarks.sln /bl:\"artifacts/log/$(_BuildConfig)/BenchmarkBuild.binlog\" + workingDirectory: $(Build.SourcesDirectory) + displayName: Regular rebuild of FSharp.Benchmarks.sln + continueOnError: true + condition: always() + # Test trimming on Windows - job: Build_And_Test_Trimming_Windows pool: @@ -806,8 +833,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.8 - insertTargetBranch: main + componentBranchName: refs/heads/release/dev17.9 + insertTargetBranch: rel/d17.9 insertTeamEmail: fsharpteam@microsoft.com insertTeamName: 'F#' completeInsertion: 'auto' diff --git a/buildtools/AssemblyCheck/SkipVerifyEmbeddedPdb.txt b/buildtools/AssemblyCheck/SkipVerifyEmbeddedPdb.txt index 9ea06757477..f823017f4a1 100644 --- a/buildtools/AssemblyCheck/SkipVerifyEmbeddedPdb.txt +++ b/buildtools/AssemblyCheck/SkipVerifyEmbeddedPdb.txt @@ -1,6 +1,5 @@ FSharp.Build.UnitTests.dll FSharp.Compiler.Benchmarks.dll -Fsharp.ProfilingStartpointProject.dll FSharp.Compiler.ComponentTests.dll FSharp.Test.Utilities.dll FSharp.Compiler.Private.Scripting.UnitTests.dll diff --git a/docs/content/fsdocs-theme.css b/docs/content/fsdocs-theme.css new file mode 100644 index 00000000000..78b11777baf --- /dev/null +++ b/docs/content/fsdocs-theme.css @@ -0,0 +1,3 @@ +:root { + --main-menu-width: 300px; +} diff --git a/docs/fcs/syntax-visitor.fsx b/docs/fcs/syntax-visitor.fsx deleted file mode 100644 index f0ea0316cfb..00000000000 --- a/docs/fcs/syntax-visitor.fsx +++ /dev/null @@ -1,189 +0,0 @@ -(** ---- -title: Tutorial: SyntaxVisitorBase -category: FSharp.Compiler.Service -categoryindex: 300 -index: 301 ---- -*) -(*** hide ***) -#I "../../artifacts/bin/FSharp.Compiler.Service/Debug/netstandard2.0" -(** -Compiler Services: Using the SyntaxVisitorBase -========================================= - -Syntax tree traversal is a common topic when interacting with the `FSharp.Compiler.Service`. -As established in [Tutorial: Expressions](./untypedtree.html#Walking-over-the-AST), the [ParsedInput](../reference/fsharp-compiler-syntax-parsedinput.html) can be traversed by a set of recursive functions. -It can be tedious to always construct these functions from scratch. - -As an alternative, a [SyntaxVisitorBase](../reference/fsharp-compiler-syntax-syntaxvisitorbase-1.html) can be used to traverse the syntax tree. -Consider, the following code sample: -*) - -let codeSample = """ -module Lib - -let myFunction paramOne paramTwo = - () -""" - -(** -Imagine we wish to grab the `myFunction` name from the `headPat` in the [SynBinding](../reference/fsharp-compiler-syntax-synbinding.html). -Let's introduce a helper function to construct the AST: -*) - -#r "FSharp.Compiler.Service.dll" -open FSharp.Compiler.CodeAnalysis -open FSharp.Compiler.Text -open FSharp.Compiler.Syntax - -let checker = FSharpChecker.Create() - -/// Helper to construct an ParsedInput from a code snippet. -let mkTree codeSample = - let parseFileResults = - checker.ParseFile( - "FileName.fs", - SourceText.ofString codeSample, - { FSharpParsingOptions.Default with SourceFiles = [| "FileName.fs" |] } - ) - |> Async.RunSynchronously - - parseFileResults.ParseTree - -(** -And create a visitor to traverse the tree: -*) - -let visitor = - { new SyntaxVisitorBase() with - override this.VisitPat(path, defaultTraverse, synPat) = - // First check if the pattern is what we are looking for. - match synPat with - | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ])) -> - // Next we can check if the current path of visited nodes, matches our expectations. - // The path will contain all the ancestors of the current node. - match path with - // The parent node of `synPat` should be a `SynBinding`. - | SyntaxNode.SynBinding _ :: _ -> - // We return a `Some` option to indicate we found what we are looking for. - Some ident.idText - // If the parent is something else, we can skip it here. - | _ -> None - | _ -> None } - -let result = SyntaxTraversal.Traverse(Position.pos0, mkTree codeSample, visitor) // Some "myFunction" - -(** -Instead of traversing manually from `ParsedInput` to `SynModuleOrNamespace` to `SynModuleDecl.Let` to `SynBinding` to `SynPat`, we leverage the default navigation that happens in `SyntaxTraversal.Traverse`. -A `SyntaxVisitorBase` will shortcut all other code paths once a single `VisitXYZ` override has found anything. - -Our code sample of course only had one let binding and thus we didn't need to specify any further logic whether to differentiate between multiple bindings. -Let's consider a second example where we know the user's cursor inside an IDE is placed after `c` and we are interested in the body expression of the let binding. -*) - -let secondCodeSample = """ -module X - -let a = 0 -let b = 1 -let c = 2 -""" - -let secondVisitor = - { new SyntaxVisitorBase() with - override this.VisitBinding(path, defaultTraverse, binding) = - match binding with - | SynBinding(expr = e) -> Some e } - -let cursorPos = Position.mkPos 6 5 - -let secondResult = - SyntaxTraversal.Traverse(cursorPos, mkTree secondCodeSample, secondVisitor) // Some (Const (Int32 2, (6,8--6,9))) - -(** -Due to our passed cursor position, we did not need to write any code to exclude the expressions of the other let bindings. -`SyntaxTraversal.Traverse` will check whether the current position is inside any syntax node before drilling deeper. - -Lastly, some `VisitXYZ` overrides can contain a defaultTraverse. This helper allows you to continue the default traversal when you currently hit a node that is not of interest. -Consider `1 + 2 + 3 + 4`, this will be reflected in a nested infix application expression. -If the cursor is at the end of the entire expression, we can grab the value of `4` using the following visitor: -*) - -let thirdCodeSample = "let sum = 1 + 2 + 3 + 4" - -(* -AST will look like: - -Let - (false, - [SynBinding - (None, Normal, false, false, [], - PreXmlDoc ((1,0), Fantomas.FCS.Xml.XmlDocCollector), - SynValData - (None, SynValInfo ([], SynArgInfo ([], false, None)), None, - None), - Named (SynIdent (sum, None), false, None, (1,4--1,7)), None, - App - (NonAtomic, false, - App - (NonAtomic, true, - LongIdent - (false, - SynLongIdent - ([op_Addition], [], [Some (OriginalNotation "+")]), - None, (1,20--1,21)), - App - (NonAtomic, false, - App - (NonAtomic, true, - LongIdent - (false, - SynLongIdent - ([op_Addition], [], - [Some (OriginalNotation "+")]), None, - (1,16--1,17)), - App - (NonAtomic, false, - App - (NonAtomic, true, - LongIdent - (false, - SynLongIdent - ([op_Addition], [], - [Some (OriginalNotation "+")]), None, - (1,12--1,13)), - Const (Int32 1, (1,10--1,11)), (1,10--1,13)), - Const (Int32 2, (1,14--1,15)), (1,10--1,15)), - (1,10--1,17)), Const (Int32 3, (1,18--1,19)), - (1,10--1,19)), (1,10--1,21)), - Const (Int32 4, (1,22--1,23)), (1,10--1,23)), (1,4--1,7), - Yes (1,0--1,23), { LeadingKeyword = Let (1,0--1,3) - InlineKeyword = None - EqualsRange = Some (1,8--1,9) }) -*) - -let thirdCursorPos = Position.mkPos 1 22 - -let thirdVisitor = - { new SyntaxVisitorBase() with - override this.VisitExpr(path, traverseSynExpr, defaultTraverse, synExpr) = - match synExpr with - | SynExpr.Const (constant = SynConst.Int32 v) -> Some v - // We do want to continue to traverse when nodes like `SynExpr.App` are found. - | otherExpr -> defaultTraverse otherExpr } - -let thirdResult = - SyntaxTraversal.Traverse(cursorPos, mkTree thirdCodeSample, thirdVisitor) // Some 4 - -(** -`defaultTraverse` is especially useful when you do not know upfront what syntax tree you will be walking. -This is a common case when dealing with IDE tooling. You won't know what actual code the end-user is currently processing. - -**Note: SyntaxVisitorBase is designed to find a single value inside a tree!** -This is not an ideal solution when you are interested in all nodes of certain shape. -It will always verify if the given cursor position is still matching the range of the node. -As a fallback the first branch will be explored when you pass `Position.pos0`. -By design, it is meant to find a single result. - -*) diff --git a/docs/fcs/untypedtree-apis.fsx b/docs/fcs/untypedtree-apis.fsx new file mode 100644 index 00000000000..c713ad8acff --- /dev/null +++ b/docs/fcs/untypedtree-apis.fsx @@ -0,0 +1,553 @@ +(** +--- +title: Tutorial: AST APIs +category: FSharp.Compiler.Service +categoryindex: 300 +index: 301 +--- +*) +(*** hide ***) +#I "../../artifacts/bin/FSharp.Compiler.Service/Debug/netstandard2.0" +(** +Compiler Services: APIs for the untyped AST +========================================= + +## The ParsedInput module + +As established in [Tutorial: Expressions](./untypedtree.html#Walking-over-the-AST), the AST held in a [`ParsedInput`](../reference/fsharp-compiler-syntax-parsedinput.html) value +can be traversed by a set of recursive functions. It can be tedious and error-prone to write these functions from scratch every time, though, +so the [`ParsedInput` module](../reference/fsharp-compiler-syntax-parsedinputmodule.html) +exposes a number of functions to make common operations easier. + +For example: + +- [`ParsedInput.exists`](../reference/fsharp-compiler-syntax-parsedinputmodule.html#exists) + - May be used by tooling to determine whether the user's cursor is in a certain context, e.g., to determine whether to offer a certain tooling action. +- [`ParsedInput.fold`](../reference/fsharp-compiler-syntax-parsedinputmodule.html#fold) + - May be used when writing analyzers to collect diagnostic information for an entire source file. +- [`ParsedInput.foldWhile`](../reference/fsharp-compiler-syntax-parsedinputmodule.html#foldWhile) + - Like `fold` but supports stopping traversal early. +- [`ParsedInput.tryNode`](../reference/fsharp-compiler-syntax-parsedinputmodule.html#tryNode) + - May be used by tooling to get the last (deepest) node under the user's cursor. +- [`ParsedInput.tryPick`](../reference/fsharp-compiler-syntax-parsedinputmodule.html#tryPick) + - May be used by tooling to find the first (shallowest) matching node near the user's cursor. +- [`ParsedInput.tryPickLast`](../reference/fsharp-compiler-syntax-parsedinputmodule.html#tryPickLast) + - May be used by tooling to find the last (deepest) matching node near the user's cursor. + +## SyntaxVisitorBase & SyntaxTraversal.Traverse + +While the `ParsedInput` module functions are usually the simplest way to meet most needs, +there is also a [`SyntaxVisitorBase`](../reference/fsharp-compiler-syntax-syntaxvisitorbase-1.html)-based API that can +provide somewhat more fine-grained control over syntax traversal for a subset of use-cases at the expense of a bit more +ceremony and complexity. + +## Examples + +Let's start by introducing a helper function for constructing an AST from source code so we can run through some real examples: +*) + +#r "FSharp.Compiler.Service.dll" +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Text +open FSharp.Compiler.Syntax + +let checker = FSharpChecker.Create() + +/// A helper for constructing a `ParsedInput` from a code snippet. +let mkTree codeSample = + let parseFileResults = + checker.ParseFile( + "FileName.fs", + SourceText.ofString codeSample, + { FSharpParsingOptions.Default with SourceFiles = [| "FileName.fs" |] } + ) + |> Async.RunSynchronously + + parseFileResults.ParseTree + +(** +### ParsedInput.exists + +Now consider the following code sample: +*) + +let brokenTypeDefn = """ +module Lib + +// Whoops, we forgot the equals sign. +type T { A: int; B: int } +""" + +(** +Let's say we have a code fix for adding an equals sign to a type definition that's missing one—like the one above. +We want to offer the fix when the user's cursor is inside of—or just after—the broken type definition. + +We can determine this by using `ParsedInput.exists` and passing in the position of the user's cursor: +*) + +// type T { A: int; B: int } +// ···········↑ +let posInMiddleOfTypeDefn = Position.mkPos 5 12 + +(** +Given that cursor position, all we need to do is find a `SynTypeDefn` node: +*) + +let isPosInTypeDefn = // true. + (posInMiddleOfTypeDefn, mkTree brokenTypeDefn) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn _ -> true + | _ -> false) + +(** +If the position passed into `ParsedInput.exists` is not contained in any node in the given AST, +but rather is below or to the right of all nodes, `ParsedInput.exists` will fall back to exploring the nearest branch above +and/or to the left. This is useful because the user's cursor may lie beyond the range of all nodes. +*) + +// type T { A: int; B: int } +// ··························↑ +let posAfterTypeDefn = Position.mkPos 5 28 + +(** +Our function still returns `true` if the cursor is past the end of the type definition node itself: +*) + +let isPosInTypeDefn' = // Still true. + (posAfterTypeDefn, mkTree brokenTypeDefn) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn _ -> true + | _ -> false) + +(** +### ParsedInput.fold + +`ParsedInput.fold` can be useful when writing an analyzer to collect diagnostics from entire input files. +*) + +(*** hide ***) +let getLineStr (line: int) : string = failwith "Nope." + +(** +Take this code that has unnecessary parentheses in both patterns and expressions: +*) + +let unnecessaryParentheses = """ +let (x) = (id (3)) +""" + +(** +We can gather the ranges of all unnecessary parentheses like this: +*) + +open System.Collections.Generic + +module HashSet = + let add item (set: HashSet<_>) = + ignore (set.Add item) + set + +let unnecessaryParenthesesRanges = + (HashSet Range.comparer, mkTree unnecessaryParentheses) ||> ParsedInput.fold (fun ranges path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; rightParenRange = Some _; range = range)) when + not (SynExpr.shouldBeParenthesizedInContext getLineStr path inner) + -> + ranges |> HashSet.add range + + | SyntaxNode.SynPat(SynPat.Paren(inner, range)) when + not (SynPat.shouldBeParenthesizedInContext path inner) + -> + ranges |> HashSet.add range + + | _ -> + ranges) + +(** +### ParsedInput.tryNode + +Sometimes, we might just want to get whatever node is directly at a given position—for example, if the user's +cursor is on an argument of a function being applied, we can find the node representing the argument and use its path +to backtrack and find the function's name. +*) + +let functionApplication = """ +f x y +""" + +(** +If we have our cursor on `y`: +*) + +// f x y +// ·····↑ +let posOnY = Position.mkPos 2 5 + +(** +The syntax node representing the function `f` technically contains the cursor's position, +but `ParsedInput.tryNode` will keep diving until it finds the _deepest_ node containing the position. + +We can thus get the node representing `y` and its ancestors (the `path`) like this: +*) + +let yAndPath = // Some (SynExpr (Ident y), [SynExpr (App …); …]) + mkTree functionApplication + |> ParsedInput.tryNode posOnY + +(** +Note that, unlike `ParsedInput.exists`, `ParsedInput.tryPick`, and `ParsedInput.tryPickLast`, +`ParsedInput.tryNode` does _not_ fall back to the nearest branch above or to the left. +*) + +// f x y +// ······↑ +let posAfterY = Position.mkPos 2 8 + +(** +If we take the same code snippet but pass in a position after `y`, +we get no node: +*) + +let nope = // None. + mkTree functionApplication + |> ParsedInput.tryNode posAfterY + +(** +### ParsedInput.tryPick + +Now imagine that we have a code fix for converting a record construction expression into an anonymous record construction +expression when there is no record type in scope whose fields match. +*) + +let recordExpr = """ +let r = { A = 1; B = 2 } +""" + +(** +We can offer this fix when the user's cursor is inside of a record expression by +using `ParsedInput.tryPick` to return the surrounding record expression's range, if any. +*) + +// let r = { A = 1; B = 2 } +// ······················↑ +let posInRecordExpr = Position.mkPos 2 25 + +(** +Here, even though `ParsedInput.tryPick` will try to cleave to the given position by default, +we want to verify that the record expression node that we've come across actually contains the position, +since, like `ParsedInput.exists`, `ParsedInput.tryPick` will also fall back to the nearest branch above and/or +to the left if no node actually contains the position. In this case, we don't want to offer the code fix +if the user's cursor isn't actually inside of the record expression. +*) + +let recordExprRange = // Some (2,8--2,24). + (posInRecordExpr, mkTree recordExpr) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Record(range = range)) when + Range.rangeContainsPos range posInRecordExpr + -> Some range + | _ -> None) + +(** +We might also sometimes want to make use of the `path` parameter. Take this simple function definition: +*) + +let myFunction = """ +module Lib + +let myFunction paramOne paramTwo = + () +""" + +(** +Imagine we want to grab the `myFunction` name from the `headPat` in the [`SynBinding`](../reference/fsharp-compiler-syntax-synbinding.html). + +We can write a function to match the node we're looking for—and _not_ match anything we're _not_ looking for (like the argument patterns)—by taking its path into account: +*) + +let myFunctionId = // Some "myFunction". + (Position.pos0, mkTree myFunction) + ||> ParsedInput.tryPick (fun path node -> + // Match on the node and the path (the node's ancestors) to see whether: + // 1. The node is a pattern. + // 2. The pattern is a long identifier pattern. + // 3. The pattern's parent node (the head of the path) is a binding. + match node, path with + | SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ]))), + SyntaxNode.SynBinding _ :: _ -> + // We have found what we're looking for. + Some ident.idText + | _ -> + // If the node or its context don't match, + // we continue. + None) + +(** +Instead of traversing manually from `ParsedInput` to `SynModuleOrNamespace` to `SynModuleDecl.Let` to `SynBinding` to `SynPat`, we leverage the default navigation that happens in `ParsedInput.tryPick`. +`ParsedInput.tryPick` will short-circuit once we have indicated that we have found what we're looking for by returning `Some value`. + +Our code sample of course only had one let-binding and thus we didn't need to specify any further logic to differentiate between bindings. + +Let's consider a second example involving multiple let-bindings: +*) + +let multipleLetsInModule = """ +module X + +let a = 0 +let b = 1 +let c = 2 +""" + +(** +In this case, we know the user's cursor inside an IDE is placed after `c`, and we are interested in the body expression of the _last_ let-binding. +*) + +// … +// let c = 2 +// ·····↑ +let posInLastLet = Position.mkPos 6 5 + +(** +Thanks to the cursor position we passed in, we do not need to write any code to exclude the expressions of the sibling let-bindings. +`ParsedInput.tryPick` will check whether the current position is inside any given syntax node before drilling deeper. +*) + +let bodyOfLetContainingPos = // Some (Const (Int32 2, (6,8--6,9))). + (posInLastLet, mkTree multipleLetsInModule) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynBinding(SynBinding(expr = e)) -> Some e + | _ -> None) + +(** +As noted above, `ParsedInput.tryPick` will short-circuit at the first matching node. +`ParsedInput.tryPickLast` can be used to get the _last_ matching node that contains a given position. + +Take this example of multiple nested modules: +*) + +let nestedModules = """ +module M + +module N = + module O = + module P = begin end +""" + +(** +By using `ParsedInput.tryPick`, we'll get the name of the outermost nested module even if we pass in a position inside the innermost, +since the innermost is contained within the outermost. + +This position is inside module `P`, which is nested inside of module `O`, which is nested inside of module `N`, +which is nested inside of top-level module `M`: +*) + +// module M +// +// module N = +// module O = +// module P = begin end +// ···························↑ +let posInsideOfInnermostNestedModule = Position.mkPos 6 28 + +(** +`ParsedInput.tryPick` short-circuits on the first match, and since module `N` is the first +nested module whose range contains position (6, 28), that's the result we get. +*) + +let outermostNestedModule = // Some ["N"]. + (posInsideOfInnermostNestedModule, mkTree nestedModules) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longId))) -> + Some [for ident in longId -> ident.idText] + | _ -> None) + +(** +### ParsedInput.tryPickLast + +If however we use the same code snippet and pass the same position into `ParsedInput.tryPickLast`, +we can get the name of the _last_ (deepest or innermost) matching node: +*) + +let innermostNestedModule = // Some ["P"]. + (posInsideOfInnermostNestedModule, mkTree nestedModules) + ||> ParsedInput.tryPickLast (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longId))) -> + Some [for ident in longId -> ident.idText] + | _ -> None) + +(** +If we want the next-to-innermost nested module, we can do likewise but make use of the `path` parameter: +*) + +let nextToInnermostNestedModule = // Some ["O"]. + (posInsideOfInnermostNestedModule, mkTree nestedModules) + ||> ParsedInput.tryPickLast (fun path node -> + match node, path with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule _), + SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longId))) :: _ -> + Some [for ident in longId -> ident.idText] + | _ -> None) + +(** +### SyntaxTraversal.Traverse + +Consider again the following code sample: +*) + +let codeSample = """ +module Lib + +let myFunction paramOne paramTwo = + () +""" + +(** +Imagine we wish to grab the `myFunction` name from the `headPat` in the [SynBinding](../reference/fsharp-compiler-syntax-synbinding.html). + +We can create a visitor to traverse the tree and find the function name: +*) + +let visitor = + { new SyntaxVisitorBase() with + override this.VisitPat(path, defaultTraverse, synPat) = + // First check if the pattern is what we are looking for. + match synPat with + | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ])) -> + // Next we can check if the current path of visited nodes, matches our expectations. + // The path will contain all the ancestors of the current node. + match path with + // The parent node of `synPat` should be a `SynBinding`. + | SyntaxNode.SynBinding _ :: _ -> + // We return a `Some` option to indicate we found what we are looking for. + Some ident.idText + // If the parent is something else, we can skip it here. + | _ -> None + | _ -> None } + +let result = SyntaxTraversal.Traverse(Position.pos0, mkTree codeSample, visitor) // Some "myFunction" + +(** +Instead of traversing manually from `ParsedInput` to `SynModuleOrNamespace` to `SynModuleDecl.Let` to `SynBinding` to `SynPat`, we leverage the default navigation that happens in `SyntaxTraversal.Traverse`. +A `SyntaxVisitorBase` will shortcut all other code paths once a single `VisitXYZ` override has found anything. + +Our code sample of course only had one let binding and thus we didn't need to specify any further logic whether to differentiate between multiple bindings. + +### SyntaxTraversal.Traverse: using position + +Let's now consider a second example where we know the user's cursor inside an IDE is placed after `c` and we are interested in the body expression of the let binding. +*) + +let secondCodeSample = """ +module X + +let a = 0 +let b = 1 +let c = 2 +""" + +let secondVisitor = + { new SyntaxVisitorBase() with + override this.VisitBinding(path, defaultTraverse, binding) = + match binding with + | SynBinding(expr = e) -> Some e } + +let cursorPos = Position.mkPos 6 5 + +let secondResult = + SyntaxTraversal.Traverse(cursorPos, mkTree secondCodeSample, secondVisitor) // Some (Const (Int32 2, (6,8--6,9))) + +(** +Due to our passed cursor position, we did not need to write any code to exclude the expressions of the other let bindings. +`SyntaxTraversal.Traverse` will check whether the current position is inside any syntax node before drilling deeper. + +### SyntaxTraversal.Traverse: using defaultTraverse + +Lastly, some `VisitXYZ` overrides can contain a defaultTraverse. This helper allows you to continue the default traversal when you currently hit a node that is not of interest. +Consider `1 + 2 + 3 + 4`, this will be reflected in a nested infix application expression. +If the cursor is at the end of the entire expression, we can grab the value of `4` using the following visitor: +*) + +let thirdCodeSample = "let sum = 1 + 2 + 3 + 4" + +(* +AST will look like: + +Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((1,0), Fantomas.FCS.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None, + None), + Named (SynIdent (sum, None), false, None, (1,4--1,7)), None, + App + (NonAtomic, false, + App + (NonAtomic, true, + LongIdent + (false, + SynLongIdent + ([op_Addition], [], [Some (OriginalNotation "+")]), + None, (1,20--1,21)), + App + (NonAtomic, false, + App + (NonAtomic, true, + LongIdent + (false, + SynLongIdent + ([op_Addition], [], + [Some (OriginalNotation "+")]), None, + (1,16--1,17)), + App + (NonAtomic, false, + App + (NonAtomic, true, + LongIdent + (false, + SynLongIdent + ([op_Addition], [], + [Some (OriginalNotation "+")]), None, + (1,12--1,13)), + Const (Int32 1, (1,10--1,11)), (1,10--1,13)), + Const (Int32 2, (1,14--1,15)), (1,10--1,15)), + (1,10--1,17)), Const (Int32 3, (1,18--1,19)), + (1,10--1,19)), (1,10--1,21)), + Const (Int32 4, (1,22--1,23)), (1,10--1,23)), (1,4--1,7), + Yes (1,0--1,23), { LeadingKeyword = Let (1,0--1,3) + InlineKeyword = None + EqualsRange = Some (1,8--1,9) }) +*) + +let thirdCursorPos = Position.mkPos 1 22 + +let thirdVisitor = + { new SyntaxVisitorBase() with + override this.VisitExpr(path, traverseSynExpr, defaultTraverse, synExpr) = + match synExpr with + | SynExpr.Const (constant = SynConst.Int32 v) -> Some v + // We do want to continue to traverse when nodes like `SynExpr.App` are found. + | otherExpr -> defaultTraverse otherExpr } + +let thirdResult = + SyntaxTraversal.Traverse(cursorPos, mkTree thirdCodeSample, thirdVisitor) // Some 4 + +(** +`defaultTraverse` is especially useful when you do not know upfront what syntax tree you will be walking. +This is a common case when dealing with IDE tooling. You won't know what actual code the end-user is currently processing. + +**Note: SyntaxVisitorBase is designed to find a single value inside a tree!** +This is not an ideal solution when you are interested in all nodes of certain shape. +It will always verify if the given cursor position is still matching the range of the node. +As a fallback the first branch will be explored when you pass `Position.pos0`. +By design, it is meant to find a single result. + +*) diff --git a/docs/img/favicon.ico b/docs/img/favicon.ico new file mode 100644 index 00000000000..ad06a8a2803 Binary files /dev/null and b/docs/img/favicon.ico differ diff --git a/docs/perf-discussions-archive.md b/docs/perf-discussions-archive.md new file mode 100644 index 00000000000..47f6b14bae9 --- /dev/null +++ b/docs/perf-discussions-archive.md @@ -0,0 +1,55 @@ +This is just a typed version of [these notes](https://github.com/dotnet/fsharp/issues/16498), generated during perf discussions on summer of 2023. Can be used as a reference point. + +--- + +# Comparisons +- OCaml +- Scala +- C# +- Rust + +# Underlying problems +- LOH allocations +- Build does too much for deltas +- GC Gen 2 + +# Major problems +- Script start up CLI +- Build on Linux & Mac +- Glitches in test discovery +- Edit & test workflow +- Edit & run workflow +- Edit & check workflow +- Unnecessary rebuilds + +# Hosted compiler problems +- Stamp overflow +- Non-deterministic +- Memory leaks +- Infinite loops +- Stay resident compiler +- Permission elevation + +# Minor problems +- Benchmarking +- Squigglies +- Colorization +- Debug +- Press dot + +# Incremental phases +- Incremental parsing file +- Incremental checking file +- Incremental optimization for deltas +- Cascading DLL builds +- Incremental DLL builds +- Incremental ILxGen for deltas +- Incremental assembly generation +- Incremental PDB generation for deltas + +# Community guidelines +- Community leadership +- Community enablement for tool performance +- Performance acceptance criteria +- Performance running +- Docs for tooling performance \ No newline at end of file diff --git a/docs/release-notes/.FSharp.Compiler.Service/8.0.100.md b/docs/release-notes/.FSharp.Compiler.Service/8.0.100.md new file mode 100644 index 00000000000..a1bc082b81c --- /dev/null +++ b/docs/release-notes/.FSharp.Compiler.Service/8.0.100.md @@ -0,0 +1,3 @@ +### Fixed + +* Include the `get,set` keywords in the range of `SynMemberDefn.AutoProperty`. ([PR #15835](https://github.com/dotnet/fsharp/pull/15835)) \ No newline at end of file diff --git a/docs/release-notes/.FSharp.Compiler.Service/8.0.200.md b/docs/release-notes/.FSharp.Compiler.Service/8.0.200.md new file mode 100644 index 00000000000..175d90b6302 --- /dev/null +++ b/docs/release-notes/.FSharp.Compiler.Service/8.0.200.md @@ -0,0 +1,21 @@ +### Fixed + +* Correctly handle assembly imports with public key token of 0 length. ([Issue #16359](https://github.com/dotnet/fsharp/issues/16359), [PR #16363](https://github.com/dotnet/fsharp/pull/16363)) +* Range of [SynField](../reference/fsharp-compiler-syntax-synfield.html) ([PR #16357](https://github.com/dotnet/fsharp/pull/16357)) +* Limit a type to 65K methods, introduce a compile-time error if any class has over approx 64K methods in generated IL. ([Issue #16398](https://github.com/dotnet/fsharp/issues/16398), [#PR 16427](https://github.com/dotnet/fsharp/pull/16427)) + +### Added + +* Raise a new error when interfaces with auto properties are implemented on constructor-less types. ([PR #16352](https://github.com/dotnet/fsharp/pull/16352)) +* Allow usage of `[]` with older `FSharp.Core` package versions. ([PR #16373](https://github.com/dotnet/fsharp/pull/16373)) +* Parser recovers on unfinished `as` patterns. ([PR #16404](https://github.com/dotnet/fsharp/pull/16404)) +* Allow type-checking of unfinished object expressions. ([PR #16413](https://github.com/dotnet/fsharp/pull/16413)) +* Parser recovers on unfinished enum case declarations. ([PR #16401](https://github.com/dotnet/fsharp/pull/16401)) +* Parser recovers on unfinished record declarations. ([PR #16357](https://github.com/dotnet/fsharp/pull/16357)) +* `MutableKeyword` to [SynFieldTrivia](../reference/fsharp-compiler-syntaxtrivia-synfieldtrivia.html) ([PR #16357](https://github.com/dotnet/fsharp/pull/16357)) +* Added support for a new parameterless constructor for `CustomOperationAttribute`, which, when applied, will use method name as keyword for custom operation in computation expression builder. ([PR #16475](https://github.com/dotnet/fsharp/pull/16475), part of implementation for [fslang-suggestions/1250](https://github.com/fsharp/fslang-suggestions/issues/1250)) +* Compiler service API for getting ranges of unnecessary parentheses. ([PR #16079](https://github.com/dotnet/fsharp/pull/16079) et seq.) + +### Changed + +* Speed up unused opens handling for empty results. ([PR #16502](https://github.com/dotnet/fsharp/pull/16502)) diff --git a/docs/release-notes/.FSharp.Compiler.Service/8.0.300.md b/docs/release-notes/.FSharp.Compiler.Service/8.0.300.md new file mode 100644 index 00000000000..1c70a67edc6 --- /dev/null +++ b/docs/release-notes/.FSharp.Compiler.Service/8.0.300.md @@ -0,0 +1,19 @@ +### Fixed + +* Code generated files with > 64K methods and generated symbols crash when loaded. Use infered sequence points for debugging. ([Issue #16399](https://github.com/dotnet/fsharp/issues/16399), [#PR 16514](https://github.com/dotnet/fsharp/pull/16514)) +* `nameof Module` expressions and patterns are processed to link files in `--test:GraphBasedChecking`. ([PR #16550](https://github.com/dotnet/fsharp/pull/16550)) + +### Added + +* Parser recovers on complex primary constructor patterns, better tree representation for primary constructor patterns. ([PR #16425](https://github.com/dotnet/fsharp/pull/16425)) +* Name resolution: keep type vars in subsequent checks ([PR #16456](https://github.com/dotnet/fsharp/pull/16456)) +* Higher-order-function-based API for working with the untyped abstract syntax tree. ([PR #16462](https://github.com/dotnet/fsharp/pull/16462)) + +### Changed + +* Autogenerated .Is* members for unions skipped for single-case unions. ([PR 16571](https://github.com/dotnet/fsharp/pull/16571)) +* `implicitCtorSynPats` in `SynTypeDefnSimpleRepr.General` is now `SynPat option` instead of `SynSimplePats option`. ([PR #16425](https://github.com/dotnet/fsharp/pull/16425)) +* `SyntaxVisitorBase<'T>.VisitSimplePats` now takes `SynPat` instead of `SynSimplePat list`. ([PR #16425](https://github.com/dotnet/fsharp/pull/16425)) +* Reduce allocations in compiler checking via `ValueOption` usage ([PR #16323](https://github.com/dotnet/fsharp/pull/16323)) +* Reverted [#16348](https://github.com/dotnet/fsharp/pull/16348) `ThreadStatic` `CancellationToken` changes to improve test stability and prevent potential unwanted cancellations. ([PR #16536](https://github.com/dotnet/fsharp/pull/16536)) +* Refactored parenthesization API. ([PR #16461])(https://github.com/dotnet/fsharp/pull/16461)) diff --git a/docs/release-notes/.FSharp.Core/8.0.200.md b/docs/release-notes/.FSharp.Core/8.0.200.md new file mode 100644 index 00000000000..8a1feafaf64 --- /dev/null +++ b/docs/release-notes/.FSharp.Core/8.0.200.md @@ -0,0 +1,4 @@ +### Added + +* More inlines for Result module. ([PR #16106](https://github.com/dotnet/fsharp/pull/16106)) +* Added a new parameterless constructor for `CustomOperationAttribute` ([PR #16475](https://github.com/dotnet/fsharp/pull/16475), part of implementation for [fslang-suggestions/1250](https://github.com/fsharp/fslang-suggestions/issues/1250)) diff --git a/docs/release-notes/.FSharp.Core/8.0.300.md b/docs/release-notes/.FSharp.Core/8.0.300.md new file mode 100644 index 00000000000..9acf7d07635 --- /dev/null +++ b/docs/release-notes/.FSharp.Core/8.0.300.md @@ -0,0 +1,3 @@ +### Fixed + +* Preserve original stack traces in resumable state machines generated code if available. ([PR #16568](https://github.com/dotnet/fsharp/pull/16568)) \ No newline at end of file diff --git a/docs/release-notes/.Language/8.0.md b/docs/release-notes/.Language/8.0.md new file mode 100644 index 00000000000..ad829f0a6b9 --- /dev/null +++ b/docs/release-notes/.Language/8.0.md @@ -0,0 +1,3 @@ +### Added + +* `while!` ([Language suggestion #1038](https://github.com/fsharp/fslang-suggestions/issues/1038), [PR #14238](https://github.com/dotnet/fsharp/pull/14238)) \ No newline at end of file diff --git a/docs/release-notes/.Language/preview.md b/docs/release-notes/.Language/preview.md new file mode 100644 index 00000000000..0fce580b51e --- /dev/null +++ b/docs/release-notes/.Language/preview.md @@ -0,0 +1,9 @@ +### Added + +* Better generic unmanaged structs handling. ([Language suggestion #692](https://github.com/fsharp/fslang-suggestions/issues/692), [PR #12154](https://github.com/dotnet/fsharp/pull/12154)) +* Bidirectional F#/C# interop for 'unmanaged' constraint. ([PR #12154](https://github.com/dotnet/fsharp/pull/12154)) +* Make `.Is*` discriminated union properties visible. ([Language suggestion #222](https://github.com/fsharp/fslang-suggestions/issues/222), [PR #16341](https://github.com/dotnet/fsharp/pull/16341)) + +### Fixed + +* Allow extension methods without type attribute work for types from imported assemblies. ([PR #16368](https://github.com/dotnet/fsharp/pull/16368)) diff --git a/docs/release-notes/.VisualStudio/17.10.md b/docs/release-notes/.VisualStudio/17.10.md new file mode 100644 index 00000000000..0045b1bd64b --- /dev/null +++ b/docs/release-notes/.VisualStudio/17.10.md @@ -0,0 +1,7 @@ +### Fixed + +* Show signature help mid-pipeline in more scenarios. ([PR #16462](https://github.com/dotnet/fsharp/pull/16462)) + +### Changed + +* Use refactored parenthesization API in unnecessary parentheses code fix. ([PR #16461])(https://github.com/dotnet/fsharp/pull/16461)) diff --git a/docs/release-notes/.VisualStudio/17.9.md b/docs/release-notes/.VisualStudio/17.9.md new file mode 100644 index 00000000000..47d796020d5 --- /dev/null +++ b/docs/release-notes/.VisualStudio/17.9.md @@ -0,0 +1,3 @@ +### Added + +* Analyzer & code fix for removing unnecessary parentheses. ([PR #16079](https://github.com/dotnet/fsharp/pull/16079) et seq.) diff --git a/docs/release-notes/.aux/Common.fsx b/docs/release-notes/.aux/Common.fsx new file mode 100644 index 00000000000..a64026d2934 --- /dev/null +++ b/docs/release-notes/.aux/Common.fsx @@ -0,0 +1,50 @@ +#i "nuget: https://api.nuget.org/v3/index.json" +#r "nuget: Markdig, 0.33.0" +#r "nuget: FsHttp, 12.1.0" + +open System.IO +open System.Xml.Linq +open System.Text.RegularExpressions +open FsHttp + +let versionProps = Path.Combine(__SOURCE_DIRECTORY__, "../../../eng/Versions.props") +let versionPropsDoc = XDocument.Load(versionProps) + +/// Find all published versions of a package on NuGet +let getAvailableNuGetVersions (packageName: string) : Set = + let packageName = packageName.ToLowerInvariant() + + http { GET $"https://api.nuget.org/v3-flatcontainer/%s{packageName}/index.json" } + |> Request.send + |> Response.deserializeJson<{| versions: string array |}> + |> fun json -> Set.ofArray json.versions + +/// Try and find the publish date on NuGet +let tryGetReleaseDate (packageName: string) (version: string) : string option = + let packageName = packageName.ToLowerInvariant() + + http { GET $"https://api.nuget.org/v3/registration5-gz-semver2/%s{packageName}/%s{version}.json" } + |> Request.send + |> Response.deserializeJson<{| published: string |}> + |> fun json -> + if System.String.IsNullOrWhiteSpace json.published then + None + else + Some(json.published.Split('T').[0]) + +/// In order for the heading to appear in the page content menu in fsdocs, +/// they need to follow a specific HTML structure. +let transformH3 (version: string) (input: string) : string = + let pattern = "

(.*?)

" + + let replacement = + $"

$1

" + + Regex.Replace(input, pattern, replacement) + +/// Process all MarkDown files from the given release folder +let processFolder (path: string) (processFile: string -> string) : string = + Directory.EnumerateFiles(path, "*.md") + |> Seq.sortByDescending Path.GetFileNameWithoutExtension + |> Seq.map processFile + |> String.concat "\n" diff --git a/docs/release-notes/About.md b/docs/release-notes/About.md new file mode 100644 index 00000000000..20e5138533c --- /dev/null +++ b/docs/release-notes/About.md @@ -0,0 +1,62 @@ +--- +category: Release Notes +categoryindex: 600 +index: 1 +title: About +--- + +# About + +The release notes for the [F\# language](./Language.md), [FSharp.Core](./FSharp.Core.md) and [FSharp.Compiler.Service](./FSharp.Compiler.Service.md) are based on the [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format. +The target audience of these release notes are the respective end-users. + +## Writing a changelog entry + +In order to keep the change logs consistent the following format was proposed for each entry: + +```md +* . ([PR #16106](https://github.com/dotnet/fsharp/pull/16106)) +``` + +Some tips: + +* Use valid [Markdown](https://www.markdownguide.org/). +* Use `*` as bullet point symbol. We don't want to mix `*` and `-`. +* Start your description with a capital and end the sentence with a dot. +* **Always** include a link to your pull request before the closing `)`, `([PR #16106](https://github.com/dotnet/fsharp/pull/16106))`. +* Optionally, include a link to an issue on `dotnet/fsharp` use `Issue #number` before the link to the pull request. + +Example: + +```md +* Correctly handle assembly imports with public key token of 0 length. ([Issue #16359](https://github.com/dotnet/fsharp/issues/16359), [PR #16363](https://github.com/dotnet/fsharp/pull/16363)) +``` + +* Optionally, include a link to a language suggestion from `dotnet/fsharp` use `Language suggestion #number` before the link to the pull request. + +Example: + +```md +* `while!` ([Language suggestion #1038](https://github.com/fsharp/fslang-suggestions/issues/1038), [PR #14238](https://github.com/dotnet/fsharp/pull/14238)) +``` + +* Choose the right section for your type of change. (`## Added`, `## Changed`, `## Deprecated`, `## Removed`, `## Fixed` or `## Security`). +* Ensure your description makes it clear what the change is about. The reader should be informed on a high level without needing to click through the pull request link and find out in the code what actually changed. +* Maintainers or other contributors might rewrite your changelog entry in the future. This might be done when multiple pull requests can be consolidated under the same umbrella. +* Related pull requests can be listed in the same entry when it makes sense. + +Example: + +```md +* Miscellaneous fixes to parentheses analysis. ([PR #16262](https://github.com/dotnet/fsharp/pull/16262), [PR #16391](https://github.com/dotnet/fsharp/pull/16391), [PR #16370](https://github.com/dotnet/fsharp/pull/16370)) +``` + +## The release process + +### General + +How does it work? Different stages/phases? + +#### FSharp.Compiler.Service + +Perhaps add some specific info if available? \ No newline at end of file diff --git a/docs/release-notes/FSharp.Compiler.Service.fsx b/docs/release-notes/FSharp.Compiler.Service.fsx new file mode 100644 index 00000000000..fc116d572cf --- /dev/null +++ b/docs/release-notes/FSharp.Compiler.Service.fsx @@ -0,0 +1,47 @@ +(** --- +category: Release Notes +categoryindex: 600 +index: 4 +title: FSharp.Compiler.Service +--- + +# FSharp.Compiler.Service +*) +(*** hide ***) +#load "./.aux/Common.fsx" + +open System.IO +open System.Xml.XPath +open Markdig +open Common + +let path = Path.Combine(__SOURCE_DIRECTORY__, ".FSharp.Compiler.Service") +let fcsMajorVersion = versionPropsDoc.XPathSelectElement("//FCSMajorVersion").Value +let nugetPackage = "FSharp.Compiler.Service" +let availableNuGetVersions = getAvailableNuGetVersions nugetPackage + +processFolder path (fun file -> + let versionInFileName = Path.GetFileNameWithoutExtension(file) + // Example: 8.0.200 + let versionParts = versionInFileName.Split '.' + + let version = $"%s{fcsMajorVersion}.%s{versionParts.[0]}.%s{versionParts.[2]}" + // TODO: Can we determine if the current version is in code freeze based on the Version.props info? + let title = + if not (availableNuGetVersions.Contains version) then + $"%s{version} - Unreleased" + else + match tryGetReleaseDate nugetPackage version with + | None -> $"%s{version} - Unreleased" + | Some d -> $"%s{version} - %s{d}" + + let nugetBadge = + if not (availableNuGetVersions.Contains version) then + System.String.Empty + else + $"\"Nuget\"" + + let content = File.ReadAllText file |> Markdown.ToHtml |> transformH3 version + + $"""

%s{title}

%s{nugetBadge}%s{content}""") +(*** include-it-raw ***) diff --git a/docs/release-notes/FSharp.Compiler.Service/8.0.200.md b/docs/release-notes/FSharp.Compiler.Service/8.0.200.md deleted file mode 100644 index 53c6e8a4e67..00000000000 --- a/docs/release-notes/FSharp.Compiler.Service/8.0.200.md +++ /dev/null @@ -1,5 +0,0 @@ -- Parens analysis: miscellaneous fixes - https://github.com/dotnet/fsharp/pull/16262 -- Parens: Keep parentheses around non-struct tuples in `&` patterns - https://github.com/dotnet/fsharp/pull/16391 -- Parens analysis: fix some parenthesization corner-cases in record expressions - https://github.com/dotnet/fsharp/pull/16370 -- Fixes #16359 - correctly handle imports with 0 length public key tokens - https://github.com/dotnet/fsharp/pull/16363 -- Raise a new error when interfaces with auto properties are implemented on constructor-less types - https://github.com/dotnet/fsharp/pull/16352 \ No newline at end of file diff --git a/docs/release-notes/FSharp.Core.fsx b/docs/release-notes/FSharp.Core.fsx new file mode 100644 index 00000000000..521ef4f630c --- /dev/null +++ b/docs/release-notes/FSharp.Core.fsx @@ -0,0 +1,42 @@ +(** --- +category: Release Notes +categoryindex: 600 +index: 3 +title: FSharp.Core +--- + +# FSharp.Core +*) +(*** hide ***) +#load "./.aux/Common.fsx" + +open System.IO +open Markdig +open Common + +let path = Path.Combine(__SOURCE_DIRECTORY__, ".FSharp.Compiler.Service") +let nugetPackage = "FSharp.Core" +let availableNuGetVersions = getAvailableNuGetVersions nugetPackage + +processFolder path (fun file -> + let version = Path.GetFileNameWithoutExtension(file) + + // TODO: Can we determine if the current version is in code freeze based on the Version.props info? + let title = + if not (availableNuGetVersions.Contains version) then + $"%s{version} - Unreleased" + else + match tryGetReleaseDate nugetPackage version with + | None -> $"%s{version} - Unreleased" + | Some d -> $"%s{version} - %s{d}" + + let nugetBadge = + if not (availableNuGetVersions.Contains version) then + System.String.Empty + else + $"\"Nuget\"" + + let content = File.ReadAllText file |> Markdown.ToHtml |> transformH3 version + + $"""

%s{title}

%s{nugetBadge}%s{content}""") +(*** include-it-raw ***) diff --git a/docs/release-notes/FSharp.Core/8.0.200.md b/docs/release-notes/FSharp.Core/8.0.200.md deleted file mode 100644 index 8bed6454108..00000000000 --- a/docs/release-notes/FSharp.Core/8.0.200.md +++ /dev/null @@ -1 +0,0 @@ -- More inlines for Result module - https://github.com/dotnet/fsharp/pull/16106 \ No newline at end of file diff --git a/docs/release-notes/Language.fsx b/docs/release-notes/Language.fsx new file mode 100644 index 00000000000..73c173e7774 --- /dev/null +++ b/docs/release-notes/Language.fsx @@ -0,0 +1,35 @@ +(** --- +category: Release Notes +categoryindex: 600 +index: 2 +title: F# Language +--- + +# F\# Language +*) +(*** hide ***) +#load "./.aux/Common.fsx" + +open System.IO +open Markdig +open Common + +let path = Path.Combine(__SOURCE_DIRECTORY__, ".Language") + +Directory.EnumerateFiles(path, "*.md") +|> Seq.sortWith (fun a b -> + let a = Path.GetFileNameWithoutExtension a + let b = Path.GetFileNameWithoutExtension b + + match a, b with + | "preview", "preview" -> 0 + | "preview", _ -> -1 + | _, "preview" -> 1 + | _, _ -> compare (int b) (int a)) +|> Seq.map (fun file -> + let version = Path.GetFileNameWithoutExtension(file) + let version = if version = "preview" then "Preview" else version + let content = File.ReadAllText file |> Markdown.ToHtml |> transformH3 version + $"""

%s{version}

%s{content}""") +|> String.concat "\n" +(*** include-it-raw ***) diff --git a/docs/release-notes/Language/preview.md b/docs/release-notes/Language/preview.md deleted file mode 100644 index 7d9996a870e..00000000000 --- a/docs/release-notes/Language/preview.md +++ /dev/null @@ -1 +0,0 @@ -- Feature: Better unmanaged structs handling - https://github.com/dotnet/fsharp/pull/12154 \ No newline at end of file diff --git a/docs/running-documentation-locally.md b/docs/running-documentation-locally.md new file mode 100644 index 00000000000..ebecfd583b7 --- /dev/null +++ b/docs/running-documentation-locally.md @@ -0,0 +1,46 @@ +--- +title: Running the documentation locally +category: Compiler Internals +categoryindex: 200 +index: 999 +--- +# Running the documentation locally + +The source of this documentation website is hosted on https://github.com/fsharp/fsharp-compiler-docs. +You can follow this guide to see the results of your document changes rendered in the browser. + +## Setup + +`fsharp/fsharp-compiler-docs` will clone the `dotnet/fsharp` repository first to generate the documentation. +You can however, easily run the documentation locally and modify the `docs` from `dotnet/fsharp`. + +* Clone `fsharp/fsharp-compiler-docs` at the same level as your local `dotnet/fsharp` repository: + + + git clone https://github.com/fsharp/fsharp-compiler-docs.git + + +* Restore the `FSharp.Compiler.Service` project in `fsharp-compiler-docs`: + + + cd fsharp-compiler-docs/FSharp.Compiler.Service + dotnet restore + + +* Restore the local tools in `fsharp-compiler-docs`: + + + cd .. + dotnet tool restore + + +* Run the documentation tool using your `dotnet/fsharp` fork as input. + + + dotnet fsdocs watch --eval --sourcefolder ../fsharp/ --input ../fsharp/docs/ + + +## Release notes caveat + +The release notes pages from `docs/release-notes` are composed from the MarkDown files in subfolders. +Changing any of these files, won't regenerate the served webpage. Only the changes to the `.fsx` will trigger the tool. This is a known limitation. diff --git a/eng/SourceBuildPrebuiltBaseline.xml b/eng/SourceBuildPrebuiltBaseline.xml index a578272a848..18c94ed53e3 100644 --- a/eng/SourceBuildPrebuiltBaseline.xml +++ b/eng/SourceBuildPrebuiltBaseline.xml @@ -3,8 +3,6 @@ - - 8 0 - 200 + 300 0 @@ -29,7 +29,7 @@ $(FSMajorVersion)-$(FSMinorVersion)-$(FSBuildVersion) $(FSMajorVersion).$(FSMinorVersion).$(FSBuildVersion) $(FSMajorVersion).$(FSMinorVersion).0.0 - 7.0.0.0 + 8.0.0.0 43 @@ -41,7 +41,7 @@ $(FCSMajorVersion)$(FCSMinorVersion)$(FCSBuildVersion) - 7.0.0 + 8.0.100 $(FSCorePackageVersionValue)-$(PreReleaseVersionLabel).* @@ -58,7 +58,7 @@ 17 - 9 + 10 $(VSMajorVersion).0 $(VSMajorVersion).$(VSMinorVersion).0 $(VSAssemblyVersionPrefix).0 @@ -77,21 +77,6 @@ - - - $(RestoreSources); - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json; - https://pkgs.dev.azure.com/azure-public/vside/_packaging/vssdk/nuget/v3/index.json; - https://pkgs.dev.azure.com/azure-public/vside/_packaging/vs-impl/nuget/v3/index.json; - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json; - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json; - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet7/nuget/v3/index.json; - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet8/nuget/v3/index.json; - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet8-transport/nuget/v3/index.json; - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json; - https://pkgs.dev.azure.com/azure-public/vside/_packaging/vssdk-archived/nuget/v3/index.json; - https://pkgs.dev.azure.com/azure-public/vside/_packaging/vs-impl-archived/nuget/v3/index.json; - @@ -106,7 +91,7 @@ 6.0.0 4.5.0 - 4.6.0-2.23126.2 + 4.6.0-3.23329.3 17.7.25-preview 17.7.35338-preview.1 17.7.58-pre @@ -183,7 +168,7 @@ 1.0.0 1.1.33 - 0.13.2 + 0.13.10 2.16.5 4.3.0.0 1.0.31 @@ -207,12 +192,11 @@ 2.4.2 5.10.3 2.2.0 - 1.0.0-beta.23426.1 - 1.0.0-prerelease.23602.3 - 1.0.0-prerelease.23602.3 - 1.0.0-prerelease.23602.3 - 1.0.0-prerelease.23602.3 - 1.0.0-prerelease.23602.3 + 1.0.0-prerelease.23614.4 + 1.0.0-prerelease.23614.4 + 1.0.0-prerelease.23614.4 + 1.0.0-prerelease.23614.4 + 1.0.0-prerelease.23614.4 diff --git a/eng/common/darc-init.ps1 b/eng/common/darc-init.ps1 index 435e7641341..8fda30bdce2 100644 --- a/eng/common/darc-init.ps1 +++ b/eng/common/darc-init.ps1 @@ -1,6 +1,6 @@ param ( $darcVersion = $null, - $versionEndpoint = 'https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16', + $versionEndpoint = 'https://maestro.dot.net/api/assets/darc-version?api-version=2019-01-16', $verbosity = 'minimal', $toolpath = $null ) diff --git a/eng/common/darc-init.sh b/eng/common/darc-init.sh index 84c1d0cc2e7..c305ae6bd77 100755 --- a/eng/common/darc-init.sh +++ b/eng/common/darc-init.sh @@ -2,7 +2,7 @@ source="${BASH_SOURCE[0]}" darcVersion='' -versionEndpoint='https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16' +versionEndpoint='https://maestro.dot.net/api/assets/darc-version?api-version=2019-01-16' verbosity='minimal' while [[ $# > 0 ]]; do diff --git a/eng/common/post-build/add-build-to-channel.ps1 b/eng/common/post-build/add-build-to-channel.ps1 index de2d957922a..49938f0c89f 100644 --- a/eng/common/post-build/add-build-to-channel.ps1 +++ b/eng/common/post-build/add-build-to-channel.ps1 @@ -2,7 +2,7 @@ param( [Parameter(Mandatory=$true)][int] $BuildId, [Parameter(Mandatory=$true)][int] $ChannelId, [Parameter(Mandatory=$true)][string] $MaestroApiAccessToken, - [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro-prod.westus2.cloudapp.azure.com', + [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro.dot.net', [Parameter(Mandatory=$false)][string] $MaestroApiVersion = '2019-01-16' ) diff --git a/eng/common/post-build/publish-using-darc.ps1 b/eng/common/post-build/publish-using-darc.ps1 index 8508397d776..1e779fec4dd 100644 --- a/eng/common/post-build/publish-using-darc.ps1 +++ b/eng/common/post-build/publish-using-darc.ps1 @@ -3,7 +3,7 @@ param( [Parameter(Mandatory=$true)][int] $PublishingInfraVersion, [Parameter(Mandatory=$true)][string] $AzdoToken, [Parameter(Mandatory=$true)][string] $MaestroToken, - [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro-prod.westus2.cloudapp.azure.com', + [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro.dot.net', [Parameter(Mandatory=$true)][string] $WaitPublishingFinish, [Parameter(Mandatory=$false)][string] $ArtifactsPublishingAdditionalParameters, [Parameter(Mandatory=$false)][string] $SymbolPublishingAdditionalParameters diff --git a/eng/common/post-build/trigger-subscriptions.ps1 b/eng/common/post-build/trigger-subscriptions.ps1 index 55dea518ac5..ac9a95778fc 100644 --- a/eng/common/post-build/trigger-subscriptions.ps1 +++ b/eng/common/post-build/trigger-subscriptions.ps1 @@ -2,7 +2,7 @@ param( [Parameter(Mandatory=$true)][string] $SourceRepo, [Parameter(Mandatory=$true)][int] $ChannelId, [Parameter(Mandatory=$true)][string] $MaestroApiAccessToken, - [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro-prod.westus2.cloudapp.azure.com', + [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro.dot.net', [Parameter(Mandatory=$false)][string] $MaestroApiVersion = '2019-01-16' ) diff --git a/eng/common/sdk-task.ps1 b/eng/common/sdk-task.ps1 index 6c4ac6fec1a..73828dd30d3 100644 --- a/eng/common/sdk-task.ps1 +++ b/eng/common/sdk-task.ps1 @@ -64,7 +64,7 @@ try { $GlobalJson.tools | Add-Member -Name "vs" -Value (ConvertFrom-Json "{ `"version`": `"16.5`" }") -MemberType NoteProperty } if( -not ($GlobalJson.tools.PSObject.Properties.Name -match "xcopy-msbuild" )) { - $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.6.0-2" -MemberType NoteProperty + $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.8.1-2" -MemberType NoteProperty } if ($GlobalJson.tools."xcopy-msbuild".Trim() -ine "none") { $xcopyMSBuildToolsFolder = InitializeXCopyMSBuild $GlobalJson.tools."xcopy-msbuild" -install $true diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index e20ee3a983c..e24ca2f46f9 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -136,7 +136,7 @@ jobs: condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - ${{ if and(eq(parameters.runAsPublic, 'false'), eq(variables['System.TeamProject'], 'internal')) }}: - - task: NuGetAuthenticate@0 + - task: NuGetAuthenticate@1 - ${{ if and(ne(parameters.artifacts.download, 'false'), ne(parameters.artifacts.download, '')) }}: - task: DownloadPipelineArtifact@2 diff --git a/eng/common/templates/job/publish-build-assets.yml b/eng/common/templates/job/publish-build-assets.yml index 42017109f37..fa5446c093d 100644 --- a/eng/common/templates/job/publish-build-assets.yml +++ b/eng/common/templates/job/publish-build-assets.yml @@ -72,7 +72,7 @@ jobs: condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - - task: NuGetAuthenticate@0 + - task: NuGetAuthenticate@1 - task: PowerShell@2 displayName: Publish Build Assets @@ -81,7 +81,7 @@ jobs: arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' /p:BuildAssetRegistryToken=$(MaestroAccessToken) - /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com + /p:MaestroApiEndpoint=https://maestro.dot.net /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} /p:OfficialBuildId=$(Build.BuildNumber) condition: ${{ parameters.condition }} diff --git a/eng/common/templates/post-build/common-variables.yml b/eng/common/templates/post-build/common-variables.yml index c24193acfc9..173914f2364 100644 --- a/eng/common/templates/post-build/common-variables.yml +++ b/eng/common/templates/post-build/common-variables.yml @@ -7,7 +7,7 @@ variables: # Default Maestro++ API Endpoint and API Version - name: MaestroApiEndPoint - value: "https://maestro-prod.westus2.cloudapp.azure.com" + value: "https://maestro.dot.net" - name: MaestroApiAccessToken value: $(MaestroAccessToken) - name: MaestroApiVersion diff --git a/eng/common/templates/post-build/post-build.yml b/eng/common/templates/post-build/post-build.yml index ef720f9d781..3f74abf7ce0 100644 --- a/eng/common/templates/post-build/post-build.yml +++ b/eng/common/templates/post-build/post-build.yml @@ -169,7 +169,7 @@ stages: # This is necessary whenever we want to publish/restore to an AzDO private feed # Since sdk-task.ps1 tries to restore packages we need to do this authentication here # otherwise it'll complain about accessing a private feed. - - task: NuGetAuthenticate@0 + - task: NuGetAuthenticate@1 displayName: 'Authenticate to AzDO Feeds' # Signing validation will optionally work with the buildmanifest file which is downloaded from @@ -266,7 +266,7 @@ stages: BARBuildId: ${{ parameters.BARBuildId }} PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - task: NuGetAuthenticate@0 + - task: NuGetAuthenticate@1 - task: PowerShell@2 displayName: Publish Using Darc diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index aa74ab4a81e..eb188cfda41 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -379,13 +379,13 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = } # Minimum VS version to require. - $vsMinVersionReqdStr = '17.6' + $vsMinVersionReqdStr = '17.7' $vsMinVersionReqd = [Version]::new($vsMinVersionReqdStr) # If the version of msbuild is going to be xcopied, # use this version. Version matches a package here: - # https://dev.azure.com/dnceng/public/_artifacts/feed/dotnet-eng/NuGet/RoslynTools.MSBuild/versions/17.6.0-2 - $defaultXCopyMSBuildVersion = '17.6.0-2' + # https://dev.azure.com/dnceng/public/_artifacts/feed/dotnet-eng/NuGet/RoslynTools.MSBuild/versions/17.8.1-2 + $defaultXCopyMSBuildVersion = '17.8.1-2' if (!$vsRequirements) { if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') { @@ -601,7 +601,15 @@ function InitializeBuildTool() { ExitWithExitCode 1 } $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet') - $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'net8.0' } + + # Use override if it exists - commonly set by source-build + if ($null -eq $env:_OverrideArcadeInitializeBuildToolFramework) { + $initializeBuildToolFramework="net8.0" + } else { + $initializeBuildToolFramework=$env:_OverrideArcadeInitializeBuildToolFramework + } + + $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = $initializeBuildToolFramework } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore diff --git a/eng/common/tools.sh b/eng/common/tools.sh index e8d47894334..3392e3a9992 100755 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -341,7 +341,12 @@ function InitializeBuildTool { # return values _InitializeBuildTool="$_InitializeDotNetCli/dotnet" _InitializeBuildToolCommand="msbuild" - _InitializeBuildToolFramework="net8.0" + # use override if it exists - commonly set by source-build + if [[ "${_OverrideArcadeInitializeBuildToolFramework:-x}" == "x" ]]; then + _InitializeBuildToolFramework="net8.0" + else + _InitializeBuildToolFramework="${_OverrideArcadeInitializeBuildToolFramework}" + fi } # Set RestoreNoCache as a workaround for https://github.com/NuGet/Home/issues/3116 diff --git a/eng/restore-internal-tools.yml b/eng/restore-internal-tools.yml index f71d0710e44..01cd835c5b7 100644 --- a/eng/restore-internal-tools.yml +++ b/eng/restore-internal-tools.yml @@ -1,5 +1,5 @@ steps: - - task: NuGetAuthenticate@0 + - task: NuGetAuthenticate@1 inputs: nuGetServiceConnections: 'devdiv/dotnet-core-internal-tooling' forceReinstallCredentialProvider: true @@ -10,4 +10,4 @@ steps: /bl:$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/RestoreInternal.binlog /v:normal displayName: Restore internal tools - condition: and(succeeded(), ne(variables['_skipRestoreInternalTools'], 'true')) \ No newline at end of file + condition: and(succeeded(), ne(variables['_skipRestoreInternalTools'], 'true')) diff --git a/global.json b/global.json index 365652e8f7e..b5234bc1761 100644 --- a/global.json +++ b/global.json @@ -1,23 +1,23 @@ { "sdk": { - "version": "8.0.100-rc.1.23463.5", + "version": "8.0.101", "allowPrerelease": true }, "tools": { - "dotnet": "8.0.100-rc.1.23463.5", + "dotnet": "8.0.101", "vs": { - "version": "17.6", + "version": "17.8", "components": [ "Microsoft.VisualStudio.Component.FSharp" ] }, - "xcopy-msbuild": "17.7.2" + "xcopy-msbuild": "17.8.1-2" }, "native-tools": { "perl": "5.38.0.1" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "8.0.0-beta.23463.1", + "Microsoft.DotNet.Arcade.Sdk": "8.0.0-beta.24060.4", "Microsoft.DotNet.Helix.Sdk": "8.0.0-beta.23255.2" } } diff --git a/src/Compiler/AbstractIL/il.fs b/src/Compiler/AbstractIL/il.fs index be994a0307c..3b7df226c9f 100644 --- a/src/Compiler/AbstractIL/il.fs +++ b/src/Compiler/AbstractIL/il.fs @@ -805,7 +805,7 @@ type ILTypeRef = member tref.AddQualifiedNameExtension basic = let sco = tref.Scope.QualifiedName - if sco = "" then + if String.IsNullOrEmpty(sco) then basic else String.concat ", " [ basic; sco ] diff --git a/src/Compiler/AbstractIL/ilwrite.fs b/src/Compiler/AbstractIL/ilwrite.fs index cd4e1bfe721..f41c8aaa08d 100644 --- a/src/Compiler/AbstractIL/ilwrite.fs +++ b/src/Compiler/AbstractIL/ilwrite.fs @@ -50,6 +50,13 @@ let emitBytesViaBuffer f = use bb = ByteBuffer.Create EmitBytesViaBufferCapacity /// Alignment and padding let align alignment n = ((n + alignment - 1) / alignment) * alignment + +/// Maximum number of methods in a dotnet type +/// This differs from the spec and file formats slightly which suggests 0xfffe is the maximum +/// this value was identified empirically. +[] +let maximumMethodsPerDotNetType = 0xfff0 + //--------------------------------------------------------------------- // Concrete token representations etc. used in PE files //--------------------------------------------------------------------- @@ -652,7 +659,7 @@ let GetBytesAsBlobIdx cenv (bytes: byte[]) = else cenv.blobs.FindOrAddSharedEntry bytes let GetStringHeapIdx cenv s = - if s = "" then 0 + if String.IsNullOrEmpty(s) then 0 else cenv.strings.FindOrAddSharedEntry s let GetGuidIdx cenv info = cenv.guids.FindOrAddSharedEntry info @@ -672,8 +679,14 @@ let GetTypeNameAsElemPair cenv n = //===================================================================== let rec GenTypeDefPass1 enc cenv (tdef: ILTypeDef) = - ignore (cenv.typeDefs.AddUniqueEntry "type index" (fun (TdKey (_, n)) -> n) (TdKey (enc, tdef.Name))) - GenTypeDefsPass1 (enc@[tdef.Name]) cenv (tdef.NestedTypes.AsList()) + ignore (cenv.typeDefs.AddUniqueEntry "type index" (fun (TdKey (_, n)) -> n) (TdKey (enc, tdef.Name))) + + // Verify that the typedef contains fewer than maximumMethodsPerDotNetType + let count = tdef.Methods.AsArray().Length + if count > maximumMethodsPerDotNetType then + errorR(Error(FSComp.SR.tooManyMethodsInDotNetTypeWritingAssembly (tdef.Name, count, maximumMethodsPerDotNetType), rangeStartup)) + + GenTypeDefsPass1 (enc@[tdef.Name]) cenv (tdef.NestedTypes.AsList()) and GenTypeDefsPass1 enc cenv tdefs = List.iter (GenTypeDefPass1 enc cenv) tdefs @@ -682,7 +695,8 @@ and GenTypeDefsPass1 enc cenv tdefs = List.iter (GenTypeDefPass1 enc cenv) tdefs //===================================================================== let rec GetIdxForTypeDef cenv key = - try cenv.typeDefs.GetTableEntry key + try + cenv.typeDefs.GetTableEntry key with :? KeyNotFoundException -> let (TdKey (enc, n) ) = key diff --git a/src/Compiler/Checking/AttributeChecking.fs b/src/Compiler/Checking/AttributeChecking.fs index 977d0ecccc6..79dc9402014 100644 --- a/src/Compiler/Checking/AttributeChecking.fs +++ b/src/Compiler/Checking/AttributeChecking.fs @@ -210,7 +210,7 @@ let TryBindMethInfoAttribute g (m: range) (AttribInfo(atref, _) as attribSpec) m (fun provAttribs -> match provAttribs.PUntaint((fun a -> a.GetAttributeConstructorArgs(provAttribs.TypeProvider.PUntaintNoFailure(id), atref.FullName)), m) with | Some args -> f3 args - | None -> None) + | None -> None) #else (fun _provAttribs -> None) #endif diff --git a/src/Compiler/Checking/CheckComputationExpressions.fs b/src/Compiler/Checking/CheckComputationExpressions.fs index 26b10550394..f0727c3fc5d 100644 --- a/src/Compiler/Checking/CheckComputationExpressions.fs +++ b/src/Compiler/Checking/CheckComputationExpressions.fs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -/// The typechecker. Left-to-right constrained type checking +/// The typechecker. Left-to-right constrained type checking /// with generalization at appropriate points. module internal FSharp.Compiler.CheckComputationExpressions @@ -28,65 +28,91 @@ open FSharp.Compiler.TypedTreeOps type cenv = TcFileState /// Used to flag if this is the first or a sebsequent translation pass through a computation expression -type CompExprTranslationPass = Initial | Subsequent +type CompExprTranslationPass = + | Initial + | Subsequent /// Used to flag if computation expression custom operations are allowed in a given context -type CustomOperationsMode = Allowed | Denied +type CustomOperationsMode = + | Allowed + | Denied -let TryFindIntrinsicOrExtensionMethInfo collectionSettings (cenv: cenv) (env: TcEnv) m ad nm ty = +let TryFindIntrinsicOrExtensionMethInfo collectionSettings (cenv: cenv) (env: TcEnv) m ad nm ty = AllMethInfosOfTypeInScope collectionSettings cenv.infoReader env.NameEnv (Some nm) ad IgnoreOverrides m ty /// Ignores an attribute let IgnoreAttribute _ = None -let (|ExprAsPat|_|) (f: SynExpr) = - match f with - | SingleIdent v1 | SynExprParen(SingleIdent v1, _, _, _) -> Some (mkSynPatVar None v1) - | SynExprParen(SynExpr.Tuple (false, elems, commas, _), _, _, _) -> - let elems = elems |> List.map (|SingleIdent|_|) - if elems |> List.forall (fun x -> x.IsSome) then - Some (SynPat.Tuple(false, (elems |> List.map (fun x -> mkSynPatVar None x.Value)), commas, f.Range)) +[] +let (|ExprAsPat|_|) (f: SynExpr) = + match f with + | SingleIdent v1 + | SynExprParen(SingleIdent v1, _, _, _) -> ValueSome(mkSynPatVar None v1) + | SynExprParen(SynExpr.Tuple(false, elems, commas, _), _, _, _) -> + let elems = elems |> List.map (|SingleIdent|_|) + + if elems |> List.forall (fun x -> x.IsSome) then + ValueSome(SynPat.Tuple(false, (elems |> List.map (fun x -> mkSynPatVar None x.Value)), commas, f.Range)) else - None - | _ -> None + ValueNone + | _ -> ValueNone -// For join clauses that join on nullable, we syntactically insert the creation of nullable values on the appropriate side of the condition, +// For join clauses that join on nullable, we syntactically insert the creation of nullable values on the appropriate side of the condition, // then pull the syntax apart again -let (|JoinRelation|_|) cenv env (expr: SynExpr) = +[] +let (|JoinRelation|_|) cenv env (expr: SynExpr) = let m = expr.Range let ad = env.eAccessRights let isOpName opName vref s = - (s = opName) && - match ResolveExprLongIdent cenv.tcSink cenv.nameResolver m ad env.eNameResEnv TypeNameResolutionInfo.Default [ident(opName, m)] None with - | Result (_, Item.Value vref2, []) -> valRefEq cenv.g vref vref2 - | _ -> false + (s = opName) + && match + ResolveExprLongIdent + cenv.tcSink + cenv.nameResolver + m + ad + env.eNameResEnv + TypeNameResolutionInfo.Default + [ ident (opName, m) ] + None + with + | Result(_, Item.Value vref2, []) -> valRefEq cenv.g vref vref2 + | _ -> false + + match expr with + | BinOpExpr(opId, a, b) when isOpName opNameEquals cenv.g.equals_operator_vref opId.idText -> ValueSome(a, b) - match expr with - | BinOpExpr(opId, a, b) when isOpName opNameEquals cenv.g.equals_operator_vref opId.idText -> Some (a, b) + | BinOpExpr(opId, a, b) when isOpName opNameEqualsNullable cenv.g.equals_nullable_operator_vref opId.idText -> - | BinOpExpr(opId, a, b) when isOpName opNameEqualsNullable cenv.g.equals_nullable_operator_vref opId.idText -> + let a = + SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet a.Range [ MangledGlobalName; "System" ] "Nullable", a, a.Range) - let a = SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet a.Range [MangledGlobalName;"System"] "Nullable", a, a.Range) - Some (a, b) + ValueSome(a, b) - | BinOpExpr(opId, a, b) when isOpName opNameNullableEquals cenv.g.nullable_equals_operator_vref opId.idText -> + | BinOpExpr(opId, a, b) when isOpName opNameNullableEquals cenv.g.nullable_equals_operator_vref opId.idText -> - let b = SynExpr.App (ExprAtomicFlag.Atomic, false, mkSynLidGet b.Range [MangledGlobalName;"System"] "Nullable", b, b.Range) - Some (a, b) + let b = + SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet b.Range [ MangledGlobalName; "System" ] "Nullable", b, b.Range) - | BinOpExpr(opId, a, b) when isOpName opNameNullableEqualsNullable cenv.g.nullable_equals_nullable_operator_vref opId.idText -> + ValueSome(a, b) - Some (a, b) + | BinOpExpr(opId, a, b) when isOpName opNameNullableEqualsNullable cenv.g.nullable_equals_nullable_operator_vref opId.idText -> - | _ -> None + ValueSome(a, b) + + | _ -> ValueNone let elimFastIntegerForLoop (spFor, spTo, id, start: SynExpr, dir, finish: SynExpr, innerExpr, m: range) = let mOp = (unionRanges start.Range finish.Range).MakeSynthetic() - let pseudoEnumExpr = - if dir then mkSynInfix mOp start ".." finish - else mkSynTrifix mOp ".. .." start (SynExpr.Const (SynConst.Int32 -1, mOp)) finish - SynExpr.ForEach (spFor, spTo, SeqExprOnly false, true, mkSynPatVar None id, pseudoEnumExpr, innerExpr, m) + + let pseudoEnumExpr = + if dir then + mkSynInfix mOp start ".." finish + else + mkSynTrifix mOp ".. .." start (SynExpr.Const(SynConst.Int32 -1, mOp)) finish + + SynExpr.ForEach(spFor, spTo, SeqExprOnly false, true, mkSynPatVar None id, pseudoEnumExpr, innerExpr, m) /// Check if a computation or sequence expression is syntactically free of 'yield' (though not yield!) let YieldFree (cenv: cenv) expr = @@ -95,30 +121,27 @@ let YieldFree (cenv: cenv) expr = // Implement yield free logic for F# Language including the LanguageFeature.ImplicitYield let rec YieldFree expr = match expr with - | SynExpr.Sequential (expr1=expr1; expr2=expr2) -> - YieldFree expr1 && YieldFree expr2 + | SynExpr.Sequential(expr1 = expr1; expr2 = expr2) -> YieldFree expr1 && YieldFree expr2 - | SynExpr.IfThenElse (thenExpr=thenExpr; elseExpr=elseExprOpt) -> - YieldFree thenExpr && Option.forall YieldFree elseExprOpt + | SynExpr.IfThenElse(thenExpr = thenExpr; elseExpr = elseExprOpt) -> YieldFree thenExpr && Option.forall YieldFree elseExprOpt - | SynExpr.TryWith (tryExpr=body; withCases=clauses) -> - YieldFree body && clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) + | SynExpr.TryWith(tryExpr = body; withCases = clauses) -> + YieldFree body + && clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) - | SynExpr.Match (clauses=clauses) | SynExpr.MatchBang (clauses=clauses) -> - clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) + | SynExpr.Match(clauses = clauses) + | SynExpr.MatchBang(clauses = clauses) -> clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) - | SynExpr.For (doBody=body) - | SynExpr.TryFinally (tryExpr=body) - | SynExpr.LetOrUse (body=body) - | SynExpr.While (doExpr=body) - | SynExpr.WhileBang (doExpr=body) - | SynExpr.ForEach (bodyExpr=body) -> - YieldFree body + | SynExpr.For(doBody = body) + | SynExpr.TryFinally(tryExpr = body) + | SynExpr.LetOrUse(body = body) + | SynExpr.While(doExpr = body) + | SynExpr.WhileBang(doExpr = body) + | SynExpr.ForEach(bodyExpr = body) -> YieldFree body - | SynExpr.LetOrUseBang(body=body) -> - YieldFree body + | SynExpr.LetOrUseBang(body = body) -> YieldFree body - | SynExpr.YieldOrReturn(flags=(true, _)) -> false + | SynExpr.YieldOrReturn(flags = (true, _)) -> false | _ -> true @@ -127,25 +150,23 @@ let YieldFree (cenv: cenv) expr = // Implement yield free logic for F# Language without the LanguageFeature.ImplicitYield let rec YieldFree expr = match expr with - | SynExpr.Sequential (expr1=expr1; expr2=expr2) -> - YieldFree expr1 && YieldFree expr2 + | SynExpr.Sequential(expr1 = expr1; expr2 = expr2) -> YieldFree expr1 && YieldFree expr2 - | SynExpr.IfThenElse (thenExpr=thenExpr; elseExpr=elseExprOpt) -> - YieldFree thenExpr && Option.forall YieldFree elseExprOpt + | SynExpr.IfThenElse(thenExpr = thenExpr; elseExpr = elseExprOpt) -> YieldFree thenExpr && Option.forall YieldFree elseExprOpt - | SynExpr.TryWith (tryExpr=e1; withCases=clauses) -> - YieldFree e1 && clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) + | SynExpr.TryWith(tryExpr = e1; withCases = clauses) -> + YieldFree e1 + && clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) - | SynExpr.Match (clauses=clauses) | SynExpr.MatchBang (clauses=clauses) -> - clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) + | SynExpr.Match(clauses = clauses) + | SynExpr.MatchBang(clauses = clauses) -> clauses |> List.forall (fun (SynMatchClause(resultExpr = res)) -> YieldFree res) - | SynExpr.For (doBody=body) - | SynExpr.TryFinally (tryExpr=body) - | SynExpr.LetOrUse (body=body) - | SynExpr.While (doExpr=body) - | SynExpr.WhileBang (doExpr=body) - | SynExpr.ForEach (bodyExpr=body) -> - YieldFree body + | SynExpr.For(doBody = body) + | SynExpr.TryFinally(tryExpr = body) + | SynExpr.LetOrUse(body = body) + | SynExpr.While(doExpr = body) + | SynExpr.WhileBang(doExpr = body) + | SynExpr.ForEach(bodyExpr = body) -> YieldFree body | SynExpr.LetOrUseBang _ | SynExpr.YieldOrReturnFrom _ @@ -157,44 +178,43 @@ let YieldFree (cenv: cenv) expr = YieldFree expr - /// Determine if a syntactic expression inside 'seq { ... }' or '[...]' counts as a "simple sequence /// of semicolon separated values". For example [1;2;3]. /// 'acceptDeprecated' is true for the '[ ... ]' case, where we allow the syntax '[ if g then t else e ]' but ask it to be parenthesized -/// -let (|SimpleSemicolonSequence|_|) cenv acceptDeprecated cexpr = +[] +let (|SimpleSemicolonSequence|_|) cenv acceptDeprecated cexpr = - let IsSimpleSemicolonSequenceElement expr = + let IsSimpleSemicolonSequenceElement expr = match expr with | SynExpr.IfThenElse _ when acceptDeprecated && YieldFree cenv expr -> true | SynExpr.IfThenElse _ - | SynExpr.TryWith _ - | SynExpr.Match _ - | SynExpr.For _ - | SynExpr.ForEach _ - | SynExpr.TryFinally _ - | SynExpr.YieldOrReturnFrom _ - | SynExpr.YieldOrReturn _ - | SynExpr.LetOrUse _ - | SynExpr.Do _ - | SynExpr.MatchBang _ - | SynExpr.LetOrUseBang _ + | SynExpr.TryWith _ + | SynExpr.Match _ + | SynExpr.For _ + | SynExpr.ForEach _ + | SynExpr.TryFinally _ + | SynExpr.YieldOrReturnFrom _ + | SynExpr.YieldOrReturn _ + | SynExpr.LetOrUse _ + | SynExpr.Do _ + | SynExpr.MatchBang _ + | SynExpr.LetOrUseBang _ | SynExpr.While _ | SynExpr.WhileBang _ -> false | _ -> true - let rec TryGetSimpleSemicolonSequenceOfComprehension expr acc = - match expr with - | SynExpr.Sequential (_, true, e1, e2, _) -> - if IsSimpleSemicolonSequenceElement e1 then + let rec TryGetSimpleSemicolonSequenceOfComprehension expr acc = + match expr with + | SynExpr.Sequential(_, true, e1, e2, _) -> + if IsSimpleSemicolonSequenceElement e1 then TryGetSimpleSemicolonSequenceOfComprehension e2 (e1 :: acc) else - None - | _ -> - if IsSimpleSemicolonSequenceElement expr then - Some(List.rev (expr :: acc)) - else - None + ValueNone + | _ -> + if IsSimpleSemicolonSequenceElement expr then + ValueSome(List.rev (expr :: acc)) + else + ValueNone TryGetSimpleSemicolonSequenceOfComprehension cexpr [] @@ -202,112 +222,162 @@ let RecordNameAndTypeResolutions cenv env tpenv expr = // This function is motivated by cases like // query { for ... join(for x in f(). } // where there is incomplete code in a query, and we are current just dropping a piece of the AST on the floor (above, the bit inside the 'join'). - // + // // The problem with dropping the AST on the floor is that we get no captured resolutions, which means no Intellisense/QuickInfo/ParamHelp. // // We check this AST-fragment, to get resolutions captured. // // This may have effects from typechecking, producing side-effects on the typecheck environment. - suppressErrorReporting (fun () -> + suppressErrorReporting (fun () -> try - ignore(TcExprOfUnknownType cenv env tpenv expr) + ignore (TcExprOfUnknownType cenv env tpenv expr) with _ -> ()) /// Used for all computation expressions except sequence expressions -let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhole, interpExpr: Expr, builderTy, comp: SynExpr) = +let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhole, interpExpr: Expr, builderTy, comp: SynExpr) = let overallTy = overallTy.Commit - + let g = cenv.g let ad = env.eAccessRights let mkSynDelay2 (e: SynExpr) = mkSynDelay (e.Range.MakeSynthetic()) e - + let builderValName = CompilerGeneratedName "builder" let mBuilderVal = interpExpr.Range - + // Give bespoke error messages for the FSharp.Core "query" builder - let isQuery = - match stripDebugPoints interpExpr with + let isQuery = + match stripDebugPoints interpExpr with // An unparameterized custom builder, e.g., `query`, `async`. - | Expr.Val (vref, _, m) + | Expr.Val(vref, _, m) // A parameterized custom builder, e.g., `builder<…>`, `builder ()`. - | Expr.App (funcExpr = Expr.Val (vref, _, m)) -> - let item = Item.CustomBuilder (vref.DisplayName, vref) + | Expr.App(funcExpr = 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 vref cenv.g.query_value_vref + valRefEq cenv.g vref cenv.g.query_value_vref | _ -> false /// Make a builder.Method(...) call - let mkSynCall nm (m: range) args = + let mkSynCall nm (m: range) args = let m = m.MakeSynthetic() // Mark as synthetic so the language service won't pick it up. - let args = - match args with - | [] -> SynExpr.Const (SynConst.Unit, m) - | [arg] -> SynExpr.Paren (SynExpr.Paren (arg, range0, None, m), range0, None, m) - | args -> SynExpr.Paren (SynExpr.Tuple (false, args, [], m), range0, None, m) - + + let args = + match args with + | [] -> SynExpr.Const(SynConst.Unit, m) + | [ arg ] -> SynExpr.Paren(SynExpr.Paren(arg, range0, None, m), range0, None, m) + | args -> SynExpr.Paren(SynExpr.Tuple(false, args, [], m), range0, None, m) + let builderVal = mkSynIdGet m builderValName - mkSynApp1 (SynExpr.DotGet (builderVal, range0, SynLongIdent([mkSynId m nm], [], [None]), m)) args m + mkSynApp1 (SynExpr.DotGet(builderVal, range0, SynLongIdent([ mkSynId m nm ], [], [ None ]), m)) args m - let hasMethInfo nm = TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad nm builderTy |> isNil |> not + let hasMethInfo nm = + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad nm builderTy + |> isNil + |> not - let sourceMethInfo = TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Source" builderTy + let sourceMethInfo = + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Source" builderTy // Optionally wrap sources of "let!", "yield!", "use!" in "query.Source" - let mkSourceExpr callExpr = - match sourceMethInfo with + let mkSourceExpr callExpr = + match sourceMethInfo with | [] -> callExpr - | _ -> mkSynCall "Source" callExpr.Range [callExpr] + | _ -> mkSynCall "Source" callExpr.Range [ callExpr ] - let mkSourceExprConditional isFromSource callExpr = + let mkSourceExprConditional isFromSource callExpr = if isFromSource then mkSourceExpr callExpr else callExpr /// Decide if the builder is an auto-quote builder let isAutoQuote = hasMethInfo "Quote" - let customOperationMethods = - AllMethInfosOfTypeInScope ResultCollectionSettings.AllResults cenv.infoReader env.NameEnv None ad IgnoreOverrides mBuilderVal builderTy - |> List.choose (fun methInfo -> - if not (IsMethInfoAccessible cenv.amap mBuilderVal ad methInfo) then None else - let nameSearch = - TryBindMethInfoAttribute cenv.g mBuilderVal cenv.g.attrib_CustomOperationAttribute methInfo + let customOperationMethods = + AllMethInfosOfTypeInScope + ResultCollectionSettings.AllResults + cenv.infoReader + env.NameEnv + None + ad + IgnoreOverrides + mBuilderVal + builderTy + |> List.choose (fun methInfo -> + if not (IsMethInfoAccessible cenv.amap mBuilderVal ad methInfo) then + None + else + let nameSearch = + TryBindMethInfoAttribute + cenv.g + mBuilderVal + cenv.g.attrib_CustomOperationAttribute + methInfo IgnoreAttribute // We do not respect this attribute for IL methods - (function Attrib(_, _, [ AttribStringArg msg ], _, _, _, _) -> Some msg | _ -> None) + (fun attr -> + // NOTE: right now, we support of custom operations with spaces in them ([]) + // In the parameterless CustomOperationAttribute - we use the method name, and also allow it to be ````-quoted (member _.``foo bar`` _ = ...) + match attr with + // Empty string and parameterless constructor - we use the method name + | Attrib(unnamedArgs = [ AttribStringArg "" ]) // Empty string as parameter + | Attrib(unnamedArgs = []) -> // No parameters, same as empty string for compat reasons. + Some methInfo.LogicalName + // Use the specified name + | Attrib(unnamedArgs = [ AttribStringArg msg ]) -> Some msg + | _ -> None) IgnoreAttribute // We do not respect this attribute for provided methods match nameSearch with | None -> None | Some nm -> let joinConditionWord = - TryBindMethInfoAttribute cenv.g mBuilderVal cenv.g.attrib_CustomOperationAttribute methInfo + TryBindMethInfoAttribute + cenv.g + mBuilderVal + cenv.g.attrib_CustomOperationAttribute + methInfo IgnoreAttribute // We do not respect this attribute for IL methods - (function Attrib(_, _, _, ExtractAttribNamedArg "JoinConditionWord" (AttribStringArg s), _, _, _) -> Some s | _ -> None) + (function + | Attrib(propVal = ExtractAttribNamedArg "JoinConditionWord" (AttribStringArg s)) -> Some s + | _ -> None) IgnoreAttribute // We do not respect this attribute for provided methods - let flagSearch (propName: string) = - TryBindMethInfoAttribute cenv.g mBuilderVal cenv.g.attrib_CustomOperationAttribute methInfo + let flagSearch (propName: string) = + TryBindMethInfoAttribute + cenv.g + mBuilderVal + cenv.g.attrib_CustomOperationAttribute + methInfo IgnoreAttribute // We do not respect this attribute for IL methods - (function Attrib(_, _, _, ExtractAttribNamedArg propName (AttribBoolArg b), _, _, _) -> Some b | _ -> None) + (function + | Attrib(propVal = ExtractAttribNamedArg propName (AttribBoolArg b)) -> Some b + | _ -> None) IgnoreAttribute // We do not respect this attribute for provided methods - let maintainsVarSpaceUsingBind = defaultArg (flagSearch "MaintainsVariableSpaceUsingBind") false + let maintainsVarSpaceUsingBind = + defaultArg (flagSearch "MaintainsVariableSpaceUsingBind") false + let maintainsVarSpace = defaultArg (flagSearch "MaintainsVariableSpace") false let allowInto = defaultArg (flagSearch "AllowIntoPattern") false let isLikeZip = defaultArg (flagSearch "IsLikeZip") false let isLikeJoin = defaultArg (flagSearch "IsLikeJoin") false let isLikeGroupJoin = defaultArg (flagSearch "IsLikeGroupJoin") false - Some (nm, maintainsVarSpaceUsingBind, maintainsVarSpace, allowInto, isLikeZip, isLikeJoin, isLikeGroupJoin, joinConditionWord, methInfo)) - - let customOperationMethodsIndexedByKeyword = + Some( + nm, + maintainsVarSpaceUsingBind, + maintainsVarSpace, + allowInto, + isLikeZip, + isLikeJoin, + isLikeGroupJoin, + joinConditionWord, + methInfo + )) + + let customOperationMethodsIndexedByKeyword = if cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations then customOperationMethods |> Seq.groupBy (fun (nm, _, _, _, _, _, _, _, _) -> nm) - |> Seq.map (fun (nm, group) -> - (nm, - group - |> Seq.toList)) + |> Seq.map (fun (nm, group) -> (nm, group |> Seq.toList)) else customOperationMethods |> Seq.groupBy (fun (nm, _, _, _, _, _, _, _, _) -> nm) @@ -315,14 +385,11 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol |> dict // Check for duplicates by method name (keywords and method names must be 1:1) - let customOperationMethodsIndexedByMethodName = + let customOperationMethodsIndexedByMethodName = if cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations then customOperationMethods |> Seq.groupBy (fun (_, _, _, _, _, _, _, _, methInfo) -> methInfo.LogicalName) - |> Seq.map (fun (nm, group) -> - (nm, - group - |> Seq.toList)) + |> Seq.map (fun (nm, group) -> (nm, group |> Seq.toList)) else customOperationMethods |> Seq.groupBy (fun (_, _, _, _, _, _, _, _, methInfo) -> methInfo.LogicalName) @@ -333,1189 +400,2003 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol let tryGetDataForCustomOperation (nm: Ident) = let isOpDataCountAllowed opDatas = match opDatas with - | [_] -> true + | [ _ ] -> true | _ :: _ -> cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations | _ -> false - match customOperationMethodsIndexedByKeyword.TryGetValue nm.idText with - | true, opDatas when isOpDataCountAllowed opDatas -> + match customOperationMethodsIndexedByKeyword.TryGetValue nm.idText with + | true, opDatas when isOpDataCountAllowed opDatas -> for opData in opDatas do - let opName, maintainsVarSpaceUsingBind, maintainsVarSpace, _allowInto, isLikeZip, isLikeJoin, isLikeGroupJoin, _joinConditionWord, methInfo = opData - if (maintainsVarSpaceUsingBind && maintainsVarSpace) || (isLikeZip && isLikeJoin) || (isLikeZip && isLikeGroupJoin) || (isLikeJoin && isLikeGroupJoin) then - errorR(Error(FSComp.SR.tcCustomOperationInvalid opName, nm.idRange)) + let (opName, + maintainsVarSpaceUsingBind, + maintainsVarSpace, + _allowInto, + isLikeZip, + isLikeJoin, + isLikeGroupJoin, + _joinConditionWord, + methInfo) = + opData + + if + (maintainsVarSpaceUsingBind && maintainsVarSpace) + || (isLikeZip && isLikeJoin) + || (isLikeZip && isLikeGroupJoin) + || (isLikeJoin && isLikeGroupJoin) + then + errorR (Error(FSComp.SR.tcCustomOperationInvalid opName, nm.idRange)) + if not (cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations) then - match customOperationMethodsIndexedByMethodName.TryGetValue methInfo.LogicalName with - | true, [_] -> () - | _ -> errorR(Error(FSComp.SR.tcCustomOperationMayNotBeOverloaded nm.idText, nm.idRange)) + match customOperationMethodsIndexedByMethodName.TryGetValue methInfo.LogicalName with + | true, [ _ ] -> () + | _ -> errorR (Error(FSComp.SR.tcCustomOperationMayNotBeOverloaded nm.idText, nm.idRange)) + Some opDatas - | true, opData :: _ -> errorR(Error(FSComp.SR.tcCustomOperationMayNotBeOverloaded nm.idText, nm.idRange)); Some [opData] + | true, opData :: _ -> + errorR (Error(FSComp.SR.tcCustomOperationMayNotBeOverloaded nm.idText, nm.idRange)) + Some [ opData ] | _ -> None /// Decide if the identifier represents a use of a custom query operator - let hasCustomOperations () = if isNil customOperationMethods then CustomOperationsMode.Denied else CustomOperationsMode.Allowed + let hasCustomOperations () = + if isNil customOperationMethods then + CustomOperationsMode.Denied + else + CustomOperationsMode.Allowed - let isCustomOperation nm = tryGetDataForCustomOperation nm |> Option.isSome + let isCustomOperation nm = + tryGetDataForCustomOperation nm |> Option.isSome - let customOperationCheckValidity m f opDatas = + let customOperationCheckValidity m f opDatas = let vs = opDatas |> List.map f let v0 = vs[0] - let opName, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo = opDatas[0] - if not (List.allEqual vs) then - errorR(Error(FSComp.SR.tcCustomOperationInvalid opName, m)) + + let (opName, + _maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + _isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + _methInfo) = + opDatas[0] + + if not (List.allEqual vs) then + errorR (Error(FSComp.SR.tcCustomOperationInvalid opName, m)) + v0 // Check for the MaintainsVariableSpace on custom operation - let customOperationMaintainsVarSpace (nm: Ident) = - match tryGetDataForCustomOperation nm with + let customOperationMaintainsVarSpace (nm: Ident) = + match tryGetDataForCustomOperation nm with | None -> false | Some opDatas -> - opDatas |> customOperationCheckValidity nm.idRange (fun (_nm, _maintainsVarSpaceUsingBind, maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpace) - - let customOperationMaintainsVarSpaceUsingBind (nm: Ident) = - match tryGetDataForCustomOperation nm with + opDatas + |> customOperationCheckValidity + nm.idRange + (fun + (_nm, + _maintainsVarSpaceUsingBind, + maintainsVarSpace, + _allowInto, + _isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + _methInfo) -> maintainsVarSpace) + + let customOperationMaintainsVarSpaceUsingBind (nm: Ident) = + match tryGetDataForCustomOperation nm with | None -> false | Some opDatas -> - opDatas |> customOperationCheckValidity nm.idRange (fun (_nm, maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpaceUsingBind) - - let customOperationIsLikeZip (nm: Ident) = - match tryGetDataForCustomOperation nm with + opDatas + |> customOperationCheckValidity + nm.idRange + (fun + (_nm, + maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + _isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + _methInfo) -> maintainsVarSpaceUsingBind) + + let customOperationIsLikeZip (nm: Ident) = + match tryGetDataForCustomOperation nm with | None -> false | Some opDatas -> - opDatas |> customOperationCheckValidity nm.idRange (fun (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeZip) - - let customOperationIsLikeJoin (nm: Ident) = - match tryGetDataForCustomOperation nm with + opDatas + |> customOperationCheckValidity + nm.idRange + (fun + (_nm, + _maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + _methInfo) -> isLikeZip) + + let customOperationIsLikeJoin (nm: Ident) = + match tryGetDataForCustomOperation nm with | None -> false | Some opDatas -> - opDatas |> customOperationCheckValidity nm.idRange (fun (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeJoin) - - let customOperationIsLikeGroupJoin (nm: Ident) = - match tryGetDataForCustomOperation nm with + opDatas + |> customOperationCheckValidity + nm.idRange + (fun + (_nm, + _maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + _isLikeZip, + isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + _methInfo) -> isLikeJoin) + + let customOperationIsLikeGroupJoin (nm: Ident) = + match tryGetDataForCustomOperation nm with | None -> false | Some opDatas -> - opDatas |> customOperationCheckValidity nm.idRange (fun (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeGroupJoin) - - let customOperationJoinConditionWord (nm: Ident) = - match tryGetDataForCustomOperation nm with + opDatas + |> customOperationCheckValidity + nm.idRange + (fun + (_nm, + _maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + _isLikeZip, + _isLikeJoin, + isLikeGroupJoin, + _joinConditionWord, + _methInfo) -> isLikeGroupJoin) + + let customOperationJoinConditionWord (nm: Ident) = + match tryGetDataForCustomOperation nm with | Some opDatas -> - opDatas |> customOperationCheckValidity nm.idRange (fun (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, joinConditionWord, _methInfo) -> joinConditionWord) - |> function None -> "on" | Some v -> v - | _ -> "on" - - let customOperationAllowsInto (nm: Ident) = - match tryGetDataForCustomOperation nm with + opDatas + |> customOperationCheckValidity + nm.idRange + (fun + (_nm, + _maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + _isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + joinConditionWord, + _methInfo) -> joinConditionWord) + |> function + | None -> "on" + | Some v -> v + | _ -> "on" + + let customOperationAllowsInto (nm: Ident) = + match tryGetDataForCustomOperation nm with | None -> false | Some opDatas -> - opDatas |> customOperationCheckValidity nm.idRange (fun (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> allowInto) - - let customOpUsageText nm = + opDatas + |> customOperationCheckValidity + nm.idRange + (fun + (_nm, + _maintainsVarSpaceUsingBind, + _maintainsVarSpace, + allowInto, + _isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + _methInfo) -> allowInto) + + let customOpUsageText nm = match tryGetDataForCustomOperation nm with - | Some ((_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, isLikeZip, isLikeJoin, isLikeGroupJoin, _joinConditionWord, _methInfo) :: _) -> + | Some((_nm, + _maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + isLikeZip, + isLikeJoin, + isLikeGroupJoin, + _joinConditionWord, + _methInfo) :: _) -> if isLikeGroupJoin then - Some (FSComp.SR.customOperationTextLikeGroupJoin(nm.idText, customOperationJoinConditionWord nm, customOperationJoinConditionWord nm)) + Some( + FSComp.SR.customOperationTextLikeGroupJoin ( + nm.idText, + customOperationJoinConditionWord nm, + customOperationJoinConditionWord nm + ) + ) elif isLikeJoin then - Some (FSComp.SR.customOperationTextLikeJoin(nm.idText, customOperationJoinConditionWord nm, customOperationJoinConditionWord nm)) + Some( + FSComp.SR.customOperationTextLikeJoin ( + nm.idText, + customOperationJoinConditionWord nm, + customOperationJoinConditionWord nm + ) + ) elif isLikeZip then - Some (FSComp.SR.customOperationTextLikeZip(nm.idText)) + Some(FSComp.SR.customOperationTextLikeZip (nm.idText)) else None - | _ -> None + | _ -> None /// Inside the 'query { ... }' use a modified name environment that contains fake 'CustomOperation' entries /// for all custom operations. This adds them to the completion lists and prevents them being used as values inside /// the query. - let env = - if List.isEmpty customOperationMethods then env else - { env with - eNameResEnv = - (env.eNameResEnv, customOperationMethods) - ||> Seq.fold (fun nenv (nm, _, _, _, _, _, _, _, methInfo) -> - AddFakeNameToNameEnv nm nenv (Item.CustomOperation (nm, (fun () -> customOpUsageText (ident (nm, mBuilderVal))), Some methInfo))) } + let env = + if List.isEmpty customOperationMethods then + env + else + { env with + eNameResEnv = + (env.eNameResEnv, customOperationMethods) + ||> Seq.fold (fun nenv (nm, _, _, _, _, _, _, _, methInfo) -> + AddFakeNameToNameEnv + nm + nenv + (Item.CustomOperation(nm, (fun () -> customOpUsageText (ident (nm, mBuilderVal))), Some methInfo))) + } // Environment is needed for completions CallEnvSink cenv.tcSink (comp.Range, env.NameEnv, ad) - let tryGetArgAttribsForCustomOperator (nm: Ident) = - match tryGetDataForCustomOperation nm with - | Some argInfos -> - argInfos - |> List.map (fun (_nm, __maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, methInfo) -> - match methInfo.GetParamAttribs(cenv.amap, mWhole) with - | [curriedArgInfo] -> Some curriedArgInfo // one for the actual argument group - | _ -> None) + let tryGetArgAttribsForCustomOperator (nm: Ident) = + match tryGetDataForCustomOperation nm with + | Some argInfos -> + argInfos + |> List.map + (fun + (_nm, + __maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + _isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + methInfo) -> + match methInfo.GetParamAttribs(cenv.amap, mWhole) with + | [ curriedArgInfo ] -> Some curriedArgInfo // one for the actual argument group + | _ -> None) |> Some | _ -> None - let tryGetArgInfosForCustomOperator (nm: Ident) = - match tryGetDataForCustomOperation nm with - | Some argInfos -> - argInfos - |> List.map (fun (_nm, __maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, methInfo) -> - match methInfo with - | FSMeth(_, _, vref, _) -> - match ArgInfosOfMember cenv.g vref with - | [curriedArgInfo] -> Some curriedArgInfo - | _ -> None - | _ -> None) + let tryGetArgInfosForCustomOperator (nm: Ident) = + match tryGetDataForCustomOperation nm with + | Some argInfos -> + argInfos + |> List.map + (fun + (_nm, + __maintainsVarSpaceUsingBind, + _maintainsVarSpace, + _allowInto, + _isLikeZip, + _isLikeJoin, + _isLikeGroupJoin, + _joinConditionWord, + methInfo) -> + match methInfo with + | FSMeth(_, _, vref, _) -> + match ArgInfosOfMember cenv.g vref with + | [ curriedArgInfo ] -> Some curriedArgInfo + | _ -> None + | _ -> None) |> Some | _ -> None - let tryExpectedArgCountForCustomOperator (nm: Ident) = - match tryGetArgAttribsForCustomOperator nm with + let tryExpectedArgCountForCustomOperator (nm: Ident) = + match tryGetArgAttribsForCustomOperator nm with | None -> None - | Some argInfosForOverloads -> - let nums = argInfosForOverloads |> List.map (function None -> -1 | Some argInfos -> List.length argInfos) + | Some argInfosForOverloads -> + let nums = + argInfosForOverloads + |> List.map (function + | None -> -1 + | Some argInfos -> List.length argInfos) // Prior to 'OverloadsForCustomOperations' we count exact arguments. // // With 'OverloadsForCustomOperations' we don't compute an exact expected argument count // if any arguments are optional, out or ParamArray. - let isSpecial = + let isSpecial = if cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations then - argInfosForOverloads |> List.exists (fun info -> - match info with + argInfosForOverloads + |> List.exists (fun info -> + match info with | None -> false - | Some args -> - args |> List.exists (fun (ParamAttribs(isParamArrayArg, _isInArg, isOutArg, optArgInfo, _callerInfo, _reflArgInfo)) -> isParamArrayArg || isOutArg || optArgInfo.IsOptional)) + | Some args -> + args + |> List.exists + (fun (ParamAttribs(isParamArrayArg, _isInArg, isOutArg, optArgInfo, _callerInfo, _reflArgInfo)) -> + isParamArrayArg || isOutArg || optArgInfo.IsOptional)) else false - if not isSpecial && nums |> List.forall (fun v -> v >= 0 && v = nums[0]) then - Some (max (nums[0] - 1) 0) // drop the computation context argument + if not isSpecial && nums |> List.forall (fun v -> v >= 0 && v = nums[0]) then + Some(max (nums[0] - 1) 0) // drop the computation context argument else None // Check for the [] attribute on an argument position - let isCustomOperationProjectionParameter i (nm: Ident) = + let isCustomOperationProjectionParameter i (nm: Ident) = match tryGetArgInfosForCustomOperator nm with | None -> false | Some argInfosForOverloads -> - let vs = - argInfosForOverloads |> List.map (function + let vs = + argInfosForOverloads + |> List.map (function | None -> false - | Some argInfos -> - i < argInfos.Length && - let _, argInfo = List.item i argInfos - HasFSharpAttribute cenv.g cenv.g.attrib_ProjectionParameterAttribute argInfo.Attribs) - if List.allEqual vs then vs[0] - else + | Some argInfos -> + i < argInfos.Length + && let _, argInfo = List.item i argInfos in + HasFSharpAttribute cenv.g cenv.g.attrib_ProjectionParameterAttribute argInfo.Attribs) + + if List.allEqual vs then + vs[0] + else let opDatas = (tryGetDataForCustomOperation nm).Value let opName, _, _, _, _, _, _, _j, _ = opDatas[0] - errorR(Error(FSComp.SR.tcCustomOperationInvalid opName, nm.idRange)) + errorR (Error(FSComp.SR.tcCustomOperationInvalid opName, nm.idRange)) false - let (|ForEachThen|_|) synExpr = - match synExpr with - | SynExpr.ForEach (_spFor, _spIn, SeqExprOnly false, isFromSource, pat1, expr1, SynExpr.Sequential (_, true, clause, rest, _), _) -> - Some (isFromSource, pat1, expr1, clause, rest) + let (|ForEachThen|_|) synExpr = + match synExpr with + | SynExpr.ForEach(_spFor, _spIn, SeqExprOnly false, isFromSource, pat1, expr1, SynExpr.Sequential(_, true, clause, rest, _), _) -> + Some(isFromSource, pat1, expr1, clause, rest) | _ -> None - let (|CustomOpId|_|) predicate synExpr = - match synExpr with + let (|CustomOpId|_|) predicate synExpr = + match synExpr with | SingleIdent nm when isCustomOperation nm && predicate nm -> Some nm | _ -> None // e1 in e2 ('in' is parsed as 'JOIN_IN') - let (|InExpr|_|) synExpr = - match synExpr with - | SynExpr.JoinIn (e1, _, e2, mApp) -> Some (e1, e2, mApp) + let (|InExpr|_|) synExpr = + match synExpr with + | SynExpr.JoinIn(e1, _, e2, mApp) -> Some(e1, e2, mApp) | _ -> None // e1 on e2 (note: 'on' is the 'JoinConditionWord') - let (|OnExpr|_|) nm synExpr = - match tryGetDataForCustomOperation nm with + let (|OnExpr|_|) nm synExpr = + match tryGetDataForCustomOperation nm with | None -> None - | Some _ -> - match synExpr with - | SynExpr.App (_, _, SynExpr.App (_, _, e1, SingleIdent opName, _), e2, _) when opName.idText = customOperationJoinConditionWord nm -> - let item = Item.CustomOperation (opName.idText, (fun () -> None), None) + | Some _ -> + match synExpr with + | SynExpr.App(funcExpr = SynExpr.App(funcExpr = e1; argExpr = SingleIdent opName); argExpr = e2) when + opName.idText = customOperationJoinConditionWord nm + -> + let item = Item.CustomOperation(opName.idText, (fun () -> None), None) CallNameResolutionSink cenv.tcSink (opName.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.AccessRights) - Some (e1, e2) + Some(e1, e2) | _ -> None // e1 into e2 - let (|IntoSuffix|_|) (e: SynExpr) = - match e with - | SynExpr.App (_, _, SynExpr.App (_, _, x, SingleIdent nm2, _), ExprAsPat intoPat, _) when nm2.idText = CustomOperations.Into -> - Some (x, nm2.idRange, intoPat) - | _ -> - None + let (|IntoSuffix|_|) (e: SynExpr) = + match e with + | SynExpr.App(funcExpr = SynExpr.App(funcExpr = x; argExpr = SingleIdent nm2); argExpr = ExprAsPat intoPat) when + nm2.idText = CustomOperations.Into + -> + Some(x, nm2.idRange, intoPat) + | _ -> None - let arbPat (m: range) = mkSynPatVar None (mkSynId (m.MakeSynthetic()) "_missingVar") + let arbPat (m: range) = + mkSynPatVar None (mkSynId (m.MakeSynthetic()) "_missingVar") - let MatchIntoSuffixOrRecover alreadyGivenError (nm: Ident) synExpr = - match synExpr with - | IntoSuffix (x, intoWordRange, intoPat) -> + let MatchIntoSuffixOrRecover alreadyGivenError (nm: Ident) synExpr = + match synExpr with + | IntoSuffix(x, intoWordRange, intoPat) -> // record the "into" as a custom operation for colorization - let item = Item.CustomOperation ("into", (fun () -> None), None) + let item = Item.CustomOperation("into", (fun () -> None), None) CallNameResolutionSink cenv.tcSink (intoWordRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) (x, intoPat, alreadyGivenError) - | _ -> - if not alreadyGivenError then - errorR(Error(FSComp.SR.tcOperatorIncorrectSyntax(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + | _ -> + if not alreadyGivenError then + errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + (synExpr, arbPat synExpr.Range, true) - let MatchOnExprOrRecover alreadyGivenError nm (onExpr: SynExpr) = - match onExpr with - | OnExpr nm (innerSource, SynExprParen(keySelectors, _, _, _)) -> - (innerSource, keySelectors) - | _ -> - if not alreadyGivenError then - suppressErrorReporting (fun () -> TcExprOfUnknownType cenv env tpenv onExpr) |> ignore - errorR(Error(FSComp.SR.tcOperatorIncorrectSyntax(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) - (arbExpr("_innerSource", onExpr.Range), mkSynBifix onExpr.Range "=" (arbExpr("_keySelectors", onExpr.Range)) (arbExpr("_keySelector2", onExpr.Range))) - - let JoinOrGroupJoinOp detector synExpr = - match synExpr with - | SynExpr.App (_, _, CustomOpId detector nm, ExprAsPat innerSourcePat, mJoinCore) -> - Some(nm, innerSourcePat, mJoinCore, false) + let MatchOnExprOrRecover alreadyGivenError nm (onExpr: SynExpr) = + match onExpr with + | OnExpr nm (innerSource, SynExprParen(keySelectors, _, _, _)) -> (innerSource, keySelectors) + | _ -> + if not alreadyGivenError then + suppressErrorReporting (fun () -> TcExprOfUnknownType cenv env tpenv onExpr) + |> ignore + + errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + + (arbExpr ("_innerSource", onExpr.Range), + mkSynBifix onExpr.Range "=" (arbExpr ("_keySelectors", onExpr.Range)) (arbExpr ("_keySelector2", onExpr.Range))) + + let JoinOrGroupJoinOp detector synExpr = + match synExpr with + | SynExpr.App(_, _, CustomOpId detector nm, ExprAsPat innerSourcePat, mJoinCore) -> Some(nm, innerSourcePat, mJoinCore, false) // join with bad pattern (gives error on "join" and continues) - | SynExpr.App (_, _, CustomOpId detector nm, _innerSourcePatExpr, mJoinCore) -> - errorR(Error(FSComp.SR.tcBinaryOperatorRequiresVariable(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + | SynExpr.App(_, _, CustomOpId detector nm, _innerSourcePatExpr, mJoinCore) -> + errorR (Error(FSComp.SR.tcBinaryOperatorRequiresVariable (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) Some(nm, arbPat mJoinCore, mJoinCore, true) // join (without anything after - gives error on "join" and continues) - | CustomOpId detector nm -> - errorR(Error(FSComp.SR.tcBinaryOperatorRequiresVariable(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + | CustomOpId detector nm -> + errorR (Error(FSComp.SR.tcBinaryOperatorRequiresVariable (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) Some(nm, arbPat synExpr.Range, synExpr.Range, true) - | _ -> - None - // JoinOrGroupJoinOp customOperationIsLikeJoin + | _ -> None + // JoinOrGroupJoinOp customOperationIsLikeJoin - let (|JoinOp|_|) synExpr = JoinOrGroupJoinOp customOperationIsLikeJoin synExpr + let (|JoinOp|_|) synExpr = + JoinOrGroupJoinOp customOperationIsLikeJoin synExpr - let (|GroupJoinOp|_|) synExpr = JoinOrGroupJoinOp customOperationIsLikeGroupJoin synExpr + let (|GroupJoinOp|_|) synExpr = + JoinOrGroupJoinOp customOperationIsLikeGroupJoin synExpr - let arbKeySelectors m = mkSynBifix m "=" (arbExpr("_keySelectors", m)) (arbExpr("_keySelector2", m)) + let arbKeySelectors m = + mkSynBifix m "=" (arbExpr ("_keySelectors", m)) (arbExpr ("_keySelector2", m)) - let (|JoinExpr|_|) synExpr = - match synExpr with - | InExpr (JoinOp(nm, innerSourcePat, _, alreadyGivenError), onExpr, mJoinCore) -> + let (|JoinExpr|_|) synExpr = + match synExpr with + | InExpr(JoinOp(nm, innerSourcePat, _, alreadyGivenError), onExpr, mJoinCore) -> let innerSource, keySelectors = MatchOnExprOrRecover alreadyGivenError nm onExpr Some(nm, innerSourcePat, innerSource, keySelectors, mJoinCore) - | JoinOp (nm, innerSourcePat, mJoinCore, alreadyGivenError) -> - if alreadyGivenError then - errorR(Error(FSComp.SR.tcOperatorRequiresIn(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) - Some (nm, innerSourcePat, arbExpr("_innerSource", synExpr.Range), arbKeySelectors synExpr.Range, mJoinCore) + | JoinOp(nm, innerSourcePat, mJoinCore, alreadyGivenError) -> + if alreadyGivenError then + errorR (Error(FSComp.SR.tcOperatorRequiresIn (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + + Some(nm, innerSourcePat, arbExpr ("_innerSource", synExpr.Range), arbKeySelectors synExpr.Range, mJoinCore) | _ -> None - let (|GroupJoinExpr|_|) synExpr = - match synExpr with - | InExpr (GroupJoinOp (nm, innerSourcePat, _, alreadyGivenError), intoExpr, mGroupJoinCore) -> - let onExpr, intoPat, alreadyGivenError = MatchIntoSuffixOrRecover alreadyGivenError nm intoExpr - let innerSource, keySelectors = MatchOnExprOrRecover alreadyGivenError nm onExpr - Some (nm, innerSourcePat, innerSource, keySelectors, intoPat, mGroupJoinCore) - | GroupJoinOp (nm, innerSourcePat, mGroupJoinCore, alreadyGivenError) -> - if alreadyGivenError then - errorR(Error(FSComp.SR.tcOperatorRequiresIn(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) - Some (nm, innerSourcePat, arbExpr("_innerSource", synExpr.Range), arbKeySelectors synExpr.Range, arbPat synExpr.Range, mGroupJoinCore) - | _ -> - None + let (|GroupJoinExpr|_|) synExpr = + match synExpr with + | InExpr(GroupJoinOp(nm, innerSourcePat, _, alreadyGivenError), intoExpr, mGroupJoinCore) -> + let onExpr, intoPat, alreadyGivenError = + MatchIntoSuffixOrRecover alreadyGivenError nm intoExpr + let innerSource, keySelectors = MatchOnExprOrRecover alreadyGivenError nm onExpr + Some(nm, innerSourcePat, innerSource, keySelectors, intoPat, mGroupJoinCore) + | GroupJoinOp(nm, innerSourcePat, mGroupJoinCore, alreadyGivenError) -> + if alreadyGivenError then + errorR (Error(FSComp.SR.tcOperatorRequiresIn (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + + Some( + nm, + innerSourcePat, + arbExpr ("_innerSource", synExpr.Range), + arbKeySelectors synExpr.Range, + arbPat synExpr.Range, + mGroupJoinCore + ) + | _ -> None - let (|JoinOrGroupJoinOrZipClause|_|) synExpr = + let (|JoinOrGroupJoinOrZipClause|_|) synExpr = - match synExpr with + match synExpr with // join innerSourcePat in innerSource on (keySelector1 = keySelector2) - | JoinExpr (nm, innerSourcePat, innerSource, keySelectors, mJoinCore) -> + | JoinExpr(nm, innerSourcePat, innerSource, keySelectors, mJoinCore) -> Some(nm, innerSourcePat, innerSource, Some keySelectors, None, mJoinCore) // groupJoin innerSourcePat in innerSource on (keySelector1 = keySelector2) into intoPat - | GroupJoinExpr (nm, innerSourcePat, innerSource, keySelectors, intoPat, mGroupJoinCore) -> + | GroupJoinExpr(nm, innerSourcePat, innerSource, keySelectors, intoPat, mGroupJoinCore) -> Some(nm, innerSourcePat, innerSource, Some keySelectors, Some intoPat, mGroupJoinCore) - // zip intoPat in secondSource - | InExpr (SynExpr.App (_, _, CustomOpId customOperationIsLikeZip nm, ExprAsPat secondSourcePat, _), secondSource, mZipCore) -> + // zip intoPat in secondSource + | InExpr(SynExpr.App(_, _, CustomOpId customOperationIsLikeZip nm, ExprAsPat secondSourcePat, _), secondSource, mZipCore) -> Some(nm, secondSourcePat, secondSource, None, None, mZipCore) // zip (without secondSource or in - gives error) - | CustomOpId customOperationIsLikeZip nm -> - errorR(Error(FSComp.SR.tcOperatorIncorrectSyntax(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) - Some(nm, arbPat synExpr.Range, arbExpr("_secondSource", synExpr.Range), None, None, synExpr.Range) + | CustomOpId customOperationIsLikeZip nm -> + errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + Some(nm, arbPat synExpr.Range, arbExpr ("_secondSource", synExpr.Range), None, None, synExpr.Range) // zip secondSource (without in - gives error) - | SynExpr.App (_, _, CustomOpId customOperationIsLikeZip nm, ExprAsPat secondSourcePat, mZipCore) -> - errorR(Error(FSComp.SR.tcOperatorIncorrectSyntax(nm.idText, Option.get (customOpUsageText nm)), mZipCore)) - Some(nm, secondSourcePat, arbExpr("_innerSource", synExpr.Range), None, None, mZipCore) + | SynExpr.App(_, _, CustomOpId customOperationIsLikeZip nm, ExprAsPat secondSourcePat, mZipCore) -> + errorR (Error(FSComp.SR.tcOperatorIncorrectSyntax (nm.idText, Option.get (customOpUsageText nm)), mZipCore)) + Some(nm, secondSourcePat, arbExpr ("_innerSource", synExpr.Range), None, None, mZipCore) - | _ -> - None + | _ -> None - let (|ForEachThenJoinOrGroupJoinOrZipClause|_|) strict synExpr = - match synExpr with - | ForEachThen (isFromSource, firstSourcePat, firstSource, JoinOrGroupJoinOrZipClause(nm, secondSourcePat, secondSource, keySelectorsOpt, pat3opt, mOpCore), innerComp) - when - (let _firstSourceSimplePats, later1 = - use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - SimplePatsOfPat cenv.synArgNameGenerator firstSourcePat - Option.isNone later1) -> - Some (isFromSource, firstSourcePat, firstSource, nm, secondSourcePat, secondSource, keySelectorsOpt, pat3opt, mOpCore, innerComp) - - | JoinOrGroupJoinOrZipClause(nm, pat2, expr2, expr3, pat3opt, mOpCore) when strict -> - errorR(Error(FSComp.SR.tcBinaryOperatorRequiresBody(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) - Some (true, arbPat synExpr.Range, arbExpr("_outerSource", synExpr.Range), nm, pat2, expr2, expr3, pat3opt, mOpCore, arbExpr("_innerComp", synExpr.Range)) - - | _ -> - None + let (|ForEachThenJoinOrGroupJoinOrZipClause|_|) strict synExpr = + match synExpr with + | ForEachThen(isFromSource, + firstSourcePat, + firstSource, + JoinOrGroupJoinOrZipClause(nm, secondSourcePat, secondSource, keySelectorsOpt, pat3opt, mOpCore), + innerComp) when + (let _firstSourceSimplePats, later1 = + use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink + SimplePatsOfPat cenv.synArgNameGenerator firstSourcePat + + Option.isNone later1) + -> + Some(isFromSource, firstSourcePat, firstSource, nm, secondSourcePat, secondSource, keySelectorsOpt, pat3opt, mOpCore, innerComp) + + | JoinOrGroupJoinOrZipClause(nm, pat2, expr2, expr3, pat3opt, mOpCore) when strict -> + errorR (Error(FSComp.SR.tcBinaryOperatorRequiresBody (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + + Some( + true, + arbPat synExpr.Range, + arbExpr ("_outerSource", synExpr.Range), + nm, + pat2, + expr2, + expr3, + pat3opt, + mOpCore, + arbExpr ("_innerComp", synExpr.Range) + ) - let (|StripApps|) e = - let rec strip e = - match e with - | SynExpr.FromParseError (SynExpr.App (_, _, f, arg, _), _) - | SynExpr.App (_, _, f, arg, _) -> - let g, acc = strip f - g, (arg :: acc) + | _ -> None + + let (|StripApps|) e = + let rec strip e = + match e with + | SynExpr.FromParseError(SynExpr.App(funcExpr = f; argExpr = arg), _) + | SynExpr.App(funcExpr = f; argExpr = arg) -> + let g, acc = strip f + g, (arg :: acc) | _ -> e, [] + let g, acc = strip e g, List.rev acc - let (|OptionalIntoSuffix|) e = - match e with - | IntoSuffix (body, intoWordRange, intoInfo) -> (body, Some (intoWordRange, intoInfo)) + let (|OptionalIntoSuffix|) e = + match e with + | IntoSuffix(body, intoWordRange, intoInfo) -> (body, Some(intoWordRange, intoInfo)) | body -> (body, None) - let (|CustomOperationClause|_|) e = - match e with - | OptionalIntoSuffix(StripApps(SingleIdent nm, _) as core, intoOpt) when isCustomOperation nm -> + let (|CustomOperationClause|_|) e = + match e with + | OptionalIntoSuffix(StripApps(SingleIdent nm, _) as core, intoOpt) when isCustomOperation nm -> // Now we know we have a custom operation, commit the name resolution - let intoInfoOpt = - match intoOpt with - | Some (intoWordRange, intoInfo) -> - let item = Item.CustomOperation ("into", (fun () -> None), None) - CallNameResolutionSink cenv.tcSink (intoWordRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) + let intoInfoOpt = + match intoOpt with + | Some(intoWordRange, intoInfo) -> + let item = Item.CustomOperation("into", (fun () -> None), None) + + CallNameResolutionSink + cenv.tcSink + (intoWordRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) + Some intoInfo | None -> None - Some (nm, Option.get (tryGetDataForCustomOperation nm), core, core.Range, intoInfoOpt) + Some(nm, Option.get (tryGetDataForCustomOperation nm), core, core.Range, intoInfoOpt) | _ -> None - let mkSynLambda p e m = SynExpr.Lambda (false, false, p, e, None, m, SynExprLambdaTrivia.Zero) + let mkSynLambda p e m = + SynExpr.Lambda(false, false, p, e, None, m, SynExprLambdaTrivia.Zero) - let mkExprForVarSpace m (patvs: Val list) = - match patvs with - | [] -> SynExpr.Const (SynConst.Unit, m) - | [v] -> SynExpr.Ident v.Id - | vs -> SynExpr.Tuple (false, (vs |> List.map (fun v -> SynExpr.Ident(v.Id))), [], m) + let mkExprForVarSpace m (patvs: Val list) = + match patvs with + | [] -> SynExpr.Const(SynConst.Unit, m) + | [ v ] -> SynExpr.Ident v.Id + | vs -> SynExpr.Tuple(false, (vs |> List.map (fun v -> SynExpr.Ident(v.Id))), [], m) - let mkSimplePatForVarSpace m (patvs: Val list) = - let spats = - match patvs with + let mkSimplePatForVarSpace m (patvs: Val list) = + let spats = + match patvs with | [] -> [] - | [v] -> [mkSynSimplePatVar false v.Id] + | [ v ] -> [ mkSynSimplePatVar false v.Id ] | vs -> vs |> List.map (fun v -> mkSynSimplePatVar false v.Id) - SynSimplePats.SimplePats (spats, [], m) - let mkPatForVarSpace m (patvs: Val list) = - match patvs with - | [] -> SynPat.Const (SynConst.Unit, m) - | [v] -> mkSynPatVar None v.Id + SynSimplePats.SimplePats(spats, [], m) + + let mkPatForVarSpace m (patvs: Val list) = + match patvs with + | [] -> SynPat.Const(SynConst.Unit, m) + | [ v ] -> mkSynPatVar None v.Id | vs -> SynPat.Tuple(false, (vs |> List.map (fun x -> mkSynPatVar None x.Id)), [], m) - let (|OptionalSequential|) e = - match e with - | SynExpr.Sequential (_sp, true, dataComp1, dataComp2, _) -> (dataComp1, Some dataComp2) + let (|OptionalSequential|) e = + match e with + | SynExpr.Sequential(_sp, true, dataComp1, dataComp2, _) -> (dataComp1, Some dataComp2) | _ -> (e, None) // "cexpr; cexpr" is treated as builder.Combine(cexpr1, cexpr1) // This is not pretty - we have to decide which range markers we use for the calls to Combine and Delay // NOTE: we should probably suppress these sequence points altogether - let rangeForCombine innerComp1 = + let rangeForCombine innerComp1 = let m = - match innerComp1 with - | SynExpr.IfThenElse (trivia={ IfToThenRange = mIfToThen }) -> mIfToThen - | SynExpr.Match (matchDebugPoint=DebugPointAtBinding.Yes mMatch) -> mMatch - | SynExpr.TryWith (trivia={ TryKeyword = mTry }) -> mTry - | SynExpr.TryFinally (trivia={ TryKeyword = mTry }) -> mTry - | SynExpr.For (forDebugPoint=DebugPointAtFor.Yes mBind) -> mBind - | SynExpr.ForEach (forDebugPoint=DebugPointAtFor.Yes mBind) -> mBind - | SynExpr.While (whileDebugPoint=DebugPointAtWhile.Yes mWhile) -> mWhile + match innerComp1 with + | SynExpr.IfThenElse(trivia = { IfToThenRange = mIfToThen }) -> mIfToThen + | SynExpr.Match(matchDebugPoint = DebugPointAtBinding.Yes mMatch) -> mMatch + | SynExpr.TryWith(trivia = { TryKeyword = mTry }) -> mTry + | SynExpr.TryFinally(trivia = { TryKeyword = mTry }) -> mTry + | SynExpr.For(forDebugPoint = DebugPointAtFor.Yes mBind) -> mBind + | SynExpr.ForEach(forDebugPoint = DebugPointAtFor.Yes mBind) -> mBind + | SynExpr.While(whileDebugPoint = DebugPointAtWhile.Yes mWhile) -> mWhile | _ -> innerComp1.Range m.NoteSourceConstruct(NotedSourceConstruct.Combine) // Check for 'where x > y', 'select x, y' and other mis-applications of infix operators, give a good error message, and return a flag - let checkForBinaryApp comp = - match comp with - | StripApps(SingleIdent nm, [StripApps(SingleIdent nm2, args); arg2]) when - IsLogicalInfixOpName nm.idText && - (match tryExpectedArgCountForCustomOperator nm2 with Some n -> n > 0 | _ -> false) && - not (List.isEmpty args) -> - let estimatedRangeOfIntendedLeftAndRightArguments = unionRanges (List.last args).Range arg2.Range - errorR(Error(FSComp.SR.tcUnrecognizedQueryBinaryOperator(), estimatedRangeOfIntendedLeftAndRightArguments)) + let checkForBinaryApp comp = + match comp with + | StripApps(SingleIdent nm, [ StripApps(SingleIdent nm2, args); arg2 ]) when + IsLogicalInfixOpName nm.idText + && (match tryExpectedArgCountForCustomOperator nm2 with + | Some n -> n > 0 + | _ -> false) + && not (List.isEmpty args) + -> + let estimatedRangeOfIntendedLeftAndRightArguments = + unionRanges (List.last args).Range arg2.Range + + errorR (Error(FSComp.SR.tcUnrecognizedQueryBinaryOperator (), estimatedRangeOfIntendedLeftAndRightArguments)) true - | SynExpr.Tuple (false, StripApps(SingleIdent nm2, args) :: _, _, m) when - (match tryExpectedArgCountForCustomOperator nm2 with Some n -> n > 0 | _ -> false) && - not (List.isEmpty args) -> - let estimatedRangeOfIntendedLeftAndRightArguments = unionRanges (List.last args).Range m.EndRange - errorR(Error(FSComp.SR.tcUnrecognizedQueryBinaryOperator(), estimatedRangeOfIntendedLeftAndRightArguments)) + | SynExpr.Tuple(false, StripApps(SingleIdent nm2, args) :: _, _, m) when + (match tryExpectedArgCountForCustomOperator nm2 with + | Some n -> n > 0 + | _ -> false) + && not (List.isEmpty args) + -> + let estimatedRangeOfIntendedLeftAndRightArguments = + unionRanges (List.last args).Range m.EndRange + + errorR (Error(FSComp.SR.tcUnrecognizedQueryBinaryOperator (), estimatedRangeOfIntendedLeftAndRightArguments)) true - | _ -> - false - - let addVarsToVarSpace (varSpace: LazyWithContext) f = - LazyWithContext.Create - ((fun m -> - let (patvs: Val list, env) = varSpace.Force m - let vs, envinner = f m env - let patvs = List.append patvs (vs |> List.filter (fun v -> not (patvs |> List.exists (fun v2 -> v.LogicalName = v2.LogicalName)))) - patvs, envinner), - id) + | _ -> false + + let addVarsToVarSpace (varSpace: LazyWithContext) f = + LazyWithContext.Create( + (fun m -> + let (patvs: Val list, env) = varSpace.Force m + let vs, envinner = f m env + + let patvs = + List.append + patvs + (vs + |> List.filter (fun v -> not (patvs |> List.exists (fun v2 -> v.LogicalName = v2.LogicalName)))) + + patvs, envinner), + id + ) // Flag that a debug point should get emitted prior to both the evaluation of 'rhsExpr' and the call to Using let addBindDebugPoint spBind e = match spBind with - | DebugPointAtBinding.Yes m -> - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, e) + | DebugPointAtBinding.Yes m -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, e) | _ -> e - let emptyVarSpace = LazyWithContext.NotLazy ([], env) + let emptyVarSpace = LazyWithContext.NotLazy([], env) // If there are no 'yield' in the computation expression, and the builder supports 'Yield', // then allow the type-directed rule interpreting non-unit-typed expressions in statement // positions as 'yield'. 'yield!' may be present in the computation expression. let enableImplicitYield = cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield - && (hasMethInfo "Yield" && hasMethInfo "Combine" && hasMethInfo "Delay" && YieldFree cenv comp) - - // q - a flag indicating if custom operators are allowed. They are not allowed inside try/with, try/finally, if/then/else etc. - // varSpace - a lazy data structure indicating the variables bound so far in the overall computation - // comp - the computation expression being analyzed - // translatedCtxt - represents the translation of the context in which the computation expression 'comp' occurs, up to a - // hole to be filled by (part of) the results of translating 'comp'. - let rec tryTrans firstTry q varSpace comp translatedCtxt = + && (hasMethInfo "Yield" + && hasMethInfo "Combine" + && hasMethInfo "Delay" + && YieldFree cenv comp) + + /// + /// Try translate the syntax sugar + /// + /// + /// a flag indicating if custom operators are allowed. They are not allowed inside try/with, try/finally, if/then/else etc. + /// a lazy data structure indicating the variables bound so far in the overall computation + /// the computation expression being analyzed + /// represents the translation of the context in which the computation expression 'comp' occurs, + /// up to a hole to be filled by (part of) the results of translating 'comp'. + let rec tryTrans + (firstTry: CompExprTranslationPass) + (q: CustomOperationsMode) + (varSpace: LazyWithContext<(Val list * TcEnv), range>) + (comp: SynExpr) + (translatedCtxt: SynExpr -> SynExpr) + : SynExpr option = // Guard the stack for deeply nested computation expressions - cenv.stackGuard.Guard <| fun () -> - - match comp with - - // for firstSourcePat in firstSource do - // join secondSourcePat in expr2 on (expr3 = expr4) - // ... - // --> - // join expr1 expr2 (fun firstSourcePat -> expr3) (fun secondSourcePat -> expr4) (fun firstSourcePat secondSourcePat -> ...) - - // for firstSourcePat in firstSource do - // groupJoin secondSourcePat in expr2 on (expr3 = expr4) into groupPat - // ... - // --> - // groupJoin expr1 expr2 (fun firstSourcePat -> expr3) (fun secondSourcePat -> expr4) (fun firstSourcePat groupPat -> ...) - - // for firstSourcePat in firstSource do - // zip secondSource into secondSourcePat - // ... - // --> - // zip expr1 expr2 (fun pat1 pat3 -> ...) - | ForEachThenJoinOrGroupJoinOrZipClause true (isFromSource, firstSourcePat, firstSource, nm, secondSourcePat, secondSource, keySelectorsOpt, secondResultPatOpt, mOpCore, innerComp) -> - - if q = CustomOperationsMode.Denied then error(Error(FSComp.SR.tcCustomOperationMayNotBeUsedHere(), nm.idRange)) - let firstSource = mkSourceExprConditional isFromSource firstSource - let secondSource = mkSourceExpr secondSource - - // Add the variables to the variable space, on demand - let varSpaceWithFirstVars = - addVarsToVarSpace varSpace (fun _mCustomOp env -> - use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv firstSourcePat None - vspecs, envinner) - - let varSpaceWithSecondVars = - addVarsToVarSpace varSpaceWithFirstVars (fun _mCustomOp env -> - use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv secondSourcePat None - vspecs, envinner) - - let varSpaceWithGroupJoinVars = - match secondResultPatOpt with - | Some pat3 -> - addVarsToVarSpace varSpaceWithFirstVars (fun _mCustomOp env -> + cenv.stackGuard.Guard + <| fun () -> + + match comp with + + // for firstSourcePat in firstSource do + // join secondSourcePat in expr2 on (expr3 = expr4) + // ... + // --> + // join expr1 expr2 (fun firstSourcePat -> expr3) (fun secondSourcePat -> expr4) (fun firstSourcePat secondSourcePat -> ...) + + // for firstSourcePat in firstSource do + // groupJoin secondSourcePat in expr2 on (expr3 = expr4) into groupPat + // ... + // --> + // groupJoin expr1 expr2 (fun firstSourcePat -> expr3) (fun secondSourcePat -> expr4) (fun firstSourcePat groupPat -> ...) + + // for firstSourcePat in firstSource do + // zip secondSource into secondSourcePat + // ... + // --> + // zip expr1 expr2 (fun pat1 pat3 -> ...) + | ForEachThenJoinOrGroupJoinOrZipClause true (isFromSource, + firstSourcePat, + firstSource, + nm, + secondSourcePat, + secondSource, + keySelectorsOpt, + secondResultPatOpt, + mOpCore, + innerComp) -> + + if q = CustomOperationsMode.Denied then + error (Error(FSComp.SR.tcCustomOperationMayNotBeUsedHere (), nm.idRange)) + + let firstSource = mkSourceExprConditional isFromSource firstSource + let secondSource = mkSourceExpr secondSource + + // Add the variables to the variable space, on demand + let varSpaceWithFirstVars = + addVarsToVarSpace varSpace (fun _mCustomOp env -> use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv pat3 None - vspecs, envinner) - | None -> varSpace - let firstSourceSimplePats, later1 = SimplePatsOfPat cenv.synArgNameGenerator firstSourcePat - let secondSourceSimplePats, later2 = SimplePatsOfPat cenv.synArgNameGenerator secondSourcePat + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv firstSourcePat None - if Option.isSome later1 then errorR (Error (FSComp.SR.tcJoinMustUseSimplePattern(nm.idText), firstSourcePat.Range)) - if Option.isSome later2 then errorR (Error (FSComp.SR.tcJoinMustUseSimplePattern(nm.idText), secondSourcePat.Range)) + vspecs, envinner) - // check 'join' or 'groupJoin' or 'zip' is permitted for this builder - match tryGetDataForCustomOperation nm with - | None -> error(Error(FSComp.SR.tcMissingCustomOperation(nm.idText), nm.idRange)) - | Some opDatas -> - let opName, _, _, _, _, _, _, _, methInfo = opDatas[0] + let varSpaceWithSecondVars = + addVarsToVarSpace varSpaceWithFirstVars (fun _mCustomOp env -> + use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - // Record the resolution of the custom operation for posterity - let item = Item.CustomOperation (opName, (fun () -> customOpUsageText nm), Some methInfo) + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv secondSourcePat None - // FUTURE: consider whether we can do better than emptyTyparInst here, in order to display instantiations - // of type variables in the quick info provided in the IDE. - CallNameResolutionSink cenv.tcSink (nm.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) + vspecs, envinner) - let mkJoinExpr keySelector1 keySelector2 innerPat e = - let mSynthetic = mOpCore.MakeSynthetic() - mkSynCall methInfo.DisplayName mOpCore - [ firstSource - secondSource - mkSynLambda firstSourceSimplePats keySelector1 mSynthetic - mkSynLambda secondSourceSimplePats keySelector2 mSynthetic - mkSynLambda firstSourceSimplePats (mkSynLambda innerPat e mSynthetic) mSynthetic ] - - let mkZipExpr e = - let mSynthetic = mOpCore.MakeSynthetic() - mkSynCall methInfo.DisplayName mOpCore - [ firstSource - secondSource - mkSynLambda firstSourceSimplePats (mkSynLambda secondSourceSimplePats e mSynthetic) mSynthetic ] - - // wraps given expression into sequence with result produced by arbExpr so result will look like: - // l; SynExpr.ArbitraryAfterError (...) - // this allows to handle cases like 'on (a > b)' // '>' is not permitted as correct join relation - // after wrapping a and b can still be typechecked (so we'll have correct completion inside 'on' part) - // but presence of SynExpr.ArbitraryAfterError allows to avoid errors about incompatible types in cases like - // query { - // for a in [1] do - // join b in [""] on (a > b) - // } - // if we typecheck raw 'a' and 'b' then we'll end up with 2 errors: - // 1. incorrect join relation - // 2. incompatible types: int and string - // with SynExpr.ArbitraryAfterError we have only first one - let wrapInArbErrSequence l caption = - SynExpr.Sequential (DebugPointAtSequential.SuppressNeither, true, l, (arbExpr(caption, l.Range.EndRange)), l.Range) - - let mkOverallExprGivenVarSpaceExpr, varSpaceInner = - - let isNullableOp opId = - match ConvertValLogicalNameToDisplayNameCore opId with - | "?=" | "=?" | "?=?" -> true - | _ -> false - - match secondResultPatOpt, keySelectorsOpt with - // groupJoin - | Some secondResultPat, Some relExpr when customOperationIsLikeGroupJoin nm -> - let secondResultSimplePats, later3 = SimplePatsOfPat cenv.synArgNameGenerator secondResultPat - if Option.isSome later3 then errorR (Error (FSComp.SR.tcJoinMustUseSimplePattern(nm.idText), secondResultPat.Range)) - match relExpr with - | JoinRelation cenv env (keySelector1, keySelector2) -> - mkJoinExpr keySelector1 keySelector2 secondResultSimplePats, varSpaceWithGroupJoinVars - | BinOpExpr (opId, l, r) -> - if isNullableOp opId.idText then - // When we cannot resolve NullableOps, recommend the relevant namespace to be added - errorR(Error(FSComp.SR.cannotResolveNullableOperators(ConvertValLogicalNameToDisplayNameCore opId.idText), relExpr.Range)) - else - errorR(Error(FSComp.SR.tcInvalidRelationInJoin(nm.idText), relExpr.Range)) - let l = wrapInArbErrSequence l "_keySelector1" - let r = wrapInArbErrSequence r "_keySelector2" - // this is not correct JoinRelation but it is still binary operation - // we've already reported error now we can use operands of binary operation as join components - mkJoinExpr l r secondResultSimplePats, varSpaceWithGroupJoinVars - | _ -> - errorR(Error(FSComp.SR.tcInvalidRelationInJoin(nm.idText), relExpr.Range)) - // since the shape of relExpr doesn't match our expectations (JoinRelation) - // then we assume that this is l.h.s. of the join relation - // so typechecker will treat relExpr as body of outerKeySelector lambda parameter in GroupJoin method - mkJoinExpr relExpr (arbExpr("_keySelector2", relExpr.Range)) secondResultSimplePats, varSpaceWithGroupJoinVars - - | None, Some relExpr when customOperationIsLikeJoin nm -> - match relExpr with - | JoinRelation cenv env (keySelector1, keySelector2) -> - mkJoinExpr keySelector1 keySelector2 secondSourceSimplePats, varSpaceWithSecondVars - | BinOpExpr (opId, l, r) -> - if isNullableOp opId.idText then - // When we cannot resolve NullableOps, recommend the relevant namespace to be added - errorR(Error(FSComp.SR.cannotResolveNullableOperators(ConvertValLogicalNameToDisplayNameCore opId.idText), relExpr.Range)) - else - errorR(Error(FSComp.SR.tcInvalidRelationInJoin(nm.idText), relExpr.Range)) - // this is not correct JoinRelation but it is still binary operation - // we've already reported error now we can use operands of binary operation as join components - let l = wrapInArbErrSequence l "_keySelector1" - let r = wrapInArbErrSequence r "_keySelector2" - mkJoinExpr l r secondSourceSimplePats, varSpaceWithGroupJoinVars - | _ -> - errorR(Error(FSComp.SR.tcInvalidRelationInJoin(nm.idText), relExpr.Range)) - // since the shape of relExpr doesn't match our expectations (JoinRelation) - // then we assume that this is l.h.s. of the join relation - // so typechecker will treat relExpr as body of outerKeySelector lambda parameter in Join method - mkJoinExpr relExpr (arbExpr("_keySelector2", relExpr.Range)) secondSourceSimplePats, varSpaceWithGroupJoinVars - - | None, None when customOperationIsLikeZip nm -> - mkZipExpr, varSpaceWithSecondVars - - | _ -> - assert false - failwith "unreachable" - - - // Case from C# spec: A query expression with a join clause with an into followed by something other than a select clause - // Case from C# spec: A query expression with a join clause without an into followed by something other than a select clause - let valsInner, _env = varSpaceInner.Force mOpCore - let varSpaceExpr = mkExprForVarSpace mOpCore valsInner - let varSpacePat = mkPatForVarSpace mOpCore valsInner - let joinExpr = mkOverallExprGivenVarSpaceExpr varSpaceExpr - let consumingExpr = SynExpr.ForEach (DebugPointAtFor.No, DebugPointAtInOrTo.No, SeqExprOnly false, false, varSpacePat, joinExpr, innerComp, mOpCore) - Some (trans CompExprTranslationPass.Initial q varSpaceInner consumingExpr translatedCtxt) - - | SynExpr.ForEach (spFor, spIn, SeqExprOnly _seqExprOnly, isFromSource, pat, sourceExpr, innerComp, _mEntireForEach) -> - let sourceExpr = - match RewriteRangeExpr sourceExpr with - | Some e -> e - | None -> sourceExpr - let wrappedSourceExpr = mkSourceExprConditional isFromSource sourceExpr + let varSpaceWithGroupJoinVars = + match secondResultPatOpt with + | Some pat3 -> + addVarsToVarSpace varSpaceWithFirstVars (fun _mCustomOp env -> + use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let mFor = - match spFor with - | DebugPointAtFor.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.For) - | DebugPointAtFor.No -> pat.Range + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv pat3 None - // For computation expressions, 'in' or 'to' is hit on each MoveNext. - // To support this a named debug point for the "in" keyword is available to inlined code. - match spIn with - | DebugPointAtInOrTo.Yes mIn -> - cenv.namedDebugPointsForInlinedCode[{Range=mFor; Name="ForLoop.InOrToKeyword"}] <- mIn - | _ -> () + vspecs, envinner) + | None -> varSpace + + let firstSourceSimplePats, later1 = + SimplePatsOfPat cenv.synArgNameGenerator firstSourcePat + + let secondSourceSimplePats, later2 = + SimplePatsOfPat cenv.synArgNameGenerator secondSourcePat + + if Option.isSome later1 then + errorR (Error(FSComp.SR.tcJoinMustUseSimplePattern (nm.idText), firstSourcePat.Range)) + + if Option.isSome later2 then + errorR (Error(FSComp.SR.tcJoinMustUseSimplePattern (nm.idText), secondSourcePat.Range)) + + // check 'join' or 'groupJoin' or 'zip' is permitted for this builder + match tryGetDataForCustomOperation nm with + | None -> error (Error(FSComp.SR.tcMissingCustomOperation (nm.idText), nm.idRange)) + | Some opDatas -> + let opName, _, _, _, _, _, _, _, methInfo = opDatas[0] + + // Record the resolution of the custom operation for posterity + let item = + Item.CustomOperation(opName, (fun () -> customOpUsageText nm), Some methInfo) + + // FUTURE: consider whether we can do better than emptyTyparInst here, in order to display instantiations + // of type variables in the quick info provided in the IDE. + CallNameResolutionSink cenv.tcSink (nm.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) + + let mkJoinExpr keySelector1 keySelector2 innerPat e = + let mSynthetic = mOpCore.MakeSynthetic() + + mkSynCall + methInfo.DisplayName + mOpCore + [ + firstSource + secondSource + mkSynLambda firstSourceSimplePats keySelector1 mSynthetic + mkSynLambda secondSourceSimplePats keySelector2 mSynthetic + mkSynLambda firstSourceSimplePats (mkSynLambda innerPat e mSynthetic) mSynthetic + ] + + let mkZipExpr e = + let mSynthetic = mOpCore.MakeSynthetic() + + mkSynCall + methInfo.DisplayName + mOpCore + [ + firstSource + secondSource + mkSynLambda firstSourceSimplePats (mkSynLambda secondSourceSimplePats e mSynthetic) mSynthetic + ] + + // wraps given expression into sequence with result produced by arbExpr so result will look like: + // l; SynExpr.ArbitraryAfterError (...) + // this allows to handle cases like 'on (a > b)' // '>' is not permitted as correct join relation + // after wrapping a and b can still be typechecked (so we'll have correct completion inside 'on' part) + // but presence of SynExpr.ArbitraryAfterError allows to avoid errors about incompatible types in cases like + // query { + // for a in [1] do + // join b in [""] on (a > b) + // } + // if we typecheck raw 'a' and 'b' then we'll end up with 2 errors: + // 1. incorrect join relation + // 2. incompatible types: int and string + // with SynExpr.ArbitraryAfterError we have only first one + let wrapInArbErrSequence l caption = + SynExpr.Sequential(DebugPointAtSequential.SuppressNeither, true, l, (arbExpr (caption, l.Range.EndRange)), l.Range) + + let mkOverallExprGivenVarSpaceExpr, varSpaceInner = + + let isNullableOp opId = + match ConvertValLogicalNameToDisplayNameCore opId with + | "?=" + | "=?" + | "?=?" -> true + | _ -> false + + match secondResultPatOpt, keySelectorsOpt with + // groupJoin + | Some secondResultPat, Some relExpr when customOperationIsLikeGroupJoin nm -> + let secondResultSimplePats, later3 = + SimplePatsOfPat cenv.synArgNameGenerator secondResultPat + + if Option.isSome later3 then + errorR (Error(FSComp.SR.tcJoinMustUseSimplePattern (nm.idText), secondResultPat.Range)) + + match relExpr with + | JoinRelation cenv env (keySelector1, keySelector2) -> + mkJoinExpr keySelector1 keySelector2 secondResultSimplePats, varSpaceWithGroupJoinVars + | BinOpExpr(opId, l, r) -> + if isNullableOp opId.idText then + // When we cannot resolve NullableOps, recommend the relevant namespace to be added + errorR ( + Error( + FSComp.SR.cannotResolveNullableOperators (ConvertValLogicalNameToDisplayNameCore opId.idText), + relExpr.Range + ) + ) + else + errorR (Error(FSComp.SR.tcInvalidRelationInJoin (nm.idText), relExpr.Range)) + + let l = wrapInArbErrSequence l "_keySelector1" + let r = wrapInArbErrSequence r "_keySelector2" + // this is not correct JoinRelation but it is still binary operation + // we've already reported error now we can use operands of binary operation as join components + mkJoinExpr l r secondResultSimplePats, varSpaceWithGroupJoinVars + | _ -> + errorR (Error(FSComp.SR.tcInvalidRelationInJoin (nm.idText), relExpr.Range)) + // since the shape of relExpr doesn't match our expectations (JoinRelation) + // then we assume that this is l.h.s. of the join relation + // so typechecker will treat relExpr as body of outerKeySelector lambda parameter in GroupJoin method + mkJoinExpr relExpr (arbExpr ("_keySelector2", relExpr.Range)) secondResultSimplePats, + varSpaceWithGroupJoinVars + + | None, Some relExpr when customOperationIsLikeJoin nm -> + match relExpr with + | JoinRelation cenv env (keySelector1, keySelector2) -> + mkJoinExpr keySelector1 keySelector2 secondSourceSimplePats, varSpaceWithSecondVars + | BinOpExpr(opId, l, r) -> + if isNullableOp opId.idText then + // When we cannot resolve NullableOps, recommend the relevant namespace to be added + errorR ( + Error( + FSComp.SR.cannotResolveNullableOperators (ConvertValLogicalNameToDisplayNameCore opId.idText), + relExpr.Range + ) + ) + else + errorR (Error(FSComp.SR.tcInvalidRelationInJoin (nm.idText), relExpr.Range)) + // this is not correct JoinRelation but it is still binary operation + // we've already reported error now we can use operands of binary operation as join components + let l = wrapInArbErrSequence l "_keySelector1" + let r = wrapInArbErrSequence r "_keySelector2" + mkJoinExpr l r secondSourceSimplePats, varSpaceWithGroupJoinVars + | _ -> + errorR (Error(FSComp.SR.tcInvalidRelationInJoin (nm.idText), relExpr.Range)) + // since the shape of relExpr doesn't match our expectations (JoinRelation) + // then we assume that this is l.h.s. of the join relation + // so typechecker will treat relExpr as body of outerKeySelector lambda parameter in Join method + mkJoinExpr relExpr (arbExpr ("_keySelector2", relExpr.Range)) secondSourceSimplePats, + varSpaceWithGroupJoinVars + + | None, None when customOperationIsLikeZip nm -> mkZipExpr, varSpaceWithSecondVars + + | _ -> + assert false + failwith "unreachable" + + // Case from C# spec: A query expression with a join clause with an into followed by something other than a select clause + // Case from C# spec: A query expression with a join clause without an into followed by something other than a select clause + let valsInner, _env = varSpaceInner.Force mOpCore + let varSpaceExpr = mkExprForVarSpace mOpCore valsInner + let varSpacePat = mkPatForVarSpace mOpCore valsInner + let joinExpr = mkOverallExprGivenVarSpaceExpr varSpaceExpr + + let consumingExpr = + SynExpr.ForEach( + DebugPointAtFor.No, + DebugPointAtInOrTo.No, + SeqExprOnly false, + false, + varSpacePat, + joinExpr, + innerComp, + mOpCore + ) + + Some(trans CompExprTranslationPass.Initial q varSpaceInner consumingExpr translatedCtxt) + + | SynExpr.ForEach(spFor, spIn, SeqExprOnly _seqExprOnly, isFromSource, pat, sourceExpr, innerComp, _mEntireForEach) -> + let sourceExpr = + match RewriteRangeExpr sourceExpr with + | Some e -> e + | None -> sourceExpr + + let wrappedSourceExpr = mkSourceExprConditional isFromSource sourceExpr + + let mFor = + match spFor with + | DebugPointAtFor.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.For) + | DebugPointAtFor.No -> pat.Range + + // For computation expressions, 'in' or 'to' is hit on each MoveNext. + // To support this a named debug point for the "in" keyword is available to inlined code. + match spIn with + | DebugPointAtInOrTo.Yes mIn -> + cenv.namedDebugPointsForInlinedCode[{ + Range = mFor + Name = "ForLoop.InOrToKeyword" + }] <- mIn + | _ -> () + + let mPat = pat.Range + + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mFor ad "For" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("For"), mFor)) - let mPat = pat.Range + // Add the variables to the query variable space, on demand + let varSpace = + addVarsToVarSpace varSpace (fun _mCustomOp env -> + use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mFor ad "For" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("For"), mFor)) + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv pat None - // Add the variables to the query variable space, on demand - let varSpace = - addVarsToVarSpace varSpace (fun _mCustomOp env -> - use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv pat None - vspecs, envinner) + vspecs, envinner) - Some (trans CompExprTranslationPass.Initial q varSpace innerComp - (fun innerCompR -> + Some( + trans CompExprTranslationPass.Initial q varSpace innerComp (fun innerCompR -> - let forCall = - mkSynCall "For" mFor [wrappedSourceExpr; SynExpr.MatchLambda (false, mPat, [SynMatchClause(pat, None, innerCompR, mPat, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero)], DebugPointAtBinding.NoneAtInvisible, mFor) ] + let forCall = + mkSynCall + "For" + mFor + [ + wrappedSourceExpr + SynExpr.MatchLambda( + false, + mPat, + [ + SynMatchClause(pat, None, innerCompR, mPat, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero) + ], + DebugPointAtBinding.NoneAtInvisible, + mFor + ) + ] let forCall = match spFor with - | DebugPointAtFor.Yes _ -> - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mFor, false, forCall) + | DebugPointAtFor.Yes _ -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mFor, false, forCall) | DebugPointAtFor.No -> forCall - translatedCtxt forCall)) - - | SynExpr.For (forDebugPoint=spFor; toDebugPoint=spTo; ident=id; identBody=start; direction=dir; toBody=finish; doBody=innerComp; range=m) -> - let mFor = match spFor with DebugPointAtFor.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.For) | _ -> m - - if isQuery then errorR(Error(FSComp.SR.tcNoIntegerForLoopInQuery(), mFor)) - - let reduced = elimFastIntegerForLoop (spFor, spTo, id, start, dir, finish, innerComp, m) - Some (trans CompExprTranslationPass.Initial q varSpace reduced translatedCtxt ) - - | SynExpr.While (spWhile, guardExpr, innerComp, _) -> - let mGuard = guardExpr.Range - let mWhile = match spWhile with DebugPointAtWhile.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.While) | _ -> mGuard - - if isQuery then error(Error(FSComp.SR.tcNoWhileInQuery(), mWhile)) + translatedCtxt forCall) + ) + + | SynExpr.For( + forDebugPoint = spFor + toDebugPoint = spTo + ident = id + identBody = start + direction = dir + toBody = finish + doBody = innerComp + range = m) -> + let mFor = + match spFor with + | DebugPointAtFor.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.For) + | _ -> m + + if isQuery then + errorR (Error(FSComp.SR.tcNoIntegerForLoopInQuery (), mFor)) + + let reduced = + elimFastIntegerForLoop (spFor, spTo, id, start, dir, finish, innerComp, m) + + Some(trans CompExprTranslationPass.Initial q varSpace reduced translatedCtxt) + + | SynExpr.While(spWhile, guardExpr, innerComp, _) -> + let mGuard = guardExpr.Range + + let mWhile = + match spWhile with + | DebugPointAtWhile.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.While) + | _ -> mGuard + + if isQuery then + error (Error(FSComp.SR.tcNoWhileInQuery (), mWhile)) + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mWhile ad "While" builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("While"), mWhile)) + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mWhile ad "Delay" builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Delay"), mWhile)) + + // 'while' is hit just before each time the guard is called + let guardExpr = + match spWhile with + | DebugPointAtWhile.Yes _ -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mWhile, false, guardExpr) + | DebugPointAtWhile.No -> guardExpr + + Some( + trans CompExprTranslationPass.Initial q varSpace innerComp (fun holeFill -> + translatedCtxt ( + mkSynCall + "While" + mWhile + [ + mkSynDelay2 guardExpr + mkSynCall "Delay" mWhile [ mkSynDelay innerComp.Range holeFill ] + ] + )) + ) + + | SynExpr.WhileBang(spWhile, guardExpr, innerComp, mOrig) -> + let mGuard = guardExpr.Range + + let mWhile = + match spWhile with + | DebugPointAtWhile.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.While) + | _ -> mGuard + + let mGuard = mGuard.MakeSynthetic() + + // 'while!' is hit just before each time the guard is called + let guardExpr = + match spWhile with + | DebugPointAtWhile.Yes _ -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mWhile, false, guardExpr) + | DebugPointAtWhile.No -> guardExpr + + let rewrittenWhileExpr = + let idFirst = mkSynId mGuard (CompilerGeneratedName "first") + let patFirst = mkSynPatVar None idFirst + + let body = + let idCond = mkSynId mGuard (CompilerGeneratedName "cond") + let patCond = mkSynPatVar None idCond + + let condBinding = + mkSynBinding + (Xml.PreXmlDoc.Empty, patCond) + (None, + false, + true, + mGuard, + DebugPointAtBinding.NoneAtSticky, + None, + SynExpr.Ident idFirst, + mGuard, + [], + [], + None, + SynBindingTrivia.Zero) + + let setCondExpr = SynExpr.Set(SynExpr.Ident idCond, SynExpr.Ident idFirst, mGuard) + + let bindCondExpr = + SynExpr.LetOrUseBang( + DebugPointAtBinding.NoneAtSticky, + false, + true, + patFirst, + guardExpr, + [], + setCondExpr, + mGuard, + SynExprLetOrUseBangTrivia.Zero + ) + + let whileExpr = + SynExpr.While( + DebugPointAtWhile.No, + SynExpr.Ident idCond, + SynExpr.Sequential(DebugPointAtSequential.SuppressBoth, true, innerComp, bindCondExpr, mWhile), + mOrig + ) + + SynExpr.LetOrUse(false, false, [ condBinding ], whileExpr, mGuard, SynExprLetOrUseTrivia.Zero) + + SynExpr.LetOrUseBang( + DebugPointAtBinding.NoneAtSticky, + false, + true, + patFirst, + guardExpr, + [], + body, + mGuard, + SynExprLetOrUseBangTrivia.Zero + ) + + tryTrans CompExprTranslationPass.Initial q varSpace rewrittenWhileExpr translatedCtxt + + | SynExpr.TryFinally(innerComp, unwindExpr, _mTryToLast, spTry, spFinally, trivia) -> + + let mTry = + match spTry with + | DebugPointAtTry.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.Try) + | _ -> trivia.TryKeyword + + let mFinally = + match spFinally with + | DebugPointAtFinally.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.Finally) + | _ -> trivia.FinallyKeyword + + // Put down a debug point for the 'finally' + let unwindExpr2 = + match spFinally with + | DebugPointAtFinally.Yes _ -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mFinally, true, unwindExpr) + | DebugPointAtFinally.No -> unwindExpr + + if isQuery then + error (Error(FSComp.SR.tcNoTryFinallyInQuery (), mTry)) + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "TryFinally" builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("TryFinally"), mTry)) + + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "Delay" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Delay"), mTry)) + + let innerExpr = transNoQueryOps innerComp + + let innerExpr = + match spTry with + | DebugPointAtTry.Yes _ -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mTry, true, innerExpr) + | _ -> innerExpr + + Some( + translatedCtxt ( + mkSynCall + "TryFinally" + mTry + [ + mkSynCall "Delay" mTry [ mkSynDelay innerComp.Range innerExpr ] + mkSynDelay2 unwindExpr2 + ] + ) + ) + + | SynExpr.Paren(range = m) -> error (Error(FSComp.SR.tcConstructIsAmbiguousInComputationExpression (), m)) + + // In some cases the node produced by `mkSynCall "Zero" m []` may be discarded in the case + // of implicit yields - for example "list { 1; 2 }" when each expression checks as an implicit yield. + // If it is not discarded, the syntax node will later be checked and the existence/non-existence of the Zero method + // will be checked/reported appropriately (though the error message won't mention computation expressions + // like our other error messages for missing methods). + | SynExpr.ImplicitZero m -> + if + (not enableImplicitYield) + && isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Zero" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Zero"), m)) + + Some(translatedCtxt (mkSynCall "Zero" m [])) + + | OptionalSequential(JoinOrGroupJoinOrZipClause(_, _, _, _, _, mClause), _) when firstTry = CompExprTranslationPass.Initial -> + + // 'join' clauses preceded by 'let' and other constructs get processed by repackaging with a 'for' loop. + let patvs, _env = varSpace.Force comp.Range + let varSpaceExpr = mkExprForVarSpace mClause patvs + let varSpacePat = mkPatForVarSpace mClause patvs + + let dataCompPrior = + translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn((true, false), varSpaceExpr, mClause))) + + // Rebind using for ... + let rebind = + SynExpr.ForEach( + DebugPointAtFor.No, + DebugPointAtInOrTo.No, + SeqExprOnly false, + false, + varSpacePat, + dataCompPrior, + comp, + comp.Range + ) + + // Retry with the 'for' loop packaging. Set firstTry=false just in case 'join' processing fails + tryTrans CompExprTranslationPass.Subsequent q varSpace rebind id + + | OptionalSequential(CustomOperationClause(nm, _, opExpr, mClause, _), _) -> + + if q = CustomOperationsMode.Denied then + error (Error(FSComp.SR.tcCustomOperationMayNotBeUsedHere (), opExpr.Range)) + + let patvs, _env = varSpace.Force comp.Range + let varSpaceExpr = mkExprForVarSpace mClause patvs + + let dataCompPriorToOp = + let isYield = not (customOperationMaintainsVarSpaceUsingBind nm) + translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn((isYield, false), varSpaceExpr, mClause))) + + // Now run the consumeCustomOpClauses + Some(consumeCustomOpClauses q varSpace dataCompPriorToOp comp false mClause) + + | SynExpr.Sequential(sp, true, innerComp1, innerComp2, m) -> + + // Check for 'where x > y' and other mis-applications of infix operators. If detected, give a good error message, and just ignore innerComp1 + if isQuery && checkForBinaryApp innerComp1 then + Some(trans CompExprTranslationPass.Initial q varSpace innerComp2 translatedCtxt) - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mWhile ad "While" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("While"), mWhile)) - - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mWhile ad "Delay" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), mWhile)) - - // 'while' is hit just before each time the guard is called - let guardExpr = - match spWhile with - | DebugPointAtWhile.Yes _ -> - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mWhile, false, guardExpr) - | DebugPointAtWhile.No -> guardExpr - - Some(trans CompExprTranslationPass.Initial q varSpace innerComp (fun holeFill -> - translatedCtxt - (mkSynCall "While" mWhile - [ mkSynDelay2 guardExpr; - mkSynCall "Delay" mWhile [mkSynDelay innerComp.Range holeFill]])) ) - - | SynExpr.WhileBang (spWhile, guardExpr, innerComp, mOrig) -> - let mGuard = guardExpr.Range - let mWhile = match spWhile with DebugPointAtWhile.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.While) | _ -> mGuard - let mGuard = mGuard.MakeSynthetic() - - // 'while!' is hit just before each time the guard is called - let guardExpr = - match spWhile with - | DebugPointAtWhile.Yes _ -> - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mWhile, false, guardExpr) - | DebugPointAtWhile.No -> guardExpr - - let rewrittenWhileExpr = - let idFirst = mkSynId mGuard (CompilerGeneratedName "first") - let patFirst = mkSynPatVar None idFirst - - let body = - let idCond = mkSynId mGuard (CompilerGeneratedName "cond") - let patCond = mkSynPatVar None idCond - let condBinding = mkSynBinding (Xml.PreXmlDoc.Empty, patCond) (None, false, true, mGuard, DebugPointAtBinding.NoneAtSticky, None, SynExpr.Ident idFirst, mGuard, [], [], None, SynBindingTrivia.Zero) - let setCondExpr = SynExpr.Set (SynExpr.Ident idCond, SynExpr.Ident idFirst, mGuard) - let bindCondExpr = SynExpr.LetOrUseBang (DebugPointAtBinding.NoneAtSticky, false, true, patFirst, guardExpr, [], setCondExpr, mGuard, SynExprLetOrUseBangTrivia.Zero) - - let whileExpr = SynExpr.While (DebugPointAtWhile.No, SynExpr.Ident idCond, SynExpr.Sequential (DebugPointAtSequential.SuppressBoth, true, innerComp, bindCondExpr, mWhile), mOrig) - SynExpr.LetOrUse (false, false, [ condBinding ], whileExpr, mGuard, SynExprLetOrUseTrivia.Zero) - - SynExpr.LetOrUseBang (DebugPointAtBinding.NoneAtSticky, false, true, patFirst, guardExpr, [], body, mGuard, SynExprLetOrUseBangTrivia.Zero) - - tryTrans CompExprTranslationPass.Initial q varSpace rewrittenWhileExpr translatedCtxt - - | SynExpr.TryFinally (innerComp, unwindExpr, _mTryToLast, spTry, spFinally, trivia) -> - - let mTry = match spTry with DebugPointAtTry.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.Try) | _ -> trivia.TryKeyword - let mFinally = match spFinally with DebugPointAtFinally.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.Finally) | _ -> trivia.FinallyKeyword - - // Put down a debug point for the 'finally' - let unwindExpr2 = - match spFinally with - | DebugPointAtFinally.Yes _ -> - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mFinally, true, unwindExpr) - | DebugPointAtFinally.No -> unwindExpr - - if isQuery then error(Error(FSComp.SR.tcNoTryFinallyInQuery(), mTry)) - - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "TryFinally" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("TryFinally"), mTry)) - - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "Delay" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), mTry)) - - let innerExpr = transNoQueryOps innerComp - - let innerExpr = - match spTry with - | DebugPointAtTry.Yes _ -> - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mTry, true, innerExpr) - | _ -> innerExpr - - Some (translatedCtxt - (mkSynCall "TryFinally" mTry [ - mkSynCall "Delay" mTry [mkSynDelay innerComp.Range innerExpr] - mkSynDelay2 unwindExpr2])) - - | SynExpr.Paren (_, _, _, m) -> - error(Error(FSComp.SR.tcConstructIsAmbiguousInComputationExpression(), m)) - - // In some cases the node produced by `mkSynCall "Zero" m []` may be discarded in the case - // of implicit yields - for example "list { 1; 2 }" when each expression checks as an implicit yield. - // If it is not discarded, the syntax node will later be checked and the existence/non-existence of the Zero method - // will be checked/reported appropriately (though the error message won't mention computation expressions - // like our other error messages for missing methods). - | SynExpr.ImplicitZero m -> - if (not enableImplicitYield) && - isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Zero" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Zero"), m)) - Some (translatedCtxt (mkSynCall "Zero" m [])) - - | OptionalSequential (JoinOrGroupJoinOrZipClause (_, _, _, _, _, mClause), _) - when firstTry = CompExprTranslationPass.Initial -> - - // 'join' clauses preceded by 'let' and other constructs get processed by repackaging with a 'for' loop. - let patvs, _env = varSpace.Force comp.Range - let varSpaceExpr = mkExprForVarSpace mClause patvs - let varSpacePat = mkPatForVarSpace mClause patvs - - let dataCompPrior = - translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn ((true, false), varSpaceExpr, mClause))) - - // Rebind using for ... - let rebind = - SynExpr.ForEach (DebugPointAtFor.No, DebugPointAtInOrTo.No, SeqExprOnly false, false, varSpacePat, dataCompPrior, comp, comp.Range) - - // Retry with the 'for' loop packaging. Set firstTry=false just in case 'join' processing fails - tryTrans CompExprTranslationPass.Subsequent q varSpace rebind id + else + if isQuery && not (innerComp1.IsArbExprAndThusAlreadyReportedError) then + match innerComp1 with + | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential + | _ -> errorR (Error(FSComp.SR.tcUnrecognizedQueryOperator (), innerComp1.RangeOfFirstPortion)) + + match tryTrans CompExprTranslationPass.Initial CustomOperationsMode.Denied varSpace innerComp1 id with + | Some c -> + // "cexpr; cexpr" is treated as builder.Combine(cexpr1, cexpr1) + let m1 = rangeForCombine innerComp1 + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + m + ad + "Combine" + builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Combine"), m)) + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Delay" builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Delay"), m)) + + let combineCall = + mkSynCall + "Combine" + m1 + [ + c + mkSynCall "Delay" m1 [ mkSynDelay innerComp2.Range (transNoQueryOps innerComp2) ] + ] + + Some(translatedCtxt combineCall) + + | None -> + // "do! expr; cexpr" is treated as { let! () = expr in cexpr } + match innerComp1 with + | SynExpr.DoBang(rhsExpr, m) -> + let sp = + match sp with + | DebugPointAtSequential.SuppressExpr -> DebugPointAtBinding.NoneAtDo + | DebugPointAtSequential.SuppressBoth -> DebugPointAtBinding.NoneAtDo + | DebugPointAtSequential.SuppressStmt -> DebugPointAtBinding.Yes m + | DebugPointAtSequential.SuppressNeither -> DebugPointAtBinding.Yes m + + Some( + trans + CompExprTranslationPass.Initial + q + varSpace + (SynExpr.LetOrUseBang( + sp, + false, + true, + SynPat.Const(SynConst.Unit, rhsExpr.Range), + rhsExpr, + [], + innerComp2, + m, + SynExprLetOrUseBangTrivia.Zero + )) + translatedCtxt + ) + + // "expr; cexpr" is treated as sequential execution + | _ -> + Some( + trans CompExprTranslationPass.Initial q varSpace innerComp2 (fun holeFill -> + let fillExpr = + if enableImplicitYield then + // When implicit yields are enabled, then if the 'innerComp1' checks as type + // 'unit' we interpret the expression as a sequential, and when it doesn't + // have type 'unit' we interpret it as a 'Yield + Combine'. + let combineExpr = + let m1 = rangeForCombine innerComp1 + let implicitYieldExpr = mkSynCall "Yield" comp.Range [ innerComp1 ] + + mkSynCall + "Combine" + m1 + [ + implicitYieldExpr + mkSynCall "Delay" m1 [ mkSynDelay holeFill.Range holeFill ] + ] + + SynExpr.SequentialOrImplicitYield(sp, innerComp1, holeFill, combineExpr, m) + else + SynExpr.Sequential(sp, true, innerComp1, holeFill, m) + + translatedCtxt fillExpr) + ) + + | SynExpr.IfThenElse(guardExpr, thenComp, elseCompOpt, spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia) -> + match elseCompOpt with + | Some elseComp -> + if isQuery then + error (Error(FSComp.SR.tcIfThenElseMayNotBeUsedWithinQueries (), trivia.IfToThenRange)) + + Some( + translatedCtxt ( + SynExpr.IfThenElse( + guardExpr, + transNoQueryOps thenComp, + Some(transNoQueryOps elseComp), + spIfToThen, + isRecovery, + mIfToEndOfElseBranch, + trivia + ) + ) + ) + | None -> + let elseComp = + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + trivia.IfToThenRange + ad + "Zero" + builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Zero"), trivia.IfToThenRange)) + + mkSynCall "Zero" trivia.IfToThenRange [] + + Some( + trans CompExprTranslationPass.Initial q varSpace thenComp (fun holeFill -> + translatedCtxt ( + SynExpr.IfThenElse( + guardExpr, + holeFill, + Some elseComp, + spIfToThen, + isRecovery, + mIfToEndOfElseBranch, + trivia + ) + )) + ) + + // 'let binds in expr' + | SynExpr.LetOrUse(isRec, false, binds, innerComp, m, trivia) -> + + // For 'query' check immediately + if isQuery then + match (List.map (BindingNormalization.NormalizeBinding ValOrMemberBinding cenv env) binds) with + | [ NormalizedBinding(_, SynBindingKind.Normal, false, false, _, _, _, _, _, _, _, _) ] when not isRec -> () + | normalizedBindings -> + let failAt m = + error (Error(FSComp.SR.tcNonSimpleLetBindingInQuery (), m)) + + match normalizedBindings with + | NormalizedBinding(mBinding = mBinding) :: _ -> failAt mBinding + | _ -> failAt m - | OptionalSequential (CustomOperationClause (nm, _, opExpr, mClause, _), _) -> + // Add the variables to the query variable space, on demand + let varSpace = + addVarsToVarSpace varSpace (fun mQueryOp env -> + // Normalize the bindings before detecting the bound variables + match (List.map (BindingNormalization.NormalizeBinding ValOrMemberBinding cenv env) binds) with + | [ NormalizedBinding(kind = SynBindingKind.Normal; mustInline = false; isMutable = false; pat = pat) ] -> + // successful case + use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - if q = CustomOperationsMode.Denied then error(Error(FSComp.SR.tcCustomOperationMayNotBeUsedHere(), opExpr.Range)) + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv pat None + + vspecs, envinner + | _ -> + // error case + error (Error(FSComp.SR.tcCustomOperationMayNotBeUsedInConjunctionWithNonSimpleLetBindings (), mQueryOp))) + + Some( + trans CompExprTranslationPass.Initial q varSpace innerComp (fun holeFill -> + translatedCtxt (SynExpr.LetOrUse(isRec, false, binds, holeFill, m, trivia))) + ) + + // 'use x = expr in expr' + | SynExpr.LetOrUse( + isUse = true + bindings = [ SynBinding(kind = SynBindingKind.Normal; headPat = pat; expr = rhsExpr; debugPoint = spBind) ] + body = innerComp) -> + let mBind = + match spBind with + | DebugPointAtBinding.Yes m -> m + | _ -> rhsExpr.Range + + if isQuery then + error (Error(FSComp.SR.tcUseMayNotBeUsedInQueries (), mBind)) + + let innerCompRange = innerComp.Range + + let consumeExpr = + SynExpr.MatchLambda( + false, + innerCompRange, + [ + SynMatchClause( + pat, + None, + transNoQueryOps innerComp, + innerCompRange, + DebugPointAtTarget.Yes, + SynMatchClauseTrivia.Zero + ) + ], + DebugPointAtBinding.NoneAtInvisible, + innerCompRange + ) + + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad "Using" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Using"), mBind)) + + Some( + translatedCtxt (mkSynCall "Using" mBind [ rhsExpr; consumeExpr ]) + |> addBindDebugPoint spBind + ) + + // 'let! pat = expr in expr' + // --> build.Bind(e1, (fun _argN -> match _argN with pat -> expr)) + // or + // --> build.BindReturn(e1, (fun _argN -> match _argN with pat -> expr-without-return)) + | SynExpr.LetOrUseBang( + bindDebugPoint = spBind + isUse = false + isFromSource = isFromSource + pat = pat + rhs = rhsExpr + andBangs = [] + body = innerComp) -> + + let mBind = + match spBind with + | DebugPointAtBinding.Yes m -> m + | _ -> rhsExpr.Range + + if isQuery then + error (Error(FSComp.SR.tcBindMayNotBeUsedInQueries (), mBind)) - let patvs, _env = varSpace.Force comp.Range - let varSpaceExpr = mkExprForVarSpace mClause patvs - - let dataCompPriorToOp = - let isYield = not (customOperationMaintainsVarSpaceUsingBind nm) - translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn ((isYield, false), varSpaceExpr, mClause))) - - // Now run the consumeCustomOpClauses - Some (consumeCustomOpClauses q varSpace dataCompPriorToOp comp false mClause) - - | SynExpr.Sequential (sp, true, innerComp1, innerComp2, m) -> - - // Check for 'where x > y' and other mis-applications of infix operators. If detected, give a good error message, and just ignore innerComp1 - if isQuery && checkForBinaryApp innerComp1 then - Some (trans CompExprTranslationPass.Initial q varSpace innerComp2 translatedCtxt) - - else - - if isQuery && not(innerComp1.IsArbExprAndThusAlreadyReportedError) then - match innerComp1 with - | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential - | _ -> errorR(Error(FSComp.SR.tcUnrecognizedQueryOperator(), innerComp1.RangeOfFirstPortion)) - - match tryTrans CompExprTranslationPass.Initial CustomOperationsMode.Denied varSpace innerComp1 id with - | Some c -> - // "cexpr; cexpr" is treated as builder.Combine(cexpr1, cexpr1) - let m1 = rangeForCombine innerComp1 - - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Combine" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Combine"), m)) - - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Delay" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), m)) - - let combineCall = mkSynCall "Combine" m1 [c; mkSynCall "Delay" m1 [mkSynDelay innerComp2.Range (transNoQueryOps innerComp2)]] - - Some (translatedCtxt combineCall) - - | None -> - // "do! expr; cexpr" is treated as { let! () = expr in cexpr } - match innerComp1 with - | SynExpr.DoBang (rhsExpr, m) -> - let sp = - match sp with - | DebugPointAtSequential.SuppressExpr -> DebugPointAtBinding.NoneAtDo - | DebugPointAtSequential.SuppressBoth -> DebugPointAtBinding.NoneAtDo - | DebugPointAtSequential.SuppressStmt -> DebugPointAtBinding.Yes m - | DebugPointAtSequential.SuppressNeither -> DebugPointAtBinding.Yes m - Some(trans CompExprTranslationPass.Initial q varSpace (SynExpr.LetOrUseBang (sp, false, true, SynPat.Const(SynConst.Unit, rhsExpr.Range), rhsExpr, [], innerComp2, m, SynExprLetOrUseBangTrivia.Zero)) translatedCtxt) - - // "expr; cexpr" is treated as sequential execution - | _ -> - Some (trans CompExprTranslationPass.Initial q varSpace innerComp2 (fun holeFill -> - let fillExpr = - if enableImplicitYield then - // When implicit yields are enabled, then if the 'innerComp1' checks as type - // 'unit' we interpret the expression as a sequential, and when it doesn't - // have type 'unit' we interpret it as a 'Yield + Combine'. - let combineExpr = - let m1 = rangeForCombine innerComp1 - let implicitYieldExpr = mkSynCall "Yield" comp.Range [innerComp1] - mkSynCall "Combine" m1 [implicitYieldExpr; mkSynCall "Delay" m1 [mkSynDelay holeFill.Range holeFill]] - SynExpr.SequentialOrImplicitYield(sp, innerComp1, holeFill, combineExpr, m) - else - SynExpr.Sequential(sp, true, innerComp1, holeFill, m) - translatedCtxt fillExpr)) - - | SynExpr.IfThenElse (guardExpr, thenComp, elseCompOpt, spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia) -> - match elseCompOpt with - | Some elseComp -> - if isQuery then error(Error(FSComp.SR.tcIfThenElseMayNotBeUsedWithinQueries(), trivia.IfToThenRange)) - Some (translatedCtxt (SynExpr.IfThenElse (guardExpr, transNoQueryOps thenComp, Some(transNoQueryOps elseComp), spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia))) - | None -> - let elseComp = - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env trivia.IfToThenRange ad "Zero" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Zero"), trivia.IfToThenRange)) - mkSynCall "Zero" trivia.IfToThenRange [] - Some (trans CompExprTranslationPass.Initial q varSpace thenComp (fun holeFill -> translatedCtxt (SynExpr.IfThenElse (guardExpr, holeFill, Some elseComp, spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia)))) - - // 'let binds in expr' - | SynExpr.LetOrUse (isRec, false, binds, innerComp, m, trivia) -> - - // For 'query' check immediately - if isQuery then - match (List.map (BindingNormalization.NormalizeBinding ValOrMemberBinding cenv env) binds) with - | [NormalizedBinding(_, SynBindingKind.Normal, false, false, _, _, _, _, _, _, _, _)] when not isRec -> - () - | normalizedBindings -> - let failAt m = error(Error(FSComp.SR.tcNonSimpleLetBindingInQuery(), m)) - match normalizedBindings with - | NormalizedBinding(_, _, _, _, _, _, _, _, _, _, mBinding, _) :: _ -> failAt mBinding - | _ -> failAt m - - // Add the variables to the query variable space, on demand - let varSpace = - addVarsToVarSpace varSpace (fun mQueryOp env -> - // Normalize the bindings before detecting the bound variables - match (List.map (BindingNormalization.NormalizeBinding ValOrMemberBinding cenv env) binds) with - | [NormalizedBinding(_vis, SynBindingKind.Normal, false, false, _, _, _, _, pat, _, _, _)] -> - // successful case + // Add the variables to the query variable space, on demand + let varSpace = + addVarsToVarSpace varSpace (fun _mCustomOp env -> use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv pat None - vspecs, envinner - | _ -> - // error case - error(Error(FSComp.SR.tcCustomOperationMayNotBeUsedInConjunctionWithNonSimpleLetBindings(), mQueryOp))) - Some (trans CompExprTranslationPass.Initial q varSpace innerComp (fun holeFill -> translatedCtxt (SynExpr.LetOrUse (isRec, false, binds, holeFill, m, trivia)))) + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv pat None - // 'use x = expr in expr' - | SynExpr.LetOrUse (isUse=true; bindings=[SynBinding (kind=SynBindingKind.Normal; headPat=pat; expr=rhsExpr; debugPoint=spBind)]; body=innerComp) -> - let mBind = match spBind with DebugPointAtBinding.Yes m -> m | _ -> rhsExpr.Range - if isQuery then error(Error(FSComp.SR.tcUseMayNotBeUsedInQueries(), mBind)) - let innerCompRange = innerComp.Range - let consumeExpr = SynExpr.MatchLambda(false, innerCompRange, [SynMatchClause(pat, None, transNoQueryOps innerComp, innerCompRange, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero)], DebugPointAtBinding.NoneAtInvisible, innerCompRange) - - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad "Using" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Using"), mBind)) - - Some (translatedCtxt (mkSynCall "Using" mBind [rhsExpr; consumeExpr ]) |> addBindDebugPoint spBind) - - // 'let! pat = expr in expr' - // --> build.Bind(e1, (fun _argN -> match _argN with pat -> expr)) - // or - // --> build.BindReturn(e1, (fun _argN -> match _argN with pat -> expr-without-return)) - | SynExpr.LetOrUseBang (bindDebugPoint=spBind; isUse=false; isFromSource=isFromSource; pat=pat; rhs=rhsExpr; andBangs=[]; body=innerComp) -> - - let mBind = match spBind with DebugPointAtBinding.Yes m -> m | _ -> rhsExpr.Range - if isQuery then error(Error(FSComp.SR.tcBindMayNotBeUsedInQueries(), mBind)) - - // Add the variables to the query variable space, on demand - let varSpace = - addVarsToVarSpace varSpace (fun _mCustomOp env -> - use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv pat None vspecs, envinner) - let rhsExpr = mkSourceExprConditional isFromSource rhsExpr - Some (transBind q varSpace mBind (addBindDebugPoint spBind) "Bind" [rhsExpr] pat innerComp translatedCtxt) - - // 'use! pat = e1 in e2' --> build.Bind(e1, (function _argN -> match _argN with pat -> build.Using(x, (fun _argN -> match _argN with pat -> e2)))) - | SynExpr.LetOrUseBang (bindDebugPoint=spBind; isUse=true; isFromSource=isFromSource; pat=SynPat.Named (ident=SynIdent(id,_); isThisVal=false) as pat; rhs=rhsExpr; andBangs=[]; body=innerComp) - | SynExpr.LetOrUseBang (bindDebugPoint=spBind; isUse=true; isFromSource=isFromSource; pat=SynPat.LongIdent (longDotId=SynLongIdent([id], _, _)) as pat; rhs=rhsExpr; andBangs=[]; body=innerComp) -> - - let mBind = match spBind with DebugPointAtBinding.Yes m -> m | _ -> rhsExpr.Range - if isQuery then error(Error(FSComp.SR.tcBindMayNotBeUsedInQueries(), mBind)) - - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad "Using" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Using"), mBind)) - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad "Bind" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Bind"), mBind)) - - let bindExpr = - let consumeExpr = SynExpr.MatchLambda(false, mBind, [SynMatchClause(pat, None, transNoQueryOps innerComp, innerComp.Range, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero)], DebugPointAtBinding.NoneAtInvisible, mBind) - let consumeExpr = mkSynCall "Using" mBind [SynExpr.Ident id; consumeExpr ] - let consumeExpr = SynExpr.MatchLambda(false, mBind, [SynMatchClause(pat, None, consumeExpr, id.idRange, DebugPointAtTarget.No, SynMatchClauseTrivia.Zero)], DebugPointAtBinding.NoneAtInvisible, mBind) let rhsExpr = mkSourceExprConditional isFromSource rhsExpr - mkSynCall "Bind" mBind [rhsExpr; consumeExpr] - |> addBindDebugPoint spBind + Some(transBind q varSpace mBind (addBindDebugPoint spBind) "Bind" [ rhsExpr ] pat innerComp translatedCtxt) + + // 'use! pat = e1 in e2' --> build.Bind(e1, (function _argN -> match _argN with pat -> build.Using(x, (fun _argN -> match _argN with pat -> e2)))) + | SynExpr.LetOrUseBang( + bindDebugPoint = spBind + isUse = true + isFromSource = isFromSource + pat = SynPat.Named(ident = SynIdent(id, _); isThisVal = false) as pat + rhs = rhsExpr + andBangs = [] + body = innerComp) + | SynExpr.LetOrUseBang( + bindDebugPoint = spBind + isUse = true + isFromSource = isFromSource + pat = SynPat.LongIdent(longDotId = SynLongIdent(id = [ id ])) as pat + rhs = rhsExpr + andBangs = [] + body = innerComp) -> + + let mBind = + match spBind with + | DebugPointAtBinding.Yes m -> m + | _ -> rhsExpr.Range + + if isQuery then + error (Error(FSComp.SR.tcBindMayNotBeUsedInQueries (), mBind)) + + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad "Using" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Using"), mBind)) + + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad "Bind" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Bind"), mBind)) + + let bindExpr = + let consumeExpr = + SynExpr.MatchLambda( + false, + mBind, + [ + SynMatchClause( + pat, + None, + transNoQueryOps innerComp, + innerComp.Range, + DebugPointAtTarget.Yes, + SynMatchClauseTrivia.Zero + ) + ], + DebugPointAtBinding.NoneAtInvisible, + mBind + ) + + let consumeExpr = mkSynCall "Using" mBind [ SynExpr.Ident id; consumeExpr ] + + let consumeExpr = + SynExpr.MatchLambda( + false, + mBind, + [ + SynMatchClause(pat, None, consumeExpr, id.idRange, DebugPointAtTarget.No, SynMatchClauseTrivia.Zero) + ], + DebugPointAtBinding.NoneAtInvisible, + mBind + ) + + let rhsExpr = mkSourceExprConditional isFromSource rhsExpr + mkSynCall "Bind" mBind [ rhsExpr; consumeExpr ] |> addBindDebugPoint spBind + + Some(translatedCtxt bindExpr) + + // 'use! pat = e1 ... in e2' where 'pat' is not a simple name --> error + | SynExpr.LetOrUseBang(isUse = true; pat = pat; andBangs = andBangs) -> + if isNil andBangs then + error (Error(FSComp.SR.tcInvalidUseBangBinding (), pat.Range)) + else + error (Error(FSComp.SR.tcInvalidUseBangBindingNoAndBangs (), comp.Range)) + + // 'let! pat1 = expr1 and! pat2 = expr2 in ...' --> + // build.BindN(expr1, expr2, ...) + // or + // build.BindNReturn(expr1, expr2, ...) + // or + // build.Bind(build.MergeSources(expr1, expr2), ...) + | SynExpr.LetOrUseBang( + bindDebugPoint = spBind + isUse = false + isFromSource = isFromSource + pat = letPat + rhs = letRhsExpr + andBangs = andBangBindings + body = innerComp + range = letBindRange) -> + if not (cenv.g.langVersion.SupportsFeature LanguageFeature.AndBang) then + error (Error(FSComp.SR.tcAndBangNotSupported (), comp.Range)) + + if isQuery then + error (Error(FSComp.SR.tcBindMayNotBeUsedInQueries (), letBindRange)) + + let mBind = + match spBind with + | DebugPointAtBinding.Yes m -> m + | _ -> letRhsExpr.Range + + let sources = + (letRhsExpr + :: [ for SynExprAndBang(body = andExpr) in andBangBindings -> andExpr ]) + |> List.map (mkSourceExprConditional isFromSource) + + let pats = + letPat :: [ for SynExprAndBang(pat = andPat) in andBangBindings -> andPat ] + + let sourcesRange = sources |> List.map (fun e -> e.Range) |> List.reduce unionRanges + + let numSources = sources.Length + let bindReturnNName = "Bind" + string numSources + "Return" + let bindNName = "Bind" + string numSources + + // Check if this is a Bind2Return etc. + let hasBindReturnN = + not ( + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + mBind + ad + bindReturnNName + builderTy + ) + ) + + if hasBindReturnN && Option.isSome (convertSimpleReturnToExpr varSpace innerComp) then + let consumePat = SynPat.Tuple(false, pats, [], letPat.Range) - Some(translatedCtxt bindExpr) + // Add the variables to the query variable space, on demand + let varSpace = + addVarsToVarSpace varSpace (fun _mCustomOp env -> + use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - // 'use! pat = e1 ... in e2' where 'pat' is not a simple name --> error - | SynExpr.LetOrUseBang (isUse=true; pat=pat; andBangs=andBangs) -> - if isNil andBangs then - error(Error(FSComp.SR.tcInvalidUseBangBinding(), pat.Range)) - else - error(Error(FSComp.SR.tcInvalidUseBangBindingNoAndBangs(), comp.Range)) - - // 'let! pat1 = expr1 and! pat2 = expr2 in ...' --> - // build.BindN(expr1, expr2, ...) - // or - // build.BindNReturn(expr1, expr2, ...) - // or - // build.Bind(build.MergeSources(expr1, expr2), ...) - | SynExpr.LetOrUseBang(bindDebugPoint=spBind; isUse=false; isFromSource=isFromSource; pat=letPat; rhs=letRhsExpr; andBangs=andBangBindings; body=innerComp; range=letBindRange) -> - if not (cenv.g.langVersion.SupportsFeature LanguageFeature.AndBang) then - error(Error(FSComp.SR.tcAndBangNotSupported(), comp.Range)) - - if isQuery then - error(Error(FSComp.SR.tcBindMayNotBeUsedInQueries(), letBindRange)) - - let mBind = match spBind with DebugPointAtBinding.Yes m -> m | _ -> letRhsExpr.Range - let sources = (letRhsExpr :: [for SynExprAndBang(body=andExpr) in andBangBindings -> andExpr ]) |> List.map (mkSourceExprConditional isFromSource) - let pats = letPat :: [for SynExprAndBang(pat = andPat) in andBangBindings -> andPat ] - let sourcesRange = sources |> List.map (fun e -> e.Range) |> List.reduce unionRanges - - let numSources = sources.Length - let bindReturnNName = "Bind"+string numSources+"Return" - let bindNName = "Bind"+string numSources - - // Check if this is a Bind2Return etc. - let hasBindReturnN = not (isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad bindReturnNName builderTy)) - if hasBindReturnN && Option.isSome (convertSimpleReturnToExpr varSpace innerComp) then - let consumePat = SynPat.Tuple(false, pats, [], letPat.Range) + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv consumePat None - // Add the variables to the query variable space, on demand - let varSpace = - addVarsToVarSpace varSpace (fun _mCustomOp env -> - use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv consumePat None vspecs, envinner) - Some (transBind q varSpace mBind (addBindDebugPoint spBind) bindNName sources consumePat innerComp translatedCtxt) - - else + Some(transBind q varSpace mBind (addBindDebugPoint spBind) bindNName sources consumePat innerComp translatedCtxt) - // Check if this is a Bind2 etc. - let hasBindN = not (isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad bindNName builderTy)) - if hasBindN then - let consumePat = SynPat.Tuple(false, pats, [], letPat.Range) + else - // Add the variables to the query variable space, on demand - let varSpace = - addVarsToVarSpace varSpace (fun _mCustomOp env -> + // Check if this is a Bind2 etc. + let hasBindN = + not ( + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + mBind + ad + bindNName + builderTy + ) + ) + + if hasBindN then + let consumePat = SynPat.Tuple(false, pats, [], letPat.Range) + + // Add the variables to the query variable space, on demand + let varSpace = + addVarsToVarSpace varSpace (fun _mCustomOp env -> use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv consumePat None - vspecs, envinner) - Some (transBind q varSpace mBind (addBindDebugPoint spBind) bindNName sources consumePat innerComp translatedCtxt) - else + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv consumePat None - // Look for the maximum supported MergeSources, MergeSources3, ... - let mkMergeSourcesName n = if n = 2 then "MergeSources" else "MergeSources"+(string n) + vspecs, envinner) - let maxMergeSources = - let rec loop (n: int) = - let mergeSourcesName = mkMergeSourcesName n - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad mergeSourcesName builderTy) then - (n-1) - else - loop (n+1) - loop 2 + Some(transBind q varSpace mBind (addBindDebugPoint spBind) bindNName sources consumePat innerComp translatedCtxt) + else - if maxMergeSources = 1 then error(Error(FSComp.SR.tcRequireMergeSourcesOrBindN(bindNName), mBind)) + // Look for the maximum supported MergeSources, MergeSources3, ... + let mkMergeSourcesName n = + if n = 2 then + "MergeSources" + else + "MergeSources" + (string n) + + let maxMergeSources = + let rec loop (n: int) = + let mergeSourcesName = mkMergeSourcesName n + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + mBind + ad + mergeSourcesName + builderTy + ) + then + (n - 1) + else + loop (n + 1) + + loop 2 + + if maxMergeSources = 1 then + error (Error(FSComp.SR.tcRequireMergeSourcesOrBindN (bindNName), mBind)) + + let rec mergeSources (sourcesAndPats: (SynExpr * SynPat) list) = + let numSourcesAndPats = sourcesAndPats.Length + assert (numSourcesAndPats <> 0) + + if numSourcesAndPats = 1 then + sourcesAndPats[0] + + elif numSourcesAndPats <= maxMergeSources then + + // Call MergeSources2(e1, e2), MergeSources3(e1, e2, e3) etc + let mergeSourcesName = mkMergeSourcesName numSourcesAndPats + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + mBind + ad + mergeSourcesName + builderTy + ) + then + error (Error(FSComp.SR.tcRequireMergeSourcesOrBindN (bindNName), mBind)) + + let source = mkSynCall mergeSourcesName sourcesRange (List.map fst sourcesAndPats) + let pat = SynPat.Tuple(false, List.map snd sourcesAndPats, [], letPat.Range) + source, pat - let rec mergeSources (sourcesAndPats: (SynExpr * SynPat) list) = - let numSourcesAndPats = sourcesAndPats.Length - assert (numSourcesAndPats <> 0) - if numSourcesAndPats = 1 then - sourcesAndPats[0] + else - elif numSourcesAndPats <= maxMergeSources then + // Call MergeSourcesMax(e1, e2, e3, e4, (...)) + let nowSourcesAndPats, laterSourcesAndPats = + List.splitAt (maxMergeSources - 1) sourcesAndPats - // Call MergeSources2(e1, e2), MergeSources3(e1, e2, e3) etc - let mergeSourcesName = mkMergeSourcesName numSourcesAndPats + let mergeSourcesName = mkMergeSourcesName maxMergeSources - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad mergeSourcesName builderTy) then - error(Error(FSComp.SR.tcRequireMergeSourcesOrBindN(bindNName), mBind)) + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + mBind + ad + mergeSourcesName + builderTy + ) + then + error (Error(FSComp.SR.tcRequireMergeSourcesOrBindN (bindNName), mBind)) - let source = mkSynCall mergeSourcesName sourcesRange (List.map fst sourcesAndPats) - let pat = SynPat.Tuple(false, List.map snd sourcesAndPats, [], letPat.Range) - source, pat + let laterSource, laterPat = mergeSources laterSourcesAndPats - else + let source = + mkSynCall mergeSourcesName sourcesRange (List.map fst nowSourcesAndPats @ [ laterSource ]) - // Call MergeSourcesMax(e1, e2, e3, e4, (...)) - let nowSourcesAndPats, laterSourcesAndPats = List.splitAt (maxMergeSources - 1) sourcesAndPats - let mergeSourcesName = mkMergeSourcesName maxMergeSources + let pat = + SynPat.Tuple(false, List.map snd nowSourcesAndPats @ [ laterPat ], [], letPat.Range) - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBind ad mergeSourcesName builderTy) then - error(Error(FSComp.SR.tcRequireMergeSourcesOrBindN(bindNName), mBind)) + source, pat - let laterSource, laterPat = mergeSources laterSourcesAndPats - let source = mkSynCall mergeSourcesName sourcesRange (List.map fst nowSourcesAndPats @ [laterSource]) - let pat = SynPat.Tuple(false, List.map snd nowSourcesAndPats @ [laterPat], [], letPat.Range) - source, pat + let mergedSources, consumePat = mergeSources (List.zip sources pats) - let mergedSources, consumePat = mergeSources (List.zip sources pats) - - // Add the variables to the query variable space, on demand - let varSpace = - addVarsToVarSpace varSpace (fun _mCustomOp env -> + // Add the variables to the query variable space, on demand + let varSpace = + addVarsToVarSpace varSpace (fun _mCustomOp env -> use _holder = TemporarilySuspendReportingTypecheckResultsToSink cenv.tcSink - let _, _, vspecs, envinner, _ = TcMatchPattern cenv (NewInferenceType g) env tpenv consumePat None - vspecs, envinner) - - // Build the 'Bind' call - Some (transBind q varSpace mBind (addBindDebugPoint spBind) "Bind" [mergedSources] consumePat innerComp translatedCtxt) - - | SynExpr.Match (spMatch, expr, clauses, m, trivia) -> - if isQuery then error(Error(FSComp.SR.tcMatchMayNotBeUsedWithQuery(), trivia.MatchKeyword)) - let clauses = clauses |> List.map (fun (SynMatchClause(pat, cond, innerComp, patm, sp, trivia)) -> SynMatchClause(pat, cond, transNoQueryOps innerComp, patm, sp, trivia)) - Some(translatedCtxt (SynExpr.Match (spMatch, expr, clauses, m, trivia))) - - // 'match! expr with pats ...' --> build.Bind(e1, (function pats ...)) - // FUTURE: consider allowing translation to BindReturn - | SynExpr.MatchBang (spMatch, expr, clauses, _m, trivia) -> - let inputExpr = mkSourceExpr expr - if isQuery then error(Error(FSComp.SR.tcMatchMayNotBeUsedWithQuery(), trivia.MatchBangKeyword)) - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env trivia.MatchBangKeyword ad "Bind" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Bind"), trivia.MatchBangKeyword)) + let _, _, vspecs, envinner, _ = + TcMatchPattern cenv (NewInferenceType g) env tpenv consumePat None - let clauses = clauses |> List.map (fun (SynMatchClause(pat, cond, innerComp, patm, sp, trivia)) -> SynMatchClause(pat, cond, transNoQueryOps innerComp, patm, sp, trivia)) - let consumeExpr = SynExpr.MatchLambda (false, trivia.MatchBangKeyword, clauses, DebugPointAtBinding.NoneAtInvisible, trivia.MatchBangKeyword) + vspecs, envinner) - let callExpr = - mkSynCall "Bind" trivia.MatchBangKeyword [inputExpr; consumeExpr] - |> addBindDebugPoint spMatch - - Some(translatedCtxt callExpr) + // Build the 'Bind' call + Some( + transBind + q + varSpace + mBind + (addBindDebugPoint spBind) + "Bind" + [ mergedSources ] + consumePat + innerComp + translatedCtxt + ) + + | SynExpr.Match(spMatch, expr, clauses, m, trivia) -> + if isQuery then + error (Error(FSComp.SR.tcMatchMayNotBeUsedWithQuery (), trivia.MatchKeyword)) + + let clauses = + clauses + |> List.map (fun (SynMatchClause(pat, cond, innerComp, patm, sp, trivia)) -> + SynMatchClause(pat, cond, transNoQueryOps innerComp, patm, sp, trivia)) + + Some(translatedCtxt (SynExpr.Match(spMatch, expr, clauses, m, trivia))) + + // 'match! expr with pats ...' --> build.Bind(e1, (function pats ...)) + // FUTURE: consider allowing translation to BindReturn + | SynExpr.MatchBang(spMatch, expr, clauses, _m, trivia) -> + let inputExpr = mkSourceExpr expr + + if isQuery then + error (Error(FSComp.SR.tcMatchMayNotBeUsedWithQuery (), trivia.MatchBangKeyword)) + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo + ResultCollectionSettings.AtMostOneResult + cenv + env + trivia.MatchBangKeyword + ad + "Bind" + builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Bind"), trivia.MatchBangKeyword)) + + let clauses = + clauses + |> List.map (fun (SynMatchClause(pat, cond, innerComp, patm, sp, trivia)) -> + SynMatchClause(pat, cond, transNoQueryOps innerComp, patm, sp, trivia)) + + let consumeExpr = + SynExpr.MatchLambda( + false, + trivia.MatchBangKeyword, + clauses, + DebugPointAtBinding.NoneAtInvisible, + trivia.MatchBangKeyword + ) + + let callExpr = + mkSynCall "Bind" trivia.MatchBangKeyword [ inputExpr; consumeExpr ] + |> addBindDebugPoint spMatch + + Some(translatedCtxt callExpr) + + | SynExpr.TryWith(innerComp, clauses, mTryToLast, spTry, spWith, trivia) -> + let mTry = + match spTry with + | DebugPointAtTry.Yes _ -> trivia.TryKeyword.NoteSourceConstruct(NotedSourceConstruct.Try) + | _ -> trivia.TryKeyword + + let spWith2 = + match spWith with + | DebugPointAtWith.Yes _ -> DebugPointAtBinding.Yes trivia.WithKeyword + | _ -> DebugPointAtBinding.NoneAtInvisible + + if isQuery then + error (Error(FSComp.SR.tcTryWithMayNotBeUsedInQueries (), mTry)) + + let clauses = + clauses + |> List.map (fun (SynMatchClause(pat, cond, clauseComp, patm, sp, trivia)) -> + SynMatchClause(pat, cond, transNoQueryOps clauseComp, patm, sp, trivia)) + + let consumeExpr = + SynExpr.MatchLambda(true, mTryToLast, clauses, spWith2, mTryToLast) + + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "TryWith" builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("TryWith"), mTry)) + + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "Delay" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("Delay"), mTry)) + + let innerExpr = transNoQueryOps innerComp + + let innerExpr = + match spTry with + | DebugPointAtTry.Yes _ -> SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mTry, true, innerExpr) + | _ -> innerExpr + + let callExpr = + mkSynCall "TryWith" mTry [ mkSynCall "Delay" mTry [ mkSynDelay2 innerExpr ]; consumeExpr ] + + Some(translatedCtxt callExpr) + + | SynExpr.YieldOrReturnFrom((true, _), synYieldExpr, m) -> + let yieldFromExpr = mkSourceExpr synYieldExpr + + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "YieldFrom" builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("YieldFrom"), m)) + + let yieldFromCall = mkSynCall "YieldFrom" m [ yieldFromExpr ] + + let yieldFromCall = + if IsControlFlowExpression synYieldExpr then + yieldFromCall + else + SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, yieldFromCall) - | SynExpr.TryWith (innerComp, clauses, mTryToLast, spTry, spWith, trivia) -> - let mTry = match spTry with DebugPointAtTry.Yes _ -> trivia.TryKeyword.NoteSourceConstruct(NotedSourceConstruct.Try) | _ -> trivia.TryKeyword - let spWith2 = match spWith with DebugPointAtWith.Yes _ -> DebugPointAtBinding.Yes trivia.WithKeyword | _ -> DebugPointAtBinding.NoneAtInvisible - - if isQuery then error(Error(FSComp.SR.tcTryWithMayNotBeUsedInQueries(), mTry)) + Some(translatedCtxt yieldFromCall) - let clauses = clauses |> List.map (fun (SynMatchClause(pat, cond, clauseComp, patm, sp, trivia)) -> SynMatchClause(pat, cond, transNoQueryOps clauseComp, patm, sp, trivia)) - let consumeExpr = SynExpr.MatchLambda(true, mTryToLast, clauses, spWith2, mTryToLast) + | SynExpr.YieldOrReturnFrom((false, _), synReturnExpr, m) -> + let returnFromExpr = mkSourceExpr synReturnExpr - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "TryWith" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("TryWith"), mTry)) + if isQuery then + error (Error(FSComp.SR.tcReturnMayNotBeUsedInQueries (), m)) - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mTry ad "Delay" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), mTry)) + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "ReturnFrom" builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod ("ReturnFrom"), m)) - let innerExpr = transNoQueryOps innerComp + let returnFromCall = mkSynCall "ReturnFrom" m [ returnFromExpr ] - let innerExpr = - match spTry with - | DebugPointAtTry.Yes _ -> - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes mTry, true, innerExpr) - | _ -> innerExpr - - let callExpr = - mkSynCall "TryWith" mTry [ - mkSynCall "Delay" mTry [mkSynDelay2 innerExpr] - consumeExpr - ] - - Some(translatedCtxt callExpr) - - | SynExpr.YieldOrReturnFrom ((true, _), synYieldExpr, m) -> - let yieldFromExpr = mkSourceExpr synYieldExpr - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "YieldFrom" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("YieldFrom"), m)) - - let yieldFromCall = mkSynCall "YieldFrom" m [yieldFromExpr] - - let yieldFromCall = - if IsControlFlowExpression synYieldExpr then - yieldFromCall - else - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, yieldFromCall) - - Some (translatedCtxt yieldFromCall) - - | SynExpr.YieldOrReturnFrom ((false, _), synReturnExpr, m) -> - let returnFromExpr = mkSourceExpr synReturnExpr - if isQuery then error(Error(FSComp.SR.tcReturnMayNotBeUsedInQueries(), m)) + let returnFromCall = + if IsControlFlowExpression synReturnExpr then + returnFromCall + else + SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, returnFromCall) - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "ReturnFrom" builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod("ReturnFrom"), m)) + Some(translatedCtxt returnFromCall) - let returnFromCall = mkSynCall "ReturnFrom" m [returnFromExpr] + | SynExpr.YieldOrReturn((isYield, _), synYieldOrReturnExpr, m) -> + let methName = (if isYield then "Yield" else "Return") - let returnFromCall = - if IsControlFlowExpression synReturnExpr then - returnFromCall - else - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, returnFromCall) + if isQuery && not isYield then + error (Error(FSComp.SR.tcReturnMayNotBeUsedInQueries (), m)) - Some (translatedCtxt returnFromCall) + if + isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad methName builderTy) + then + error (Error(FSComp.SR.tcRequireBuilderMethod (methName), m)) - | SynExpr.YieldOrReturn ((isYield, _), synYieldOrReturnExpr, m) -> - let methName = (if isYield then "Yield" else "Return") - if isQuery && not isYield then error(Error(FSComp.SR.tcReturnMayNotBeUsedInQueries(), m)) + let yieldOrReturnCall = mkSynCall methName m [ synYieldOrReturnExpr ] - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad methName builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod(methName), m)) - - let yieldOrReturnCall = mkSynCall methName m [synYieldOrReturnExpr] - - let yieldOrReturnCall = - if IsControlFlowExpression synYieldOrReturnExpr then - yieldOrReturnCall - else - SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, yieldOrReturnCall) + let yieldOrReturnCall = + if IsControlFlowExpression synYieldOrReturnExpr then + yieldOrReturnCall + else + SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, yieldOrReturnCall) - Some(translatedCtxt yieldOrReturnCall) + Some(translatedCtxt yieldOrReturnCall) - | _ -> None + | _ -> None and consumeCustomOpClauses q (varSpace: LazyWithContext<_, _>) dataCompPrior compClausesExpr lastUsesBind mClause = @@ -1525,10 +2406,10 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol let varSpaceSimplePat = mkSimplePatForVarSpace mClause patvs let varSpacePat = mkPatForVarSpace mClause patvs - match compClausesExpr with - + match compClausesExpr with + // Detect one custom operation... This clause will always match at least once... - | OptionalSequential (CustomOperationClause (nm, opDatas, opExpr, mClause, optionalIntoPat), optionalCont) -> + | OptionalSequential(CustomOperationClause(nm, opDatas, opExpr, mClause, optionalIntoPat), optionalCont) -> let opName, _, _, _, _, _, _, _, methInfo = opDatas[0] let isLikeZip = customOperationIsLikeZip nm @@ -1536,16 +2417,18 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol let isLikeGroupJoin = customOperationIsLikeZip nm // Record the resolution of the custom operation for posterity - let item = Item.CustomOperation (opName, (fun () -> customOpUsageText nm), Some methInfo) + let item = + Item.CustomOperation(opName, (fun () -> customOpUsageText nm), Some methInfo) // FUTURE: consider whether we can do better than emptyTyparInst here, in order to display instantiations // of type variables in the quick info provided in the IDE. CallNameResolutionSink cenv.tcSink (nm.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.eAccessRights) if isLikeZip || isLikeJoin || isLikeGroupJoin then - errorR(Error(FSComp.SR.tcBinaryOperatorRequiresBody(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) - match optionalCont with - | None -> + errorR (Error(FSComp.SR.tcBinaryOperatorRequiresBody (nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) + + match optionalCont with + | None -> // we are about to drop the 'opExpr' AST on the floor. we've already reported an error. attempt to get name resolutions before dropping it RecordNameAndTypeResolutions cenv env tpenv opExpr dataCompPrior @@ -1557,217 +2440,346 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol let expectedArgCount = tryExpectedArgCountForCustomOperator nm - let dataCompAfterOp = - match opExpr with + let dataCompAfterOp = + match opExpr with | StripApps(SingleIdent nm, args) -> let argCountsMatch = match expectedArgCount with | Some n -> n = args.Length | None -> cenv.g.langVersion.SupportsFeature LanguageFeature.OverloadsForCustomOperations + if argCountsMatch then // Check for the [] attribute on each argument position - let args = args |> List.mapi (fun i arg -> - if isCustomOperationProjectionParameter (i+1) nm then - SynExpr.Lambda (false, false, varSpaceSimplePat, arg, None, arg.Range.MakeSynthetic(), SynExprLambdaTrivia.Zero) - else arg) + let args = + args + |> List.mapi (fun i arg -> + if isCustomOperationProjectionParameter (i + 1) nm then + SynExpr.Lambda( + false, + false, + varSpaceSimplePat, + arg, + None, + arg.Range.MakeSynthetic(), + SynExprLambdaTrivia.Zero + ) + else + arg) + mkSynCall methInfo.DisplayName mClause (dataCompPrior :: args) - else + else let expectedArgCount = defaultArg expectedArgCount 0 - errorR(Error(FSComp.SR.tcCustomOperationHasIncorrectArgCount(nm.idText, expectedArgCount, args.Length), nm.idRange)) - mkSynCall methInfo.DisplayName mClause ([ dataCompPrior ] @ List.init expectedArgCount (fun i -> arbExpr("_arg" + string i, mClause))) + + errorR ( + Error( + FSComp.SR.tcCustomOperationHasIncorrectArgCount (nm.idText, expectedArgCount, args.Length), + nm.idRange + ) + ) + + mkSynCall + methInfo.DisplayName + mClause + ([ dataCompPrior ] + @ List.init expectedArgCount (fun i -> arbExpr ("_arg" + string i, mClause))) | _ -> failwith "unreachable" - match optionalCont with - | None -> - match optionalIntoPat with - | Some intoPat -> errorR(Error(FSComp.SR.tcIntoNeedsRestOfQuery(), intoPat.Range)) + match optionalCont with + | None -> + match optionalIntoPat with + | Some intoPat -> errorR (Error(FSComp.SR.tcIntoNeedsRestOfQuery (), intoPat.Range)) | None -> () + dataCompAfterOp - | Some contExpr -> - - // select a.Name into name; ... - // distinct into d; ... - // - // Rebind the into pattern and process the rest of the clauses - match optionalIntoPat with - | Some intoPat -> - if not (customOperationAllowsInto nm) then - error(Error(FSComp.SR.tcOperatorDoesntAcceptInto(nm.idText), intoPat.Range)) - - // Rebind using either for ... or let!.... - let rebind = - if maintainsVarSpaceUsingBind then - SynExpr.LetOrUseBang (DebugPointAtBinding.NoneAtLet, false, false, intoPat, dataCompAfterOp, [], contExpr, intoPat.Range, SynExprLetOrUseBangTrivia.Zero) - else - SynExpr.ForEach (DebugPointAtFor.No, DebugPointAtInOrTo.No, SeqExprOnly false, false, intoPat, dataCompAfterOp, contExpr, intoPat.Range) - - trans CompExprTranslationPass.Initial q emptyVarSpace rebind id - - // select a.Name; ... - // distinct; ... - // - // Process the rest of the clauses - | None -> - if maintainsVarSpace || maintainsVarSpaceUsingBind then - consumeCustomOpClauses q varSpace dataCompAfterOp contExpr maintainsVarSpaceUsingBind mClause + | Some contExpr -> + + // select a.Name into name; ... + // distinct into d; ... + // + // Rebind the into pattern and process the rest of the clauses + match optionalIntoPat with + | Some intoPat -> + if not (customOperationAllowsInto nm) then + error (Error(FSComp.SR.tcOperatorDoesntAcceptInto (nm.idText), intoPat.Range)) + + // Rebind using either for ... or let!.... + let rebind = + if maintainsVarSpaceUsingBind then + SynExpr.LetOrUseBang( + DebugPointAtBinding.NoneAtLet, + false, + false, + intoPat, + dataCompAfterOp, + [], + contExpr, + intoPat.Range, + SynExprLetOrUseBangTrivia.Zero + ) else - consumeCustomOpClauses q emptyVarSpace dataCompAfterOp contExpr false mClause + SynExpr.ForEach( + DebugPointAtFor.No, + DebugPointAtInOrTo.No, + SeqExprOnly false, + false, + intoPat, + dataCompAfterOp, + contExpr, + intoPat.Range + ) + + trans CompExprTranslationPass.Initial q emptyVarSpace rebind id + + // select a.Name; ... + // distinct; ... + // + // Process the rest of the clauses + | None -> + if maintainsVarSpace || maintainsVarSpaceUsingBind then + consumeCustomOpClauses q varSpace dataCompAfterOp contExpr maintainsVarSpaceUsingBind mClause + else + consumeCustomOpClauses q emptyVarSpace dataCompAfterOp contExpr false mClause - // No more custom operator clauses in compClausesExpr, but there may be clauses like join, yield etc. + // No more custom operator clauses in compClausesExpr, but there may be clauses like join, yield etc. // Bind/iterate the dataCompPrior and use compClausesExpr as the body. - | _ -> + | _ -> // Rebind using either for ... or let!.... - let rebind = - if lastUsesBind then - SynExpr.LetOrUseBang (DebugPointAtBinding.NoneAtLet, false, false, varSpacePat, dataCompPrior, [], compClausesExpr, compClausesExpr.Range, SynExprLetOrUseBangTrivia.Zero) - else - SynExpr.ForEach (DebugPointAtFor.No, DebugPointAtInOrTo.No, SeqExprOnly false, false, varSpacePat, dataCompPrior, compClausesExpr, compClausesExpr.Range) - + let rebind = + if lastUsesBind then + SynExpr.LetOrUseBang( + DebugPointAtBinding.NoneAtLet, + false, + false, + varSpacePat, + dataCompPrior, + [], + compClausesExpr, + compClausesExpr.Range, + SynExprLetOrUseBangTrivia.Zero + ) + else + SynExpr.ForEach( + DebugPointAtFor.No, + DebugPointAtInOrTo.No, + SeqExprOnly false, + false, + varSpacePat, + dataCompPrior, + compClausesExpr, + compClausesExpr.Range + ) + trans CompExprTranslationPass.Initial q varSpace rebind id and transNoQueryOps comp = trans CompExprTranslationPass.Initial CustomOperationsMode.Denied emptyVarSpace comp id - and trans firstTry q varSpace comp translatedCtxt = - match tryTrans firstTry q varSpace comp translatedCtxt with + and trans firstTry q varSpace comp translatedCtxt = + match tryTrans firstTry q varSpace comp translatedCtxt with | Some e -> e - | None -> + | None -> // This only occurs in final position in a sequence - match comp with + match comp with // "do! expr;" in final position is treated as { let! () = expr in return () } when Return is provided (and no Zero with Default attribute is available) or as { let! () = expr in zero } otherwise - | SynExpr.DoBang (rhsExpr, m) -> + | SynExpr.DoBang(rhsExpr, m) -> let mUnit = rhsExpr.Range let rhsExpr = mkSourceExpr rhsExpr - if isQuery then error(Error(FSComp.SR.tcBindMayNotBeUsedInQueries(), m)) + + if isQuery then + error (Error(FSComp.SR.tcBindMayNotBeUsedInQueries (), m)) + let bodyExpr = - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Return" builderTy) then + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Return" builderTy + ) + then SynExpr.ImplicitZero m else - match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Zero" builderTy with + match + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Zero" builderTy + with | minfo :: _ when MethInfoHasAttribute cenv.g m cenv.g.attrib_DefaultValueAttribute minfo -> SynExpr.ImplicitZero m - | _ -> SynExpr.YieldOrReturn ((false, true), SynExpr.Const (SynConst.Unit, m), m) - let letBangBind = SynExpr.LetOrUseBang (DebugPointAtBinding.NoneAtDo, false, false, SynPat.Const(SynConst.Unit, mUnit), rhsExpr, [], bodyExpr, m, SynExprLetOrUseBangTrivia.Zero) + | _ -> SynExpr.YieldOrReturn((false, true), SynExpr.Const(SynConst.Unit, m), m) + + let letBangBind = + SynExpr.LetOrUseBang( + DebugPointAtBinding.NoneAtDo, + false, + false, + SynPat.Const(SynConst.Unit, mUnit), + rhsExpr, + [], + bodyExpr, + m, + SynExprLetOrUseBangTrivia.Zero + ) + trans CompExprTranslationPass.Initial q varSpace letBangBind translatedCtxt // "expr;" in final position is treated as { expr; zero } // Suppress the sequence point on the "zero" - | _ -> + | _ -> // Check for 'where x > y' and other mis-applications of infix operators. If detected, give a good error message, and just ignore comp - if isQuery && checkForBinaryApp comp then + if isQuery && checkForBinaryApp comp then trans CompExprTranslationPass.Initial q varSpace (SynExpr.ImplicitZero comp.Range) translatedCtxt else - if isQuery && not comp.IsArbExprAndThusAlreadyReportedError then - match comp with + if isQuery && not comp.IsArbExprAndThusAlreadyReportedError then + match comp with | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential - | _ -> errorR(Error(FSComp.SR.tcUnrecognizedQueryOperator(), comp.RangeOfFirstPortion)) + | _ -> errorR (Error(FSComp.SR.tcUnrecognizedQueryOperator (), comp.RangeOfFirstPortion)) + trans CompExprTranslationPass.Initial q varSpace (SynExpr.ImplicitZero comp.Range) (fun holeFill -> - let fillExpr = - if enableImplicitYield then - let implicitYieldExpr = mkSynCall "Yield" comp.Range [comp] - SynExpr.SequentialOrImplicitYield(DebugPointAtSequential.SuppressExpr, comp, holeFill, implicitYieldExpr, comp.Range) + let fillExpr = + if enableImplicitYield then + let implicitYieldExpr = mkSynCall "Yield" comp.Range [ comp ] + + SynExpr.SequentialOrImplicitYield( + DebugPointAtSequential.SuppressExpr, + comp, + holeFill, + implicitYieldExpr, + comp.Range + ) else SynExpr.Sequential(DebugPointAtSequential.SuppressExpr, true, comp, holeFill, comp.Range) - translatedCtxt fillExpr) - and transBind q varSpace bindRange addBindDebugPoint bindName bindArgs (consumePat: SynPat) (innerComp: SynExpr) translatedCtxt = + translatedCtxt fillExpr) + + and transBind q varSpace bindRange addBindDebugPoint bindName bindArgs (consumePat: SynPat) (innerComp: SynExpr) translatedCtxt = let innerRange = innerComp.Range - - let innerCompReturn = + + let innerCompReturn = if cenv.g.langVersion.SupportsFeature LanguageFeature.AndBang then convertSimpleReturnToExpr varSpace innerComp - else None + else + None - match innerCompReturn with - | Some (innerExpr, customOpInfo) when - (let bindName = bindName + "Return" - not (isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad bindName builderTy))) -> + match innerCompReturn with + | Some(innerExpr, customOpInfo) when + (let bindName = bindName + "Return" + + not ( + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad bindName builderTy + ) + )) + -> let bindName = bindName + "Return" - + // Build the `BindReturn` call let dataCompPriorToOp = - let consumeExpr = SynExpr.MatchLambda(false, consumePat.Range, [SynMatchClause(consumePat, None, innerExpr, innerRange, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero)], DebugPointAtBinding.NoneAtInvisible, innerRange) - translatedCtxt (mkSynCall bindName bindRange (bindArgs @ [consumeExpr])) - - match customOpInfo with + let consumeExpr = + SynExpr.MatchLambda( + false, + consumePat.Range, + [ + SynMatchClause(consumePat, None, innerExpr, innerRange, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero) + ], + DebugPointAtBinding.NoneAtInvisible, + innerRange + ) + + translatedCtxt (mkSynCall bindName bindRange (bindArgs @ [ consumeExpr ])) + + match customOpInfo with | None -> dataCompPriorToOp - | Some (innerComp, mClause) -> + | Some(innerComp, mClause) -> // If the `BindReturn` was forced by a custom operation, continue to process the clauses of the CustomOp consumeCustomOpClauses q varSpace dataCompPriorToOp innerComp false mClause - | _ -> + | _ -> - if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad bindName builderTy) then - error(Error(FSComp.SR.tcRequireBuilderMethod(bindName), bindRange)) + if + isNil ( + TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env bindRange ad bindName builderTy + ) + then + error (Error(FSComp.SR.tcRequireBuilderMethod (bindName), bindRange)) // Build the `Bind` call trans CompExprTranslationPass.Initial q varSpace innerComp (fun holeFill -> - let consumeExpr = SynExpr.MatchLambda(false, consumePat.Range, [SynMatchClause(consumePat, None, holeFill, innerRange, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero)], DebugPointAtBinding.NoneAtInvisible, innerRange) - let bindCall = mkSynCall bindName bindRange (bindArgs @ [consumeExpr]) + let consumeExpr = + SynExpr.MatchLambda( + false, + consumePat.Range, + [ + SynMatchClause(consumePat, None, holeFill, innerRange, DebugPointAtTarget.Yes, SynMatchClauseTrivia.Zero) + ], + DebugPointAtBinding.NoneAtInvisible, + innerRange + ) + + let bindCall = mkSynCall bindName bindRange (bindArgs @ [ consumeExpr ]) translatedCtxt (bindCall |> addBindDebugPoint)) /// This function is for desugaring into .Bind{N}Return calls if possible /// The outer option indicates if .BindReturn is possible. When it returns None, .BindReturn cannot be used /// The inner option indicates if a custom operation is involved inside and convertSimpleReturnToExpr varSpace innerComp = - match innerComp with - | SynExpr.YieldOrReturn ((false, _), returnExpr, m) -> + match innerComp with + | SynExpr.YieldOrReturn((false, _), returnExpr, m) -> let returnExpr = SynExpr.DebugPoint(DebugPointAtLeafExpr.Yes m, false, returnExpr) - Some (returnExpr, None) + Some(returnExpr, None) - | SynExpr.Match (spMatch, expr, clauses, m, trivia) -> - let clauses = - clauses |> List.map (fun (SynMatchClause(pat, cond, innerComp2, patm, sp, trivia)) -> + | SynExpr.Match(spMatch, expr, clauses, m, trivia) -> + let clauses = + clauses + |> List.map (fun (SynMatchClause(pat, cond, innerComp2, patm, sp, trivia)) -> match convertSimpleReturnToExpr varSpace innerComp2 with | None -> None // failure - | Some (_, Some _) -> None // custom op on branch = failure - | Some (innerExpr2, None) -> Some (SynMatchClause(pat, cond, innerExpr2, patm, sp, trivia))) + | Some(_, Some _) -> None // custom op on branch = failure + | Some(innerExpr2, None) -> Some(SynMatchClause(pat, cond, innerExpr2, patm, sp, trivia))) + if clauses |> List.forall Option.isSome then - Some (SynExpr.Match (spMatch, expr, (clauses |> List.map Option.get), m, trivia), None) + Some(SynExpr.Match(spMatch, expr, (clauses |> List.map Option.get), m, trivia), None) else None - | SynExpr.IfThenElse (guardExpr, thenComp, elseCompOpt, spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia) -> + | SynExpr.IfThenElse(guardExpr, thenComp, elseCompOpt, spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia) -> match convertSimpleReturnToExpr varSpace thenComp with | None -> None - | Some (_, Some _) -> None - | Some (thenExpr, None) -> - let elseExprOptOpt = - match elseCompOpt with - // When we are missing an 'else' part alltogether in case of 'if cond then return exp', we fallback from BindReturn into regular Bind+Return - | None -> None - | Some elseComp -> - match convertSimpleReturnToExpr varSpace elseComp with - | None -> None // failure - | Some (_, Some _) -> None // custom op on branch = failure - | Some (elseExpr, None) -> Some (Some elseExpr) - match elseExprOptOpt with - | None -> None - | Some elseExprOpt -> Some (SynExpr.IfThenElse (guardExpr, thenExpr, elseExprOpt, spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia), None) + | Some(_, Some _) -> None + | Some(thenExpr, None) -> + let elseExprOptOpt = + match elseCompOpt with + // When we are missing an 'else' part alltogether in case of 'if cond then return exp', we fallback from BindReturn into regular Bind+Return + | None -> None + | Some elseComp -> + match convertSimpleReturnToExpr varSpace elseComp with + | None -> None // failure + | Some(_, Some _) -> None // custom op on branch = failure + | Some(elseExpr, None) -> Some(Some elseExpr) + + match elseExprOptOpt with + | None -> None + | Some elseExprOpt -> + Some(SynExpr.IfThenElse(guardExpr, thenExpr, elseExprOpt, spIfToThen, isRecovery, mIfToEndOfElseBranch, trivia), None) - | SynExpr.LetOrUse (isRec, false, binds, innerComp, m, trivia) -> + | SynExpr.LetOrUse(isRec, false, binds, innerComp, m, trivia) -> match convertSimpleReturnToExpr varSpace innerComp with | None -> None - | Some (_, Some _) -> None - | Some (innerExpr, None) -> Some (SynExpr.LetOrUse (isRec, false, binds, innerExpr, m, trivia), None) + | Some(_, Some _) -> None + | Some(innerExpr, None) -> Some(SynExpr.LetOrUse(isRec, false, binds, innerExpr, m, trivia), None) - | OptionalSequential (CustomOperationClause (nm, _, _, mClause, _), _) when customOperationMaintainsVarSpaceUsingBind nm -> + | OptionalSequential(CustomOperationClause(nm, _, _, mClause, _), _) when customOperationMaintainsVarSpaceUsingBind nm -> let patvs, _env = varSpace.Force comp.Range let varSpaceExpr = mkExprForVarSpace mClause patvs - - Some (varSpaceExpr, Some (innerComp, mClause)) - | SynExpr.Sequential (sp, true, innerComp1, innerComp2, m) -> + Some(varSpaceExpr, Some(innerComp, mClause)) + + | SynExpr.Sequential(sp, true, innerComp1, innerComp2, m) -> // Check the first part isn't a computation expression construct if isSimpleExpr innerComp1 then // Check the second part is a simple return match convertSimpleReturnToExpr varSpace innerComp2 with | None -> None - | Some (innerExpr2, optionalCont) -> Some (SynExpr.Sequential (sp, true, innerComp1, innerExpr2, m), optionalCont) + | Some(innerExpr2, optionalCont) -> Some(SynExpr.Sequential(sp, true, innerComp1, innerExpr2, m), optionalCont) else None @@ -1776,7 +2788,7 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol /// Check if an expression has no computation expression constructs and isSimpleExpr comp = - match comp with + match comp with | ForEachThenJoinOrGroupJoinOrZipClause false _ -> false | SynExpr.ForEach _ -> false | SynExpr.For _ -> false @@ -1784,61 +2796,85 @@ let TcComputationExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (mWhol | SynExpr.WhileBang _ -> false | SynExpr.TryFinally _ -> false | SynExpr.ImplicitZero _ -> false - | OptionalSequential (JoinOrGroupJoinOrZipClause _, _) -> false - | OptionalSequential (CustomOperationClause _, _) -> false - | SynExpr.Sequential (_, _, innerComp1, innerComp2, _) -> isSimpleExpr innerComp1 && isSimpleExpr innerComp2 - | SynExpr.IfThenElse (thenExpr=thenComp; elseExpr=elseCompOpt) -> - isSimpleExpr thenComp && (match elseCompOpt with None -> true | Some c -> isSimpleExpr c) - | SynExpr.LetOrUse (body=innerComp) -> isSimpleExpr innerComp + | OptionalSequential(JoinOrGroupJoinOrZipClause _, _) -> false + | OptionalSequential(CustomOperationClause _, _) -> false + | SynExpr.Sequential(_, _, innerComp1, innerComp2, _) -> isSimpleExpr innerComp1 && isSimpleExpr innerComp2 + | SynExpr.IfThenElse(thenExpr = thenComp; elseExpr = elseCompOpt) -> + isSimpleExpr thenComp + && (match elseCompOpt with + | None -> true + | Some c -> isSimpleExpr c) + | SynExpr.LetOrUse(body = innerComp) -> isSimpleExpr innerComp | SynExpr.LetOrUseBang _ -> false - | SynExpr.Match (clauses=clauses) -> - clauses |> List.forall (fun (SynMatchClause(resultExpr = innerComp)) -> isSimpleExpr innerComp) + | SynExpr.Match(clauses = clauses) -> + clauses + |> List.forall (fun (SynMatchClause(resultExpr = innerComp)) -> isSimpleExpr innerComp) | SynExpr.MatchBang _ -> false - | SynExpr.TryWith (tryExpr=innerComp; withCases=clauses) -> - isSimpleExpr innerComp && - clauses |> List.forall (fun (SynMatchClause(resultExpr = clauseComp)) -> isSimpleExpr clauseComp) + | SynExpr.TryWith(tryExpr = innerComp; withCases = clauses) -> + isSimpleExpr innerComp + && clauses + |> List.forall (fun (SynMatchClause(resultExpr = clauseComp)) -> isSimpleExpr clauseComp) | SynExpr.YieldOrReturnFrom _ -> false | SynExpr.YieldOrReturn _ -> false | SynExpr.DoBang _ -> false | _ -> true - let basicSynExpr = - trans CompExprTranslationPass.Initial (hasCustomOperations ()) (LazyWithContext.NotLazy ([], env)) comp id + let basicSynExpr = + trans CompExprTranslationPass.Initial (hasCustomOperations ()) (LazyWithContext.NotLazy([], env)) comp id - let mDelayOrQuoteOrRun = mBuilderVal.NoteSourceConstruct(NotedSourceConstruct.DelayOrQuoteOrRun).MakeSynthetic() + let mDelayOrQuoteOrRun = + mBuilderVal + .NoteSourceConstruct(NotedSourceConstruct.DelayOrQuoteOrRun) + .MakeSynthetic() // Add a call to 'Delay' if the method is present - let delayedExpr = - match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Delay" builderTy with + let delayedExpr = + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Delay" builderTy with | [] -> basicSynExpr - | _ -> - mkSynCall "Delay" mDelayOrQuoteOrRun [(mkSynDelay2 basicSynExpr)] + | _ -> mkSynCall "Delay" mDelayOrQuoteOrRun [ (mkSynDelay2 basicSynExpr) ] // Add a call to 'Quote' if the method is present - let quotedSynExpr = - if isAutoQuote then - SynExpr.Quote (mkSynIdGet mDelayOrQuoteOrRun (CompileOpName "<@ @>"), false, delayedExpr, true, mWhole) - else delayedExpr - + let quotedSynExpr = + if isAutoQuote then + SynExpr.Quote(mkSynIdGet mDelayOrQuoteOrRun (CompileOpName "<@ @>"), false, delayedExpr, true, mWhole) + else + delayedExpr + // Add a call to 'Run' if the method is present - let runExpr = - match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Run" builderTy with + let runExpr = + match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Run" builderTy with | [] -> quotedSynExpr - | _ -> mkSynCall "Run" mDelayOrQuoteOrRun [quotedSynExpr] - - let lambdaExpr = - SynExpr.Lambda (false, false, SynSimplePats.SimplePats ([mkSynSimplePatVar false (mkSynId mBuilderVal builderValName)], [], mBuilderVal), runExpr, None, mBuilderVal, SynExprLambdaTrivia.Zero) + | _ -> mkSynCall "Run" mDelayOrQuoteOrRun [ quotedSynExpr ] + + let lambdaExpr = + SynExpr.Lambda( + false, + false, + SynSimplePats.SimplePats([ mkSynSimplePatVar false (mkSynId mBuilderVal builderValName) ], [], mBuilderVal), + runExpr, + None, + mBuilderVal, + SynExprLambdaTrivia.Zero + ) let env = match comp with - | SynExpr.YieldOrReturn ((true, _), _, _) -> { env with eContextInfo = ContextInfo.YieldInComputationExpression } - | SynExpr.YieldOrReturn ((_, true), _, _) -> { env with eContextInfo = ContextInfo.ReturnInComputationExpression } + | SynExpr.YieldOrReturn(flags = (true, _)) -> + { env with + eContextInfo = ContextInfo.YieldInComputationExpression + } + | SynExpr.YieldOrReturn(flags = (_, true)) -> + { env with + eContextInfo = ContextInfo.ReturnInComputationExpression + } | _ -> env - let lambdaExpr, tpenv = TcExpr cenv (MustEqual (mkFunTy g builderTy overallTy)) env tpenv lambdaExpr + let lambdaExpr, tpenv = + TcExpr cenv (MustEqual(mkFunTy g builderTy overallTy)) env tpenv lambdaExpr // beta-var-reduce to bind the builder using a 'let' binding - let coreExpr = mkApps cenv.g ((lambdaExpr, tyOfExpr cenv.g lambdaExpr), [], [interpExpr], mBuilderVal) + let coreExpr = + mkApps cenv.g ((lambdaExpr, tyOfExpr cenv.g lambdaExpr), [], [ interpExpr ], mBuilderVal) coreExpr, tpenv @@ -1847,13 +2883,16 @@ let mkSeqEmpty (cenv: cenv) env m genTy = let g = cenv.g let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy g genResultTy) - mkCallSeqEmpty g m genResultTy + mkCallSeqEmpty g m genResultTy let mkSeqCollect (cenv: cenv) env m enumElemTy genTy lam enumExpr = let g = cenv.g let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy cenv.g genResultTy) - let enumExpr = mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g enumElemTy) (tyOfExpr cenv.g enumExpr) enumExpr + + let enumExpr = + mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g enumElemTy) (tyOfExpr cenv.g enumExpr) enumExpr + mkCallSeqCollect cenv.g m enumElemTy genResultTy lam enumExpr let mkSeqUsing (cenv: cenv) (env: TcEnv) m resourceTy genTy resourceExpr lam = @@ -1861,58 +2900,83 @@ let mkSeqUsing (cenv: cenv) (env: TcEnv) m resourceTy genTy resourceExpr lam = AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace cenv.g.system_IDisposable_ty resourceTy let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy cenv.g genResultTy) - mkCallSeqUsing cenv.g m resourceTy genResultTy resourceExpr lam + mkCallSeqUsing cenv.g m resourceTy genResultTy resourceExpr lam let mkSeqDelay (cenv: cenv) env m genTy lam = let g = cenv.g let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy cenv.g genResultTy) - mkCallSeqDelay cenv.g m genResultTy (mkUnitDelayLambda cenv.g m lam) + mkCallSeqDelay cenv.g m genResultTy (mkUnitDelayLambda cenv.g m lam) let mkSeqAppend (cenv: cenv) env m genTy e1 e2 = let g = cenv.g let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy cenv.g genResultTy) - let e1 = mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e1) e1 - let e2 = mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e2) e2 - mkCallSeqAppend cenv.g m genResultTy e1 e2 + + let e1 = + mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e1) e1 + + let e2 = + mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e2) e2 + + mkCallSeqAppend cenv.g m genResultTy e1 e2 let mkSeqFromFunctions (cenv: cenv) env m genTy e1 e2 = let g = cenv.g let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy cenv.g genResultTy) - let e2 = mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e2) e2 - mkCallSeqGenerated cenv.g m genResultTy e1 e2 + + let e2 = + mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e2) e2 + + mkCallSeqGenerated cenv.g m genResultTy e1 e2 let mkSeqFinally (cenv: cenv) env m genTy e1 e2 = let g = cenv.g let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy cenv.g genResultTy) - let e1 = mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e1) e1 - mkCallSeqFinally cenv.g m genResultTy e1 e2 + + let e1 = + mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g e1) e1 + + mkCallSeqFinally cenv.g m genResultTy e1 e2 let mkSeqTryWith (cenv: cenv) env m genTy origSeq exnFilter exnHandler = let g = cenv.g let genResultTy = NewInferenceType g UnifyTypes cenv env m genTy (mkSeqTy cenv.g genResultTy) - let origSeq = mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g origSeq) origSeq - mkCallSeqTryWith cenv.g m genResultTy origSeq exnFilter exnHandler -let mkSeqExprMatchClauses (pat, vspecs) innerExpr = - [MatchClause(pat, None, TTarget(vspecs, innerExpr, None), pat.Range) ] + let origSeq = + mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g genResultTy) (tyOfExpr cenv.g origSeq) origSeq + + mkCallSeqTryWith cenv.g m genResultTy origSeq exnFilter exnHandler -let compileSeqExprMatchClauses (cenv: cenv) env inputExprMark (pat: Pattern, vspecs) innerExpr inputExprOpt bindPatTy genInnerTy = +let mkSeqExprMatchClauses (pat, vspecs) innerExpr = + [ MatchClause(pat, None, TTarget(vspecs, innerExpr, None), pat.Range) ] + +let compileSeqExprMatchClauses (cenv: cenv) env inputExprMark (pat: Pattern, vspecs) innerExpr inputExprOpt bindPatTy genInnerTy = let patMark = pat.Range - let tclauses = mkSeqExprMatchClauses (pat, vspecs) innerExpr - CompilePatternForMatchClauses cenv env inputExprMark patMark false ThrowIncompleteMatchException inputExprOpt bindPatTy genInnerTy tclauses + let tclauses = mkSeqExprMatchClauses (pat, vspecs) innerExpr + + CompilePatternForMatchClauses + cenv + env + inputExprMark + patMark + false + ThrowIncompleteMatchException + inputExprOpt + bindPatTy + genInnerTy + tclauses /// This case is used for computation expressions which are sequence expressions. Technically the code path is different because it /// typechecks rather than doing a shallow syntactic translation, and generates calls into the Seq.* library -/// and helpers rather than to the builder methods (there is actually no builder for 'seq' in the library). -/// These are later detected by state machine compilation. +/// and helpers rather than to the builder methods (there is actually no builder for 'seq' in the library). +/// These are later detected by state machine compilation. /// /// Also "ienumerable extraction" is performed on arguments to "for". -let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = +let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = let g = cenv.g let genEnumElemTy = NewInferenceType g @@ -1922,68 +2986,94 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = let flex = not (isTyparTy cenv.g genEnumElemTy) // If there are no 'yield' in the computation expression then allow the type-directed rule - // interpreting non-unit-typed expressions in statement positions as 'yield'. 'yield!' may be + // interpreting non-unit-typed expressions in statement positions as 'yield'. 'yield!' may be // present in the computation expression. let enableImplicitYield = cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield && (YieldFree cenv comp) - let mkSeqDelayedExpr m (coreExpr: Expr) = + let mkSeqDelayedExpr m (coreExpr: Expr) = let overallTy = tyOfExpr cenv.g coreExpr mkSeqDelay cenv env m overallTy coreExpr let rec tryTcSequenceExprBody env genOuterTy tpenv comp = - match comp with - | SynExpr.ForEach (spFor, spIn, SeqExprOnly _seqExprOnly, _isFromSource, pat, pseudoEnumExpr, innerComp, _m) -> + match comp with + | SynExpr.ForEach(spFor, spIn, SeqExprOnly _seqExprOnly, _isFromSource, pat, pseudoEnumExpr, innerComp, _m) -> let pseudoEnumExpr = match RewriteRangeExpr pseudoEnumExpr with | Some e -> e | None -> pseudoEnumExpr - // This expression is not checked with the knowledge it is an IEnumerable, since we permit other enumerable types with GetEnumerator/MoveNext methods, as does C# - let pseudoEnumExpr, arbitraryTy, tpenv = TcExprOfUnknownType cenv env tpenv pseudoEnumExpr - let enumExpr, enumElemTy = ConvertArbitraryExprToEnumerable cenv arbitraryTy env pseudoEnumExpr - let patR, _, vspecs, envinner, tpenv = TcMatchPattern cenv enumElemTy env tpenv pat None + // This expression is not checked with the knowledge it is an IEnumerable, since we permit other enumerable types with GetEnumerator/MoveNext methods, as does C# + let pseudoEnumExpr, arbitraryTy, tpenv = + TcExprOfUnknownType cenv env tpenv pseudoEnumExpr + + let enumExpr, enumElemTy = + ConvertArbitraryExprToEnumerable cenv arbitraryTy env pseudoEnumExpr + + let patR, _, vspecs, envinner, tpenv = + TcMatchPattern cenv enumElemTy env tpenv pat None + let innerExpr, tpenv = let envinner = { envinner with eIsControlFlow = true } tcSequenceExprBody envinner genOuterTy tpenv innerComp - + let enumExprRange = enumExpr.Range // We attach the debug point to the lambda expression so we can fetch it out again in LowerComputedListOrArraySeqExpr - let mFor = match spFor with DebugPointAtFor.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.For) | _ -> enumExprRange + let mFor = + match spFor with + | DebugPointAtFor.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.For) + | _ -> enumExprRange // We attach the debug point to the lambda expression so we can fetch it out again in LowerComputedListOrArraySeqExpr - let mIn = match spIn with DebugPointAtInOrTo.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.InOrTo) | _ -> pat.Range + let mIn = + match spIn with + | DebugPointAtInOrTo.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.InOrTo) + | _ -> pat.Range - match patR, vspecs, innerExpr with + match patR, vspecs, innerExpr with // Legacy peephole optimization: // "seq { .. for x in e1 -> e2 .. }" == "e1 |> Seq.map (fun x -> e2)" // "seq { .. for x in e1 do yield e2 .. }" == "e1 |> Seq.map (fun x -> e2)" // // This transformation is visible in quotations and thus needs to remain. - | (TPat_as (TPat_wild _, PatternValBinding (v, _), _), - [_], - DebugPoints(Expr.App (Expr.Val (vref, _, _), _, [genEnumElemTy], [yieldExpr], _mYield), recreate)) - when valRefEq cenv.g vref cenv.g.seq_singleton_vref -> + | (TPat_as(TPat_wild _, PatternValBinding(v, _), _), + [ _ ], + 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 - // Note: the 'yield' part of the debug point for 'yield expr' is currently lost in debug points. + // Note: the 'yield' part of the debug point for 'yield expr' is currently lost in debug points. let lam = mkLambda mIn v (recreate yieldExpr, genEnumElemTy) - let enumExpr = mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g enumElemTy) (tyOfExpr cenv.g enumExpr) enumExpr + + let enumExpr = + mkCoerceIfNeeded cenv.g (mkSeqTy cenv.g enumElemTy) (tyOfExpr cenv.g enumExpr) enumExpr + Some(mkCallSeqMap cenv.g mFor enumElemTy genEnumElemTy lam enumExpr, tpenv) - | _ -> + | _ -> // The debug point mFor is attached to the 'collect' // The debug point mIn is attached to the lambda - let matchv, matchExpr = compileSeqExprMatchClauses cenv env enumExprRange (patR, vspecs) innerExpr None enumElemTy genOuterTy + let matchv, matchExpr = + compileSeqExprMatchClauses cenv env enumExprRange (patR, vspecs) innerExpr None enumElemTy genOuterTy + let lam = mkLambda mIn matchv (matchExpr, tyOfExpr cenv.g matchExpr) Some(mkSeqCollect cenv env mFor enumElemTy genOuterTy lam enumExpr, tpenv) - | SynExpr.For (forDebugPoint=spFor; toDebugPoint=spTo; ident=id; identBody=start; direction=dir; toBody=finish; doBody=innerComp; range=m) -> + | SynExpr.For( + forDebugPoint = spFor + toDebugPoint = spTo + ident = id + identBody = start + direction = dir + toBody = finish + doBody = innerComp + range = m) -> Some(tcSequenceExprBody env genOuterTy tpenv (elimFastIntegerForLoop (spFor, spTo, id, start, dir, finish, innerComp, m))) - | SynExpr.While (spWhile, guardExpr, innerComp, _m) -> + | SynExpr.While(spWhile, guardExpr, innerComp, _m) -> let guardExpr, tpenv = let env = { env with eIsControlFlow = false } TcExpr cenv (MustEqual cenv.g.bool_ty) env tpenv guardExpr @@ -1991,10 +3081,10 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = let innerExpr, tpenv = let env = { env with eIsControlFlow = true } tcSequenceExprBody env genOuterTy tpenv innerComp - + let guardExprMark = guardExpr.Range let guardLambdaExpr = mkUnitDelayLambda cenv.g guardExprMark guardExpr - + // We attach the debug point to the lambda expression so we can fetch it out again in LowerComputedListOrArraySeqExpr let mWhile = match spWhile with @@ -2004,78 +3094,105 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = let innerDelayedExpr = mkSeqDelayedExpr mWhile innerExpr Some(mkSeqFromFunctions cenv env guardExprMark genOuterTy guardLambdaExpr innerDelayedExpr, tpenv) - | SynExpr.TryFinally (innerComp, unwindExpr, mTryToLast, spTry, spFinally, trivia) -> + | SynExpr.TryFinally(innerComp, unwindExpr, mTryToLast, spTry, spFinally, trivia) -> let env = { env with eIsControlFlow = true } let innerExpr, tpenv = tcSequenceExprBody env genOuterTy tpenv innerComp let unwindExpr, tpenv = TcExpr cenv (MustEqual cenv.g.unit_ty) env tpenv unwindExpr - + // We attach the debug points to the lambda expressions so we can fetch it out again in LowerComputedListOrArraySeqExpr - let mTry = - match spTry with + let mTry = + match spTry with | DebugPointAtTry.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.Try) | _ -> trivia.TryKeyword - let mFinally = - match spFinally with + let mFinally = + match spFinally with | DebugPointAtFinally.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.Finally) | _ -> trivia.FinallyKeyword let innerExpr = mkSeqDelayedExpr mTry innerExpr let unwindExpr = mkUnitDelayLambda cenv.g mFinally unwindExpr - + Some(mkSeqFinally cenv env mTryToLast genOuterTy innerExpr unwindExpr, tpenv) - | SynExpr.Paren (_, _, _, m) when not (cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield)-> - error(Error(FSComp.SR.tcConstructIsAmbiguousInSequenceExpression(), m)) + | SynExpr.Paren(range = m) when not (cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield) -> + error (Error(FSComp.SR.tcConstructIsAmbiguousInSequenceExpression (), m)) - | SynExpr.ImplicitZero m -> - Some(mkSeqEmpty cenv env m genOuterTy, tpenv ) + | SynExpr.ImplicitZero m -> Some(mkSeqEmpty cenv env m genOuterTy, tpenv) - | SynExpr.DoBang (_rhsExpr, m) -> - error(Error(FSComp.SR.tcDoBangIllegalInSequenceExpression(), m)) + | SynExpr.DoBang(_rhsExpr, m) -> error (Error(FSComp.SR.tcDoBangIllegalInSequenceExpression (), m)) - | SynExpr.Sequential (sp, true, innerComp1, innerComp2, m) -> - let env1 = { env with eIsControlFlow = (match sp with DebugPointAtSequential.SuppressNeither | DebugPointAtSequential.SuppressExpr -> true | _ -> false) } + | SynExpr.Sequential(sp, true, innerComp1, innerComp2, m) -> + let env1 = + { env with + eIsControlFlow = + (match sp with + | DebugPointAtSequential.SuppressNeither + | DebugPointAtSequential.SuppressExpr -> true + | _ -> false) + } - let res, tpenv = tcSequenceExprBodyAsSequenceOrStatement env1 genOuterTy tpenv innerComp1 + let res, tpenv = + tcSequenceExprBodyAsSequenceOrStatement env1 genOuterTy tpenv innerComp1 - let env2 = { env with eIsControlFlow = (match sp with DebugPointAtSequential.SuppressNeither | DebugPointAtSequential.SuppressStmt -> true | _ -> false) } + let env2 = + { env with + eIsControlFlow = + (match sp with + | DebugPointAtSequential.SuppressNeither + | DebugPointAtSequential.SuppressStmt -> true + | _ -> false) + } // "expr; cexpr" is treated as sequential execution // "cexpr; cexpr" is treated as append - match res with - | Choice1Of2 innerExpr1 -> + match res with + | Choice1Of2 innerExpr1 -> let innerExpr2, tpenv = tcSequenceExprBody env2 genOuterTy tpenv innerComp2 let innerExpr2 = mkSeqDelayedExpr innerExpr2.Range innerExpr2 Some(mkSeqAppend cenv env innerComp1.Range genOuterTy innerExpr1 innerExpr2, tpenv) - | Choice2Of2 stmt1 -> + | Choice2Of2 stmt1 -> let innerExpr2, tpenv = tcSequenceExprBody env2 genOuterTy tpenv innerComp2 Some(Expr.Sequential(stmt1, innerExpr2, NormalSeq, m), tpenv) - | SynExpr.IfThenElse (guardExpr, thenComp, elseCompOpt, spIfToThen, _isRecovery, mIfToEndOfElseBranch, trivia) -> + | SynExpr.IfThenElse(guardExpr, thenComp, elseCompOpt, spIfToThen, _isRecovery, mIfToEndOfElseBranch, trivia) -> let guardExpr', tpenv = TcExpr cenv (MustEqual cenv.g.bool_ty) env tpenv guardExpr let env = { env with eIsControlFlow = true } let thenExpr, tpenv = tcSequenceExprBody env genOuterTy tpenv thenComp - let elseComp = (match elseCompOpt with Some c -> c | None -> SynExpr.ImplicitZero trivia.IfToThenRange) + + let elseComp = + (match elseCompOpt with + | Some c -> c + | None -> SynExpr.ImplicitZero trivia.IfToThenRange) + let elseExpr, tpenv = tcSequenceExprBody env genOuterTy tpenv elseComp Some(mkCond spIfToThen mIfToEndOfElseBranch genOuterTy guardExpr' thenExpr elseExpr, tpenv) // 'let x = expr in expr' - | SynExpr.LetOrUse (isUse=false (* not a 'use' binding *)) -> - TcLinearExprs - (fun overallTy envinner tpenv e -> tcSequenceExprBody envinner overallTy.Commit tpenv e) - cenv env overallTy - tpenv + | SynExpr.LetOrUse(isUse = false) -> + TcLinearExprs + (fun overallTy envinner tpenv e -> tcSequenceExprBody envinner overallTy.Commit tpenv e) + cenv + env + overallTy + tpenv true - comp - id |> Some + comp + id + |> Some // 'use x = expr in expr' - | SynExpr.LetOrUse (isUse=true; bindings=[SynBinding (kind=SynBindingKind.Normal; headPat=pat; expr=rhsExpr; debugPoint=spBind)]; body=innerComp; range=wholeExprMark) -> + | SynExpr.LetOrUse( + isUse = true + bindings = [ SynBinding(kind = SynBindingKind.Normal; headPat = pat; expr = rhsExpr; debugPoint = spBind) ] + body = innerComp + range = wholeExprMark) -> let bindPatTy = NewInferenceType g let inputExprTy = NewInferenceType g - let pat', _, vspecs, envinner, tpenv = TcMatchPattern cenv bindPatTy env tpenv pat None + + let pat', _, vspecs, envinner, tpenv = + TcMatchPattern cenv bindPatTy env tpenv pat None UnifyTypes cenv env m inputExprTy bindPatTy @@ -2087,84 +3204,117 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = let envinner = { envinner with eIsControlFlow = true } tcSequenceExprBody envinner genOuterTy tpenv innerComp - let mBind = - match spBind with + let mBind = + match spBind with | DebugPointAtBinding.Yes m -> m.NoteSourceConstruct(NotedSourceConstruct.Binding) | _ -> inputExpr.Range let inputExprMark = inputExpr.Range - let matchv, matchExpr = compileSeqExprMatchClauses cenv envinner inputExprMark (pat', vspecs) innerExpr (Some inputExpr) bindPatTy genOuterTy + let matchv, matchExpr = + compileSeqExprMatchClauses cenv envinner inputExprMark (pat', vspecs) innerExpr (Some inputExpr) bindPatTy genOuterTy let consumeExpr = mkLambda mBind matchv (matchExpr, genOuterTy) // The 'mBind' is attached to the lambda Some(mkSeqUsing cenv env wholeExprMark bindPatTy genOuterTy inputExpr consumeExpr, tpenv) - | SynExpr.LetOrUseBang (range=m) -> - error(Error(FSComp.SR.tcUseForInSequenceExpression(), m)) + | SynExpr.LetOrUseBang(range = m) -> error (Error(FSComp.SR.tcUseForInSequenceExpression (), m)) - | SynExpr.Match (spMatch, expr, clauses, _m, _trivia) -> + | SynExpr.Match(spMatch, expr, clauses, _m, _trivia) -> 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 inputTy env tpenv pat cond - let envinner = - match sp with - | DebugPointAtTarget.Yes -> { envinner with eIsControlFlow = true } - | DebugPointAtTarget.No -> envinner - let innerExpr, tpenv = tcSequenceExprBody envinner genOuterTy tpenv innerComp - MatchClause(patR, condR, TTarget(vspecs, innerExpr, None), patR.Range), tpenv) + let tclauses, tpenv = + (tpenv, clauses) + ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, _, sp, _)) -> + let patR, condR, vspecs, envinner, tpenv = + TcMatchPattern cenv inputTy env tpenv pat cond + + let envinner = + match sp with + | DebugPointAtTarget.Yes -> { envinner with eIsControlFlow = true } + | DebugPointAtTarget.No -> envinner + + let innerExpr, tpenv = tcSequenceExprBody envinner genOuterTy tpenv innerComp + MatchClause(patR, condR, TTarget(vspecs, innerExpr, None), patR.Range), tpenv) let inputExprTy = tyOfExpr cenv.g inputExpr let inputExprMark = inputExpr.Range - let matchv, matchExpr = CompilePatternForMatchClauses cenv env inputExprMark inputExprMark true ThrowIncompleteMatchException (Some inputExpr) inputExprTy genOuterTy tclauses + + let matchv, matchExpr = + CompilePatternForMatchClauses + cenv + env + inputExprMark + inputExprMark + true + ThrowIncompleteMatchException + (Some inputExpr) + inputExprTy + genOuterTy + tclauses Some(mkLet spMatch inputExprMark matchv inputExpr matchExpr, tpenv) - | SynExpr.TryWith (innerTry,withList,mTryToWith,_spTry,_spWith,trivia) -> - if not(g.langVersion.SupportsFeature(LanguageFeature.TryWithInSeqExpression)) then - error(Error(FSComp.SR.tcTryIllegalInSequenceExpression(), mTryToWith)) + | SynExpr.TryWith(innerTry, withList, mTryToWith, _spTry, _spWith, trivia) -> + if not (g.langVersion.SupportsFeature(LanguageFeature.TryWithInSeqExpression)) then + error (Error(FSComp.SR.tcTryIllegalInSequenceExpression (), mTryToWith)) let env = { env with eIsControlFlow = true } - let tryExpr, tpenv = - let inner,tpenv = tcSequenceExprBody env genOuterTy tpenv innerTry + + let tryExpr, tpenv = + let inner, tpenv = tcSequenceExprBody env genOuterTy tpenv innerTry mkSeqDelayedExpr mTryToWith inner, tpenv // Compile the pattern twice, once as a filter with all succeeding targets returning "1", and once as a proper catch block. - let clauses, tpenv = - (tpenv, withList) ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, m, sp, _)) -> - let patR, condR, vspecs, envinner, tpenv = TcMatchPattern cenv g.exn_ty env tpenv pat cond + let clauses, tpenv = + (tpenv, withList) + ||> List.mapFold (fun tpenv (SynMatchClause(pat, cond, innerComp, m, sp, _)) -> + let patR, condR, vspecs, envinner, tpenv = + TcMatchPattern cenv g.exn_ty env tpenv pat cond + let envinner = match sp with | DebugPointAtTarget.Yes -> { envinner with eIsControlFlow = true } | DebugPointAtTarget.No -> envinner + let matchBody, tpenv = tcSequenceExprBody envinner genOuterTy tpenv innerComp - let handlerClause = MatchClause(patR, condR, TTarget(vspecs, matchBody, None), patR.Range) - let filterClause = MatchClause(patR, condR, TTarget([], Expr.Const(Const.Int32 1,m,g.int_ty), None), patR.Range) - (handlerClause,filterClause), tpenv) + + let handlerClause = + MatchClause(patR, condR, TTarget(vspecs, matchBody, None), patR.Range) + + let filterClause = + MatchClause(patR, condR, TTarget([], Expr.Const(Const.Int32 1, m, g.int_ty), None), patR.Range) + + (handlerClause, filterClause), tpenv) let handlers, filterClauses = List.unzip clauses let withRange = trivia.WithToEndRange - let v1, filterExpr = CompilePatternForMatchClauses cenv env withRange withRange true FailFilter None g.exn_ty g.int_ty filterClauses - let v2, handlerExpr = CompilePatternForMatchClauses cenv env withRange withRange true FailFilter None g.exn_ty genOuterTy handlers + + let v1, filterExpr = + CompilePatternForMatchClauses cenv env withRange withRange true FailFilter None g.exn_ty g.int_ty filterClauses + + let v2, handlerExpr = + CompilePatternForMatchClauses cenv env withRange withRange true FailFilter None g.exn_ty genOuterTy handlers let filterLambda = mkLambda filterExpr.Range v1 (filterExpr, genOuterTy) let handlerLambda = mkLambda handlerExpr.Range v2 (handlerExpr, genOuterTy) - let combinatorExpr = mkSeqTryWith cenv env mTryToWith genOuterTy tryExpr filterLambda handlerLambda - Some (combinatorExpr,tpenv) + let combinatorExpr = + mkSeqTryWith cenv env mTryToWith genOuterTy tryExpr filterLambda handlerLambda + + Some(combinatorExpr, tpenv) - | SynExpr.YieldOrReturnFrom ((isYield, _), synYieldExpr, m) -> + | SynExpr.YieldOrReturnFrom((isYield, _), synYieldExpr, m) -> let env = { env with eIsControlFlow = false } let resultExpr, genExprTy, tpenv = TcExprOfUnknownType cenv env tpenv synYieldExpr - if not isYield then errorR(Error(FSComp.SR.tcUseYieldBangForMultipleResults(), m)) + if not isYield then + errorR (Error(FSComp.SR.tcUseYieldBangForMultipleResults (), m)) AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace genOuterTy genExprTy - let resultExpr = mkCoerceExpr(resultExpr, genOuterTy, m, genExprTy) + let resultExpr = mkCoerceExpr (resultExpr, genOuterTy, m, genExprTy) let resultExpr = if IsControlFlowExpression synYieldExpr then @@ -2174,11 +3324,12 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = Some(resultExpr, tpenv) - | SynExpr.YieldOrReturn ((isYield, _), synYieldExpr, m) -> + | SynExpr.YieldOrReturn((isYield, _), synYieldExpr, m) -> let env = { env with eIsControlFlow = false } let genResultTy = NewInferenceType g - if not isYield then errorR(Error(FSComp.SR.tcSeqResultsUseYield(), m)) + if not isYield then + errorR (Error(FSComp.SR.tcSeqResultsUseYield (), m)) UnifyTypes cenv env m genOuterTy (mkSeqTy cenv.g genResultTy) @@ -2192,30 +3343,34 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = else mkDebugPoint m resultExpr - Some(resultExpr, tpenv ) + Some(resultExpr, tpenv) | _ -> None - + and tcSequenceExprBody env (genOuterTy: TType) tpenv comp = - let res, tpenv = tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv comp - match res with - | Choice1Of2 expr -> - expr, tpenv - | Choice2Of2 stmt -> + let res, tpenv = tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv comp + + match res with + | Choice1Of2 expr -> expr, tpenv + | Choice2Of2 stmt -> let m = comp.Range let resExpr = Expr.Sequential(stmt, mkSeqEmpty cenv env m genOuterTy, NormalSeq, m) resExpr, tpenv and tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv comp = - match tryTcSequenceExprBody env genOuterTy tpenv comp with - | Some (expr, tpenv) -> Choice1Of2 expr, tpenv - | None -> + match tryTcSequenceExprBody env genOuterTy tpenv comp with + | Some(expr, tpenv) -> Choice1Of2 expr, tpenv + | None -> - let env = { env with eContextInfo = ContextInfo.SequenceExpression genOuterTy } + let env = + { env with + eContextInfo = ContextInfo.SequenceExpression genOuterTy + } if enableImplicitYield then let hasTypeUnit, expr, tpenv = TryTcStmt cenv env tpenv comp - if hasTypeUnit then + + if hasTypeUnit then Choice2Of2 expr, tpenv else let genResultTy = NewInferenceType g @@ -2224,7 +3379,10 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = let expr, tpenv = TcExprFlex cenv flex true genResultTy env tpenv comp let exprTy = tyOfExpr cenv.g expr AddCxTypeMustSubsumeType env.eContextInfo env.DisplayEnv cenv.css mExpr NoTrace genResultTy exprTy - let resExpr = mkCallSeqSingleton cenv.g mExpr genResultTy (mkCoerceExpr(expr, genResultTy, mExpr, exprTy)) + + let resExpr = + mkCallSeqSingleton cenv.g mExpr genResultTy (mkCoerceExpr (expr, genResultTy, mExpr, exprTy)) + Choice1Of2 resExpr, tpenv else let stmt, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv comp @@ -2236,28 +3394,32 @@ let TcSequenceExpression (cenv: cenv) env tpenv comp (overallTy: OverallTy) m = let TcSequenceExpressionEntry (cenv: cenv) env (overallTy: OverallTy) tpenv (hasBuilder, comp) m = match RewriteRangeExpr comp with - | Some replacementExpr -> - TcExpr cenv overallTy env tpenv replacementExpr + | Some replacementExpr -> TcExpr cenv overallTy env tpenv replacementExpr | None -> - let implicitYieldEnabled = cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield + let implicitYieldEnabled = + cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield - let validateObjectSequenceOrRecordExpression = not implicitYieldEnabled + let validateObjectSequenceOrRecordExpression = not implicitYieldEnabled - match comp with - | SynExpr.New _ -> - errorR(Error(FSComp.SR.tcInvalidObjectExpressionSyntaxForm(), m)) - | SimpleSemicolonSequence cenv false _ when validateObjectSequenceOrRecordExpression -> - errorR(Error(FSComp.SR.tcInvalidObjectSequenceOrRecordExpression(), m)) - | _ -> - () + match comp with + | SynExpr.New _ -> + try + TcExprUndelayed cenv overallTy env tpenv comp |> ignore + with RecoverableException e -> + errorRecovery e m + + errorR (Error(FSComp.SR.tcInvalidObjectExpressionSyntaxForm (), m)) + | SimpleSemicolonSequence cenv false _ when validateObjectSequenceOrRecordExpression -> + errorR (Error(FSComp.SR.tcInvalidObjectSequenceOrRecordExpression (), m)) + | _ -> () - if not hasBuilder && not cenv.g.compilingFSharpCore then - error(Error(FSComp.SR.tcInvalidSequenceExpressionSyntaxForm(), m)) - - TcSequenceExpression cenv env tpenv comp overallTy m + if not hasBuilder && not cenv.g.compilingFSharpCore then + error (Error(FSComp.SR.tcInvalidSequenceExpressionSyntaxForm (), m)) -let TcArrayOrListComputedExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (isArray, comp) m = + TcSequenceExpression cenv env tpenv comp overallTy m + +let TcArrayOrListComputedExpression (cenv: cenv) env (overallTy: OverallTy) tpenv (isArray, comp) m = let g = cenv.g // The syntax '[ n .. m ]' and '[ n .. step .. m ]' is not really part of array or list syntax. @@ -2265,7 +3427,7 @@ let TcArrayOrListComputedExpression (cenv: cenv) env (overallTy: OverallTy) tpen // // The elaborated form of '[ n .. m ]' is 'List.ofSeq (seq (op_Range n m))' and this shouldn't change match RewriteRangeExpr comp with - | Some replacementExpr -> + | Some replacementExpr -> let genCollElemTy = NewInferenceType g let genCollTy = (if isArray then mkArrayType else mkListTy) cenv.g genCollElemTy @@ -2276,87 +3438,131 @@ let TcArrayOrListComputedExpression (cenv: cenv) env (overallTy: OverallTy) tpen let expr, tpenv = TcExpr cenv (MustEqual exprTy) env tpenv replacementExpr - let expr = - if cenv.g.compilingFSharpCore then - expr - else + let expr = + if cenv.g.compilingFSharpCore then + expr + else // We add a call to 'seq ... ' to make sure sequence expression compilation gets applied to the contents of the // comprehension. But don't do this in FSharp.Core.dll since 'seq' may not yet be defined. mkCallSeq cenv.g m genCollElemTy expr - - let expr = mkCoerceExpr(expr, exprTy, expr.Range, overallTy.Commit) - let expr = - if isArray then + let expr = mkCoerceExpr (expr, exprTy, expr.Range, overallTy.Commit) + + let expr = + if isArray then mkCallSeqToArray cenv.g m genCollElemTy expr - else + else mkCallSeqToList cenv.g m genCollElemTy expr + expr, tpenv | None -> - // LanguageFeatures.ImplicitYield do not require this validation - let implicitYieldEnabled = cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield - let validateExpressionWithIfRequiresParenthesis = not implicitYieldEnabled - let acceptDeprecatedIfThenExpression = not implicitYieldEnabled + // LanguageFeatures.ImplicitYield do not require this validation + let implicitYieldEnabled = + cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield + + let validateExpressionWithIfRequiresParenthesis = not implicitYieldEnabled + let acceptDeprecatedIfThenExpression = not implicitYieldEnabled - match comp with - | SimpleSemicolonSequence cenv acceptDeprecatedIfThenExpression elems -> match comp with - | SimpleSemicolonSequence cenv false _ -> () - | _ when validateExpressionWithIfRequiresParenthesis -> errorR(Deprecated(FSComp.SR.tcExpressionWithIfRequiresParenthesis(), m)) - | _ -> () + | SimpleSemicolonSequence cenv acceptDeprecatedIfThenExpression elems -> + match comp with + | SimpleSemicolonSequence cenv false _ -> () + | _ when validateExpressionWithIfRequiresParenthesis -> + errorR (Deprecated(FSComp.SR.tcExpressionWithIfRequiresParenthesis (), m)) + | _ -> () - let replacementExpr = - if isArray then - // This are to improve parsing/processing speed for parser tables by converting to an array blob ASAP - let nelems = elems.Length - if nelems > 0 && List.forall (function SynExpr.Const (SynConst.UInt16 _, _) -> true | _ -> false) elems - then SynExpr.Const (SynConst.UInt16s (Array.ofList (List.map (function SynExpr.Const (SynConst.UInt16 x, _) -> x | _ -> failwith "unreachable") elems)), m) - elif nelems > 0 && List.forall (function SynExpr.Const (SynConst.Byte _, _) -> true | _ -> false) elems - then SynExpr.Const (SynConst.Bytes (Array.ofList (List.map (function SynExpr.Const (SynConst.Byte x, _) -> x | _ -> failwith "unreachable") elems), SynByteStringKind.Regular, m), m) - else SynExpr.ArrayOrList (isArray, elems, m) - else - if cenv.g.langVersion.SupportsFeature(LanguageFeature.ReallyLongLists) then - SynExpr.ArrayOrList (isArray, elems, m) - else - if elems.Length > 500 then - error(Error(FSComp.SR.tcListLiteralMaxSize(), m)) - SynExpr.ArrayOrList (isArray, elems, m) + let replacementExpr = + if isArray then + // This are to improve parsing/processing speed for parser tables by converting to an array blob ASAP + let nelems = elems.Length + + if + nelems > 0 + && List.forall + (function + | SynExpr.Const(SynConst.UInt16 _, _) -> true + | _ -> false) + elems + then + SynExpr.Const( + SynConst.UInt16s( + Array.ofList ( + List.map + (function + | SynExpr.Const(SynConst.UInt16 x, _) -> x + | _ -> failwith "unreachable") + elems + ) + ), + m + ) + elif + nelems > 0 + && List.forall + (function + | SynExpr.Const(SynConst.Byte _, _) -> true + | _ -> false) + elems + then + SynExpr.Const( + SynConst.Bytes( + Array.ofList ( + List.map + (function + | SynExpr.Const(SynConst.Byte x, _) -> x + | _ -> failwith "unreachable") + elems + ), + SynByteStringKind.Regular, + m + ), + m + ) + else + SynExpr.ArrayOrList(isArray, elems, m) + else if cenv.g.langVersion.SupportsFeature(LanguageFeature.ReallyLongLists) then + SynExpr.ArrayOrList(isArray, elems, m) + else + if elems.Length > 500 then + error (Error(FSComp.SR.tcListLiteralMaxSize (), m)) - TcExprUndelayed cenv overallTy env tpenv replacementExpr - | _ -> + SynExpr.ArrayOrList(isArray, elems, m) - let genCollElemTy = NewInferenceType g + TcExprUndelayed cenv overallTy env tpenv replacementExpr + | _ -> - let genCollTy = (if isArray then mkArrayType else mkListTy) cenv.g genCollElemTy + let genCollElemTy = NewInferenceType g - // Propagating type directed conversion, e.g. for - // let x : seq = [ yield 1; if true then yield 2 ] - TcPropagatingExprLeafThenConvert cenv overallTy genCollTy env (* canAdhoc *) m (fun () -> - - let exprTy = mkSeqTy cenv.g genCollElemTy + let genCollTy = (if isArray then mkArrayType else mkListTy) cenv.g genCollElemTy - // Check the comprehension - let expr, tpenv = TcSequenceExpression cenv env tpenv comp (MustEqual exprTy) m + // Propagating type directed conversion, e.g. for + // let x : seq = [ yield 1; if true then yield 2 ] + TcPropagatingExprLeafThenConvert cenv overallTy genCollTy env (* canAdhoc *) m (fun () -> - let expr = mkCoerceIfNeeded cenv.g exprTy (tyOfExpr cenv.g expr) expr + let exprTy = mkSeqTy cenv.g genCollElemTy - let expr = - if cenv.g.compilingFSharpCore then - //warning(Error(FSComp.SR.fslibUsingComputedListOrArray(), expr.Range)) - expr - else - // We add a call to 'seq ... ' to make sure sequence expression compilation gets applied to the contents of the - // comprehension. But don't do this in FSharp.Core.dll since 'seq' may not yet be defined. - mkCallSeq cenv.g m genCollElemTy expr - - let expr = mkCoerceExpr(expr, exprTy, expr.Range, overallTy.Commit) + // Check the comprehension + let expr, tpenv = TcSequenceExpression cenv env tpenv comp (MustEqual exprTy) m - let expr = - if isArray then - mkCallSeqToArray cenv.g m genCollElemTy expr - else - mkCallSeqToList cenv.g m genCollElemTy expr - - expr, tpenv) + let expr = mkCoerceIfNeeded cenv.g exprTy (tyOfExpr cenv.g expr) expr + + let expr = + if cenv.g.compilingFSharpCore then + //warning(Error(FSComp.SR.fslibUsingComputedListOrArray(), expr.Range)) + expr + else + // We add a call to 'seq ... ' to make sure sequence expression compilation gets applied to the contents of the + // comprehension. But don't do this in FSharp.Core.dll since 'seq' may not yet be defined. + mkCallSeq cenv.g m genCollElemTy expr + + let expr = mkCoerceExpr (expr, exprTy, expr.Range, overallTy.Commit) + + let expr = + if isArray then + mkCallSeqToArray cenv.g m genCollElemTy expr + else + mkCallSeqToList cenv.g m genCollElemTy expr + + expr, tpenv) diff --git a/src/Compiler/Checking/CheckDeclarations.fs b/src/Compiler/Checking/CheckDeclarations.fs index 1a958832ce6..469b1ab4ee3 100644 --- a/src/Compiler/Checking/CheckDeclarations.fs +++ b/src/Compiler/Checking/CheckDeclarations.fs @@ -866,7 +866,8 @@ module AddAugmentationDeclarations = let ShouldAugmentUnion (g: TcGlobals) (tycon: Tycon) = g.langVersion.SupportsFeature LanguageFeature.UnionIsPropertiesVisible && - HasDefaultAugmentationAttribute g (mkLocalTyconRef tycon) + HasDefaultAugmentationAttribute g (mkLocalTyconRef tycon) && + tycon.UnionCasesArray.Length > 1 let AddUnionAugmentationValues (cenv: cenv) (env: TcEnv) tycon = let tcref = mkLocalTyconRef tycon @@ -1039,7 +1040,7 @@ module MutRecBindingChecking = let innerState = (None, envForTycon, tpenv, recBindIdx, uncheckedBindsRev) [Phase2AIncrClassCtor (staticCtorInfo, None)], innerState - | Some (SynMemberDefn.ImplicitCtor (vis, Attributes attrs, SynSimplePats.SimplePats(pats=spats), thisIdOpt, xmlDoc, m,_)), ContainerInfo(_, Some memberContainerInfo) -> + | Some (SynMemberDefn.ImplicitCtor (vis, Attributes attrs, pat, thisIdOpt, xmlDoc, m,_)), ContainerInfo(_, Some memberContainerInfo) -> let (MemberOrValContainerInfo(tcref, _, baseValOpt, safeInitInfo, _)) = memberContainerInfo @@ -1050,7 +1051,7 @@ module MutRecBindingChecking = let staticCtorInfo = TcStaticImplicitCtorInfo_Phase2A(cenv, envForTycon, tcref, m, copyOfTyconTypars) // Phase2A: make incrCtorInfo - ctorv, thisVal etc, type depends on argty(s) - let incrCtorInfo = TcImplicitCtorInfo_Phase2A(cenv, envForTycon, tpenv, tcref, vis, attrs, spats, thisIdOpt, baseValOpt, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy, xmlDoc) + let incrCtorInfo = TcImplicitCtorInfo_Phase2A(cenv, envForTycon, tpenv, tcref, vis, attrs, pat, thisIdOpt, baseValOpt, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy, xmlDoc) // Phase2A: Add copyOfTyconTypars from incrCtorInfo - or from tcref let envForTycon = AddDeclaredTypars CheckForDuplicateTypars staticCtorInfo.IncrCtorDeclaredTypars envForTycon @@ -1203,11 +1204,13 @@ module MutRecBindingChecking = if cenv.g.langVersion.SupportsFeature(LanguageFeature.CSharpExtensionAttributeNotRequired) then tyconOpt |> Option.map (fun tycon -> - tryAddExtensionAttributeIfNotAlreadyPresent + tryAddExtensionAttributeIfNotAlreadyPresentForType + g (fun tryFindExtensionAttribute -> tycon.MembersOfFSharpTyconSorted |> Seq.tryPick (fun m -> tryFindExtensionAttribute m.Attribs) ) + envForTycon.eModuleOrNamespaceTypeAccumulator tycon ) else @@ -1332,10 +1335,10 @@ module MutRecBindingChecking = // Phase2B: typecheck the argument to an 'inherits' call and build the new object expr for the inherit-call | Phase2AInherit (synBaseTy, arg, baseValOpt, m) -> - let baseTy, tpenv = TcType cenv NoNewTypars CheckCxs ItemOccurence.Use WarnOnIWSAM.Yes envInstance tpenv synBaseTy - let baseTy = baseTy |> convertToTypeWithMetadataIfPossible g let inheritsExpr, tpenv = - try + try + let baseTy, tpenv = TcType cenv NoNewTypars CheckCxs ItemOccurence.Use WarnOnIWSAM.Yes envInstance tpenv synBaseTy + let baseTy = baseTy |> convertToTypeWithMetadataIfPossible g TcNewExpr cenv envInstance tpenv baseTy (Some synBaseTy.Range) true arg m with RecoverableException e -> errorRecovery e m @@ -1437,7 +1440,25 @@ module MutRecBindingChecking = let innerState = (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) Phase2BMember rbind.RecBindingInfo.Index, innerState) - + + let tyconOpt = + if not(cenv.g.langVersion.SupportsFeature(LanguageFeature.CSharpExtensionAttributeNotRequired)) then + tyconOpt + else + // We need to redo this check, which already happened in TcMutRecBindings_Phase2A_CreateRecursiveValuesAndCheckArgumentPatterns + // Because the environment is being reset in the case of recursive modules. + tyconOpt + |> Option.map (fun tycon -> + tryAddExtensionAttributeIfNotAlreadyPresentForType + g + (fun tryFindExtensionAttribute -> + tycon.MembersOfFSharpTyconSorted + |> Seq.tryPick (fun m -> tryFindExtensionAttribute m.Attribs) + ) + envForTycon.eModuleOrNamespaceTypeAccumulator + tycon + ) + let defnBs = MutRecShape.Tycon (TyconBindingsPhase2B(tyconOpt, tcref, defnBs)) let outerState = (tpenv, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable, envNonRec) defnBs, outerState) @@ -1906,9 +1927,10 @@ module MutRecBindingChecking = let private ReportErrorOnStaticClass (synMembers: SynMemberDefn list) = for mem in synMembers do match mem with - | SynMemberDefn.ImplicitCtor(ctorArgs = SynSimplePats.SimplePats(pats = pats)) when (not pats.IsEmpty) -> - for pat in pats do - warning(Error(FSComp.SR.chkConstructorWithArgumentsOnStaticClasses(), pat.Range)) + | SynMemberDefn.ImplicitCtor(ctorArgs = pat) -> + match pat with + | SynPat.Paren(innerPat, _) -> warning(Error(FSComp.SR.chkConstructorWithArgumentsOnStaticClasses(), innerPat.Range)) + | _ -> () | SynMemberDefn.Member(SynBinding(valData = SynValData(memberFlags = Some memberFlags)), m) when memberFlags.MemberKind = SynMemberKind.Constructor -> warning(Error(FSComp.SR.chkAdditionalConstructorOnStaticClasses(), m)) | SynMemberDefn.Member(SynBinding(valData = SynValData(memberFlags = Some memberFlags)), m) when memberFlags.IsInstance -> @@ -2475,7 +2497,7 @@ module TcExceptionDeclarations = let TcExnSignature (cenv: cenv) envInitial parent tpenv (SynExceptionSig(exnRepr=core; members=aug), scopem) = match core with - | SynExceptionDefnRepr(caseName = SynUnionCase(ident = SynIdent(ident, _))) when ident.idText = "" -> + | SynExceptionDefnRepr(caseName = SynUnionCase(ident = SynIdent(ident, _))) when String.IsNullOrEmpty(ident.idText) -> [], [], None, envInitial | _ -> let g = cenv.g @@ -2603,8 +2625,8 @@ module EstablishTypeDefinitionCores = match implicitCtorSynPats with | None -> () - | Some spats -> - let ctorArgNames, patEnv = TcSimplePatsOfUnknownType cenv true NoCheckCxs env tpenv spats + | Some pat -> + let ctorArgNames, patEnv, _ = TcSimplePatsOfUnknownType cenv true NoCheckCxs env tpenv pat let (TcPatLinearEnv(_, names, _)) = patEnv @@ -2770,19 +2792,24 @@ module EstablishTypeDefinitionCores = match synTyconRepr with | SynTypeDefnSimpleRepr.General (SynTypeDefnKind.Delegate (_ty, arity), _, _, _, _, _, _, _) -> arity.ArgNames | SynTypeDefnSimpleRepr.General (SynTypeDefnKind.Unspecified, _, _, _, _, _, Some synPats, _) -> - let rec patName (p: SynSimplePat) = + let rec patName (p: SynPat) = match p with - | SynSimplePat.Id (id, _, _, _, _, _) -> id.idText - | SynSimplePat.Typed(pat, _, _) -> patName pat - | SynSimplePat.Attrib(pat, _, _) -> patName pat + | SynPat.Named(ident = (SynIdent(id, _))) -> Some id.idText + | SynPat.Typed(pat = pat) + | SynPat.Attrib(pat = pat) -> patName pat + | _ -> None - let rec pats (p: SynSimplePats) = - match p with - | SynSimplePats.SimplePats (pats = ps) -> ps + let getSimplePats (pat: SynPat) = + match pat with + | SynPat.Paren(pat, _) -> + match pat with + | SynPat.Tuple(false, pats, _, _) -> pats + | pat -> [pat] + | _ -> [] let patNames = - pats synPats - |> List.map patName + getSimplePats synPats + |> List.choose patName patNames | _ -> [] @@ -2915,7 +2942,7 @@ module EstablishTypeDefinitionCores = | Some (tc, args, m) -> let ad = envinner.AccessRights match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInType OpenQualified envinner.NameEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.Yes with - | Result (_, tcrefBeforeStaticArguments) when + | Result (_, tcrefBeforeStaticArguments, _) when tcrefBeforeStaticArguments.IsProvided && not tcrefBeforeStaticArguments.IsErased -> @@ -3357,14 +3384,13 @@ module EstablishTypeDefinitionCores = | rf :: _ -> errorR (Error(FSComp.SR.tcInterfaceTypesAndDelegatesCannotContainFields(), rf.Range)) | _ -> () - let primaryConstructorInDelegateCheck(implicitCtorSynPats : SynSimplePats option) = + let primaryConstructorInDelegateCheck(implicitCtorSynPats : SynPat option) = match implicitCtorSynPats with | None -> () - | Some spats -> - let ctorArgNames, _ = TcSimplePatsOfUnknownType cenv true CheckCxs envinner tpenv spats + | Some pat -> + let ctorArgNames, _, _ = TcSimplePatsOfUnknownType cenv true CheckCxs envinner tpenv pat if not ctorArgNames.IsEmpty then - match spats with - | SynSimplePats.SimplePats(range = m) -> errorR (Error(FSComp.SR.parsOnlyClassCanTakeValueArguments(), m)) + errorR (Error(FSComp.SR.parsOnlyClassCanTakeValueArguments(), pat.Range)) let envinner = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars m) envinner let envinner = MakeInnerEnvForTyconRef envinner thisTyconRef false @@ -3518,9 +3544,9 @@ module EstablishTypeDefinitionCores = match implicitCtorSynPats with | None -> () - | Some spats -> - if tycon.IsFSharpStructOrEnumTycon then - let ctorArgNames, patEnv = TcSimplePatsOfUnknownType cenv true CheckCxs envinner tpenv spats + | Some pat -> + if tycon.IsFSharpStructOrEnumTycon then + let ctorArgNames, patEnv, _ = TcSimplePatsOfUnknownType cenv true CheckCxs envinner tpenv pat let (TcPatLinearEnv(_, names, _)) = patEnv @@ -4091,11 +4117,11 @@ module TcDeclarations = | _ -> let resInfo = TypeNameResolutionStaticArgsInfo.FromTyArgs synTypars.Length - let _, tcref = + let tcref = match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.Binding OpenQualified envForDecls.NameEnv ad longPath resInfo PermitDirectReferenceToGeneratedType.No with | Result res -> // Update resolved type parameters with the names from the source. - let _, tcref = res + let _, tcref, _ = res if tcref.TyparsNoRange.Length = synTypars.Length then (tcref.TyparsNoRange, synTypars) ||> List.zip @@ -4105,11 +4131,12 @@ module TcDeclarations = typar.SetIdent(untypedIdent) ) - res - | res when inSig && List.isSingleton longPath -> - errorR(Deprecated(FSComp.SR.tcReservedSyntaxForAugmentation(), m)) - ForceRaise res - | res -> ForceRaise res + tcref + + | Exception exn -> + if inSig && List.isSingleton longPath then + errorR(Deprecated(FSComp.SR.tcReservedSyntaxForAugmentation(), m)) + ForceRaise (Exception exn) tcref let isInterfaceOrDelegateOrEnum = @@ -4285,7 +4312,7 @@ module TcDeclarations = // Convert auto properties to let bindings in the pre-list let rec preAutoProps memb = match memb with - | SynMemberDefn.AutoProperty(ident = id) when id.idText = "" -> [] + | SynMemberDefn.AutoProperty(ident = id) when String.IsNullOrEmpty(id.idText) -> [] | SynMemberDefn.AutoProperty(attributes=Attributes attribs; isStatic=isStatic; ident=id; typeOpt=tyOpt; propKind=propKind; xmlDoc=xmlDoc; synExpr=synExpr; range=mWholeAutoProp) -> // Only the keep the field-targeted attributes let attribs = attribs |> List.filter (fun a -> match a.Target with Some t when t.idText = "field" -> true | _ -> false) @@ -4313,7 +4340,7 @@ module TcDeclarations = // Convert auto properties to member bindings in the post-list let rec postAutoProps memb = match memb with - | SynMemberDefn.AutoProperty(ident = id) when id.idText = "" -> [] + | SynMemberDefn.AutoProperty(ident = id) when String.IsNullOrEmpty(id.idText) -> [] | SynMemberDefn.AutoProperty(attributes=Attributes attribs; isStatic=isStatic; ident=id; typeOpt=tyOpt; propKind=propKind; memberFlags=memberFlags; memberFlagsForSet=memberFlagsForSet; xmlDoc=xmlDoc; accessibility=access; trivia = { GetSetKeywords = mGetSetOpt }) -> let mMemberPortion = id.idRange // Only the keep the non-field-targeted attributes @@ -4420,7 +4447,7 @@ module TcDeclarations = let implicitCtorSynPats = members |> List.tryPick (function - | SynMemberDefn.ImplicitCtor (ctorArgs = SynSimplePats.SimplePats _ as spats) -> Some spats + | SynMemberDefn.ImplicitCtor (ctorArgs = pat) -> Some pat | _ -> None) // An ugly bit of code to pre-determine if a type has a nullary constructor, prior to establishing the @@ -4429,7 +4456,7 @@ module TcDeclarations = members |> List.exists (function | SynMemberDefn.Member(memberDefn=SynBinding(valData=SynValData(memberFlags=Some memberFlags); headPat = SynPatForConstructorDecl SynPatForNullaryArgs)) -> memberFlags.MemberKind=SynMemberKind.Constructor - | SynMemberDefn.ImplicitCtor (ctorArgs = SynSimplePats.SimplePats(pats = spats)) -> isNil spats + | SynMemberDefn.ImplicitCtor (ctorArgs = SynPat.Const(SynConst.Unit, _)) -> true | _ -> false) let repr = SynTypeDefnSimpleRepr.General(kind, inherits, slotsigs, fields, isConcrete, isIncrClass, implicitCtorSynPats, m) let isAtOriginalTyconDefn = not (isAugmentationTyconDefnRepr repr) @@ -4535,16 +4562,20 @@ module TcDeclarations = |> List.map (function | MutRecShape.Tycon (Some tycon, bindings) -> let tycon = - tryAddExtensionAttributeIfNotAlreadyPresent + tryAddExtensionAttributeIfNotAlreadyPresentForType + g (fun tryFindExtensionAttribute -> tycon.MembersOfFSharpTyconSorted |> Seq.tryPick (fun m -> tryFindExtensionAttribute m.Attribs) ) + envFinal.eModuleOrNamespaceTypeAccumulator tycon + MutRecShape.Tycon (Some tycon, bindings) | MutRecShape.Module ((MutRecDefnsPhase2DataForModule(moduleOrNamespaceType, entity), env), shapes) -> let entity = - tryAddExtensionAttributeIfNotAlreadyPresent + tryAddExtensionAttributeIfNotAlreadyPresentForModule + g (fun tryFindExtensionAttribute -> moduleOrNamespaceType.Value.AllValsAndMembers |> Seq.filter(fun v -> v.IsModuleBinding) @@ -4666,8 +4697,28 @@ module TcDeclarations = let envForTycon = AddDeclaredTypars CheckForDuplicateTypars declaredTyconTypars envForDecls let envForTycon = MakeInnerEnvForTyconRef envForTycon tcref (declKind = ExtrinsicExtensionBinding) - TcTyconMemberSpecs cenv envForTycon (TyconContainerInfo(innerParent, tcref, declaredTyconTypars, NoSafeInitInfo)) declKind tpenv members) + let vals, env = TcTyconMemberSpecs cenv envForTycon (TyconContainerInfo(innerParent, tcref, declaredTyconTypars, NoSafeInitInfo)) declKind tpenv members + if not(cenv.g.langVersion.SupportsFeature(LanguageFeature.CSharpExtensionAttributeNotRequired)) then + vals, env + else + // Check if any of the vals has the `[]` attribute + // If this is the case, add it to the type in the env. + let extensionAttributeOnVals = + vals + |> List.tryPick (fun v -> tryFindExtensionAttribute g v.Attribs) + + let typeEntity = + envForTycon.eModuleOrNamespaceTypeAccumulator.Value.AllEntitiesByLogicalMangledName.TryFind(tcref.LogicalName) + + match extensionAttributeOnVals, typeEntity with + | Some extensionAttribute, Some typeEntity -> + if Option.isNone (tryFindExtensionAttribute g typeEntity.Attribs) then + typeEntity.entity_attribs <- extensionAttribute :: typeEntity.Attribs + | _ -> () + vals, env + + ) // Do this for each 'val' declaration in a module (fun envForDecls (containerInfo, valSpec) -> let tpenv = emptyUnscopedTyparEnv @@ -4707,18 +4758,6 @@ module TcDeclarations = // Updates the types of the modules to contain the contents so far, which now includes values and members MutRecBindingChecking.TcMutRecDefns_UpdateModuleContents mutRecNSInfo mutRecDefnsAfterVals - // Generate the union augmentation values for all tycons. - // TODO nullness :: this is the handling of DU .Is* properties WITHIN signature files. - // Watch https://github.com/fsharp/fslang-design/discussions - //(envMutRec, mutRecDefnsAfterCore) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls ((tyconCore, _, _), tyconOpt, _, _, _) -> - // let (MutRecDefnsPhase1DataForTycon (isAtOriginalTyconDefn=isAtOriginalTyconDefn)) = tyconCore - // match tyconOpt with - // | Some tycon when isAtOriginalTyconDefn -> - // if tycon.IsUnionTycon && AddAugmentationDeclarations.ShouldAugmentUnion cenv.g tycon then - // let vspecs = AddAugmentationDeclarations.AddUnionAugmentationValues cenv envForDecls tycon - // ignore vspecs - // | _ -> ()) - envMutRec //------------------------------------------------------------------------- @@ -5030,7 +5069,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem return ([], [], []), env, env | SynModuleDecl.Exception (SynExceptionDefn(SynExceptionDefnRepr(caseName = SynUnionCase(ident = SynIdent(id, _))) as exnRepr, withKeyword, ms, mExDefn), m) -> - if id.idText = "" then + if String.IsNullOrEmpty(id.idText) then return ([], [], []), env, env else let edef = SynExceptionDefn(exnRepr, withKeyword, desugarGetSetMembers ms, mExDefn) @@ -5139,7 +5178,8 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem // //[] //let PlusOne (a:int) = a + 1 - tryAddExtensionAttributeIfNotAlreadyPresent + tryAddExtensionAttributeIfNotAlreadyPresentForModule + g (fun tryFindExtensionAttribute -> match moduleContents with | ModuleOrNamespaceContents.TMDefs(defs) -> @@ -5533,7 +5573,7 @@ let CheckValueRestriction denvAtEnd infoReader rootSigOpt implFileTypePriorToSig // for example FSharp 1.0 3661. (match v.ValReprInfo with None -> true | Some tvi -> tvi.HasNoArgs)) then match ftyvs with - | tp :: _ -> errorR (ValueRestriction(denvAtEnd, infoReader, false, v, tp, v.Range)) + | tp :: _ -> errorR (ValueRestriction(denvAtEnd, infoReader, v, tp, v.Range)) | _ -> () mty.ModuleAndNamespaceDefinitions |> List.iter (fun v -> check v.ModuleOrNamespaceType) try check implFileTypePriorToSig with RecoverableException e -> errorRecovery e m @@ -5546,7 +5586,7 @@ let SolveInternalUnknowns g (cenv: cenv) denvAtEnd moduleContents extraAttribs = if (tp.Rigidity <> TyparRigidity.Rigid) && not tp.IsSolved then ChooseTyparSolutionAndSolve cenv.css denvAtEnd tp -let CheckModuleSignature g (cenv: cenv) m denvAtEnd rootSigOpt implFileTypePriorToSig implFileSpecPriorToSig moduleContents = +let CheckModuleSignature g (cenv: cenv) m denvAtEnd rootSigOpt implFileTypePriorToSig implFileSpecPriorToSig moduleContents fileName qualifiedNameOfFile = match rootSigOpt with | None -> // Deep copy the inferred type of the module @@ -5554,7 +5594,13 @@ let CheckModuleSignature g (cenv: cenv) m denvAtEnd rootSigOpt implFileTypePrior (implFileTypePriorToSigCopied, moduleContents) - | Some sigFileType -> + | Some sigFileType -> + use _ = + Activity.start "CheckDeclarations.CheckModuleSignature" + [| + Activity.Tags.fileName, fileName + Activity.Tags.qualifiedNameOfFile, qualifiedNameOfFile + |] // We want to show imperative type variables in any types in error messages at this late point let denv = { denvAtEnd with showInferenceTyparAnnotations=true } @@ -5680,7 +5726,7 @@ let CheckOneImplFile // Check the module matches the signature let implFileTy, implFileContents = conditionallySuppressErrorReporting (checkForErrors()) (fun () -> - CheckModuleSignature g cenv m denvAtEnd rootSigOpt implFileTypePriorToSig implFileSpecPriorToSig moduleContents) + CheckModuleSignature g cenv m denvAtEnd rootSigOpt implFileTypePriorToSig implFileSpecPriorToSig moduleContents fileName qualNameOfFile.Text) do conditionallySuppressErrorReporting (checkForErrors()) (fun () -> @@ -5700,6 +5746,12 @@ let CheckOneImplFile try let reportErrors = not (checkForErrors()) let tcVal = LightweightTcValForUsingInBuildMethodCall g + use _ = + Activity.start "PostTypeCheckSemanticChecks.CheckImplFile" + [| + Activity.Tags.fileName, fileName + Activity.Tags.qualifiedNameOfFile, qualNameOfFile.Text + |] PostTypeCheckSemanticChecks.CheckImplFile (g, cenv.amap, reportErrors, cenv.infoReader, env.eInternalsVisibleCompPaths, cenv.thisCcu, tcVal, envAtEnd.DisplayEnv, diff --git a/src/Compiler/Checking/CheckExpressions.fs b/src/Compiler/Checking/CheckExpressions.fs index ec76756ef5e..ebf81a3ecd8 100644 --- a/src/Compiler/Checking/CheckExpressions.fs +++ b/src/Compiler/Checking/CheckExpressions.fs @@ -94,7 +94,7 @@ exception UnionPatternsBindDifferentNames of range exception VarBoundTwice of Ident -exception ValueRestriction of DisplayEnv * InfoReader * bool * Val * Typar * range +exception ValueRestriction of DisplayEnv * InfoReader * Val * Typar * range exception ValNotMutable of DisplayEnv * ValRef * range @@ -767,7 +767,7 @@ let TcConst (cenv: cenv) (overallTy: TType) m env synConst = | SynMeasure.One _ -> Measure.One | SynMeasure.Named(tc, m) -> let ad = env.eAccessRights - let _, tcref = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.Use OpenQualified env.eNameResEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) + 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.Const tcref @@ -3152,15 +3152,17 @@ let BuildRecdFieldSet g m objExpr (rfinfo: RecdFieldInfo) argExpr = // Helpers dealing with named and optional args at callsites //------------------------------------------------------------------------- +[] let (|BinOpExpr|_|) expr = match expr with - | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent opId, a, _), b, _) -> Some (opId, a, b) - | _ -> None + | SynExpr.App (_, _, SynExpr.App (_, _, SingleIdent opId, a, _), b, _) -> ValueSome (opId, a, b) + | _ -> ValueNone +[] let (|SimpleEqualsExpr|_|) expr = match expr with - | BinOpExpr(opId, a, b) when opId.idText = opNameEquals -> Some (a, b) - | _ -> None + | BinOpExpr(opId, a, b) when opId.idText = opNameEquals -> ValueSome (a, b) + | _ -> ValueNone /// Detect a named argument at a callsite let TryGetNamedArg expr = @@ -4120,7 +4122,8 @@ and TcConstraintWhereTyparSupportsMember cenv env newOk tpenv synSupportTys synM let g = cenv.g let traitInfo, tpenv = TcPseudoMemberSpec cenv newOk env synSupportTys tpenv synMemberSig m match traitInfo with - | TTrait(objTys, ".ctor", memberFlags, argTys, returnTy, _) when memberFlags.MemberKind = SynMemberKind.Constructor -> + | TTrait(tys=objTys; memberName=".ctor"; memberFlags=memberFlags; objAndArgTys=argTys; returnTyOpt=returnTy) + when memberFlags.MemberKind = SynMemberKind.Constructor -> match objTys, argTys with | [ty], [] when typeEquiv g ty (GetFSharpViewOfReturnType g returnTy) -> AddCxTypeMustSupportDefaultCtor env.DisplayEnv cenv.css m NoTrace ty @@ -4169,7 +4172,7 @@ and TcPseudoMemberSpec cenv newOk env synTypes tpenv synMemberSig m = let item = Item.OtherName (Some id, memberConstraintTy, None, None, id.idRange) CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurence.Use, env.AccessRights) - TTrait(tys, logicalCompiledName, memberFlags, argTys, returnTy, ref None), tpenv + TTrait(tys, logicalCompiledName, memberFlags, argTys, returnTy, ref None, ref None), tpenv | _ -> error(Error(FSComp.SR.tcInvalidConstraint(), m)) @@ -4508,7 +4511,7 @@ and TcLongIdentType kindOpt (cenv: cenv) newOk checkConstraints occ iwsam env tp let m = synLongId.Range let ad = env.eAccessRights - let tinstEnclosing, tcref = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver occ OpenQualified env.NameEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) + let tinstEnclosing, tcref, inst = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver occ OpenQualified env.NameEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) CheckIWSAM cenv env checkConstraints iwsam m tcref @@ -4522,7 +4525,7 @@ and TcLongIdentType kindOpt (cenv: cenv) newOk checkConstraints occ iwsam env tp | _, TyparKind.Measure -> TType_measure (Measure.Const tcref), tpenv | _, TyparKind.Type -> - TcTypeApp cenv newOk checkConstraints occ env tpenv m tcref tinstEnclosing [] + TcTypeApp cenv newOk checkConstraints occ env tpenv m tcref tinstEnclosing [] inst /// Some.Long.TypeName /// ty1 SomeLongTypeName @@ -4530,7 +4533,7 @@ and TcLongIdentAppType kindOpt (cenv: cenv) newOk checkConstraints occ iwsam env let (SynLongIdent(tc, _, _)) = longId let ad = env.eAccessRights - let tinstEnclosing, tcref = + let tinstEnclosing, tcref, inst = let tyResInfo = TypeNameResolutionStaticArgsInfo.FromTyArgs args.Length ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInType OpenQualified env.eNameResEnv ad tc tyResInfo PermitDirectReferenceToGeneratedType.No |> ForceRaise @@ -4549,7 +4552,7 @@ and TcLongIdentAppType kindOpt (cenv: cenv) newOk checkConstraints occ iwsam env | _, TyparKind.Type -> if postfix && tcref.Typars m |> List.exists (fun tp -> match tp.Kind with TyparKind.Measure -> true | _ -> false) then error(Error(FSComp.SR.tcInvalidUnitsOfMeasurePrefix(), m)) - TcTypeApp cenv newOk checkConstraints occ env tpenv m tcref tinstEnclosing args + TcTypeApp cenv newOk checkConstraints occ env tpenv m tcref tinstEnclosing args inst | _, TyparKind.Measure -> match args, postfix with @@ -4568,8 +4571,8 @@ and TcNestedAppType (cenv: cenv) newOk checkConstraints occ iwsam env tpenv synL let leftTy, tpenv = TcType cenv newOk checkConstraints occ iwsam env tpenv synLeftTy match leftTy with | AppTy g (tcref, tinst) -> - let tcref = ResolveTypeLongIdentInTyconRef cenv.tcSink cenv.nameResolver env.eNameResEnv (TypeNameResolutionInfo.ResolveToTypeRefs (TypeNameResolutionStaticArgsInfo.FromTyArgs args.Length)) ad m tcref longId - TcTypeApp cenv newOk checkConstraints occ env tpenv m tcref tinst args + let tcref, inst = ResolveTypeLongIdentInTyconRef cenv.tcSink cenv.nameResolver env.eNameResEnv (TypeNameResolutionInfo.ResolveToTypeRefs (TypeNameResolutionStaticArgsInfo.FromTyArgs args.Length)) ad m tcref longId + TcTypeApp cenv newOk checkConstraints occ env tpenv m tcref tinst args inst | _ -> error(Error(FSComp.SR.tcTypeHasNoNestedTypes(), m)) @@ -4994,7 +4997,7 @@ and TcProvidedTypeApp (cenv: cenv) env tpenv tcref args m = /// Note that the generic type may be a nested generic type List.ListEnumerator. /// In this case, 'argsR is only the instantiation of the suffix type arguments, and pathTypeArgs gives /// the prefix of type arguments. -and TcTypeApp (cenv: cenv) newOk checkConstraints occ env tpenv m tcref pathTypeArgs (synArgTys: SynType list) = +and TcTypeApp (cenv: cenv) newOk checkConstraints occ env tpenv m tcref pathTypeArgs (synArgTys: SynType list) (tinst: TypeInst) = let g = cenv.g CheckTyconAccessible cenv.amap m env.AccessRights tcref |> ignore CheckEntityAttributes g tcref m |> CommitOperationResult @@ -5005,16 +5008,22 @@ and TcTypeApp (cenv: cenv) newOk checkConstraints occ env tpenv m tcref pathType if tcref.Deref.IsProvided then TcProvidedTypeApp cenv env tpenv tcref synArgTys m else #endif - let tps, _, tinst, _ = FreshenTyconRef2 g m tcref - - // If we're not checking constraints, i.e. when we first assert the super/interfaces of a type definition, then just - // clear the constraint lists of the freshly generated type variables. A little ugly but fairly localized. - if checkConstraints = NoCheckCxs then tps |> List.iter (fun tp -> tp.SetConstraints []) let synArgTysLength = synArgTys.Length let pathTypeArgsLength = pathTypeArgs.Length if tinst.Length <> pathTypeArgsLength + synArgTysLength then error (TyconBadArgs(env.DisplayEnv, tcref, pathTypeArgsLength + synArgTysLength, m)) + let tps = tinst |> List.skip pathTypeArgsLength |> List.map (fun t -> + match t with + | TType_var(typar, _) + | TType_measure(Measure.Var typar) -> typar + | t -> failwith $"TcTypeApp: {t}" + ) + + // If we're not checking constraints, i.e. when we first assert the super/interfaces of a type definition, then just + // clear the constraint lists of the freshly generated type variables. A little ugly but fairly localized. + if checkConstraints = NoCheckCxs then tps |> List.iter (fun tp -> tp.SetConstraints []) + let argTys, tpenv = // Get the suffix of typars let tpsForArgs = List.skip (tps.Length - synArgTysLength) tps @@ -5060,9 +5069,9 @@ and TcNestedTypeApplication (cenv: cenv) newOk checkConstraints occ iwsam env tp error(Error(FSComp.SR.tcTypeHasNoNestedTypes(), mWholeTypeApp)) match ty with - | TType_app(tcref, _, _) -> + | TType_app(tcref, inst, _) -> CheckIWSAM cenv env checkConstraints iwsam mWholeTypeApp tcref - TcTypeApp cenv newOk checkConstraints occ env tpenv mWholeTypeApp tcref pathTypeArgs tyargs + TcTypeApp cenv newOk checkConstraints occ env tpenv mWholeTypeApp tcref pathTypeArgs tyargs inst | _ -> error(InternalError("TcNestedTypeApplication: expected type application", mWholeTypeApp)) @@ -7064,31 +7073,34 @@ and TcObjectExpr (cenv: cenv) env tpenv (objTy, realObjTy, argopt, binds, extraI TcRecordConstruction cenv objTy true env tpenv None objTy fldsList mWholeExpr else - let item = ForceRaise (ResolveObjectConstructor cenv.nameResolver env.DisplayEnv mObjTy ad objTy) + let ctorCall, baseIdOpt, tpenv = + if isInterfaceTy g objTy then + match argopt with + | None -> + BuildObjCtorCall g mWholeExpr, None, tpenv + | Some _ -> + error(Error(FSComp.SR.tcConstructorForInterfacesDoNotTakeArguments(), mNewExpr)) + else + let item = ForceRaise (ResolveObjectConstructor cenv.nameResolver env.DisplayEnv mObjTy ad objTy) - if isFSharpObjModelTy g objTy && GetCtorShapeCounter env = 1 then - error(Error(FSComp.SR.tcObjectsMustBeInitializedWithObjectExpression(), mNewExpr)) + if isFSharpObjModelTy g objTy && GetCtorShapeCounter env = 1 then + error(Error(FSComp.SR.tcObjectsMustBeInitializedWithObjectExpression(), mNewExpr)) - let ctorCall, baseIdOpt, tpenv = - match item, argopt with - | Item.CtorGroup(methodName, minfos), Some (arg, baseIdOpt) -> - let meths = minfos |> List.map (fun minfo -> minfo, None) - let afterResolution = ForNewConstructors cenv.tcSink env mObjTy methodName minfos - let ad = env.AccessRights - - let expr, tpenv = TcMethodApplicationThen cenv env (MustEqual objTy) None tpenv None [] mWholeExpr mObjTy methodName ad PossiblyMutates false meths afterResolution CtorValUsedAsSuperInit [arg] ExprAtomicFlag.Atomic None [] - // The 'base' value is always bound - let baseIdOpt = (match baseIdOpt with None -> Some(ident("base", mObjTy)) | Some id -> Some id) - expr, baseIdOpt, tpenv - | Item.FakeInterfaceCtor intfTy, None -> - UnifyTypes cenv env mWholeExpr objTy intfTy - let expr = BuildObjCtorCall g mWholeExpr - expr, None, tpenv - | Item.FakeInterfaceCtor _, Some _ -> - error(Error(FSComp.SR.tcConstructorForInterfacesDoNotTakeArguments(), mNewExpr)) - | Item.CtorGroup _, None -> - error(Error(FSComp.SR.tcConstructorRequiresArguments(), mNewExpr)) - | _ -> error(Error(FSComp.SR.tcNewRequiresObjectConstructor(), mNewExpr)) + match item, argopt with + | Item.CtorGroup(methodName, minfos), Some (arg, baseIdOpt) -> + let meths = minfos |> List.map (fun minfo -> minfo, None) + let afterResolution = ForNewConstructors cenv.tcSink env mObjTy methodName minfos + let ad = env.AccessRights + + let expr, tpenv = TcMethodApplicationThen cenv env (MustEqual objTy) None tpenv None [] mWholeExpr mObjTy methodName ad PossiblyMutates false meths afterResolution CtorValUsedAsSuperInit [arg] ExprAtomicFlag.Atomic None [] + // The 'base' value is always bound + let baseIdOpt = (match baseIdOpt with None -> Some(ident("base", mObjTy)) | Some id -> Some id) + expr, baseIdOpt, tpenv + + | Item.CtorGroup _, None -> + error(Error(FSComp.SR.tcConstructorRequiresArguments(), mNewExpr)) + + | _ -> error(Error(FSComp.SR.tcNewRequiresObjectConstructor(), mNewExpr)) let baseValOpt = MakeAndPublishBaseVal cenv env baseIdOpt objTy let env = Option.foldBack (AddLocalVal g cenv.tcSink mNewExpr) baseValOpt env @@ -8194,8 +8206,11 @@ and TcNameOfExpr (cenv: cenv) env tpenv (synArg: SynExpr) = when (match item with | Item.DelegateCtor _ - | Item.CtorGroup _ - | Item.FakeInterfaceCtor _ -> false + | Item.CtorGroup _ -> false + | Item.Types _ when delayed.IsEmpty -> + match delayed with + | [] | [DelayedTypeApp _] -> false + | _ -> true | _ -> true) -> let overallTy = match overallTyOpt with None -> MustEqual (NewInferenceType g) | Some t -> t let _, _ = TcItemThen cenv overallTy env tpenv res None delayed @@ -8209,10 +8224,10 @@ and TcNameOfExpr (cenv: cenv) env tpenv (synArg: SynExpr) = if (match delayed with [DelayedTypeApp _] | [] -> true | _ -> false) then let (TypeNameResolutionInfo(_, staticArgsInfo)) = GetLongIdentTypeNameInfo delayed match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInAttribute OpenQualified env.eNameResEnv ad longId staticArgsInfo PermitDirectReferenceToGeneratedType.No with - | Result (tinstEnclosing, tcref) when IsEntityAccessible cenv.amap m ad tcref -> + | Result (tinstEnclosing, tcref, inst) when IsEntityAccessible cenv.amap m ad tcref -> match delayed with | [DelayedTypeApp (tyargs, _, mExprAndTypeArgs)] -> - TcTypeApp cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv mExprAndTypeArgs tcref tinstEnclosing tyargs |> ignore + TcTypeApp cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv mExprAndTypeArgs tcref tinstEnclosing tyargs inst |> ignore | _ -> () true // resolved to a type name, done with checks | _ -> @@ -8427,9 +8442,6 @@ and TcItemThen (cenv: cenv) (overallTy: OverallTy) env tpenv (tinstEnclosing, it | Item.CtorGroup(nm, minfos) -> TcCtorItemThen cenv overallTy env item nm minfos tinstEnclosing tpenv mItem afterResolution delayed - | Item.FakeInterfaceCtor _ -> - error(Error(FSComp.SR.tcInvalidUseOfInterfaceType(), mItem)) - | Item.ImplicitOp(id, sln) -> TcImplicitOpItemThen cenv overallTy env id sln tpenv mItem delayed @@ -8667,7 +8679,10 @@ and TcTypeItemThen (cenv: cenv) overallTy env nm ty tpenv mItem tinstEnclosing d // In this case the type is not generic, and indeed we should never have returned Item.Types. // That's because ResolveTypeNamesToCtors should have been set at the original // call to ResolveLongIdentAsExprAndComputeRange - error(Error(FSComp.SR.tcInvalidUseOfTypeName(), mItem)) + if isInterfaceTy g ty then + error(Error(FSComp.SR.tcInvalidUseOfInterfaceType(), mItem)) + else + error(Error(FSComp.SR.tcInvalidUseOfTypeName(), mItem)) and TcMethodItemThen (cenv: cenv) overallTy env item methodName minfos tpenv mItem afterResolution staticTyOpt delayed = let ad = env.eAccessRights @@ -8860,7 +8875,7 @@ and TcImplicitOpItemThen (cenv: cenv) overallTy env id sln tpenv mItem delayed = let memberFlags = StaticMemberFlags SynMemberKind.Member let logicalCompiledName = ComputeLogicalName id memberFlags - let traitInfo = TTrait(argTys, logicalCompiledName, memberFlags, argTys, Some retTy, sln) + let traitInfo = TTrait(argTys, logicalCompiledName, memberFlags, argTys, Some retTy, ref None, sln) let expr = Expr.Op (TOp.TraitCall traitInfo, [], ves, mItem) let expr = mkLambdas g mItem [] vs (expr, retTy) @@ -9358,7 +9373,7 @@ and TcLookupItemThen cenv overallTy env tpenv mObjExpr objExpr objExprTy delayed | Item.Trait traitInfo -> TcTraitItemThen cenv overallTy env (Some objExpr) traitInfo tpenv mItem delayed - | Item.FakeInterfaceCtor _ | Item.DelegateCtor _ -> error (Error (FSComp.SR.tcConstructorsCannotBeFirstClassValues(), mItem)) + | Item.DelegateCtor _ -> error (Error (FSComp.SR.tcConstructorsCannotBeFirstClassValues(), mItem)) // These items are not expected here - they can't be the result of a instance member dot-lookup "expr.Ident" | Item.ActivePatternResult _ @@ -10904,7 +10919,7 @@ and TcAttributeEx canFail (cenv: cenv) (env: TcEnv) attrTgt attrEx (synAttr: Syn match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInAttribute OpenQualified env.eNameResEnv ad tycon TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No with | Exception err -> raze err - | Result(tinstEnclosing, tcref) -> success(TcTypeApp cenv NoNewTypars CheckCxs ItemOccurence.UseInAttribute env tpenv mAttr tcref tinstEnclosing []) + | Result(tinstEnclosing, tcref, inst) -> success(TcTypeApp cenv NoNewTypars CheckCxs ItemOccurence.UseInAttribute env tpenv mAttr tcref tinstEnclosing [] inst) ForceRaise ((try1 (tyid.idText + "Attribute")) |> otherwise (fun () -> (try1 tyid.idText))) diff --git a/src/Compiler/Checking/CheckExpressions.fsi b/src/Compiler/Checking/CheckExpressions.fsi index 16a759c2e3d..852fee213e6 100644 --- a/src/Compiler/Checking/CheckExpressions.fsi +++ b/src/Compiler/Checking/CheckExpressions.fsi @@ -75,7 +75,7 @@ exception UnionPatternsBindDifferentNames of range exception VarBoundTwice of Ident -exception ValueRestriction of DisplayEnv * InfoReader * bool * Val * Typar * range +exception ValueRestriction of DisplayEnv * InfoReader * Val * Typar * range exception ValNotMutable of DisplayEnv * ValRef * range @@ -712,7 +712,8 @@ val TcMatchPattern: synWhenExprOpt: SynExpr option -> Pattern * Expr option * Val list * TcEnv * UnscopedTyparEnv -val (|BinOpExpr|_|): SynExpr -> (Ident * SynExpr * SynExpr) option +[] +val (|BinOpExpr|_|): SynExpr -> (Ident * SynExpr * SynExpr) voption /// Check a set of let bindings in a class or module val TcLetBindings: diff --git a/src/Compiler/Checking/CheckFormatStrings.fs b/src/Compiler/Checking/CheckFormatStrings.fs index e32d073cbd1..ec8b4ae2b91 100644 --- a/src/Compiler/Checking/CheckFormatStrings.fs +++ b/src/Compiler/Checking/CheckFormatStrings.fs @@ -2,6 +2,7 @@ module internal FSharp.Compiler.CheckFormatStrings +open System open System.Text open Internal.Utilities.Library open Internal.Utilities.Library.Extras @@ -58,7 +59,7 @@ let escapeDotnetFormatString str = [] let (|PrefixedBy|_|) (prefix: string) (str: string) = - if str.StartsWith prefix then + if str.StartsWithOrdinal(prefix) then ValueSome prefix.Length else ValueNone @@ -370,12 +371,12 @@ let parseFormatStringInternal // type checker. They should always have '(...)' after for format string. let requireAndSkipInterpolationHoleFormat i = if i < len && fmt[i] = '(' then - let i2 = fmt.IndexOf(")", i+1) + let i2 = fmt.IndexOfOrdinal(")", i+1) if i2 = -1 then failwith (FSComp.SR.forFormatInvalidForInterpolated3()) else let dotnetAlignment = match widthValue with None -> "" | Some w -> "," + (if info.leftJustify then "-" else "") + string w - let dotnetNumberFormat = match fmt[i+1..i2-1] with "" -> "" | s -> ":" + s + let dotnetNumberFormat = match fmt[i+1..i2-1] with s when String.IsNullOrEmpty(s) -> "" | s -> ":" + s appendToDotnetFormatString ("{" + string dotnetFormatStringInterpolationHoleCount + dotnetAlignment + dotnetNumberFormat + "}") dotnetFormatStringInterpolationHoleCount <- dotnetFormatStringInterpolationHoleCount + 1 i2+1 diff --git a/src/Compiler/Checking/CheckIncrementalClasses.fs b/src/Compiler/Checking/CheckIncrementalClasses.fs index 8ef4d3734f9..85262e72a4c 100644 --- a/src/Compiler/Checking/CheckIncrementalClasses.fs +++ b/src/Compiler/Checking/CheckIncrementalClasses.fs @@ -123,7 +123,7 @@ let TcStaticImplicitCtorInfo_Phase2A(cenv: cenv, env, tcref: TyconRef, m, copyOf /// Check and elaborate the "left hand side" of the implicit class construction /// syntax. -let TcImplicitCtorInfo_Phase2A(cenv: cenv, env, tpenv, tcref: TyconRef, vis, attrs, spats, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy, xmlDoc: PreXmlDoc) = +let TcImplicitCtorInfo_Phase2A(cenv: cenv, env, tpenv, tcref: TyconRef, vis, attrs, pat: SynPat, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy, xmlDoc: PreXmlDoc) = let g = cenv.g let baseValOpt = @@ -135,16 +135,30 @@ let TcImplicitCtorInfo_Phase2A(cenv: cenv, env, tpenv, tcref: TyconRef, vis, att 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 ctorArgNames, patEnv, SynSimplePats.SimplePats(spats, _, _) = TcSimplePatsOfUnknownType cenv true CheckCxs env tpenv pat + + let rec reportGeneratedPattern spat = + match spat with + | SynSimplePat.Id(_, _, isCompilerGenerated, _, _, m) -> + if isCompilerGenerated then + errorR (Error(FSComp.SR.parsOnlySimplePatternsAreAllowedInConstructors(), m)) + + | SynSimplePat.Typed(pat, _, _) + | SynSimplePat.Attrib(pat, _, _) -> + reportGeneratedPattern pat + + for spat in spats do + reportGeneratedPattern spat let (TcPatLinearEnv(_, names, _)) = patEnv // Create the values with the given names let _, vspecs = MakeAndPublishSimpleVals cenv env names - if tcref.IsStructOrEnumTycon && isNil spats then + match tcref.IsStructOrEnumTycon, pat with + | true, SynPat.Const(SynConst.Unit, _) -> errorR (ParameterlessStructCtor(tcref.Range)) + | _ -> () // Put them in order let ctorArgs = List.map (fun v -> NameMap.find v vspecs) ctorArgNames diff --git a/src/Compiler/Checking/CheckIncrementalClasses.fsi b/src/Compiler/Checking/CheckIncrementalClasses.fsi index 0de56111ff9..428ae98b632 100644 --- a/src/Compiler/Checking/CheckIncrementalClasses.fsi +++ b/src/Compiler/Checking/CheckIncrementalClasses.fsi @@ -130,7 +130,7 @@ val TcImplicitCtorInfo_Phase2A: tcref: TyconRef * vis: SynAccess option * attrs: SynAttribute list * - spats: SynSimplePat list * + pat: SynPat * thisIdOpt: Ident option * baseValOpt: Val option * safeInitInfo: SafeInitData * diff --git a/src/Compiler/Checking/CheckPatterns.fs b/src/Compiler/Checking/CheckPatterns.fs index 00229e5eb4b..896df82f844 100644 --- a/src/Compiler/Checking/CheckPatterns.fs +++ b/src/Compiler/Checking/CheckPatterns.fs @@ -171,11 +171,13 @@ and TcSimplePats (cenv: cenv) optionalArgsOK checkConstraints ty env patEnv synS let ps', patEnvR = (patEnv, List.zip ptys ps) ||> List.mapFold (fun patEnv (ty, pat) -> TcSimplePat optionalArgsOK checkConstraints cenv ty env patEnv pat) ps', patEnvR -and TcSimplePatsOfUnknownType (cenv: cenv) optionalArgsOK checkConstraints env tpenv synSimplePats = +and TcSimplePatsOfUnknownType (cenv: cenv) optionalArgsOK checkConstraints env tpenv (pat: SynPat) = let g = cenv.g let argTy = NewInferenceType g let patEnv = TcPatLinearEnv (tpenv, NameMap.empty, Set.empty) - TcSimplePats cenv optionalArgsOK checkConstraints argTy env patEnv synSimplePats + let spats, _ = SimplePatsOfPat cenv.synArgNameGenerator pat + let names, patEnv = TcSimplePats cenv optionalArgsOK checkConstraints argTy env patEnv spats + names, patEnv, spats and TcPatBindingName cenv env id ty isMemberThis vis1 valReprInfo (vFlags: TcPatValFlags) (names, takenNames: Set) = let (TcPatValFlags(inlineFlag, declaredTypars, argAttribs, isMutable, vis2, isCompGen)) = vFlags diff --git a/src/Compiler/Checking/CheckPatterns.fsi b/src/Compiler/Checking/CheckPatterns.fsi index 46e400b8a92..da797b35a88 100644 --- a/src/Compiler/Checking/CheckPatterns.fsi +++ b/src/Compiler/Checking/CheckPatterns.fsi @@ -15,8 +15,8 @@ val TcSimplePatsOfUnknownType: checkConstraints: CheckConstraints -> env: TcEnv -> tpenv: UnscopedTyparEnv -> - synSimplePats: SynSimplePats -> - string list * TcPatLinearEnv + pat: SynPat -> + string list * TcPatLinearEnv * SynSimplePats // Check a pattern, e.g. for a binding or a match clause val TcPat: diff --git a/src/Compiler/Checking/ConstraintSolver.fs b/src/Compiler/Checking/ConstraintSolver.fs index 9a4ef131363..188e07399c2 100644 --- a/src/Compiler/Checking/ConstraintSolver.fs +++ b/src/Compiler/Checking/ConstraintSolver.fs @@ -57,12 +57,12 @@ open FSharp.Compiler.Import open FSharp.Compiler.InfoReader open FSharp.Compiler.Infos open FSharp.Compiler.MethodCalls +open FSharp.Compiler.NameResolution open FSharp.Compiler.Syntax open FSharp.Compiler.Syntax.PrettyNaming open FSharp.Compiler.SyntaxTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.Text -open FSharp.Compiler.Text.Range open FSharp.Compiler.TypedTree open FSharp.Compiler.TypedTreeBasics open FSharp.Compiler.TypedTreeOps @@ -79,7 +79,7 @@ open FSharp.Compiler.TypeProviders // of the constraint resolution carried out by type checking. //------------------------------------------------------------------------- -let compgenId = mkSynId range0 unassignedTyparName +let compgenId = mkSynId Range.range0 unassignedTyparName let NewCompGenTypar (kind, rigid, staticReq, dynamicReq, error) = Construct.NewTypar(kind, rigid, SynTypar(compgenId, staticReq, true), error, dynamicReq, [], false, false) @@ -97,29 +97,10 @@ let NewInferenceMeasurePar () = let NewErrorTypar () = NewCompGenTypar (TyparKind.Type, TyparRigidity.Flexible, TyparStaticReq.None, TyparDynamicReq.No, true) - -let NewErrorMeasureVar () = - NewCompGenTypar (TyparKind.Measure, TyparRigidity.Flexible, TyparStaticReq.None, TyparDynamicReq.No, true) - -let NewInferenceType (g: TcGlobals) = - let tp = Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, SynTypar(compgenId, TyparStaticReq.None, true), false, TyparDynamicReq.No, [], false, false) - let nullness = if g.langFeatureNullness then NewNullnessVar() else KnownAmbivalentToNull - TType_var (tp, nullness) let NewErrorType () = mkTyparTy (NewErrorTypar ()) -let NewErrorMeasure () = - Measure.Var (NewErrorMeasureVar ()) - -let NewByRefKindInferenceType (g: TcGlobals) m = - let tp = Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, SynTypar(compgenId, TyparStaticReq.HeadType, true), false, TyparDynamicReq.No, [], false, false) - if g.byrefkind_InOut_tcr.CanDeref then - tp.SetConstraints [TyparConstraint.DefaultsTo(10, TType_app(g.byrefkind_InOut_tcr, [], g.knownWithoutNull), m)] - mkTyparTy tp - -let NewInferenceTypes g l = l |> List.map (fun _ -> NewInferenceType g) - let FreshenTypar (g: TcGlobals) rigid (tp: Typar) = let clearStaticReq = g.langVersion.SupportsFeature LanguageFeature.InterfacesWithAbstractStaticMembers let staticReq = if clearStaticReq then TyparStaticReq.None else tp.StaticReq @@ -142,13 +123,6 @@ let FreshenTypeInst g m tpsorig = let FreshMethInst g m fctps tinst tpsorig = FreshenAndFixupTypars g m TyparRigidity.Flexible fctps tinst tpsorig -let FreshenTypars g m tpsorig = - match tpsorig with - | [] -> [] - | _ -> - let _, _, tpTys = FreshenTypeInst g m tpsorig - tpTys - let FreshenMethInfo m (minfo: MethInfo) = let _, _, tpTys = FreshMethInst minfo.TcGlobals m (minfo.GetFormalTyparsOfDeclaringType m) minfo.DeclaringTypeInst minfo.FormalMethodTypars tpTys @@ -1576,7 +1550,7 @@ and SolveDimensionlessNumericType (csenv: ConstraintSolverEnv) ndeep m2 trace ty /// 2. Some additional solutions are forced prior to generalization (permitWeakResolution= Yes or YesDuringCodeGen). See above and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload permitWeakResolution ndeep m2 trace traitInfo : OperationResult = trackErrors { - let (TTrait(supportTys, nm, memFlags, traitObjAndArgTys, retTy, sln)) = traitInfo + let (TTrait(supportTys, nm, memFlags, traitObjAndArgTys, retTy, source, sln)) = traitInfo // Do not re-solve if already solved if sln.Value.IsSome then return true else @@ -1593,8 +1567,8 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload let supportTys = ListSet.setify (typeAEquiv g aenv) supportTys // Rebuild the trait info after removing duplicates - let traitInfo = TTrait(supportTys, nm, memFlags, traitObjAndArgTys, retTy, sln) - let retTy = GetFSharpViewOfReturnType g retTy + let traitInfo = traitInfo.WithSupportTypes supportTys + let retTy = GetFSharpViewOfReturnType g retTy // Assert the object type if the constraint is for an instance member if memFlags.IsInstance then @@ -1895,13 +1869,13 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload None let anonRecdPropSearch = - let isGetProp = nm.StartsWith "get_" + let isGetProp = nm.StartsWithOrdinal("get_") if not isRigid && isGetProp && memFlags.IsInstance then let propName = nm[4..] let props = supportTys |> List.choose (fun ty -> - match NameResolution.TryFindAnonRecdFieldOfType g ty propName with - | Some (NameResolution.Item.AnonRecdField(anonInfo, tinst, i, _)) -> Some (anonInfo, tinst, i) + match TryFindAnonRecdFieldOfType g ty propName with + | Some (Item.AnonRecdField(anonInfo, tinst, i, _)) -> Some (anonInfo, tinst, i) | _ -> None) match props with | [ prop ] -> Some prop @@ -1936,8 +1910,17 @@ and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload if List.isSingleton supportTys then FSComp.SR.csTypeDoesNotSupportOperatorNullable(tyString, opName) else FSComp.SR.csTypesDoNotSupportOperatorNullable(tyString, opName) | _ -> - if List.isSingleton supportTys then FSComp.SR.csTypeDoesNotSupportOperator(tyString, opName) - else FSComp.SR.csTypesDoNotSupportOperator(tyString, opName) + match supportTys, source.Value with + | [_], Some s when s.StartsWith("Operators.") -> + let opSource = s[10..] + if opSource = nm then FSComp.SR.csTypeDoesNotSupportOperator(tyString, opName) + else FSComp.SR.csTypeDoesNotSupportOperator(tyString, opSource) + | [_], Some s -> + FSComp.SR.csFunctionDoesNotSupportType(s, tyString, nm) + | [_], _ + -> FSComp.SR.csTypeDoesNotSupportOperator(tyString, opName) + | _, _ + -> FSComp.SR.csTypesDoNotSupportOperator(tyString, opName) return! ErrorD(ConstraintSolverError(err, m, m2)) | _ -> @@ -2114,7 +2097,6 @@ and TransactMemberConstraintSolution traitInfo (trace: OptionalTrace) sln = /// Only consider overload resolution if canonicalizing or all the types are now nominal. /// That is, don't perform resolution if more nominal information may influence the set of available overloads and GetRelevantMethodsForTrait (csenv: ConstraintSolverEnv) (permitWeakResolution: PermitWeakResolution) nm traitInfo : (TType * MethInfo) list = - let (TTrait(_, _, memFlags, _, _, _)) = traitInfo let results = if permitWeakResolution.Permit || MemberConstraintSupportIsReadyForDeterminingOverloads csenv traitInfo then let m = csenv.m @@ -2124,7 +2106,7 @@ and GetRelevantMethodsForTrait (csenv: ConstraintSolverEnv) (permitWeakResolutio let minfos = [ for (supportTy, nominalTy) in nominalTys do let infos = - match memFlags.MemberKind with + match traitInfo.MemberFlags.MemberKind with | SynMemberKind.Constructor -> GetIntrinsicConstructorInfosOfType csenv.SolverState.InfoReader m nominalTy | _ -> @@ -2148,8 +2130,7 @@ and GetRelevantMethodsForTrait (csenv: ConstraintSolverEnv) (permitWeakResolutio // The trait name "op_Explicit" also covers "op_Implicit", so look for that one too. if nm = "op_Explicit" then - let (TTrait(supportTys, _, memFlags, argTys, retTy, soln)) = traitInfo - let traitInfo2 = TTrait(supportTys, "op_Implicit", memFlags, argTys, retTy, soln) + let traitInfo2 = traitInfo.WithMemberName "op_Implicit" results @ GetRelevantMethodsForTrait csenv permitWeakResolution "op_Implicit" traitInfo2 else results @@ -2206,7 +2187,7 @@ and SupportTypeOfMemberConstraintIsSolved (csenv: ConstraintSolverEnv) (traitInf /// Get all the unsolved typars (statically resolved or not) relevant to the member constraint and GetFreeTyparsOfMemberConstraint (csenv: ConstraintSolverEnv) traitInfo = - let (TTrait(supportTys, _, _, argTys, retTy, _)) = traitInfo + let (TTrait(tys=supportTys; objAndArgTys=argTys; returnTyOpt=retTy)) = traitInfo freeInTypesLeftToRightSkippingConstraints csenv.g (supportTys @ argTys @ Option.toList retTy) and MemberConstraintIsReadyForWeakResolution csenv traitInfo = @@ -2290,8 +2271,8 @@ and AddMemberConstraint (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTr and TraitsAreRelated (csenv: ConstraintSolverEnv) retry traitInfo1 traitInfo2 = let g = csenv.g - let (TTrait(tys1, nm1, memFlags1, argTys1, _, _)) = traitInfo1 - let (TTrait(tys2, nm2, memFlags2, argTys2, _, _)) = traitInfo2 + let (TTrait(tys=tys1; memberName=nm1; memberFlags=memFlags1; objAndArgTys=argTys1)) = traitInfo1 + let (TTrait(tys=tys2; memberName=nm2; memberFlags=memFlags2; objAndArgTys=argTys2)) = traitInfo2 memFlags1.IsInstance = memFlags2.IsInstance && nm1 = nm2 && // Multiple op_Explicit and op_Implicit constraints can exist for the same type variable. @@ -2317,8 +2298,8 @@ and EnforceConstraintConsistency (csenv: ConstraintSolverEnv) ndeep m2 trace ret match tpc1, tpc2 with | TyparConstraint.MayResolveMember(traitInfo1, _), TyparConstraint.MayResolveMember(traitInfo2, _) when TraitsAreRelated csenv retry traitInfo1 traitInfo2 -> - let (TTrait(tys1, _, _, argTys1, rty1, _)) = traitInfo1 - let (TTrait(tys2, _, _, argTys2, rty2, _)) = traitInfo2 + let (TTrait(tys=tys1; objAndArgTys=argTys1; returnTyOpt=rty1)) = traitInfo1 + let (TTrait(tys=tys2; objAndArgTys=argTys2; returnTyOpt=rty2)) = traitInfo2 if retry then match tys1, tys2 with | [ty1], [ty2] -> do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace ty1 ty2 diff --git a/src/Compiler/Checking/ConstraintSolver.fsi b/src/Compiler/Checking/ConstraintSolver.fsi index 990d1b20861..371fa31e598 100644 --- a/src/Compiler/Checking/ConstraintSolver.fsi +++ b/src/Compiler/Checking/ConstraintSolver.fsi @@ -15,61 +15,6 @@ open FSharp.Compiler.Text open FSharp.Compiler.TypedTree open FSharp.Compiler.TypedTreeOps -/// Create a type variable representing the use of a "_" in F# code -val NewAnonTypar: TyparKind * range * TyparRigidity * TyparStaticReq * TyparDynamicReq -> Typar - -/// Create an inference type variable -val NewInferenceType: TcGlobals -> TType - -/// Create an inference type variable for the kind of a byref pointer -val NewByRefKindInferenceType: TcGlobals -> range -> TType - -/// Create an inference type variable representing an error condition when checking an expression -val NewErrorType: unit -> TType - -/// Create an inference type variable representing an error condition when checking a measure -val NewErrorMeasure: unit -> Measure - -/// Create a list of inference type variables, one for each element in the input list -val NewInferenceTypes: TcGlobals -> 'T list -> TType list - -/// Given a set of formal type parameters and their constraints, make new inference type variables for -/// each and ensure that the constraints on the new type variables are adjusted to refer to these. -/// -/// Returns -/// 1. the new type parameters -/// 2. the instantiation mapping old type parameters to inference variables -/// 3. the inference type variables as a list of types. -val FreshenAndFixupTypars: - g: TcGlobals -> - m: range -> - rigid: TyparRigidity -> - Typars -> - TType list -> - Typars -> - Typars * TyparInstantiation * TType list - -/// Given a set of type parameters, make new inference type variables for -/// each and ensure that the constraints on the new type variables are adjusted. -/// -/// Returns -/// 1. the new type parameters -/// 2. the instantiation mapping old type parameters to inference variables -/// 3. the inference type variables as a list of types. -val FreshenTypeInst: g: TcGlobals -> range -> Typars -> Typars * TyparInstantiation * TType list - -/// Given a set of type parameters, make new inference type variables for -/// each and ensure that the constraints on the new type variables are adjusted. -/// -/// Returns the inference type variables as a list of types. -val FreshenTypars: g: TcGlobals -> range -> Typars -> TType list - -/// Given a method, which may be generic, make new inference type variables for -/// its generic parameters, and ensure that the constraints the new type variables are adjusted. -/// -/// Returns the inference type variables as a list of types. -val FreshenMethInfo: range -> MethInfo -> TType list - /// Information about the context of a type equation. [] type ContextInfo = diff --git a/src/Compiler/Checking/FindUnsolved.fs b/src/Compiler/Checking/FindUnsolved.fs index cfc34649ae5..10eb7ab672c 100644 --- a/src/Compiler/Checking/FindUnsolved.fs +++ b/src/Compiler/Checking/FindUnsolved.fs @@ -167,7 +167,7 @@ and accOp cenv env (op, tyargs, args, m) = | _ -> () /// Walk a trait call, collecting type variables -and accTraitInfo cenv env (mFallback : range) (TTrait(tys, _nm, _, argTys, retTy, _sln)) = +and accTraitInfo cenv env (mFallback : range) (TTrait(tys=tys; objAndArgTys=argTys; returnTyOpt=retTy)) = argTys |> accTypeInst cenv env mFallback retTy |> Option.iter (accTy cenv env mFallback) tys |> List.iter (accTy cenv env mFallback) diff --git a/src/Compiler/Checking/InfoReader.fs b/src/Compiler/Checking/InfoReader.fs index c006dc916cf..0028d830b35 100644 --- a/src/Compiler/Checking/InfoReader.fs +++ b/src/Compiler/Checking/InfoReader.fs @@ -4,6 +4,7 @@ /// Select members from a type by name, searching the type hierarchy if needed module internal FSharp.Compiler.InfoReader +open System open System.Collections.Concurrent open System.Collections.Generic open Internal.Utilities.Library @@ -1097,14 +1098,14 @@ let GetXmlDocSigOfEntityRef infoReader m (eref: EntityRef) = else let ccuFileName = libFileOfEntityRef eref let m = eref.Deref - if m.XmlDocSig = "" then + if String.IsNullOrEmpty(m.XmlDocSig) then m.XmlDocSig <- XmlDocSigOfEntity eref Some (ccuFileName, m.XmlDocSig) let GetXmlDocSigOfScopedValRef g (tcref: TyconRef) (vref: ValRef) = let ccuFileName = libFileOfEntityRef tcref let v = vref.Deref - if v.XmlDocSig = "" && v.HasDeclaringEntity then + if String.IsNullOrEmpty(v.XmlDocSig) && v.HasDeclaringEntity then let ap = buildAccessPath vref.DeclaringEntity.CompilationPathOpt let path = if vref.DeclaringEntity.IsModule then @@ -1118,14 +1119,14 @@ let GetXmlDocSigOfScopedValRef g (tcref: TyconRef) (vref: ValRef) = let GetXmlDocSigOfRecdFieldRef (rfref: RecdFieldRef) = let tcref = rfref.TyconRef let ccuFileName = libFileOfEntityRef tcref - if rfref.RecdField.XmlDocSig = "" then + if String.IsNullOrEmpty(rfref.RecdField.XmlDocSig) then rfref.RecdField.XmlDocSig <- XmlDocSigOfProperty [tcref.CompiledRepresentationForNamedType.FullName; rfref.RecdField.LogicalName] Some (ccuFileName, rfref.RecdField.XmlDocSig) let GetXmlDocSigOfUnionCaseRef (ucref: UnionCaseRef) = let tcref = ucref.TyconRef let ccuFileName = libFileOfEntityRef tcref - if ucref.UnionCase.XmlDocSig = "" then + if String.IsNullOrEmpty(ucref.UnionCase.XmlDocSig) then ucref.UnionCase.XmlDocSig <- XmlDocSigOfUnionCase [tcref.CompiledRepresentationForNamedType.FullName; ucref.CaseName] Some (ccuFileName, ucref.UnionCase.XmlDocSig) @@ -1171,7 +1172,7 @@ let GetXmlDocSigOfValRef g (vref: ValRef) = if not vref.IsLocalRef then let ccuFileName = vref.nlr.Ccu.FileName let v = vref.Deref - if v.XmlDocSig = "" && v.HasDeclaringEntity then + if String.IsNullOrEmpty(v.XmlDocSig) && v.HasDeclaringEntity then v.XmlDocSig <- XmlDocSigOfVal g false vref.DeclaringEntity.CompiledRepresentationForNamedType.Name v Some (ccuFileName, v.XmlDocSig) else diff --git a/src/Compiler/Checking/MethodCalls.fs b/src/Compiler/Checking/MethodCalls.fs index 4c1174a8d98..4006f9f0e2a 100644 --- a/src/Compiler/Checking/MethodCalls.fs +++ b/src/Compiler/Checking/MethodCalls.fs @@ -538,7 +538,7 @@ type CalledMeth<'T> // Detect the special case where an indexer setter using param aray takes 'value' argument after ParamArray arguments let isIndexerSetter = match pinfoOpt with - | Some pinfo when pinfo.HasSetter && minfo.LogicalName.StartsWith "set_" && (List.concat fullCurriedCalledArgs).Length >= 2 -> true + | Some pinfo when pinfo.HasSetter && minfo.LogicalName.StartsWithOrdinal("set_") && (List.concat fullCurriedCalledArgs).Length >= 2 -> true | _ -> false let argSetInfos = diff --git a/src/Compiler/Checking/NameResolution.fs b/src/Compiler/Checking/NameResolution.fs index d8c31361ec4..5abb8569589 100644 --- a/src/Compiler/Checking/NameResolution.fs +++ b/src/Compiler/Checking/NameResolution.fs @@ -201,9 +201,6 @@ type Item = /// Represents the resolution of a name to a constructor | CtorGroup of string * MethInfo list - /// Represents the resolution of a name to the fake constructor simulated for an interface type. - | FakeInterfaceCtor of TType - /// Represents the resolution of a name to a delegate | DelegateCtor of TType @@ -276,8 +273,7 @@ type Item = | ValueSome tcref -> tcref.DisplayNameCore | _ -> nm |> DemangleGenericTypeName - | Item.CtorGroup(nm, _) -> nm |> DemangleGenericTypeName - | Item.FakeInterfaceCtor ty + | Item.CtorGroup(nm, _) -> nm |> DemangleGenericTypeName | Item.DelegateCtor ty -> match ty with | AbbrevOrAppTy tcref -> tcref.DisplayNameCore @@ -1570,6 +1566,85 @@ let FreshenUnionCaseRef (ncenv: NameResolver) m (ucref: UnionCaseRef) = let FreshenRecdFieldRef (ncenv: NameResolver) m (rfref: RecdFieldRef) = RecdFieldInfo(ncenv.InstantiationGenerator m (rfref.Tycon.Typars m), rfref) +//------------------------------------------------------------------------- +// Generate type variables and record them in within the scope of the +// compilation environment, which currently corresponds to the scope +// of the constraint resolution carried out by type checking. +//------------------------------------------------------------------------- + +let compgenId = mkSynId range0 unassignedTyparName + +let NewCompGenTypar (kind, rigid, staticReq, dynamicReq, error) = + Construct.NewTypar(kind, rigid, SynTypar(compgenId, staticReq, true), error, dynamicReq, [], false, false) + +let AnonTyparId m = mkSynId m unassignedTyparName + +let NewAnonTypar (kind, m, rigid, var, dyn) = + Construct.NewTypar (kind, rigid, SynTypar(AnonTyparId m, var, true), false, dyn, [], false, false) + +let NewNamedInferenceMeasureVar (_m: range, rigid, var, id) = + Construct.NewTypar(TyparKind.Measure, rigid, SynTypar(id, var, false), false, TyparDynamicReq.No, [], false, false) + +let NewInferenceMeasurePar () = + NewCompGenTypar (TyparKind.Measure, TyparRigidity.Flexible, TyparStaticReq.None, TyparDynamicReq.No, false) + +let NewErrorTypar () = + NewCompGenTypar (TyparKind.Type, TyparRigidity.Flexible, TyparStaticReq.None, TyparDynamicReq.No, true) + +let NewErrorMeasureVar () = + NewCompGenTypar (TyparKind.Measure, TyparRigidity.Flexible, TyparStaticReq.None, TyparDynamicReq.No, true) + +let NewInferenceType (g: TcGlobals) = + ignore g // included for future, minimizing code diffs, see https://github.com/dotnet/fsharp/pull/6804 + mkTyparTy (Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, SynTypar(compgenId, TyparStaticReq.None, true), false, TyparDynamicReq.No, [], false, false)) + +let NewErrorType () = + mkTyparTy (NewErrorTypar ()) + +let NewErrorMeasure () = + Measure.Var (NewErrorMeasureVar ()) + +let NewByRefKindInferenceType (g: TcGlobals) m = + let tp = Construct.NewTypar (TyparKind.Type, TyparRigidity.Flexible, SynTypar(compgenId, TyparStaticReq.HeadType, true), false, TyparDynamicReq.No, [], false, false) + if g.byrefkind_InOut_tcr.CanDeref then + tp.SetConstraints [TyparConstraint.DefaultsTo(10, TType_app(g.byrefkind_InOut_tcr, [], g.knownWithoutNull), m)] + mkTyparTy tp + +let NewInferenceTypes g l = l |> List.map (fun _ -> NewInferenceType g) + +let FreshenTypar (g: TcGlobals) rigid (tp: Typar) = + let clearStaticReq = g.langVersion.SupportsFeature LanguageFeature.InterfacesWithAbstractStaticMembers + let staticReq = if clearStaticReq then TyparStaticReq.None else tp.StaticReq + let dynamicReq = if rigid = TyparRigidity.Rigid then TyparDynamicReq.Yes else TyparDynamicReq.No + NewCompGenTypar (tp.Kind, rigid, staticReq, dynamicReq, false) + +// QUERY: should 'rigid' ever really be 'true'? We set this when we know +// we are going to have to generalize a typar, e.g. when implementing a +// abstract generic method slot. But we later check the generalization +// condition anyway, so we could get away with a non-rigid typar. This +// would sort of be cleaner, though give errors later. +let FreshenAndFixupTypars g m rigid fctps tinst tpsorig = + let tps = tpsorig |> List.map (FreshenTypar g rigid) + let renaming, tinst = FixupNewTypars m fctps tinst tpsorig tps + tps, renaming, tinst + +let FreshenTypeInst g m tpsorig = + FreshenAndFixupTypars g m TyparRigidity.Flexible [] [] tpsorig + +let FreshMethInst g m fctps tinst tpsorig = + FreshenAndFixupTypars g m TyparRigidity.Flexible fctps tinst tpsorig + +let FreshenTypars g m tpsorig = + match tpsorig with + | [] -> [] + | _ -> + let _, _, tpTys = FreshenTypeInst g m tpsorig + tpTys + +let FreshenMethInfo m (minfo: MethInfo) = + let _, _, tpTys = FreshMethInst minfo.TcGlobals m (minfo.GetFormalTyparsOfDeclaringType m) minfo.DeclaringTypeInst minfo.FormalMethodTypars + tpTys + /// This must be called after fetching unqualified items that may need to be freshened /// or have type instantiations let ResolveUnqualifiedItem (ncenv: NameResolver) nenv m res = @@ -1713,6 +1788,8 @@ type ItemOccurence = | RelatedText /// This is a usage of a module or namespace name in open statement | Open + /// Not permitted item uses like interface names used as expressions + | InvalidUse type FormatStringCheckContext = { SourceText: ISourceText @@ -1741,88 +1818,100 @@ let (|ValRefOfProp|_|) (pi: PropInfo) = pi.ArbitraryValRef let (|ValRefOfMeth|_|) (mi: MethInfo) = mi.ArbitraryValRef let (|ValRefOfEvent|_|) (evt: EventInfo) = evt.ArbitraryValRef +[] let rec (|RecordFieldUse|_|) (item: Item) = match item with - | Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref, name))) -> Some (name, tcref) - | Item.SetterArg(_, RecordFieldUse f) -> Some f - | _ -> None + | Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref, name))) -> ValueSome (name, tcref) + | Item.SetterArg(_, RecordFieldUse f) -> ValueSome f + | _ -> ValueNone +[] let (|UnionCaseFieldUse|_|) (item: Item) = match item with - | Item.UnionCaseField (uci, fieldIndex) -> Some (fieldIndex, uci.UnionCaseRef) - | _ -> None + | Item.UnionCaseField (uci, fieldIndex) -> ValueSome (fieldIndex, uci.UnionCaseRef) + | _ -> ValueNone +[] let rec (|ILFieldUse|_|) (item: Item) = match item with - | Item.ILField finfo -> Some finfo - | Item.SetterArg(_, ILFieldUse f) -> Some f - | _ -> None + | Item.ILField finfo -> ValueSome finfo + | Item.SetterArg(_, ILFieldUse f) -> ValueSome f + | _ -> ValueNone +[] let rec (|PropertyUse|_|) (item: Item) = match item with - | Item.Property(info = pinfo :: _) -> Some pinfo - | Item.SetterArg(_, PropertyUse pinfo) -> Some pinfo - | _ -> None + | Item.Property(info = pinfo :: _) -> ValueSome pinfo + | Item.SetterArg(_, PropertyUse pinfo) -> ValueSome pinfo + | _ -> ValueNone +[] let rec (|FSharpPropertyUse|_|) (item: Item) = match item with - | Item.Property(info = [ValRefOfProp vref]) -> Some vref - | Item.SetterArg(_, FSharpPropertyUse propDef) -> Some propDef - | _ -> None + | Item.Property(info = [ValRefOfProp vref]) -> ValueSome vref + | Item.SetterArg(_, FSharpPropertyUse propDef) -> ValueSome propDef + | _ -> ValueNone +[] let (|MethodUse|_|) (item: Item) = match item with - | Item.MethodGroup(_, [minfo], _) -> Some minfo - | _ -> None + | Item.MethodGroup(_, [minfo], _) -> ValueSome minfo + | _ -> ValueNone +[] let (|FSharpMethodUse|_|) (item: Item) = match item with - | Item.MethodGroup(_, [ValRefOfMeth vref], _) -> Some vref - | Item.Value vref when vref.IsMember -> Some vref - | _ -> None + | Item.MethodGroup(_, [ValRefOfMeth vref], _) -> ValueSome vref + | Item.Value vref when vref.IsMember -> ValueSome vref + | _ -> ValueNone +[] let (|EntityUse|_|) (item: Item) = match item with - | Item.UnqualifiedType (tcref :: _) -> Some tcref - | Item.ExnCase tcref -> Some tcref + | Item.UnqualifiedType (tcref :: _) -> ValueSome tcref + | Item.ExnCase tcref -> ValueSome tcref | Item.Types(_, [AbbrevOrAppTy tcref]) - | Item.DelegateCtor(AbbrevOrAppTy tcref) - | Item.FakeInterfaceCtor(AbbrevOrAppTy tcref) -> Some tcref + | Item.DelegateCtor(AbbrevOrAppTy tcref) -> ValueSome tcref | Item.CtorGroup(_, ctor :: _) -> match ctor.ApparentEnclosingType with - | AbbrevOrAppTy tcref -> Some tcref - | _ -> None - | _ -> None + | AbbrevOrAppTy tcref -> ValueSome tcref + | _ -> ValueNone + | _ -> ValueNone +[] let (|EventUse|_|) (item: Item) = match item with - | Item.Event einfo -> Some einfo - | _ -> None + | Item.Event einfo -> ValueSome einfo + | _ -> ValueNone +[] let (|FSharpEventUse|_|) (item: Item) = match item with - | Item.Event(ValRefOfEvent vref) -> Some vref - | _ -> None + | Item.Event(ValRefOfEvent vref) -> ValueSome vref + | _ -> ValueNone +[] let (|UnionCaseUse|_|) (item: Item) = match item with - | Item.UnionCase(UnionCaseInfo(_, u1), _) -> Some u1 - | _ -> None + | Item.UnionCase(UnionCaseInfo(_, u1), _) -> ValueSome u1 + | _ -> ValueNone +[] let (|ValUse|_|) (item: Item) = match item with | Item.Value vref | FSharpPropertyUse vref | FSharpMethodUse vref | FSharpEventUse vref - | Item.CustomBuilder(_, vref) -> Some vref - | _ -> None + | Item.CustomBuilder(_, vref) -> ValueSome vref + | _ -> ValueNone +[] let (|ActivePatternCaseUse|_|) (item: Item) = match item with - | Item.ActivePatternCase(APElemRef(_, vref, idx, _)) -> Some (vref.SigRange, vref.DefinitionRange, idx) - | Item.ActivePatternResult(ap, _, idx, _) -> Some (ap.Range, ap.Range, idx) - | _ -> None + | Item.ActivePatternCase(APElemRef(_, vref, idx, _)) -> ValueSome (vref.SigRange, vref.DefinitionRange, idx) + | Item.ActivePatternResult(ap, _, idx, _) -> ValueSome (ap.Range, ap.Range, idx) + | _ -> ValueNone let tyconRefDefnHash (_g: TcGlobals) (eref1: EntityRef) = hash eref1.LogicalName @@ -2229,7 +2318,6 @@ let CheckAllTyparsInferrable amap m item = | Item.Trait _ | Item.CtorGroup _ - | Item.FakeInterfaceCtor _ | Item.DelegateCtor _ | Item.Types _ | Item.ModuleOrNamespaces _ @@ -2470,7 +2558,8 @@ let private ResolveObjectConstructorPrim (ncenv: NameResolver) edenv resInfo m a else let ctorInfos = GetIntrinsicConstructorInfosOfType ncenv.InfoReader m ty if isNil ctorInfos && isInterfaceTy g ty then - success (resInfo, Item.FakeInterfaceCtor ty) + let tcref = tcrefOfAppTy g ty + success (resInfo, Item.Types(tcref.DisplayName, [ty])) else let defaultStructCtorInfo = if (not (ctorInfos |> List.exists (fun x -> x.IsNullary)) && @@ -2843,9 +2932,10 @@ let private ResolveLongIdentInTyconRefs atMostOne (ncenv: NameResolver) nenv loo // ResolveExprLongIdentInModuleOrNamespace //------------------------------------------------------------------------- +[] let (|AccessibleEntityRef|_|) amap m ad (modref: ModuleOrNamespaceRef) mspec = let eref = modref.NestedTyconRef mspec - if IsEntityAccessible amap m ad eref then Some eref else None + if IsEntityAccessible amap m ad eref then ValueSome eref else ValueNone let rec ResolveExprLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv (typeNameResInfo: TypeNameResolutionInfo) ad resInfo depth m modref (mty: ModuleOrNamespaceType) (id: Ident) (rest: Ident list) = // resInfo records the modules or namespaces actually relevant to a resolution @@ -3070,33 +3160,50 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified match AtMostOneResult m innerSearch with | Result _ as res -> res | _ -> - let failingCase = - match typeError with - | Some e -> raze e - | _ -> - let suggestNamesAndTypes (addToBuffer: string -> unit) = - for e in nenv.eUnqualifiedItems do - if canSuggestThisItem e.Value then - addToBuffer e.Value.DisplayName - - for e in nenv.TyconsByDemangledNameAndArity fullyQualified do - if IsEntityAccessible ncenv.amap m ad e.Value then - addToBuffer e.Value.DisplayName - - for kv in nenv.ModulesAndNamespaces fullyQualified do - for modref in kv.Value do - if IsEntityAccessible ncenv.amap m ad modref then - addToBuffer modref.DisplayName - - // check if the user forgot to use qualified access - for e in nenv.eTyconsByDemangledNameAndArity do - let hasRequireQualifiedAccessAttribute = HasFSharpAttribute ncenv.g ncenv.g.attrib_RequireQualifiedAccessAttribute e.Value.Attribs - if hasRequireQualifiedAccessAttribute then - if e.Value.IsUnionTycon && e.Value.UnionCasesArray |> Array.exists (fun c -> c.LogicalName = id.idText) then - addToBuffer (e.Value.DisplayName + "." + id.idText) - - raze (UndefinedName(0, FSComp.SR.undefinedNameValueOfConstructor, id, suggestNamesAndTypes)) - failingCase + + match typeError with + | Some e -> raze e + | _ -> + + let tyconSearch () = + let tcrefs = LookupTypeNameInEnvNoArity fullyQualified id.idText nenv + if isNil tcrefs then NoResultsOrUsefulErrors else + + let tcrefs = ResolveUnqualifiedTyconRefs nenv tcrefs + let typeNameResInfo = TypeNameResolutionInfo.ResolveToTypeRefs typeNameResInfo.StaticArgsInfo + CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities (tcrefs, typeNameResInfo, PermitDirectReferenceToGeneratedType.No, unionRanges m id.idRange) + |> CollectResults success + + match tyconSearch () with + | Result((resInfo, tcref) :: _) -> + let _, _, tyargs = FreshenTypeInst ncenv.g m (tcref.Typars m) + let item = Item.Types(id.idText, [TType_app(tcref, tyargs, ncenv.g.knownWithoutNull)]) + success (resInfo, item) + | _ -> + + let suggestNamesAndTypes (addToBuffer: string -> unit) = + for e in nenv.eUnqualifiedItems do + if canSuggestThisItem e.Value then + addToBuffer e.Value.DisplayName + + for e in nenv.TyconsByDemangledNameAndArity fullyQualified do + if IsEntityAccessible ncenv.amap m ad e.Value then + addToBuffer e.Value.DisplayName + + for kv in nenv.ModulesAndNamespaces fullyQualified do + for modref in kv.Value do + if IsEntityAccessible ncenv.amap m ad modref then + addToBuffer modref.DisplayName + + // check if the user forgot to use qualified access + for e in nenv.eTyconsByDemangledNameAndArity do + let hasRequireQualifiedAccessAttribute = HasFSharpAttribute ncenv.g ncenv.g.attrib_RequireQualifiedAccessAttribute e.Value.Attribs + if hasRequireQualifiedAccessAttribute then + if e.Value.IsUnionTycon && e.Value.UnionCasesArray |> Array.exists (fun c -> c.LogicalName = id.idText) then + addToBuffer (e.Value.DisplayName + "." + id.idText) + + raze (UndefinedName(0, FSComp.SR.undefinedNameValueOfConstructor, id, suggestNamesAndTypes)) + match res with | Exception e -> raze e | Result (resInfo, item) -> @@ -3434,9 +3541,12 @@ let ResolveTypeLongIdentInTyconRef sink (ncenv: NameResolver) nenv typeNameResIn | id :: rest -> ForceRaise (ResolveTypeLongIdentInTyconRefPrim ncenv typeNameResInfo ad ResolutionInfo.Empty PermitDirectReferenceToGeneratedType.No 0 m tcref id rest) ResolutionInfo.SendEntityPathToSink(sink, ncenv, nenv, ItemOccurence.Use, ad, resInfo, ResultTyparChecker(fun () -> true)) - let item = Item.Types(tcref.DisplayName, [FreshenTycon ncenv m tcref]) - CallNameResolutionSink sink (rangeOfLid lid, nenv, item, emptyTyparInst, ItemOccurence.UseInType, ad) - tcref + + let _, tinst, tyargs = FreshenTypeInst ncenv.g m (tcref.Typars m) + let item = Item.Types(tcref.DisplayName, [TType_app(tcref, tyargs, ncenv.g.knownWithoutNull)]) + CallNameResolutionSink sink (rangeOfLid lid, nenv, item, tinst, ItemOccurence.UseInType, ad) + + tcref, tyargs /// Create an UndefinedName error with details let SuggestTypeLongIdentInModuleOrNamespace depth (modref: ModuleOrNamespaceRef) amap ad m (id: Ident) = @@ -3580,7 +3690,6 @@ let rec ResolveTypeLongIdentPrim sink (ncenv: NameResolver) occurence first full let r = AddResults searchSoFar (modulSearchFailed()) AtMostOneResult m2 (r |?> (fun tcrefs -> CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities (tcrefs, typeNameResInfo, genOk, m))) - /// Resolve a long identifier representing a type and report it let ResolveTypeLongIdentAux sink (ncenv: NameResolver) occurence fullyQualified nenv ad (lid: Ident list) staticResInfo genOk = let m = rangeOfLid lid @@ -3595,15 +3704,20 @@ let ResolveTypeLongIdentAux sink (ncenv: NameResolver) occurence fullyQualified match res with | Result (resInfo, tcref) -> ResolutionInfo.SendEntityPathToSink(sink, ncenv, nenv, ItemOccurence.UseInType, ad, resInfo, ResultTyparChecker(fun () -> true)) - let item = Item.Types(tcref.DisplayName, [FreshenTycon ncenv m tcref]) - CallNameResolutionSink sink (m, nenv, item, emptyTyparInst, occurence, ad) - | _ -> () - res + + let _, tinst, tyargs = FreshenTypeInst ncenv.g m (tcref.Typars m) + let item = Item.Types(tcref.DisplayName, [TType_app(tcref, tyargs, ncenv.g.knownWithoutNull)]) + CallNameResolutionSink sink (m, nenv, item, tinst, occurence, ad) + + Result(resInfo, tcref, tyargs) + + | Exception exn -> + Exception exn /// Resolve a long identifier representing a type and report it let ResolveTypeLongIdent sink ncenv occurence fullyQualified nenv ad lid staticResInfo genOk = let res = ResolveTypeLongIdentAux sink ncenv occurence fullyQualified nenv ad lid staticResInfo genOk - (res |?> fun (resInfo, tcref) -> (resInfo.EnclosingTypeInst, tcref)) + res |?> fun (resInfo, tcref, ttypes) -> (resInfo.EnclosingTypeInst, tcref, ttypes) //------------------------------------------------------------------------- // Resolve F#/IL "." syntax in records etc. @@ -3997,6 +4111,11 @@ let NeedsWorkAfterResolution namedItem = | Item.ActivePatternCase apref -> not (List.isEmpty apref.ActivePatternVal.Typars) | _ -> false +let isWrongItemInExpr item = + match item with + | Item.Types _ -> true + | _ -> false + /// Specifies additional work to do after an item has been processed further in type checking. [] type AfterResolution = @@ -4059,17 +4178,23 @@ let ResolveLongIdentAsExprAndComputeRange (sink: TcResultsSink) (ncenv: NameReso | Some _ -> if NeedsWorkAfterResolution item then AfterResolution.RecordResolution(None, (fun tpinst -> callSink(item, tpinst)), callSinkWithSpecificOverload, (fun () -> callSink (item, emptyTyparInst))) + + elif isWrongItemInExpr item then + CallNameResolutionSink sink (itemRange, nenv, item, emptyTyparInst, ItemOccurence.InvalidUse, ad) + AfterResolution.DoNothing + else callSink (item, emptyTyparInst) AfterResolution.DoNothing success (tinstEnclosing, item, itemRange, rest, afterResolution) +[] let (|NonOverridable|_|) namedItem = match namedItem with - | Item.MethodGroup(_, minfos, _) when minfos |> List.exists(fun minfo -> minfo.IsVirtual || minfo.IsAbstract) -> None - | Item.Property(info = pinfos) when pinfos |> List.exists(fun pinfo -> pinfo.IsVirtualProperty) -> None - | _ -> Some () + | Item.MethodGroup(_, minfos, _) when minfos |> List.exists(fun minfo -> minfo.IsVirtual || minfo.IsAbstract) -> ValueNone + | Item.Property(info = pinfos) when pinfos |> List.exists(fun pinfo -> pinfo.IsVirtualProperty) -> ValueNone + | _ -> ValueSome () /// Called for 'expression.Bar' - for VS IntelliSense, we can filter out static members from method groups /// Also called for 'GenericType.Bar' - for VS IntelliSense, we can filter out non-static members from method groups @@ -4500,7 +4625,6 @@ let InfosForTyconConstructors (ncenv: NameResolver) m ad (tcref: TyconRef) = match ResolveObjectConstructor ncenv (DisplayEnv.Empty g) m ad ty with | Result item -> match item with - | Item.FakeInterfaceCtor _ -> None | Item.CtorGroup(nm, ctorInfos) -> let ctors = ctorInfos @@ -5301,7 +5425,6 @@ let rec GetCompletionForItem (ncenv: NameResolver) (nenv: NameResolutionEnv) m a | _ -> () | Item.DelegateCtor _ - | Item.FakeInterfaceCtor _ | Item.CtorGroup _ | Item.UnqualifiedType _ -> for tcref in nenv.TyconsByDemangledNameAndArity(OpenQualified).Values do diff --git a/src/Compiler/Checking/NameResolution.fsi b/src/Compiler/Checking/NameResolution.fsi index 3ba5113b004..c80125f1862 100755 --- a/src/Compiler/Checking/NameResolution.fsi +++ b/src/Compiler/Checking/NameResolution.fsi @@ -94,9 +94,6 @@ type Item = /// Represents the resolution of a name to a constructor | CtorGroup of string * MethInfo list - /// Represents the resolution of a name to the fake constructor simulated for an interface type. - | FakeInterfaceCtor of TType - /// Represents the resolution of a name to a delegate | DelegateCtor of TType @@ -385,6 +382,7 @@ type internal ItemOccurence = | Implemented | RelatedText | Open + | InvalidUse /// Check for equality, up to signature matching val ItemsAreEffectivelyEqual: TcGlobals -> Item -> Item -> bool @@ -678,6 +676,67 @@ exception internal UpperCaseIdentifierInPattern of range /// Generate a new reference to a record field with a fresh type instantiation val FreshenRecdFieldRef: NameResolver -> range -> RecdFieldRef -> RecdFieldInfo +/// Create a type variable representing the use of a "_" in F# code +val NewAnonTypar: TyparKind * range * TyparRigidity * TyparStaticReq * TyparDynamicReq -> Typar + +val NewNamedInferenceMeasureVar: range * TyparRigidity * TyparStaticReq * Ident -> Typar + +val NewNamedInferenceMeasureVar: range * TyparRigidity * TyparStaticReq * Ident -> Typar + +val NewInferenceMeasurePar: unit -> Typar + +/// Create an inference type variable +val NewInferenceType: TcGlobals -> TType + +/// Create an inference type variable for the kind of a byref pointer +val NewByRefKindInferenceType: TcGlobals -> range -> TType + +/// Create an inference type variable representing an error condition when checking an expression +val NewErrorType: unit -> TType + +/// Create an inference type variable representing an error condition when checking a measure +val NewErrorMeasure: unit -> Measure + +/// Create a list of inference type variables, one for each element in the input list +val NewInferenceTypes: TcGlobals -> 'T list -> TType list + +/// Given a set of type parameters, make new inference type variables for +/// each and ensure that the constraints on the new type variables are adjusted. +/// +/// Returns the inference type variables as a list of types. +val FreshenTypars: g: TcGlobals -> range -> Typars -> TType list + +/// Given a method, which may be generic, make new inference type variables for +/// its generic parameters, and ensure that the constraints the new type variables are adjusted. +/// +/// Returns the inference type variables as a list of types. +val FreshenMethInfo: range -> MethInfo -> TType list + +/// Given a set of formal type parameters and their constraints, make new inference type variables for +/// each and ensure that the constraints on the new type variables are adjusted to refer to these. +/// +/// Returns +/// 1. the new type parameters +/// 2. the instantiation mapping old type parameters to inference variables +/// 3. the inference type variables as a list of types. +val FreshenAndFixupTypars: + g: TcGlobals -> + m: range -> + rigid: TyparRigidity -> + fctps: Typars -> + tinst: TType list -> + tpsorig: Typar list -> + Typar list * TyparInstantiation * TTypes + +/// Given a set of type parameters, make new inference type variables for +/// each and ensure that the constraints on the new type variables are adjusted. +/// +/// Returns +/// 1. the new type parameters +/// 2. the instantiation mapping old type parameters to inference variables +/// 3. the inference type variables as a list of types. +val FreshenTypeInst: g: TcGlobals -> m: range -> tpsorig: Typar list -> Typar list * TyparInstantiation * TTypes + /// Resolve a long identifier to a namespace, module. val internal ResolveLongIdentAsModuleOrNamespace: sink: TcResultsSink -> @@ -735,7 +794,7 @@ val internal ResolveTypeLongIdentInTyconRef: m: range -> tcref: TyconRef -> lid: Ident list -> - TyconRef + TyconRef * TypeInst /// Resolve a long identifier to a type definition val internal ResolveTypeLongIdent: @@ -748,7 +807,7 @@ val internal ResolveTypeLongIdent: lid: Ident list -> staticResInfo: TypeNameResolutionStaticArgsInfo -> genOk: PermitDirectReferenceToGeneratedType -> - ResultOrException + ResultOrException /// Resolve a long identifier to a field val internal ResolveField: diff --git a/src/Compiler/Checking/NicePrint.fs b/src/Compiler/Checking/NicePrint.fs index 718fcc7610c..ed4126347d2 100644 --- a/src/Compiler/Checking/NicePrint.fs +++ b/src/Compiler/Checking/NicePrint.fs @@ -55,7 +55,7 @@ module internal PrintUtilities = let comment str = wordL (tagText (sprintf "(* %s *)" str)) - let isDiscard (name: string) = name.StartsWith("_") + let isDiscard (name: string) = name.StartsWithOrdinal("_") let ensureFloat (s: string) = if String.forall (fun c -> Char.IsDigit c || c = '-') s then @@ -224,7 +224,7 @@ module internal PrintUtilities = else s) let pathText = trimPathByDisplayEnv denv path - if pathText = "" then tyconTextL else leftL (tagUnknownEntity pathText) ^^ tyconTextL + if String.IsNullOrEmpty(pathText) then tyconTextL else leftL (tagUnknownEntity pathText) ^^ tyconTextL let layoutBuiltinAttribute (denv: DisplayEnv) (attrib: BuiltinAttribInfo) = let tcref = attrib.TyconRef @@ -833,7 +833,7 @@ module PrintTypes = and layoutTraitWithInfo denv env traitInfo = let g = denv.g - let (TTrait(tys, _, memFlags, _, _, _)) = traitInfo + let (TTrait(tys=tys;memberFlags=memFlags)) = traitInfo let nm = traitInfo.MemberDisplayNameCore let nameL = ConvertValLogicalNameToDisplayLayout false (tagMember >> wordL) nm if denv.shortConstraints then @@ -2827,7 +2827,7 @@ let minimalStringsOfTwoTypes denv ty1 ty2 = let denv = denv.SetOpenPaths [] let denv = { denv with includeStaticParametersInTypeNames=true } let makeName t = - let assemblyName = PrintTypes.layoutAssemblyName denv t |> function "" -> "" | name -> sprintf " (%s)" name + let assemblyName = PrintTypes.layoutAssemblyName denv t |> function null | "" -> "" | name -> sprintf " (%s)" name sprintf "%s%s" (stringOfTy denv t) assemblyName (makeName ty1, makeName ty2, stringOfTyparConstraints denv tpcs) diff --git a/src/Compiler/Checking/PatternMatchCompilation.fs b/src/Compiler/Checking/PatternMatchCompilation.fs index 3caacecb982..168bd86e60e 100644 --- a/src/Compiler/Checking/PatternMatchCompilation.fs +++ b/src/Compiler/Checking/PatternMatchCompilation.fs @@ -740,19 +740,22 @@ let ChooseInvestigationPointLeftToRight frontiers = // This is an initial attempt to remove extra typetests/castclass for simple list pattern matching "match x with h :: t -> ... | [] -> ..." // The problem with this technique is that it creates extra locals which inhibit the process of converting pattern matches into linear let bindings. +[] let (|ListConsDiscrim|_|) g = function | (DecisionTreeTest.UnionCase (ucref, tinst)) (* check we can use a simple 'isinst' instruction *) - when tyconRefEq g ucref.TyconRef g.list_tcr_canon & ucref.CaseName = "op_ColonColon" -> Some tinst - | _ -> None + when tyconRefEq g ucref.TyconRef g.list_tcr_canon & ucref.CaseName = "op_ColonColon" -> ValueSome tinst + | _ -> ValueNone +[] let (|ListEmptyDiscrim|_|) g = function | (DecisionTreeTest.UnionCase (ucref, tinst)) (* check we can use a simple 'isinst' instruction *) - when tyconRefEq g ucref.TyconRef g.list_tcr_canon & ucref.CaseName = "op_Nil" -> Some tinst - | _ -> None + when tyconRefEq g ucref.TyconRef g.list_tcr_canon & ucref.CaseName = "op_Nil" -> ValueSome tinst + | _ -> ValueNone #endif +[] let (|ConstNeedsDefaultCase|_|) c = match c with | Const.Decimal _ @@ -767,8 +770,8 @@ let (|ConstNeedsDefaultCase|_|) c = | Const.UInt64 _ | Const.IntPtr _ | Const.UIntPtr _ - | Const.Char _ -> Some () - | _ -> None + | Const.Char _ -> ValueSome () + | _ -> ValueNone /// Build a dtree, equivalent to: TDSwitch("expr", edges, default, m) /// diff --git a/src/Compiler/Checking/PostInferenceChecks.fs b/src/Compiler/Checking/PostInferenceChecks.fs index d92bc67b827..5be7444b85b 100644 --- a/src/Compiler/Checking/PostInferenceChecks.fs +++ b/src/Compiler/Checking/PostInferenceChecks.fs @@ -346,7 +346,7 @@ let rec CheckTypeDeep (cenv: cenv) (visitTy, visitTyconRefOpt, visitAppTyOpt, vi | TType_var (tp, _) when tp.Solution.IsSome -> for cx in tp.Constraints do match cx with - | TyparConstraint.MayResolveMember(TTrait(_, _, _, _, _, soln), _) -> + | TyparConstraint.MayResolveMember(TTrait(solution=soln), _) -> match visitTraitSolutionOpt, soln.Value with | Some visitTraitSolution, Some sln -> visitTraitSolution sln | _ -> () @@ -433,11 +433,11 @@ and CheckTypeConstraintDeep cenv f g env x = | TyparConstraint.IsReferenceType _ | TyparConstraint.RequiresDefaultConstructor _ -> () -and CheckTraitInfoDeep cenv (_, _, _, visitTraitSolutionOpt, _ as f) g env (TTrait(tys, _, _, argTys, retTy, soln)) = - CheckTypesDeep cenv f g env tys - CheckTypesDeep cenv f g env argTys - Option.iter (CheckTypeDeep cenv f g env true ) retTy - match visitTraitSolutionOpt, soln.Value with +and CheckTraitInfoDeep cenv (_, _, _, visitTraitSolutionOpt, _ as f) g env traitInfo = + CheckTypesDeep cenv f g env traitInfo.SupportTypes + CheckTypesDeep cenv f g env traitInfo.CompiledObjectAndArgumentTypes + Option.iter (CheckTypeDeep cenv f g env true ) traitInfo.CompiledReturnType + match visitTraitSolutionOpt, traitInfo.Solution with | Some visitTraitSolution, Some sln -> visitTraitSolution sln | _ -> () diff --git a/src/Compiler/Checking/QuotationTranslator.fs b/src/Compiler/Checking/QuotationTranslator.fs index fa0d317ab95..8173c13755f 100644 --- a/src/Compiler/Checking/QuotationTranslator.fs +++ b/src/Compiler/Checking/QuotationTranslator.fs @@ -167,33 +167,37 @@ exception IgnoringPartOfQuotedTermWarning of string * range let wfail e = raise (InvalidQuotedTerm e) +[] let (|ModuleValueOrMemberUse|_|) g expr = let rec loop expr args = 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) + ValueSome(vref, vFlags, f, fty, tyargs, actualArgs @ args) | Expr.App (f, _fTy, [], actualArgs, _) -> loop f (actualArgs @ args) | Expr.Val (vref, vFlags, _m) as f when (match vref.TryDeclaringEntity with ParentNone -> false | _ -> true) -> let fty = tyOfExpr g f - Some(vref, vFlags, f, fty, [], args) + ValueSome(vref, vFlags, f, fty, [], args) | _ -> - None + ValueNone loop expr [] +[] let (|SimpleArrayLoopUpperBound|_|) expr = match expr with - | Expr.Op (TOp.ILAsm ([AI_sub], _), _, [Expr.Op (TOp.ILAsm ([I_ldlen; AI_conv ILBasicType.DT_I4], _), _, _, _); Expr.Const (Const.Int32 1, _, _) ], _) -> Some () - | _ -> None + | Expr.Op (TOp.ILAsm ([AI_sub], _), _, [Expr.Op (TOp.ILAsm ([I_ldlen; AI_conv ILBasicType.DT_I4], _), _, _, _); Expr.Const (Const.Int32 1, _, _) ], _) -> ValueSome () + | _ -> ValueNone +[] let (|SimpleArrayLoopBody|_|) g expr = match expr with | Expr.Lambda (_, a, b, ([_] as args), DebugPoints (Expr.Let (TBind(forVarLoop, DebugPoints (Expr.Op (TOp.ILAsm ([I_ldelem_any(ILArrayShape [(Some 0, None)], _)], _), [elemTy], [arr; idx], m1), _), seqPoint), body, m2, freeVars), _), m, ty) -> let body = Expr.Let (TBind(forVarLoop, mkCallArrayGet g m1 elemTy arr idx, seqPoint), body, m2, freeVars) let expr = Expr.Lambda (newUnique(), a, b, args, body, m, ty) - Some (arr, elemTy, expr) - | _ -> None + ValueSome (arr, elemTy, expr) + | _ -> ValueNone +[] let (|ObjectInitializationCheck|_|) g expr = // recognize "if this.init@ < 1 then failinit" match expr with @@ -207,8 +211,8 @@ let (|ObjectInitializationCheck|_|) g expr = name.StartsWithOrdinal("init") && selfRef.IsMemberThisVal && valRefEq g failInitRef (ValRefForIntrinsic g.fail_init_info) && - isUnitTy g resultTy -> Some() - | _ -> None + isUnitTy g resultTy -> ValueSome() + | _ -> ValueNone let isSplice g vref = valRefEq g vref g.splice_expr_vref || valRefEq g vref g.splice_raw_expr_vref diff --git a/src/Compiler/Checking/QuotationTranslator.fsi b/src/Compiler/Checking/QuotationTranslator.fsi index 288a8e1e73d..25567f51a63 100644 --- a/src/Compiler/Checking/QuotationTranslator.fsi +++ b/src/Compiler/Checking/QuotationTranslator.fsi @@ -41,10 +41,17 @@ val ConvExprPublic: QuotationGenerationScope -> suppressWitnesses: bool -> Expr val ConvReflectedDefinition: QuotationGenerationScope -> string -> Val -> Expr -> QuotationPickler.MethodBaseData * QuotationPickler.ExprData +[] val (|ModuleValueOrMemberUse|_|): - TcGlobals -> Expr -> (ValRef * ValUseFlag * Expr * TType * TypeInst * Expr list) option + TcGlobals -> Expr -> (ValRef * ValUseFlag * Expr * TType * TypeInst * Expr list) voption + +[] +val (|SimpleArrayLoopUpperBound|_|): Expr -> unit voption + +[] +val (|SimpleArrayLoopBody|_|): TcGlobals -> Expr -> (Expr * TType * Expr) voption + +[] +val (|ObjectInitializationCheck|_|): TcGlobals -> Expr -> unit voption -val (|SimpleArrayLoopUpperBound|_|): Expr -> unit option -val (|SimpleArrayLoopBody|_|): TcGlobals -> Expr -> (Expr * TType * Expr) option -val (|ObjectInitializationCheck|_|): TcGlobals -> Expr -> unit option val isSplice: TcGlobals -> ValRef -> bool diff --git a/src/Compiler/Checking/SignatureHash.fs b/src/Compiler/Checking/SignatureHash.fs index 2e22ca00ce4..077522a7151 100644 --- a/src/Compiler/Checking/SignatureHash.fs +++ b/src/Compiler/Checking/SignatureHash.fs @@ -477,7 +477,7 @@ let calculateHashOfImpliedSignature g observer (expr: ModuleOrNamespaceContents) let rec hashModuleOrNameSpaceBinding (monb: ModuleOrNamespaceBinding) = match monb with - | ModuleOrNamespaceBinding.Binding b when b.Var.LogicalName.StartsWith("doval@") -> 0 + | ModuleOrNamespaceBinding.Binding b when b.Var.LogicalName.StartsWithOrdinal("doval@") -> 0 | ModuleOrNamespaceBinding.Binding b -> HashTastMemberOrVals.hashValOrMemberNoInst (g, observer) (mkLocalValRef b.Var) | ModuleOrNamespaceBinding.Module(moduleInfo, contents) -> hashSingleModuleOrNameSpaceIncludingName (moduleInfo, contents) diff --git a/src/Compiler/Checking/TailCallChecks.fs b/src/Compiler/Checking/TailCallChecks.fs index 1faa9a50a35..cd8dfd2b77c 100644 --- a/src/Compiler/Checking/TailCallChecks.fs +++ b/src/Compiler/Checking/TailCallChecks.fs @@ -18,11 +18,12 @@ open FSharp.Compiler.TypeRelations let PostInferenceChecksStackGuardDepth = GetEnvInteger "FSHARP_TailCallChecks" 50 +[] let (|ValUseAtApp|_|) e = match e with | InnerExprPat(Expr.App(funcExpr = InnerExprPat(Expr.Val(valRef = vref; flags = valUseFlags))) | Expr.Val( - valRef = vref; flags = valUseFlags)) -> Some(vref, valUseFlags) - | _ -> None + valRef = vref; flags = valUseFlags)) -> ValueSome(vref, valUseFlags) + | _ -> ValueNone type TailCallReturnType = | MustReturnVoid // indicates "has unit return type and must return void" @@ -67,8 +68,6 @@ type cenv = amap: Import.ImportMap - reportErrors: bool - /// Values in module that have been marked [] mustTailCall: Zset } @@ -139,12 +138,8 @@ let rec mkArgsForAppliedExpr isBaseCall argsl x = | Expr.Op(TOp.Coerce, _, [ f ], _) -> mkArgsForAppliedExpr isBaseCall argsl f | _ -> [] -/// Check an expression, where the expression is in a position where byrefs can be generated -let rec CheckExprNoByrefs cenv (tailCall: TailCall) expr = - CheckExpr cenv expr PermitByRefExpr.No tailCall - /// Check an expression, warn if it's attributed with TailCall but our analysis concludes it's not a valid tail call -and CheckForNonTailRecCall (cenv: cenv) expr (tailCall: TailCall) = +let CheckForNonTailRecCall (cenv: cenv) expr (tailCall: TailCall) = let g = cenv.g let expr = stripExpr expr let expr = stripDebugPoints expr @@ -152,68 +147,70 @@ and CheckForNonTailRecCall (cenv: cenv) expr (tailCall: TailCall) = match expr with | Expr.App(f, _fty, _tyargs, argsl, m) -> - if cenv.reportErrors then - if cenv.g.langVersion.SupportsFeature LanguageFeature.WarningWhenTailRecAttributeButNonTailRecUsage then - match f with - | ValUseAtApp(vref, valUseFlags) when cenv.mustTailCall.Contains vref.Deref -> - - let canTailCall = - match tailCall with - | TailCall.No -> // an upper level has already decided that this is not in a tailcall position - false - | TailCall.Yes returnType -> - if vref.IsMemberOrModuleBinding && vref.ValReprInfo.IsSome then - let topValInfo = vref.ValReprInfo.Value - - let nowArgs, laterArgs = - let _, curriedArgInfos, _, _ = - GetValReprTypeInFSharpForm cenv.g topValInfo vref.Type m - - if argsl.Length >= curriedArgInfos.Length then - (List.splitAfter curriedArgInfos.Length argsl) - else - ([], argsl) - - let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal vref.Deref - - let _, _, _, returnTy, _ = - GetValReprTypeInCompiledForm g topValInfo numEnclosingTypars vref.Type m - - let _, _, isNewObj, isSuperInit, isSelfInit, _, _, _ = - GetMemberCallInfo cenv.g (vref, valUseFlags) - - let isCCall = - match valUseFlags with - | PossibleConstrainedCall _ -> true - | _ -> false - - let hasByrefArg = nowArgs |> List.exists (tyOfExpr cenv.g >> isByrefTy cenv.g) - - let mustGenerateUnitAfterCall = - (Option.isNone returnTy && returnType <> TailCallReturnType.MustReturnVoid) - - let noTailCallBlockers = - not isNewObj - && not isSuperInit - && not isSelfInit - && not mustGenerateUnitAfterCall - && isNil laterArgs - && not (IsValRefIsDllImport cenv.g vref) - && not isCCall - && not hasByrefArg - - noTailCallBlockers // blockers that will prevent the IL level from emmiting a tail instruction + match f with + | ValUseAtApp(vref, valUseFlags) when cenv.mustTailCall.Contains vref.Deref -> + + let canTailCall = + match tailCall with + | TailCall.No -> // an upper level has already decided that this is not in a tailcall position + false + | TailCall.Yes returnType -> + if vref.IsMemberOrModuleBinding && vref.ValReprInfo.IsSome then + let topValInfo = vref.ValReprInfo.Value + + let nowArgs, laterArgs = + let _, curriedArgInfos, _, _ = + GetValReprTypeInFSharpForm cenv.g topValInfo vref.Type m + + if argsl.Length >= curriedArgInfos.Length then + (List.splitAfter curriedArgInfos.Length argsl) else - true + ([], argsl) - // warn if we call inside of recursive scope in non-tail-call manner/with tail blockers. See - // ``Warn successfully in match clause`` - // ``Warn for byref parameters`` - if not canTailCall then - warning (Error(FSComp.SR.chkNotTailRecursive vref.DisplayName, m)) - | _ -> () + let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal vref.Deref + + let _, _, _, returnTy, _ = + GetValReprTypeInCompiledForm g topValInfo numEnclosingTypars vref.Type m + + let _, _, isNewObj, isSuperInit, isSelfInit, _, _, _ = + GetMemberCallInfo cenv.g (vref, valUseFlags) + + let isCCall = + match valUseFlags with + | PossibleConstrainedCall _ -> true + | _ -> false + + let hasByrefArg = nowArgs |> List.exists (tyOfExpr cenv.g >> isByrefTy cenv.g) + + let mustGenerateUnitAfterCall = + (Option.isNone returnTy && returnType <> TailCallReturnType.MustReturnVoid) + + let noTailCallBlockers = + not isNewObj + && not isSuperInit + && not isSelfInit + && not mustGenerateUnitAfterCall + && isNil laterArgs + && not (IsValRefIsDllImport cenv.g vref) + && not isCCall + && not hasByrefArg + + noTailCallBlockers // blockers that will prevent the IL level from emmiting a tail instruction + else + true + + // warn if we call inside of recursive scope in non-tail-call manner/with tail blockers. See + // ``Warn successfully in match clause`` + // ``Warn for byref parameters`` + if not canTailCall then + warning (Error(FSComp.SR.chkNotTailRecursive vref.DisplayName, m)) + | _ -> () | _ -> () +/// Check an expression, where the expression is in a position where byrefs can be generated +let rec CheckExprNoByrefs cenv (tailCall: TailCall) expr = + CheckExpr cenv expr PermitByRefExpr.No tailCall + /// Check call arguments, including the return argument. and CheckCall cenv args ctxts (tailCall: TailCall) = // detect CPS-like expressions @@ -729,19 +726,13 @@ and CheckBindings cenv binds = let CheckModuleBinding cenv (isRec: bool) (TBind _ as bind) = // warn for non-rec functions which have the attribute - if - cenv.reportErrors - && cenv.g.langVersion.SupportsFeature LanguageFeature.WarningWhenTailCallAttrOnNonRec - then + if cenv.g.langVersion.SupportsFeature LanguageFeature.WarningWhenTailCallAttrOnNonRec then let isNotAFunction = match bind.Var.ValReprInfo with | Some info -> info.HasNoArgs | _ -> false - if - (not isRec || isNotAFunction) - && HasFSharpAttribute cenv.g cenv.g.attrib_TailCallAttribute bind.Var.Attribs - then + if (not isRec || isNotAFunction) && cenv.g.HasTailCallAttrib bind.Var.Attribs then warning (Error(FSComp.SR.chkTailCallAttrOnNonRec (), bind.Var.Range)) // Check if a let binding to the result of a rec expression is not inside the rec expression @@ -807,7 +798,7 @@ and CheckDefnInModule cenv mdef = let mustTailCall = Seq.fold (fun mustTailCall (v: Val) -> - if HasFSharpAttribute cenv.g cenv.g.attrib_TailCallAttribute v.Attribs then + if cenv.g.HasTailCallAttrib v.Attribs then let newSet = Zset.add v mustTailCall newSet else @@ -844,14 +835,17 @@ and CheckModuleSpec cenv isRec mbind = | ModuleOrNamespaceBinding.Module(_mspec, rhs) -> CheckDefnInModule cenv rhs -let CheckImplFile (g, amap, reportErrors, implFileContents) = - let cenv = - { - g = g - reportErrors = reportErrors - stackGuard = StackGuard(PostInferenceChecksStackGuardDepth, "CheckImplFile") - amap = amap - mustTailCall = Zset.empty valOrder - } - - CheckDefnInModule cenv implFileContents +let CheckImplFile (g: TcGlobals, amap, reportErrors, implFileContents) = + if + reportErrors + && g.langVersion.SupportsFeature LanguageFeature.WarningWhenTailRecAttributeButNonTailRecUsage + then + let cenv = + { + g = g + stackGuard = StackGuard(PostInferenceChecksStackGuardDepth, "CheckImplFile") + amap = amap + mustTailCall = Zset.empty valOrder + } + + CheckDefnInModule cenv implFileContents diff --git a/src/Compiler/Checking/infos.fs b/src/Compiler/Checking/infos.fs index 022a0c6e4c9..5952a87ca98 100644 --- a/src/Compiler/Checking/infos.fs +++ b/src/Compiler/Checking/infos.fs @@ -850,7 +850,7 @@ type MethInfo = member x.IsUnionCaseTester = let tcref = x.ApparentEnclosingTyconRef tcref.IsUnionTycon && - x.LogicalName.StartsWith("get_Is") && + x.LogicalName.StartsWithOrdinal("get_Is") && match x.ArbitraryValRef with | Some v -> v.IsImplied | None -> false @@ -2455,18 +2455,19 @@ let SettersOfPropInfos (pinfos: PropInfo list) = pinfos |> List.choose (fun pinf let GettersOfPropInfos (pinfos: PropInfo list) = pinfos |> List.choose (fun pinfo -> if pinfo.HasGetter then Some(pinfo.GetterMethod, Some pinfo) else None) +[] let (|DifferentGetterAndSetter|_|) (pinfo: PropInfo) = if not (pinfo.HasGetter && pinfo.HasSetter) then - None + ValueNone else match pinfo.GetterMethod.ArbitraryValRef, pinfo.SetterMethod.ArbitraryValRef with | Some getValRef, Some setValRef -> if getValRef.Accessibility <> setValRef.Accessibility then - Some (getValRef, setValRef) + ValueSome (getValRef, setValRef) else match getValRef.ValReprInfo with | Some getValReprInfo when // Getter has an index parameter - getValReprInfo.TotalArgCount > 1 -> Some (getValRef, setValRef) - | _ -> None - | _ -> None \ No newline at end of file + getValReprInfo.TotalArgCount > 1 -> ValueSome (getValRef, setValRef) + | _ -> ValueNone + | _ -> ValueNone \ No newline at end of file diff --git a/src/Compiler/Checking/infos.fsi b/src/Compiler/Checking/infos.fsi index 41998e5253c..406919bfa37 100644 --- a/src/Compiler/Checking/infos.fsi +++ b/src/Compiler/Checking/infos.fsi @@ -1107,4 +1107,5 @@ val SettersOfPropInfos: pinfos: PropInfo list -> (MethInfo * PropInfo option) li val GettersOfPropInfos: pinfos: PropInfo list -> (MethInfo * PropInfo option) list -val (|DifferentGetterAndSetter|_|): pinfo: PropInfo -> (ValRef * ValRef) option +[] +val (|DifferentGetterAndSetter|_|): pinfo: PropInfo -> (ValRef * ValRef) voption diff --git a/src/Compiler/CodeGen/IlxGen.fs b/src/Compiler/CodeGen/IlxGen.fs index 6680057750a..30ea98a1a00 100644 --- a/src/Compiler/CodeGen/IlxGen.fs +++ b/src/Compiler/CodeGen/IlxGen.fs @@ -5,6 +5,7 @@ module internal FSharp.Compiler.IlxGen open FSharp.Compiler.IlxGenSupport +open System open System.IO open System.Reflection open System.Collections.Generic @@ -420,7 +421,7 @@ let CompLocForFixedPath fragName qname (CompPath(sref, cpath)) = let ns = List.map fst ns let ns = textOfPath ns let encl = t |> List.map (fun (s, _) -> s) - let ns = if ns = "" then None else Some ns + let ns = if String.IsNullOrEmpty(ns) then None else Some ns { QualifiedNameOfFile = fragName @@ -2707,7 +2708,7 @@ let CodeGenThen (cenv: cenv) mgbuf (entryPointInfo, methodName, eenv, alreadyUse match selfArgOpt with | Some selfArg when selfArg.LogicalName <> "this" - && not (selfArg.LogicalName.StartsWith("_")) + && not (selfArg.LogicalName.StartsWithOrdinal("_")) && not cenv.options.localOptimizationsEnabled -> let ilTy = selfArg.Type |> GenType cenv m eenv.tyenv @@ -2846,7 +2847,7 @@ and GenExprPreSteps (cenv: cenv) (cgbuf: CodeGenBuffer) eenv expr sequel = 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 + | false, _ when String.IsNullOrEmpty(debugPointName) -> CG.EmitDebugPoint cgbuf m | false, _ -> // printfn $"---- Unfound debug point {debugPointName} at {m}" // for KeyValue(k,v) in cenv.namedDebugPointsForInlinedCode do @@ -8646,7 +8647,7 @@ and GenMarshal cenv attribs = 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 + | x when String.IsNullOrEmpty(x) -> None | res -> if (safeArraySubType = ILNativeVariant.IDispatch) diff --git a/src/Compiler/DependencyManager/DependencyProvider.fs b/src/Compiler/DependencyManager/DependencyProvider.fs index adb9ca6ae7c..0fb7be23b6c 100644 --- a/src/Compiler/DependencyManager/DependencyProvider.fs +++ b/src/Compiler/DependencyManager/DependencyProvider.fs @@ -614,7 +614,7 @@ type DependencyProvider 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.StartsWithOrdinal(kv.Value.Key + ":")) with | None -> let err, msg = this.CreatePackageManagerUnknownError(compilerTools, outputDir, path.Split(':').[0], reportError) diff --git a/src/Compiler/DependencyManager/NativeDllResolveHandler.fs b/src/Compiler/DependencyManager/NativeDllResolveHandler.fs index 12aa28c48cc..8a3161a89d8 100644 --- a/src/Compiler/DependencyManager/NativeDllResolveHandler.fs +++ b/src/Compiler/DependencyManager/NativeDllResolveHandler.fs @@ -8,6 +8,7 @@ open System.IO open System.Reflection open System.Runtime.InteropServices open Internal.Utilities +open Internal.Utilities.Library open Internal.Utilities.FSharpEnvironment open FSharp.Compiler.IO @@ -88,7 +89,7 @@ type internal NativeDllResolveHandlerCoreClr(nativeProbingRoots: NativeResolutio 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 + not (name.Contains(s + ".") || name.EndsWithOrdinal(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 diff --git a/src/Compiler/Driver/CompilerDiagnostics.fs b/src/Compiler/Driver/CompilerDiagnostics.fs index 6c3868a3081..c5fa370ccb8 100644 --- a/src/Compiler/Driver/CompilerDiagnostics.fs +++ b/src/Compiler/Driver/CompilerDiagnostics.fs @@ -145,7 +145,7 @@ type Exception with | IntfImplInIntrinsicAugmentation m | OverrideInExtrinsicAugmentation m | IntfImplInExtrinsicAugmentation m - | ValueRestriction(_, _, _, _, _, m) + | ValueRestriction(_, _, _, _, m) | LetRecUnsound(_, _, m) | ObsoleteError(_, m) | ObsoleteWarning(_, m) @@ -591,11 +591,8 @@ module OldStyleMessages = let DeprecatedE () = Message("Deprecated", "%s") let LibraryUseOnlyE () = Message("LibraryUseOnly", "") let MissingFieldsE () = Message("MissingFields", "%s") - let ValueRestriction1E () = Message("ValueRestriction1", "%s%s%s") - let ValueRestriction2E () = Message("ValueRestriction2", "%s%s%s") - let ValueRestriction3E () = Message("ValueRestriction3", "%s") - let ValueRestriction4E () = Message("ValueRestriction4", "%s%s%s") - let ValueRestriction5E () = Message("ValueRestriction5", "%s%s%s") + let ValueRestrictionFunctionE () = Message("ValueRestrictionFunction", "%s%s%s") + let ValueRestrictionE () = Message("ValueRestriction", "%s%s%s") let RecoverableParseErrorE () = Message("RecoverableParseError", "") let ReservedKeywordE () = Message("ReservedKeyword", "%s") let IndentationProblemE () = Message("IndentationProblem", "%s") @@ -960,9 +957,11 @@ type Exception with [ knownReturnType; genericParametersMessage; argsMessage ] |> List.choose id |> String.concat (nl + nl) - |> function - | "" -> nl - | result -> nl + nl + result + nl + nl + |> fun result -> + if String.IsNullOrEmpty(result) then + nl + else + nl + nl + result + nl + nl match failure with | NoOverloadsFound(methodName, overloads, _) -> @@ -1822,7 +1821,7 @@ type Exception with | MissingFields(sl, _) -> os.AppendString(MissingFieldsE().Format(String.concat "," sl + ".")) - | ValueRestriction(denv, infoReader, hasSig, v, _, _) -> + | ValueRestriction(denv, infoReader, v, _, _) -> let denv = { denv with showInferenceTyparAnnotations = true @@ -1830,55 +1829,22 @@ type Exception with let tau = v.TauType - if hasSig then - if isFunTy denv.g tau && (arityOfVal v).HasNoArgs then - let msg = - ValueRestriction1E().Format - v.DisplayName - (NicePrint.stringOfQualifiedValOrMember denv infoReader (mkLocalValRef v)) - v.DisplayName - - os.AppendString msg - else - let msg = - ValueRestriction2E().Format - v.DisplayName - (NicePrint.stringOfQualifiedValOrMember denv infoReader (mkLocalValRef v)) - v.DisplayName + if isFunTy denv.g tau && (arityOfVal v).HasNoArgs then + let msg = + ValueRestrictionFunctionE().Format + v.DisplayName + (NicePrint.stringOfQualifiedValOrMember denv infoReader (mkLocalValRef v)) + v.DisplayName - os.AppendString msg + os.AppendString msg else - match v.MemberInfo with - | Some membInfo when - (match membInfo.MemberFlags.MemberKind with - | SynMemberKind.PropertyGet - | SynMemberKind.PropertySet - | SynMemberKind.Constructor -> true // can't infer extra polymorphism - // can infer extra polymorphism - | _ -> false) - -> - let msg = - ValueRestriction3E() - .Format(NicePrint.stringOfQualifiedValOrMember denv infoReader (mkLocalValRef v)) - - os.AppendString msg - | _ -> - if isFunTy denv.g tau && (arityOfVal v).HasNoArgs then - let msg = - ValueRestriction4E().Format - v.DisplayName - (NicePrint.stringOfQualifiedValOrMember denv infoReader (mkLocalValRef v)) - v.DisplayName - - os.AppendString msg - else - let msg = - ValueRestriction5E().Format - v.DisplayName - (NicePrint.stringOfQualifiedValOrMember denv infoReader (mkLocalValRef v)) - v.DisplayName + let msg = + ValueRestrictionE().Format + v.DisplayName + (NicePrint.stringOfQualifiedValOrMember denv infoReader (mkLocalValRef v)) + v.DisplayName - os.AppendString msg + os.AppendString msg | Parsing.RecoverableParseError -> os.AppendString(RecoverableParseErrorE().Format) diff --git a/src/Compiler/Driver/CompilerImports.fs b/src/Compiler/Driver/CompilerImports.fs index 8b106683b29..4421ed299ed 100644 --- a/src/Compiler/Driver/CompilerImports.fs +++ b/src/Compiler/Driver/CompilerImports.fs @@ -490,6 +490,26 @@ let IsExe fileName = let ext = Path.GetExtension fileName String.Compare(ext, ".exe", StringComparison.OrdinalIgnoreCase) = 0 +let addConstraintSources(ia: ImportedAssembly) = + let contents = ia.FSharpViewOfMetadata.Contents + let addCxsToMember name (v: Val) = + for typar in fst v.GeneralizedType do + for cx in typar.Constraints do + match cx with + | TyparConstraint.MayResolveMember(TTrait(source=source), _) -> + source.Value <- Some name + | _ -> () + let rec addCxsToModule name (m: ModuleOrNamespaceType) = + for e in m.ModuleAndNamespaceDefinitions do + if e.IsModuleOrNamespace then + let mname = + if String.length name > 0 then name + "." + e.DisplayName + elif e.IsModule then e.DisplayName + else "" + addCxsToModule mname e.ModuleOrNamespaceType + for memb in m.AllValsAndMembers do addCxsToMember (name + "." + memb.LogicalName) memb + addCxsToModule "" contents.ModuleOrNamespaceType + type TcConfig with member tcConfig.TryResolveLibWithDirectories(r: AssemblyReference) = @@ -2327,6 +2347,9 @@ and [] TcImports let _dllinfos, phase2s = results |> Array.choose id |> List.ofArray |> List.unzip fixupOrphanCcus () let ccuinfos = List.collect (fun phase2 -> phase2 ()) phase2s + if importsBase.IsSome then + importsBase.Value.CcuTable.Values |> Seq.iter addConstraintSources + ccuTable.Values |> Seq.iter addConstraintSources return ccuinfos } diff --git a/src/Compiler/Driver/CompilerOptions.fs b/src/Compiler/Driver/CompilerOptions.fs index 04c766d8b9f..b85cf795f0e 100644 --- a/src/Compiler/Driver/CompilerOptions.fs +++ b/src/Compiler/Driver/CompilerOptions.fs @@ -109,7 +109,7 @@ let compilerOptionUsage (CompilerOption(s, tag, spec, _, _)) = | OptionFloat _ -> sprintf "--%s:%s" s tag | OptionRest _ -> sprintf "--%s ..." s | OptionGeneral _ -> - if tag = "" then + if String.IsNullOrEmpty(tag) then sprintf "%s" s else sprintf "%s:%s" s tag (* still being decided *) @@ -270,7 +270,7 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler let optArgs = String.Join(":", opts[1..]) let opt = - if option = "" then + if String.IsNullOrEmpty(option) then "" // if it doesn't start with a '-' or '/', reject outright elif option[0] <> '-' && option[0] <> '/' then @@ -298,13 +298,13 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler opt, token, optArgs let getOptionArg compilerOption (argString: string) = - if argString = "" then + if String.IsNullOrEmpty(argString) then errorR (Error(FSComp.SR.buildOptionRequiresParameter (compilerOptionUsage compilerOption), rangeCmdArgs)) argString let getOptionArgList compilerOption (argString: string) = - if argString = "" then + if String.IsNullOrEmpty(argString) then errorR (Error(FSComp.SR.buildOptionRequiresParameter (compilerOptionUsage compilerOption), rangeCmdArgs)) [] else @@ -375,19 +375,19 @@ let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: Compiler reportDeprecatedOption d f blocks t - | CompilerOption(s, _, OptionUnit f, d, _) :: _ when optToken = s && argString = "" -> + | CompilerOption(s, _, OptionUnit f, d, _) :: _ when optToken = s && String.IsNullOrEmpty(argString) -> reportDeprecatedOption d f () t - | CompilerOption(s, _, OptionSwitch f, d, _) :: _ when getSwitchOpt optToken = s && argString = "" -> + | CompilerOption(s, _, OptionSwitch f, d, _) :: _ when getSwitchOpt optToken = s && String.IsNullOrEmpty(argString) -> reportDeprecatedOption d f (getSwitch opt) t - | CompilerOption(s, _, OptionSet f, d, _) :: _ when optToken = s && argString = "" -> + | CompilerOption(s, _, OptionSet f, d, _) :: _ when optToken = s && String.IsNullOrEmpty(argString) -> reportDeprecatedOption d f.Value <- true t - | CompilerOption(s, _, OptionClear f, d, _) :: _ when optToken = s && argString = "" -> + | CompilerOption(s, _, OptionClear f, d, _) :: _ when optToken = s && String.IsNullOrEmpty(argString) -> reportDeprecatedOption d f.Value <- false t diff --git a/src/Compiler/Driver/CreateILModule.fs b/src/Compiler/Driver/CreateILModule.fs index 7fa60a25957..04cda7f6c3f 100644 --- a/src/Compiler/Driver/CreateILModule.fs +++ b/src/Compiler/Driver/CreateILModule.fs @@ -409,7 +409,7 @@ module MainModuleBuilder = yield! codegenResults.ilAssemAttrs if Option.isSome pdbfile then - tcGlobals.mkDebuggableAttributeV2 (tcConfig.jitTracking, disableJitOptimizations, false (* enableEnC *) ) + tcGlobals.mkDebuggableAttributeV2 (tcConfig.jitTracking, disableJitOptimizations) yield! reflectedDefinitionAttrs ] @@ -584,19 +584,22 @@ module MainModuleBuilder = [ resource ] // a user cannot specify both win32res and win32manifest - if not (tcConfig.win32manifest = "") && not (tcConfig.win32res = "") then + if + not (String.IsNullOrEmpty(tcConfig.win32manifest)) + && not (String.IsNullOrEmpty(tcConfig.win32res)) + then error (Error(FSComp.SR.fscTwoResourceManifests (), rangeCmdArgs)) let win32Manifest = // use custom manifest if provided - if not (tcConfig.win32manifest = "") then + if not (String.IsNullOrEmpty(tcConfig.win32manifest)) then 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 = "") + || not (String.IsNullOrEmpty(tcConfig.win32res)) then "" // otherwise, include the default manifest @@ -618,9 +621,9 @@ module MainModuleBuilder = [ for av in assemblyVersionResources assemblyVersion do ILNativeResource.Out av - if not (tcConfig.win32res = "") then + if not (String.IsNullOrEmpty(tcConfig.win32res)) then ILNativeResource.Out(FileSystem.OpenFileForReadShim(tcConfig.win32res).ReadAllBytes()) - if tcConfig.includewin32manifest && not (win32Manifest = "") then + if tcConfig.includewin32manifest && not (String.IsNullOrEmpty(win32Manifest)) then ILNativeResource.Out [| yield! ResFileFormat.ResFileHeader() @@ -631,8 +634,8 @@ module MainModuleBuilder = )) |] if - tcConfig.win32res = "" - && tcConfig.win32icon <> "" + String.IsNullOrEmpty(tcConfig.win32res) + && not (String.IsNullOrEmpty(tcConfig.win32icon)) && tcConfig.target <> CompilerTarget.Dll then use ms = new MemoryStream() diff --git a/src/Compiler/Driver/FxResolver.fs b/src/Compiler/Driver/FxResolver.fs index 6f8643c30a1..42681600f88 100644 --- a/src/Compiler/Driver/FxResolver.fs +++ b/src/Compiler/Driver/FxResolver.fs @@ -238,7 +238,7 @@ type internal FxResolver dotnetConfig.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) + pattern.Length - let endPos = dotnetConfig.IndexOf("\"", startPos) + let endPos = dotnetConfig.IndexOfOrdinal("\"", startPos) let ver = dotnetConfig[startPos .. endPos - 1] let path = @@ -364,7 +364,7 @@ type internal FxResolver let implDir, warnings = getImplementationAssemblyDir () let version = DirectoryInfo(implDir).Name - if version.StartsWith("x") then + if version.StartsWithOrdinal("x") then // Is running on the desktop (None, None), warnings else @@ -403,7 +403,7 @@ type internal FxResolver | ".NET", "Core" when arr.Length >= 3 -> Some("netcoreapp" + (getTfmNumber arr[2])) | ".NET", "Framework" when arr.Length >= 3 -> - if arr[2].StartsWith("4.8") then + if arr[2].StartsWithOrdinal("4.8") then Some "net48" else Some "net472" @@ -560,7 +560,7 @@ type internal FxResolver dotnetConfig.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) + pattern.Length - let endPos = dotnetConfig.IndexOf("\"", startPos) + let endPos = dotnetConfig.IndexOfOrdinal("\"", startPos) let tfm = dotnetConfig[startPos .. endPos - 1] tfm with _ -> diff --git a/src/Compiler/Driver/GraphChecking/DependencyResolution.fs b/src/Compiler/Driver/GraphChecking/DependencyResolution.fs index 9300385b483..11ba984ca51 100644 --- a/src/Compiler/Driver/GraphChecking/DependencyResolution.fs +++ b/src/Compiler/Driver/GraphChecking/DependencyResolution.fs @@ -1,7 +1,6 @@ module internal FSharp.Compiler.GraphChecking.DependencyResolution open FSharp.Compiler.Syntax -open Internal.Utilities.Library /// Find a path from a starting TrieNode and return the end node or None let queryTriePartial (trie: TrieNode) (path: LongIdentifier) : TrieNode option = @@ -118,6 +117,20 @@ let rec processStateEntry (trie: TrieNode) (state: FileContentQueryState) (entry FoundDependencies = foundDependencies } + | ModuleName name -> + // We need to check if the module name is a hit in the Trie. + let state' = + let queryResult = queryTrie trie [ name ] + processIdentifier queryResult state + + match state.OwnNamespace with + | None -> state' + | Some ns -> + // If there we currently have our own namespace, + // the combination of that namespace + module name should be checked as well. + let queryResult = queryTrieDual trie ns [ name ] + processIdentifier queryResult state' + /// /// For a given file's content, collect all missing ("ghost") file dependencies that the core resolution algorithm didn't return, /// but are required to satisfy the type-checker. diff --git a/src/Compiler/Driver/GraphChecking/FileContentMapping.fs b/src/Compiler/Driver/GraphChecking/FileContentMapping.fs index 8ece68bd4bb..a460779e51d 100644 --- a/src/Compiler/Driver/GraphChecking/FileContentMapping.fs +++ b/src/Compiler/Driver/GraphChecking/FileContentMapping.fs @@ -18,6 +18,11 @@ let longIdentToPath (skipLast: bool) (longId: LongIdent) : LongIdentifier = let synLongIdentToPath (skipLast: bool) (synLongIdent: SynLongIdent) = longIdentToPath skipLast synLongIdent.LongIdent +/// In some rare cases we are interested in the name of a single Ident. +/// For example `nameof ModuleName` in expressions or patterns. +let visitIdentAsPotentialModuleName (moduleNameIdent: Ident) = + FileContentEntry.ModuleName moduleNameIdent.idText + let visitSynLongIdent (lid: SynLongIdent) : FileContentEntry list = visitLongIdent lid.LongIdent let visitLongIdent (lid: LongIdent) = @@ -200,7 +205,7 @@ let visitSynMemberDefn (md: SynMemberDefn) : FileContentEntry list = | SynMemberDefn.GetSetMember(memberDefnForGet, memberDefnForSet, _, _) -> yield! collectFromOption visitBinding memberDefnForGet yield! collectFromOption visitBinding memberDefnForSet - | SynMemberDefn.ImplicitCtor(ctorArgs = ctorArgs) -> yield! visitSynSimplePats ctorArgs + | SynMemberDefn.ImplicitCtor(ctorArgs = pat) -> yield! visitPat pat | SynMemberDefn.ImplicitInherit(inheritType, inheritArgs, _, _) -> yield! visitSynType inheritType yield! visitSynExpr inheritArgs @@ -305,9 +310,28 @@ let visitSynTypeConstraint (tc: SynTypeConstraint) : FileContentEntry list = | SynTypeConstraint.WhereTyparIsEnum(typeArgs = typeArgs) -> List.collect visitSynType typeArgs | SynTypeConstraint.WhereTyparIsDelegate(typeArgs = typeArgs) -> List.collect visitSynType typeArgs +[] +let inline (|NameofIdent|_|) (ident: Ident) = + if ident.idText = "nameof" then ValueSome() else ValueNone + +/// Special case of `nameof Module` type of expression +let (|NameofExpr|_|) (e: SynExpr) = + let rec stripParen (e: SynExpr) = + match e with + | SynExpr.Paren(expr = expr) -> stripParen expr + | _ -> e + + match e with + | SynExpr.App(flag = ExprAtomicFlag.NonAtomic; isInfix = false; funcExpr = SynExpr.Ident NameofIdent; argExpr = moduleNameExpr) -> + match stripParen moduleNameExpr with + | SynExpr.Ident moduleNameIdent -> Some moduleNameIdent + | _ -> None + | _ -> None + let visitSynExpr (e: SynExpr) : FileContentEntry list = let rec visit (e: SynExpr) (continuation: FileContentEntry list -> FileContentEntry list) : FileContentEntry list = match e with + | NameofExpr moduleNameIdent -> continuation [ visitIdentAsPotentialModuleName moduleNameIdent ] | SynExpr.Const _ -> continuation [] | SynExpr.Paren(expr = expr) -> visit expr continuation | SynExpr.Quote(operator = operator; quotedExpr = quotedExpr) -> @@ -392,7 +416,7 @@ let visitSynExpr (e: SynExpr) : FileContentEntry list = | SynExpr.IfThenElse(ifExpr = ifExpr; thenExpr = thenExpr; elseExpr = elseExpr) -> let continuations = List.map visit (ifExpr :: thenExpr :: Option.toList elseExpr) Continuation.concatenate continuations continuation - | SynExpr.Typar _ -> continuation [] + | SynExpr.Typar _ | SynExpr.Ident _ -> continuation [] | SynExpr.LongIdent(longDotId = longDotId) -> continuation (visitSynLongIdent longDotId) | SynExpr.LongIdentSet(longDotId, expr, _) -> visit expr (fun nodes -> visitSynLongIdent longDotId @ nodes |> continuation) @@ -520,9 +544,29 @@ let visitSynExpr (e: SynExpr) : FileContentEntry list = visit e id +/// Special case of `| nameof Module ->` type of pattern +let (|NameofPat|_|) (pat: SynPat) = + let rec stripPats p = + match p with + | SynPat.Paren(pat = pat) -> stripPats pat + | _ -> p + + match pat with + | SynPat.LongIdent(longDotId = SynLongIdent(id = [ NameofIdent ]); typarDecls = None; argPats = SynArgPats.Pats [ moduleNamePat ]) -> + match stripPats moduleNamePat with + | SynPat.LongIdent( + longDotId = SynLongIdent.SynLongIdent(id = [ moduleNameIdent ]; dotRanges = []; trivia = [ None ]) + extraId = None + typarDecls = None + argPats = SynArgPats.Pats [] + accessibility = None) -> Some moduleNameIdent + | _ -> None + | _ -> None + let visitPat (p: SynPat) : FileContentEntry list = let rec visit (p: SynPat) (continuation: FileContentEntry list -> FileContentEntry list) : FileContentEntry list = match p with + | NameofPat moduleNameIdent -> continuation [ visitIdentAsPotentialModuleName moduleNameIdent ] | SynPat.Paren(pat = pat) -> visit pat continuation | SynPat.Typed(pat = pat; targetType = t) -> visit pat (fun nodes -> nodes @ visitSynType t) | SynPat.Const _ -> continuation [] diff --git a/src/Compiler/Driver/GraphChecking/Graph.fs b/src/Compiler/Driver/GraphChecking/Graph.fs index dd51ea190a2..dbe4c6b6cc7 100644 --- a/src/Compiler/Driver/GraphChecking/Graph.fs +++ b/src/Compiler/Driver/GraphChecking/Graph.fs @@ -27,26 +27,43 @@ module internal Graph = |> Array.map (fun (KeyValue(k, v)) -> k, v) |> readOnlyDict - let transitive<'Node when 'Node: equality> (graph: Graph<'Node>) : Graph<'Node> = - /// Find transitive dependencies of a single node. - let transitiveDeps (node: 'Node) = - let visited = HashSet<'Node>() + let nodes (graph: Graph<'Node>) : Set<'Node> = + graph.Values |> Seq.collect id |> Seq.append graph.Keys |> Set + + /// Find transitive dependencies of a single node. + let transitiveDeps (node: 'Node) (graph: Graph<'Node>) = + let visited = HashSet<'Node>() - let rec dfs (node: 'Node) = - graph[node] - // Add direct dependencies. - // Use HashSet.Add return value semantics to filter out those that were added previously. - |> Array.filter visited.Add - |> Array.iter dfs + let rec dfs (node: 'Node) = + graph[node] + // Add direct dependencies. + // Use HashSet.Add return value semantics to filter out those that were added previously. + |> Array.filter visited.Add + |> Array.iter dfs - dfs node - visited |> Seq.toArray + dfs node + visited |> Seq.toArray + let transitive<'Node when 'Node: equality> (graph: Graph<'Node>) : Graph<'Node> = graph.Keys |> Seq.toArray - |> Array.Parallel.map (fun node -> node, transitiveDeps node) + |> Array.Parallel.map (fun node -> node, graph |> transitiveDeps node) |> readOnlyDict + // TODO: optimize + /// Get subgraph of the given graph that contains only nodes that are reachable from the given node. + let subGraphFor node graph = + let allDeps = graph |> transitiveDeps node + let relevant n = n = node || allDeps |> Array.contains n + + graph + |> Seq.choose (fun (KeyValue(src, deps)) -> + if relevant src then + Some(src, deps |> Array.filter relevant) + else + None) + |> make + /// Create a reverse of the graph let reverse (originalGraph: Graph<'Node>) : Graph<'Node> = originalGraph @@ -69,7 +86,7 @@ module internal Graph = let print (graph: Graph<'Node>) : unit = printCustom graph (fun node -> node.ToString()) - let serialiseToMermaid path (graph: Graph) = + let serialiseToMermaid (graph: Graph) = let sb = StringBuilder() let appendLine (line: string) = sb.AppendLine(line) |> ignore @@ -84,8 +101,10 @@ module internal Graph = appendLine $" %i{idx} --> %i{depIdx}" appendLine "```" + sb.ToString() + let writeMermaidToFile path (graph: Graph) = use out = FileSystem.OpenFileForWriteShim(path, fileMode = System.IO.FileMode.Create) - out.WriteAllText(sb.ToString()) + graph |> serialiseToMermaid |> out.WriteAllText diff --git a/src/Compiler/Driver/GraphChecking/Graph.fsi b/src/Compiler/Driver/GraphChecking/Graph.fsi index 95542470d8a..a93e429d2fe 100644 --- a/src/Compiler/Driver/GraphChecking/Graph.fsi +++ b/src/Compiler/Driver/GraphChecking/Graph.fsi @@ -10,12 +10,18 @@ module internal Graph = /// Build the graph. val make: nodeDeps: seq<'Node * 'Node array> -> Graph<'Node> when 'Node: equality val map<'T, 'U when 'U: equality> : f: ('T -> 'U) -> graph: Graph<'T> -> Graph<'U> + /// Get all nodes of the graph. + val nodes: graph: Graph<'Node> -> Set<'Node> /// Create a transitive closure of the graph in O(n^2) time (but parallelize it). /// The resulting graph contains edge A -> C iff the input graph contains a (directed) non-zero length path from A to C. val transitive<'Node when 'Node: equality> : graph: Graph<'Node> -> Graph<'Node> + /// Get a sub-graph of the graph containing only the nodes reachable from the given node. + val subGraphFor: node: 'Node -> graph: Graph<'Node> -> Graph<'Node> when 'Node: equality /// Create a reverse of the graph. val reverse<'Node when 'Node: equality> : originalGraph: Graph<'Node> -> Graph<'Node> /// Print the contents of the graph to the standard output. val print: graph: Graph<'Node> -> unit + /// Create a simple Mermaid graph + val serialiseToMermaid: graph: Graph -> string /// Create a simple Mermaid graph and save it under the path specified. - val serialiseToMermaid: path: string -> graph: Graph -> unit + val writeMermaidToFile: path: string -> graph: Graph -> unit diff --git a/src/Compiler/Driver/GraphChecking/GraphProcessing.fs b/src/Compiler/Driver/GraphChecking/GraphProcessing.fs index 47993e00862..afe491b4b74 100644 --- a/src/Compiler/Driver/GraphChecking/GraphProcessing.fs +++ b/src/Compiler/Driver/GraphChecking/GraphProcessing.fs @@ -1,6 +1,9 @@ module internal FSharp.Compiler.GraphChecking.GraphProcessing open System.Threading +open FSharp.Compiler.GraphChecking +open System.Threading.Tasks +open System /// Information about the node in a graph, describing its relation with other nodes. type NodeInfo<'Item> = @@ -32,6 +35,9 @@ type ProcessedNode<'Item, 'Result> = Result: 'Result } +type GraphProcessingException(msg, ex: System.Exception) = + inherit exn(msg, ex) + let processGraph<'Item, 'Result when 'Item: equality and 'Item: comparison> (graph: Graph<'Item>) (work: ('Item -> ProcessedNode<'Item, 'Result>) -> NodeInfo<'Item> -> 'Result) @@ -150,7 +156,7 @@ let processGraph<'Item, 'Result when 'Item: equality and 'Item: comparison> // If we stopped early due to an exception, reraise it. match getExn () with | None -> () - | Some(item, ex) -> raise (System.Exception($"Encountered exception when processing item '{item}'", ex)) + | Some(item, ex) -> raise (GraphProcessingException($"Encountered exception when processing item '{item}'", ex)) // All calculations succeeded - extract the results and sort in input order. nodes.Values @@ -162,3 +168,131 @@ let processGraph<'Item, 'Result when 'Item: equality and 'Item: comparison> node.Info.Item, result) |> Seq.sortBy fst |> Seq.toArray + +let processGraphAsync<'Item, 'Result when 'Item: equality and 'Item: comparison> + (graph: Graph<'Item>) + (work: ('Item -> ProcessedNode<'Item, 'Result>) -> NodeInfo<'Item> -> Async<'Result>) + : Async<('Item * 'Result)[]> = + async { + let transitiveDeps = graph |> Graph.transitive + let dependants = graph |> Graph.reverse + // Cancellation source used to signal either an exception in one of the items or end of processing. + let! parentCt = Async.CancellationToken + use localCts = new CancellationTokenSource() + + let completionSignal = TaskCompletionSource() + + use _ = parentCt.Register(fun () -> completionSignal.TrySetCanceled() |> ignore) + + use cts = CancellationTokenSource.CreateLinkedTokenSource(parentCt, localCts.Token) + + let makeNode (item: 'Item) : GraphNode<'Item, 'Result> = + let info = + let exists = graph.ContainsKey item + + if + not exists + || not (transitiveDeps.ContainsKey item) + || not (dependants.ContainsKey item) + then + printfn $"Unexpected inconsistent state of the graph for item '{item}'" + + { + Item = item + Deps = graph[item] + TransitiveDeps = transitiveDeps[item] + Dependants = dependants[item] + } + + { + Info = info + Result = None + ProcessedDepsCount = IncrementableInt(0) + } + + let nodes = graph.Keys |> Seq.map (fun item -> item, makeNode item) |> readOnlyDict + + let lookupMany items = + items |> Array.map (fun item -> nodes[item]) + + let leaves = + nodes.Values |> Seq.filter (fun n -> n.Info.Deps.Length = 0) |> Seq.toArray + + let getItemPublicNode item = + let node = nodes[item] + + { + ProcessedNode.Info = node.Info + ProcessedNode.Result = + node.Result + |> Option.defaultWith (fun () -> failwith $"Results for item '{node.Info.Item}' are not yet available") + } + + let processedCount = IncrementableInt(0) + + let raiseExn (item, ex: exn) = + localCts.Cancel() + + match ex with + | :? OperationCanceledException -> completionSignal.TrySetCanceled() + | _ -> + completionSignal.TrySetException( + GraphProcessingException($"[*] Encountered exception when processing item '{item}': {ex.Message}", ex) + ) + |> ignore + + let incrementProcessedNodesCount () = + if processedCount.Increment() = nodes.Count then + completionSignal.TrySetResult() |> ignore + + let rec queueNode node = + Async.Start( + async { + let! res = processNode node |> Async.Catch + + match res with + | Choice1Of2() -> () + | Choice2Of2 ex -> raiseExn (node.Info.Item, ex) + }, + cts.Token + ) + + and processNode (node: GraphNode<'Item, 'Result>) : Async = + async { + + let info = node.Info + + let! singleRes = work getItemPublicNode info + node.Result <- Some singleRes + + let unblockedDependants = + node.Info.Dependants + |> lookupMany + // For every dependant, increment its number of processed dependencies, + // and filter dependants which now have all dependencies processed (but didn't before). + |> Array.filter (fun dependant -> + let pdc = dependant.ProcessedDepsCount.Increment() + // Note: We cannot read 'dependant.ProcessedDepsCount' again to avoid returning the same item multiple times. + pdc = dependant.Info.Deps.Length) + + unblockedDependants |> Array.iter queueNode + incrementProcessedNodesCount () + } + + leaves |> Array.iter queueNode + + // Wait for end of processing, an exception, or an external cancellation request. + do! completionSignal.Task |> Async.AwaitTask + + // All calculations succeeded - extract the results and sort in input order. + return + nodes.Values + |> Seq.map (fun node -> + let result = + node.Result + |> Option.defaultWith (fun () -> failwith $"Unexpected lack of result for item '{node.Info.Item}'") + + node.Info.Item, result) + |> Seq.sortBy fst + |> Seq.toArray + } diff --git a/src/Compiler/Driver/GraphChecking/GraphProcessing.fsi b/src/Compiler/Driver/GraphChecking/GraphProcessing.fsi index cb9a95a59f8..585daa52fd7 100644 --- a/src/Compiler/Driver/GraphChecking/GraphProcessing.fsi +++ b/src/Compiler/Driver/GraphChecking/GraphProcessing.fsi @@ -15,6 +15,10 @@ type ProcessedNode<'Item, 'Result> = { Info: NodeInfo<'Item> Result: 'Result } +type GraphProcessingException = + inherit exn + new: msg: string * ex: System.Exception -> GraphProcessingException + /// /// A generic method to generate results for a graph of work items in parallel. /// Processes leaves first, and after each node has been processed, schedules any now unblocked dependants. @@ -33,3 +37,8 @@ val processGraph<'Item, 'Result when 'Item: equality and 'Item: comparison> : work: (('Item -> ProcessedNode<'Item, 'Result>) -> NodeInfo<'Item> -> 'Result) -> parentCt: CancellationToken -> ('Item * 'Result)[] + +val processGraphAsync<'Item, 'Result when 'Item: equality and 'Item: comparison> : + graph: Graph<'Item> -> + work: (('Item -> ProcessedNode<'Item, 'Result>) -> NodeInfo<'Item> -> Async<'Result>) -> + Async<('Item * 'Result)[]> diff --git a/src/Compiler/Driver/GraphChecking/Types.fs b/src/Compiler/Driver/GraphChecking/Types.fs index 00538b6e599..c667a573f69 100644 --- a/src/Compiler/Driver/GraphChecking/Types.fs +++ b/src/Compiler/Driver/GraphChecking/Types.fs @@ -73,6 +73,9 @@ type internal FileContentEntry = /// Being explicit about nested modules allows for easier reasoning what namespaces (paths) are open. /// We can scope an `OpenStatement` to the everything that is happening inside the nested module. | NestedModule of name: string * nestedContent: FileContentEntry list + /// A single identifier that could be the name of a module. + /// Example use-case: `let x = nameof Foo` where `Foo` is a module. + | ModuleName of name: Identifier type internal FileContent = { diff --git a/src/Compiler/Driver/GraphChecking/Types.fsi b/src/Compiler/Driver/GraphChecking/Types.fsi index 468ef65889c..096719b6be7 100644 --- a/src/Compiler/Driver/GraphChecking/Types.fsi +++ b/src/Compiler/Driver/GraphChecking/Types.fsi @@ -67,6 +67,9 @@ type internal FileContentEntry = /// Being explicit about nested modules allows for easier reasoning what namespaces (paths) are open. /// For example we can limit the scope of an `OpenStatement` to symbols defined inside the nested module. | NestedModule of name: string * nestedContent: FileContentEntry list + /// A single identifier that could be the name of a module. + /// Example use-case: `let x = nameof Foo` where `Foo` is a module. + | ModuleName of name: Identifier /// File identifiers and its content extract for dependency resolution type internal FileContent = diff --git a/src/Compiler/Driver/ParseAndCheckInputs.fs b/src/Compiler/Driver/ParseAndCheckInputs.fs index a9fc59b66d3..5a23c95ca7b 100644 --- a/src/Compiler/Driver/ParseAndCheckInputs.fs +++ b/src/Compiler/Driver/ParseAndCheckInputs.fs @@ -1483,7 +1483,7 @@ let CheckOneInputWithCallback prefixPathOpt, tcSink, tcState: TcState, - inp: ParsedInput, + input: ParsedInput, _skipImplIfSigExists: bool): (unit -> bool) * TcConfig * TcImports * TcGlobals * LongIdent option * TcResultsSink * TcState * ParsedInput * bool) : Cancellable> = @@ -1491,7 +1491,7 @@ let CheckOneInputWithCallback try CheckSimulateException tcConfig - let m = inp.Range + let m = input.Range let amap = tcImports.GetImportMap() let conditionalDefines = @@ -1500,7 +1500,7 @@ let CheckOneInputWithCallback else Some tcConfig.conditionalDefines - match inp with + match input with | ParsedInput.SigFile file -> let qualNameOfFile = file.QualifiedName @@ -1740,6 +1740,43 @@ module private TypeCheckingGraphProcessing = finalFileResults, state +let TransformDependencyGraph (graph: Graph, filePairs: FilePairMap) = + let mkArtificialImplFile n = NodeToTypeCheck.ArtificialImplFile n + let mkPhysicalFile n = NodeToTypeCheck.PhysicalFile n + + /// Map any signature dependencies to the ArtificialImplFile counterparts, + /// unless the signature dependency is the backing file of the current (implementation) file. + let mapDependencies idx deps = + Array.map + (fun dep -> + if filePairs.IsSignature dep then + let implIdx = filePairs.GetImplementationIndex dep + + if implIdx = idx then + // This is the matching signature for the implementation. + // Retain the direct dependency onto the signature file. + mkPhysicalFile dep + else + mkArtificialImplFile dep + else + mkPhysicalFile dep) + deps + + // Transform the graph to include ArtificialImplFile nodes when necessary. + graph + |> Seq.collect (fun (KeyValue(fileIdx, deps)) -> + if filePairs.IsSignature fileIdx then + // Add an additional ArtificialImplFile node for the signature file. + [| + // Mark the current file as physical and map the dependencies. + mkPhysicalFile fileIdx, mapDependencies fileIdx deps + // Introduce a new node that depends on the signature. + mkArtificialImplFile fileIdx, [| mkPhysicalFile fileIdx |] + |] + else + [| mkPhysicalFile fileIdx, mapDependencies fileIdx deps |]) + |> Graph.make + /// Constructs a file dependency graph and type-checks the files in parallel where possible. let CheckMultipleInputsUsingGraphMode ((ctok, checkForErrors, tcConfig: TcConfig, tcImports: TcImports, tcGlobals, prefixPathOpt, tcState, eagerFormat, inputs): @@ -1768,42 +1805,7 @@ let CheckMultipleInputsUsingGraphMode let filePairs = FilePairMap(sourceFiles) let graph, trie = DependencyResolution.mkGraph filePairs sourceFiles - let nodeGraph = - let mkArtificialImplFile n = NodeToTypeCheck.ArtificialImplFile n - let mkPhysicalFile n = NodeToTypeCheck.PhysicalFile n - - /// Map any signature dependencies to the ArtificialImplFile counterparts, - /// unless the signature dependency is the backing file of the current (implementation) file. - let mapDependencies idx deps = - Array.map - (fun dep -> - if filePairs.IsSignature dep then - let implIdx = filePairs.GetImplementationIndex dep - - if implIdx = idx then - // This is the matching signature for the implementation. - // Retain the direct dependency onto the signature file. - mkPhysicalFile dep - else - mkArtificialImplFile dep - else - mkPhysicalFile dep) - deps - - // Transform the graph to include ArtificialImplFile nodes when necessary. - graph - |> Seq.collect (fun (KeyValue(fileIdx, deps)) -> - if filePairs.IsSignature fileIdx then - // Add an additional ArtificialImplFile node for the signature file. - [| - // Mark the current file as physical and map the dependencies. - mkPhysicalFile fileIdx, mapDependencies fileIdx deps - // Introduce a new node that depends on the signature. - mkArtificialImplFile fileIdx, [| mkPhysicalFile fileIdx |] - |] - else - [| mkPhysicalFile fileIdx, mapDependencies fileIdx deps |]) - |> Graph.make + let nodeGraph = TransformDependencyGraph(graph, filePairs) // Persist the graph to a Mermaid diagram if specified. if tcConfig.typeCheckingConfig.DumpGraph then @@ -1823,7 +1825,7 @@ let CheckMultipleInputsUsingGraphMode .TrimStart([| '\\'; '/' |]) (idx, friendlyFileName)) - |> Graph.serialiseToMermaid graphFile) + |> Graph.writeMermaidToFile graphFile) let _ = ctok // TODO Use it let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger diff --git a/src/Compiler/Driver/ParseAndCheckInputs.fsi b/src/Compiler/Driver/ParseAndCheckInputs.fsi index 745afa51be4..875be616a8e 100644 --- a/src/Compiler/Driver/ParseAndCheckInputs.fsi +++ b/src/Compiler/Driver/ParseAndCheckInputs.fsi @@ -13,12 +13,44 @@ open FSharp.Compiler.CompilerImports open FSharp.Compiler.Diagnostics open FSharp.Compiler.DependencyManager open FSharp.Compiler.DiagnosticsLogger +open FSharp.Compiler.GraphChecking +open FSharp.Compiler.NameResolution open FSharp.Compiler.Syntax open FSharp.Compiler.TcGlobals open FSharp.Compiler.Text open FSharp.Compiler.TypedTree open FSharp.Compiler.UnicodeLexing +/// Auxiliary type for re-using signature information in TcEnvFromImpls. +/// +/// TcState has two typing environments: TcEnvFromSignatures && TcEnvFromImpls +/// When type checking a file, depending on the type (implementation or signature), it will use one of these typing environments (TcEnv). +/// Checking a file will populate the respective TcEnv. +/// +/// When a file has a dependencies, the information of the signature file in case a pair (implementation file backed by a signature) will suffice to type-check that file. +/// Example: if `B.fs` has a dependency on `A`, the information of `A.fsi` is enough for `B.fs` to type-check, on condition that information is available in the TcEnvFromImpls. +/// We introduce a special ArtificialImplFile node in the graph to satisfy this. `B.fs -> [ A.fsi ]` becomes `B.fs -> [ ArtificialImplFile A ]. +/// The `ArtificialImplFile A` node will duplicate the signature information which A.fsi provided earlier. +/// Processing a `ArtificialImplFile` node will add the information from the TcEnvFromSignatures to the TcEnvFromImpls. +/// This means `A` will be known in both TcEnvs and therefor `B.fs` can be type-checked. +/// By doing this, we can speed up the graph processing as type checking a signature file is less expensive than its implementation counterpart. +/// +/// When we need to actually type-check an implementation file backed by a signature, we cannot have the duplicate information of the signature file present in TcEnvFromImpls. +/// Example `A.fs -> [ A.fsi ]`. An implementation file always depends on its signature. +/// Type-checking `A.fs` will add the actual information to TcEnvFromImpls and we do not depend on the `ArtificialImplFile A` for `A.fs`. +/// +/// In order to deal correctly with the `ArtificialImplFile` logic, we need to transform the resolved graph to contain the additional pair nodes. +/// After we have type-checked the graph, we exclude the ArtificialImplFile nodes as they are not actual physical files in our project. +[] +type NodeToTypeCheck = + /// A real physical file in the current project. + /// This can be either an implementation or a signature file. + | PhysicalFile of fileIndex: FileIndex + /// An artificial node that will add the earlier processed signature information to the TcEnvFromImpls. + /// Dependants on this type of node will perceive that a file is known in both TcEnvFromSignatures and TcEnvFromImpls. + /// Even though the actual implementation file was not type-checked. + | ArtificialImplFile of signatureFileIndex: FileIndex + val IsScript: string -> bool val ComputeQualifiedNameOfFileFromUniquePath: range * string list -> QualifiedNameOfFile @@ -131,6 +163,8 @@ type TcState = member CreatesGeneratedProvidedTypes: bool +type PartialResult = TcEnv * TopAttribs * CheckedImplFile option * ModuleOrNamespaceType + /// Get the initial type checking state for a set of inputs val GetInitialTcState: range * string * TcConfig * TcGlobals * TcImports * TcEnv * OpenDeclaration list -> TcState @@ -151,6 +185,42 @@ val CheckOneInput: input: ParsedInput -> Cancellable<(TcEnv * TopAttribs * CheckedImplFile option * ModuleOrNamespaceType) * TcState> +val CheckOneInputWithCallback: + node: NodeToTypeCheck -> + checkForErrors: (unit -> bool) * + tcConfig: TcConfig * + tcImports: TcImports * + tcGlobals: TcGlobals * + prefixPathOpt: LongIdent option * + tcSink: TcResultsSink * + tcState: TcState * + input: ParsedInput * + _skipImplIfSigExists: bool -> + Cancellable> + +val AddCheckResultsToTcState: + tcGlobals: TcGlobals * + amap: Import.ImportMap * + hadSig: bool * + prefixPathOpt: LongIdent option * + tcSink: TcResultsSink * + tcImplEnv: TcEnv * + qualNameOfFile: QualifiedNameOfFile * + implFileSigType: ModuleOrNamespaceType -> + tcState: TcState -> + ModuleOrNamespaceType * TcState + +val AddSignatureResultToTcImplEnv: + tcImports: TcImports * + tcGlobals: TcGlobals * + prefixPathOpt: LongIdent option * + tcSink: TcResultsSink * + tcState: TcState * + input: ParsedInput -> + (TcState -> PartialResult * TcState) + +val TransformDependencyGraph: graph: Graph * filePairs: FilePairMap -> Graph + /// Finish the checking of multiple inputs val CheckMultipleInputsFinish: (TcEnv * TopAttribs * 'T option * 'U) list * TcState -> (TcEnv * TopAttribs * 'T list * 'U list) * TcState diff --git a/src/Compiler/Driver/fsc.fs b/src/Compiler/Driver/fsc.fs index d3bfd2e74cc..eab380bae5c 100644 --- a/src/Compiler/Driver/fsc.fs +++ b/src/Compiler/Driver/fsc.fs @@ -349,7 +349,7 @@ module InterfaceFileWriter = let writeAllToSameFile declaredImpls = /// Use a UTF-8 Encoding with no Byte Order Mark let os = - if tcConfig.printSignatureFile = "" then + if String.IsNullOrEmpty(tcConfig.printSignatureFile) then Console.Out else FileSystem diff --git a/src/Compiler/FSComp.txt b/src/Compiler/FSComp.txt index 3eba9541293..b6211ffaea5 100644 --- a/src/Compiler/FSComp.txt +++ b/src/Compiler/FSComp.txt @@ -315,6 +315,7 @@ csExpectTypeWithOperatorButGivenFunction,"Expecting a type supporting the operat csExpectTypeWithOperatorButGivenTuple,"Expecting a type supporting the operator '%s' but given a tuple type" csTypesDoNotSupportOperator,"None of the types '%s' support the operator '%s'" csTypeDoesNotSupportOperator,"The type '%s' does not support the operator '%s'" +csFunctionDoesNotSupportType,"'%s' does not support the type '%s', because the latter lacks the required (real or built-in) member '%s'" csTypesDoNotSupportOperatorNullable,"None of the types '%s' support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'." csTypeDoesNotSupportOperatorNullable,"The type '%s' does not support the operator '%s'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'." csTypeDoesNotSupportConversion,"The type '%s' does not support a conversion to the type '%s'" @@ -1750,4 +1751,6 @@ featureReuseSameFieldsInStructUnions,"Share underlying fields in a [] di 3860,chkStaticMembersOnObjectExpressions,"Object expressions cannot implement interfaces with static abstract members or declare static members." 3861,chkTailCallAttrOnNonRec,"The TailCall attribute should only be applied to recursive functions." 3862,parsStaticMemberImcompleteSyntax,"Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration." -3863,parsExpectingField,"Expecting record field" \ No newline at end of file +3863,parsExpectingField,"Expecting record field" +3864,tooManyMethodsInDotNetTypeWritingAssembly,"The type '%s' has too many methods. Found: '%d', maximum: '%d'" +3865,parsOnlySimplePatternsAreAllowedInConstructors,"Only simple patterns are allowed in primary constructors" \ No newline at end of file diff --git a/src/Compiler/FSStrings.resx b/src/Compiler/FSStrings.resx index 60558f2e35b..e0a53a33ae1 100644 --- a/src/Compiler/FSStrings.resx +++ b/src/Compiler/FSStrings.resx @@ -1044,20 +1044,11 @@ The following fields require values: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. syntax error diff --git a/src/Compiler/FSharp.Compiler.Service.fsproj b/src/Compiler/FSharp.Compiler.Service.fsproj index 65c00a7702d..61fcb193a1a 100644 --- a/src/Compiler/FSharp.Compiler.Service.fsproj +++ b/src/Compiler/FSharp.Compiler.Service.fsproj @@ -21,6 +21,7 @@ $(OtherFlags) --warnon:3218 $(OtherFlags) --warnon:3390 + true $(IntermediateOutputPath)$(TargetFramework)\ $(IntermediateOutputPath)$(TargetFramework)\ @@ -76,7 +77,8 @@ - + + @@ -90,6 +92,7 @@ FSStrings.resx FSStrings.resources + @@ -124,6 +127,8 @@ + + @@ -144,6 +149,8 @@ + + @@ -156,6 +163,8 @@ + + @@ -475,6 +484,10 @@ + + + + @@ -492,7 +505,12 @@ - + + + + + + diff --git a/src/Compiler/Facilities/AsyncMemoize.fs b/src/Compiler/Facilities/AsyncMemoize.fs new file mode 100644 index 00000000000..8309eaa1c15 --- /dev/null +++ b/src/Compiler/Facilities/AsyncMemoize.fs @@ -0,0 +1,610 @@ +namespace Internal.Utilities.Collections + +open System +open System.Collections.Generic +open System.Diagnostics +open System.IO +open System.Threading +open System.Threading.Tasks + +open FSharp.Compiler +open FSharp.Compiler.BuildGraph +open FSharp.Compiler.Diagnostics +open FSharp.Compiler.DiagnosticsLogger +open System.Runtime.CompilerServices + +[] +module internal Utils = + + /// Return file name with one directory above it + let shortPath path = + let dirPath = Path.GetDirectoryName path + + let dir = + dirPath.Split Path.DirectorySeparatorChar + |> Array.tryLast + |> Option.map (sprintf "%s/") + |> Option.defaultValue "" + + $"{dir}{Path.GetFileName path}" + + let replayDiagnostics (logger: DiagnosticsLogger) = Seq.iter ((<|) logger.DiagnosticSink) + + let (|TaskCancelled|_|) (ex: exn) = + match ex with + | :? System.Threading.Tasks.TaskCanceledException as tce -> Some tce + //| :? System.AggregateException as ae -> + // if ae.InnerExceptions |> Seq.forall (fun e -> e :? System.Threading.Tasks.TaskCanceledException) then + // ae.InnerExceptions |> Seq.tryHead |> Option.map (fun e -> e :?> System.Threading.Tasks.TaskCanceledException) + // else + // None + | _ -> None + +type internal StateUpdate<'TValue> = + | CancelRequest + | OriginatorCanceled + | JobCompleted of 'TValue * (PhasedDiagnostic * FSharpDiagnosticSeverity) list + | JobFailed of exn * (PhasedDiagnostic * FSharpDiagnosticSeverity) list + +type internal MemoizeReply<'TValue> = + | New of CancellationToken + | Existing of Task<'TValue> + +type internal MemoizeRequest<'TValue> = GetOrCompute of NodeCode<'TValue> * CancellationToken + +[] +type internal Job<'TValue> = + | Running of TaskCompletionSource<'TValue> * CancellationTokenSource * NodeCode<'TValue> * DateTime * ResizeArray + | Completed of 'TValue * (PhasedDiagnostic * FSharpDiagnosticSeverity) list + | Canceled of DateTime + | Failed of DateTime * exn // TODO: probably we don't need to keep this + + member this.DebuggerDisplay = + match this with + | Running(_, cts, _, ts, _) -> + let cancellation = + if cts.IsCancellationRequested then + " ! Cancellation Requested" + else + "" + + $"Running since {ts.ToShortTimeString()}{cancellation}" + | Completed(value, diags) -> $"Completed {value}" + (if diags.Length > 0 then $" ({diags.Length})" else "") + | Canceled _ -> "Canceled" + | Failed(_, ex) -> $"Failed {ex}" + +type internal JobEvent = + | Started + | Finished + | Canceled + | Evicted + | Collected + | Weakened + | Strengthened + | Failed + | Cleared + +type internal ICacheKey<'TKey, 'TVersion> = + abstract member GetKey: unit -> 'TKey + abstract member GetVersion: unit -> 'TVersion + abstract member GetLabel: unit -> string + +[] +type Extensions = + + [] + static member internal WithExtraVersion(cacheKey: ICacheKey<_, _>, extraVersion) = + { new ICacheKey<_, _> with + member _.GetLabel() = cacheKey.GetLabel() + member _.GetKey() = cacheKey.GetKey() + member _.GetVersion() = cacheKey.GetVersion(), extraVersion + } + +type private KeyData<'TKey, 'TVersion> = + { + Label: string + Key: 'TKey + Version: 'TVersion + } + +type internal AsyncLock() = + + let semaphore = new SemaphoreSlim(1, 1) + + member _.Semaphore = semaphore + + member _.Do(f) = + task { + do! semaphore.WaitAsync() + + try + return! f () + finally + semaphore.Release() |> ignore + } + + interface IDisposable with + member _.Dispose() = semaphore.Dispose() + +type internal CachingDiagnosticsLogger(originalLogger: DiagnosticsLogger option) = + inherit DiagnosticsLogger($"CachingDiagnosticsLogger") + + let capturedDiagnostics = ResizeArray() + + override _.ErrorCount = + originalLogger + |> Option.map (fun x -> x.ErrorCount) + |> Option.defaultValue capturedDiagnostics.Count + + override _.DiagnosticSink(diagnostic: PhasedDiagnostic, severity: FSharpDiagnosticSeverity) = + originalLogger |> Option.iter (fun x -> x.DiagnosticSink(diagnostic, severity)) + capturedDiagnostics.Add(diagnostic, severity) + + member _.CapturedDiagnostics = capturedDiagnostics |> Seq.toList + +[] +type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality> + (?keepStrongly, ?keepWeakly, ?name: string, ?cancelDuplicateRunningJobs: bool) = + + let name = defaultArg name "N/A" + let cancelDuplicateRunningJobs = defaultArg cancelDuplicateRunningJobs false + + let event = Event<_>() + + let mutable errors = 0 + let mutable hits = 0 + let mutable started = 0 + let mutable completed = 0 + let mutable canceled = 0 + let mutable restarted = 0 + let mutable failed = 0 + let mutable evicted = 0 + let mutable collected = 0 + let mutable strengthened = 0 + let mutable cleared = 0 + + let mutable cancel_ct_registration_original = 0 + let mutable cancel_exception_original = 0 + let mutable cancel_original_processed = 0 + let mutable cancel_ct_registration_subsequent = 0 + let mutable cancel_exception_subsequent = 0 + let mutable cancel_subsequent_processed = 0 + + let failures = ResizeArray() + let mutable avgDurationMs = 0.0 + + let cache = + LruCache<'TKey, 'TVersion, Job<'TValue>>( + keepStrongly = defaultArg keepStrongly 100, + keepWeakly = defaultArg keepWeakly 200, + requiredToKeep = + (function + | Running _ -> true + | Job.Canceled at when at > DateTime.Now.AddMinutes -5.0 -> true + | Job.Failed(at, _) when at > DateTime.Now.AddMinutes -5.0 -> true + | _ -> false), + event = + (function + | CacheEvent.Evicted -> + (fun k -> + Interlocked.Increment &evicted |> ignore + event.Trigger(JobEvent.Evicted, k)) + | CacheEvent.Collected -> + (fun k -> + Interlocked.Increment &collected |> ignore + event.Trigger(JobEvent.Collected, k)) + | CacheEvent.Weakened -> (fun k -> event.Trigger(JobEvent.Weakened, k)) + | CacheEvent.Strengthened -> + (fun k -> + Interlocked.Increment &strengthened |> ignore + event.Trigger(JobEvent.Strengthened, k)) + | CacheEvent.Cleared -> + (fun k -> + Interlocked.Increment &cleared |> ignore + event.Trigger(JobEvent.Cleared, k))) + ) + + let requestCounts = Dictionary, int>() + let cancellationRegistrations = Dictionary<_, _>() + + let saveRegistration key registration = + cancellationRegistrations[key] <- + match cancellationRegistrations.TryGetValue key with + | true, registrations -> registration :: registrations + | _ -> [ registration ] + + let cancelRegistration key = + match cancellationRegistrations.TryGetValue key with + | true, registrations -> + for r: CancellationTokenRegistration in registrations do + r.Dispose() + + cancellationRegistrations.Remove key |> ignore + | _ -> () + + let incrRequestCount key = + requestCounts[key] <- + if requestCounts.ContainsKey key then + requestCounts[key] + 1 + else + 1 + + let decrRequestCount key = + if requestCounts.ContainsKey key then + requestCounts[key] <- requestCounts[key] - 1 + + let log (eventType, keyData: KeyData<_, _>) = + event.Trigger(eventType, (keyData.Label, keyData.Key, keyData.Version)) + + let lock = new AsyncLock() + + let processRequest post (key: KeyData<_, _>, msg) diagnosticLogger = + + lock.Do(fun () -> + task { + + let cached, otherVersions = cache.GetAll(key.Key, key.Version) + + return + match msg, cached with + | GetOrCompute _, Some(Completed(result, diags)) -> + Interlocked.Increment &hits |> ignore + diags |> replayDiagnostics diagnosticLogger + Existing(Task.FromResult result) + | GetOrCompute(_, ct), Some(Running(tcs, _, _, _, loggers)) -> + Interlocked.Increment &hits |> ignore + incrRequestCount key + + ct.Register(fun _ -> + let _name = name + Interlocked.Increment &cancel_ct_registration_subsequent |> ignore + post (key, CancelRequest)) + |> saveRegistration key + + loggers.Add diagnosticLogger + + Existing tcs.Task + + | GetOrCompute(computation, ct), None + | GetOrCompute(computation, ct), Some(Job.Canceled _) + | GetOrCompute(computation, ct), Some(Job.Failed _) -> + Interlocked.Increment &started |> ignore + incrRequestCount key + + ct.Register(fun _ -> + let _name = name + Interlocked.Increment &cancel_ct_registration_original |> ignore + post (key, OriginatorCanceled)) + |> saveRegistration key + + let cts = new CancellationTokenSource() + + cache.Set( + key.Key, + key.Version, + key.Label, + (Running(TaskCompletionSource(), cts, computation, DateTime.Now, ResizeArray())) + ) + + otherVersions + |> Seq.choose (function + | v, Running(_tcs, cts, _, _, _) -> Some(v, cts) + | _ -> None) + |> Seq.iter (fun (_v, cts) -> + use _ = Activity.start $"{name}: Duplicate running job" [| "key", key.Label |] + //System.Diagnostics.Trace.TraceWarning($"{name} Duplicate {key.Label}") + if cancelDuplicateRunningJobs then + //System.Diagnostics.Trace.TraceWarning("Canceling") + cts.Cancel()) + + New cts.Token + }) + + let internalError key message = + let ex = exn (message) + failures.Add(key, ex) + Interlocked.Increment &errors |> ignore + // raise ex -- Suppose there's no need to raise here - where does it even go? + + let processStateUpdate post (key: KeyData<_, _>, action: StateUpdate<_>) = + task { + do! Task.Delay 0 + + do! + lock.Do(fun () -> + task { + + let cached = cache.TryGet(key.Key, key.Version) + + match action, cached with + + | OriginatorCanceled, Some(Running(tcs, cts, computation, _, _)) -> + + Interlocked.Increment &cancel_original_processed |> ignore + + decrRequestCount key + + if requestCounts[key] < 1 then + cancelRegistration key + cts.Cancel() + tcs.TrySetCanceled() |> ignore + // Remember the job in case it completes after cancellation + cache.Set(key.Key, key.Version, key.Label, Job.Canceled DateTime.Now) + requestCounts.Remove key |> ignore + log (Canceled, key) + Interlocked.Increment &canceled |> ignore + use _ = Activity.start $"{name}: Canceled job" [| "key", key.Label |] + () + + else + // We need to restart the computation + Task.Run(fun () -> + Async.StartAsTask( + async { + + let cachingLogger = new CachingDiagnosticsLogger(None) + + try + // TODO: Should unify starting and restarting + log (Started, key) + Interlocked.Increment &restarted |> ignore + System.Diagnostics.Trace.TraceInformation $"{name} Restarted {key.Label}" + let currentLogger = DiagnosticsThreadStatics.DiagnosticsLogger + DiagnosticsThreadStatics.DiagnosticsLogger <- cachingLogger + + try + let! result = computation |> Async.AwaitNodeCode + post (key, (JobCompleted(result, cachingLogger.CapturedDiagnostics))) + return () + finally + DiagnosticsThreadStatics.DiagnosticsLogger <- currentLogger + with + | TaskCancelled _ -> + Interlocked.Increment &cancel_exception_subsequent |> ignore + post (key, CancelRequest) + () + | ex -> post (key, (JobFailed(ex, cachingLogger.CapturedDiagnostics))) + } + ), + cts.Token) + |> ignore + + | CancelRequest, Some(Running(tcs, cts, _c, _, _)) -> + + Interlocked.Increment &cancel_subsequent_processed |> ignore + + decrRequestCount key + + if requestCounts[key] < 1 then + cancelRegistration key + cts.Cancel() + tcs.TrySetCanceled() |> ignore + // Remember the job in case it completes after cancellation + cache.Set(key.Key, key.Version, key.Label, Job.Canceled DateTime.Now) + requestCounts.Remove key |> ignore + log (Canceled, key) + Interlocked.Increment &canceled |> ignore + use _ = Activity.start $"{name}: Canceled job" [| "key", key.Label |] + () + + // Probably in some cases cancellation can be fired off even after we just unregistered it + | CancelRequest, None + | CancelRequest, Some(Completed _) + | CancelRequest, Some(Job.Canceled _) + | CancelRequest, Some(Job.Failed _) + | OriginatorCanceled, None + | OriginatorCanceled, Some(Completed _) + | OriginatorCanceled, Some(Job.Canceled _) + | OriginatorCanceled, Some(Job.Failed _) -> () + + | JobFailed(ex, diags), Some(Running(tcs, _cts, _c, _ts, loggers)) -> + cancelRegistration key + cache.Set(key.Key, key.Version, key.Label, Job.Failed(DateTime.Now, ex)) + requestCounts.Remove key |> ignore + log (Failed, key) + Interlocked.Increment &failed |> ignore + failures.Add(key.Label, ex) + + for logger in loggers do + diags |> replayDiagnostics logger + + tcs.TrySetException ex |> ignore + + | JobCompleted(result, diags), Some(Running(tcs, _cts, _c, started, loggers)) -> + cancelRegistration key + cache.Set(key.Key, key.Version, key.Label, (Completed(result, diags))) + requestCounts.Remove key |> ignore + log (Finished, key) + Interlocked.Increment &completed |> ignore + let duration = float (DateTime.Now - started).Milliseconds + + avgDurationMs <- + if completed < 2 then + duration + else + avgDurationMs + (duration - avgDurationMs) / float completed + + for logger in loggers do + diags |> replayDiagnostics logger + + if tcs.TrySetResult result = false then + internalError key.Label "Invalid state: Completed job already completed" + + // Sometimes job can be canceled but it still manages to complete (or fail) + | JobFailed _, Some(Job.Canceled _) + | JobCompleted _, Some(Job.Canceled _) -> () + + // Job can't be evicted from cache while it's running because then subsequent requesters would be waiting forever + | JobFailed _, None -> internalError key.Label "Invalid state: Running job missing in cache (failed)" + + | JobCompleted _, None -> internalError key.Label "Invalid state: Running job missing in cache (completed)" + + | JobFailed(ex, _diags), Some(Completed(_job, _diags2)) -> + internalError key.Label $"Invalid state: Failed Completed job \n%A{ex}" + + | JobCompleted(_result, _diags), Some(Completed(_job, _diags2)) -> + internalError key.Label "Invalid state: Double-Completed job" + + | JobFailed(ex, _diags), Some(Job.Failed(_, ex2)) -> + internalError key.Label $"Invalid state: Double-Failed job \n%A{ex} \n%A{ex2}" + + | JobCompleted(_result, _diags), Some(Job.Failed(_, ex2)) -> + internalError key.Label $"Invalid state: Completed Failed job \n%A{ex2}" + }) + } + + let rec post msg = + Task.Run(fun () -> processStateUpdate post msg :> Task) |> ignore + + member this.Get'(key, computation) = + + let wrappedKey = + { new ICacheKey<_, _> with + member _.GetKey() = key + member _.GetVersion() = Unchecked.defaultof<_> + member _.GetLabel() = key.ToString() + } + + this.Get(wrappedKey, computation) + + member _.Get(key: ICacheKey<_, _>, computation) = + + let key = + { + Label = key.GetLabel() + Key = key.GetKey() + Version = key.GetVersion() + } + + node { + let! ct = NodeCode.CancellationToken + + let callerDiagnosticLogger = DiagnosticsThreadStatics.DiagnosticsLogger + + match! + processRequest post (key, GetOrCompute(computation, ct)) callerDiagnosticLogger + |> NodeCode.AwaitTask + with + | New internalCt -> + + let linkedCtSource = CancellationTokenSource.CreateLinkedTokenSource(ct, internalCt) + let cachingLogger = new CachingDiagnosticsLogger(Some callerDiagnosticLogger) + + try + return! + Async.StartAsTask( + async { + // TODO: Should unify starting and restarting + let currentLogger = DiagnosticsThreadStatics.DiagnosticsLogger + DiagnosticsThreadStatics.DiagnosticsLogger <- cachingLogger + + log (Started, key) + + try + let! result = computation |> Async.AwaitNodeCode + post (key, (JobCompleted(result, cachingLogger.CapturedDiagnostics))) + return result + finally + DiagnosticsThreadStatics.DiagnosticsLogger <- currentLogger + }, + cancellationToken = linkedCtSource.Token + ) + |> NodeCode.AwaitTask + with + | TaskCancelled ex -> + // TODO: do we need to do anything else here? Presumably it should be done by the registration on + // the cancellation token or before we triggered our own cancellation + + // Let's send this again just in case. It seems sometimes it's not triggered from the registration? + + Interlocked.Increment &cancel_exception_original |> ignore + + post (key, (OriginatorCanceled)) + return raise ex + | ex -> + post (key, (JobFailed(ex, cachingLogger.CapturedDiagnostics))) + return raise ex + + | Existing job -> return! job |> NodeCode.AwaitTask + + } + + member _.Clear() = cache.Clear() + + member _.Clear predicate = cache.Clear predicate + + member val Event = event.Publish + + member this.OnEvent = this.Event.Add + + member _.Locked = lock.Semaphore.CurrentCount < 1 + + member _.Running = + cache.GetValues() + |> Seq.filter (function + | _, _, Running _ -> true + | _ -> false) + |> Seq.toArray + + member this.DebuggerDisplay = + let locked = if this.Locked then " [LOCKED]" else "" + + let valueStats = + cache.GetValues() + |> Seq.countBy (function + | _, _, Running _ -> "Running" + | _, _, Completed _ -> "Completed" + | _, _, Job.Canceled _ -> "Canceled" + | _, _, Job.Failed _ -> "Failed") + |> Map + + let running = + valueStats.TryFind "Running" + |> Option.map (sprintf " Running: %d ") + |> Option.defaultValue "" + + let avgDuration = avgDurationMs |> sprintf "| Avg: %.0f ms" + + let hitRatio = + if started > 0 then + $" (%.0f{float hits / (float (started + hits)) * 100.0} %%)" + else + "" + + let stats = + [| + if errors + failed > 0 then + " (_!_) " + if errors > 0 then $"| ERRORS: {errors} " else "" + if failed > 0 then $"| FAILED: {failed} " else "" + $"| hits: {hits}{hitRatio} " + if started > 0 then $"| started: {started} " else "" + if completed > 0 then $"| completed: {completed} " else "" + if canceled > 0 then $"| canceled: {canceled} " else "" + if restarted > 0 then $"| restarted: {restarted} " else "" + if evicted > 0 then $"| evicted: {evicted} " else "" + if collected > 0 then $"| collected: {collected} " else "" + if cleared > 0 then $"| cleared: {cleared} " else "" + if strengthened > 0 then + $"| strengthened: {strengthened} " + else + "" + |] + |> String.concat "" + + $"{locked}{running}{cache.DebuggerDisplay} {stats}{avgDuration}" + +/// A drop-in replacement for AsyncMemoize that disables caching and just runs the computation every time. +[] +type internal AsyncMemoizeDisabled<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality> + (?keepStrongly, ?keepWeakly, ?name: string, ?cancelDuplicateRunningJobs: bool) = + + do ignore (keepStrongly, keepWeakly, name, cancelDuplicateRunningJobs) + + let mutable requests = 0 + + member _.Get(_key: ICacheKey<_, _>, computation) = + Interlocked.Increment &requests |> ignore + computation + + member _.DebuggerDisplay = $"(disabled) requests: {requests}" diff --git a/src/Compiler/Facilities/AsyncMemoize.fsi b/src/Compiler/Facilities/AsyncMemoize.fsi new file mode 100644 index 00000000000..a142605ac22 --- /dev/null +++ b/src/Compiler/Facilities/AsyncMemoize.fsi @@ -0,0 +1,81 @@ +namespace Internal.Utilities.Collections + +open System.Threading.Tasks +open FSharp.Compiler.BuildGraph + +[] +module internal Utils = + + /// Return file name with one directory above it + val shortPath: path: string -> string + + val (|TaskCancelled|_|): ex: exn -> TaskCanceledException option + +type internal JobEvent = + | Started + | Finished + | Canceled + | Evicted + | Collected + | Weakened + | Strengthened + | Failed + | Cleared + +type internal ICacheKey<'TKey, 'TVersion> = + + abstract GetKey: unit -> 'TKey + + abstract GetLabel: unit -> string + + abstract GetVersion: unit -> 'TVersion + +[] +type Extensions = + + [] + static member internal WithExtraVersion: cacheKey: ICacheKey<'a, 'b> * extraVersion: 'c -> ICacheKey<'a, ('b * 'c)> + +type internal AsyncLock = + interface System.IDisposable + + new: unit -> AsyncLock + + member Do: f: (unit -> #Task<'b>) -> Task<'b> + +/// +/// A cache/memoization for computations that makes sure that the same computation wil only be computed once even if it's needed +/// at multiple places/times. +/// +/// Strongly holds at most one result per key. +/// +type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality> = + + /// Maximum number of strongly held results to keep in the cache + /// Maximum number of weakly held results to keep in the cache + /// Name of the cache - used in tracing messages + /// If true, when a job is started, all other jobs with the same key will be canceled. + new: + ?keepStrongly: int * ?keepWeakly: int * ?name: string * ?cancelDuplicateRunningJobs: bool -> + AsyncMemoize<'TKey, 'TVersion, 'TValue> + + member Clear: unit -> unit + + member Clear: predicate: ('TKey -> bool) -> unit + + member Get: key: ICacheKey<'TKey, 'TVersion> * computation: NodeCode<'TValue> -> NodeCode<'TValue> + + member Get': key: 'TKey * computation: NodeCode<'TValue> -> NodeCode<'TValue> + + member Event: IEvent + + member OnEvent: ((JobEvent * (string * 'TKey * 'TVersion) -> unit) -> unit) + +/// A drop-in replacement for AsyncMemoize that disables caching and just runs the computation every time. +type internal AsyncMemoizeDisabled<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality> = + + new: + ?keepStrongly: obj * ?keepWeakly: obj * ?name: string * ?cancelDuplicateRunningJobs: bool -> + AsyncMemoizeDisabled<'TKey, 'TVersion, 'TValue> + + member Get: _key: ICacheKey<'a, 'b> * computation: 'c -> 'c diff --git a/src/Compiler/Facilities/BuildGraph.fs b/src/Compiler/Facilities/BuildGraph.fs index 8927862c23c..1df58c1024b 100644 --- a/src/Compiler/Facilities/BuildGraph.fs +++ b/src/Compiler/Facilities/BuildGraph.fs @@ -17,14 +17,12 @@ let wrapThreadStaticInfo computation = async { let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger let phase = DiagnosticsThreadStatics.BuildPhase - let ct = Cancellable.Token try return! computation finally DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- phase - Cancellable.Token <- ct } type Async<'T> with @@ -127,7 +125,6 @@ type NodeCode private () = static member RunImmediate(computation: NodeCode<'T>, ct: CancellationToken) = let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger let phase = DiagnosticsThreadStatics.BuildPhase - let ct2 = Cancellable.Token try try @@ -135,7 +132,6 @@ type NodeCode private () = async { DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- phase - Cancellable.Token <- ct2 return! computation |> Async.AwaitNodeCode } @@ -143,7 +139,6 @@ type NodeCode private () = finally DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- phase - Cancellable.Token <- ct2 with :? AggregateException as ex when ex.InnerExceptions.Count = 1 -> raise (ex.InnerExceptions[0]) @@ -153,14 +148,12 @@ type NodeCode private () = static member StartAsTask_ForTesting(computation: NodeCode<'T>, ?ct: CancellationToken) = let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger let phase = DiagnosticsThreadStatics.BuildPhase - let ct2 = Cancellable.Token try let work = async { DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- phase - Cancellable.Token <- ct2 return! computation |> Async.AwaitNodeCode } @@ -168,7 +161,6 @@ type NodeCode private () = finally DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger DiagnosticsThreadStatics.BuildPhase <- phase - Cancellable.Token <- ct2 static member CancellationToken = cancellationToken diff --git a/src/Compiler/Facilities/CompilerLocation.fs b/src/Compiler/Facilities/CompilerLocation.fs index fa49445b769..11f944c5f30 100644 --- a/src/Compiler/Facilities/CompilerLocation.fs +++ b/src/Compiler/Facilities/CompilerLocation.fs @@ -28,8 +28,7 @@ module internal FSharpEnvironment = let FSharpCoreLibRunningVersion = try match versionOf with - | null -> None - | "" -> None + | s when String.IsNullOrEmpty(s) -> None | s -> Some(s) with _ -> None @@ -184,7 +183,7 @@ module internal FSharpEnvironment = | None -> () | Some(p: string) -> match Path.GetDirectoryName(p) with - | s when s = "" || isNull s || Path.GetFileName(p) = "packages" || s = p -> () + | s when String.IsNullOrEmpty(s) || Path.GetFileName(p) = "packages" || s = p -> () | parentDir -> yield! searchParentDirChain (Some parentDir) assemblyName for p in searchToolPaths path compilerToolPaths do diff --git a/src/Compiler/Facilities/DiagnosticsLogger.fs b/src/Compiler/Facilities/DiagnosticsLogger.fs index 24f6ebf2e6d..08a46d1a25d 100644 --- a/src/Compiler/Facilities/DiagnosticsLogger.fs +++ b/src/Compiler/Facilities/DiagnosticsLogger.fs @@ -374,7 +374,7 @@ type CapturingDiagnosticsLogger(nm, ?eagerFormat) = let errors = diagnostics.ToArray() errors |> Array.iter diagnosticsLogger.DiagnosticSink -/// Type holds thread-static globals for use by the compile. +/// Type holds thread-static globals for use by the compiler. type internal DiagnosticsThreadStatics = [] static val mutable private buildPhase: BuildPhase diff --git a/src/Compiler/Facilities/Hashing.fs b/src/Compiler/Facilities/Hashing.fs new file mode 100644 index 00000000000..2dfbb38b7ee --- /dev/null +++ b/src/Compiler/Facilities/Hashing.fs @@ -0,0 +1,81 @@ +namespace Internal.Utilities.Hashing + +open System +open System.Threading + +/// Tools for hashing things with MD5 into a string that can be used as a cache key. +module internal Md5StringHasher = + + let private md5 = + new ThreadLocal<_>(fun () -> System.Security.Cryptography.MD5.Create()) + + let private computeHash (bytes: byte array) = md5.Value.ComputeHash(bytes) + + let hashString (s: string) = + System.Text.Encoding.UTF8.GetBytes(s) |> computeHash + + let empty = String.Empty + + let addBytes (bytes: byte array) (s: string) = + let sbytes = s |> hashString + + Array.append sbytes bytes + |> computeHash + |> System.BitConverter.ToString + |> (fun x -> x.Replace("-", "")) + + let addString (s: string) (s2: string) = + s |> System.Text.Encoding.UTF8.GetBytes |> addBytes <| s2 + + let addSeq<'item> (items: 'item seq) (addItem: 'item -> string -> string) (s: string) = + items |> Seq.fold (fun s a -> addItem a s) s + + let addStrings strings = addSeq strings addString + + // If we use this make it an extension method? + //let addVersions<'a, 'b when 'a :> ICacheKey<'b, string>> (versions: 'a seq) (s: string) = + // versions |> Seq.map (fun x -> x.GetVersion()) |> addStrings <| s + + let addBool (b: bool) (s: string) = + b |> BitConverter.GetBytes |> addBytes <| s + + let addDateTime (dt: System.DateTime) (s: string) = dt.Ticks.ToString() |> addString <| s + +module internal Md5Hasher = + + let private md5 = + new ThreadLocal<_>(fun () -> System.Security.Cryptography.MD5.Create()) + + let computeHash (bytes: byte array) = md5.Value.ComputeHash(bytes) + + let empty = Array.empty + + let hashString (s: string) = + s |> System.Text.Encoding.UTF8.GetBytes |> computeHash + + let addBytes (bytes: byte array) (s: byte array) = + + Array.append s bytes |> computeHash + + let addString (s: string) (s2: byte array) = + s |> System.Text.Encoding.UTF8.GetBytes |> addBytes <| s2 + + let addSeq<'item> (items: 'item seq) (addItem: 'item -> byte array -> byte array) (s: byte array) = + items |> Seq.fold (fun s a -> addItem a s) s + + let addStrings strings = addSeq strings addString + let addBytes' bytes = addSeq bytes addBytes + + // If we use this make it an extension method? + //let addVersions<'a, 'b when 'a :> ICacheKey<'b, string>> (versions: 'a seq) (s: string) = + // versions |> Seq.map (fun x -> x.GetVersion()) |> addStrings <| s + + let addBool (b: bool) (s: byte array) = + b |> BitConverter.GetBytes |> addBytes <| s + + let addDateTime (dt: System.DateTime) (s: byte array) = + dt.Ticks |> BitConverter.GetBytes |> addBytes <| s + + let addDateTimes (dts: System.DateTime seq) (s: byte array) = s |> addSeq dts addDateTime + + let toString (bytes: byte array) = bytes |> System.BitConverter.ToString diff --git a/src/Compiler/Facilities/Hashing.fsi b/src/Compiler/Facilities/Hashing.fsi new file mode 100644 index 00000000000..121afb29eb2 --- /dev/null +++ b/src/Compiler/Facilities/Hashing.fsi @@ -0,0 +1,46 @@ +namespace Internal.Utilities.Hashing + +/// Tools for hashing things with MD5 into a string that can be used as a cache key. +module internal Md5StringHasher = + + val hashString: s: string -> byte array + + val empty: string + + val addBytes: bytes: byte array -> s: string -> string + + val addString: s: string -> s2: string -> string + + val addSeq: items: 'item seq -> addItem: ('item -> string -> string) -> s: string -> string + + val addStrings: strings: string seq -> (string -> string) + + val addBool: b: bool -> s: string -> string + + val addDateTime: dt: System.DateTime -> s: string -> string + +module internal Md5Hasher = + + val computeHash: bytes: byte array -> byte array + + val empty: 'a array + + val hashString: s: string -> byte array + + val addBytes: bytes: byte array -> s: byte array -> byte array + + val addString: s: string -> s2: byte array -> byte array + + val addSeq: items: 'item seq -> addItem: ('item -> byte array -> byte array) -> s: byte array -> byte array + + val addStrings: strings: string seq -> (byte array -> byte array) + + val addBytes': bytes: byte array seq -> (byte array -> byte array) + + val addBool: b: bool -> s: byte array -> byte array + + val addDateTime: dt: System.DateTime -> s: byte array -> byte array + + val addDateTimes: dts: System.DateTime seq -> s: byte array -> byte array + + val toString: bytes: byte array -> string diff --git a/src/Compiler/Facilities/prim-lexing.fs b/src/Compiler/Facilities/prim-lexing.fs index 4aa1d3a79e5..6b927ef4a96 100644 --- a/src/Compiler/Facilities/prim-lexing.fs +++ b/src/Compiler/Facilities/prim-lexing.fs @@ -6,6 +6,11 @@ namespace FSharp.Compiler.Text open System open System.IO +open System.Collections.Immutable +open Internal.Utilities.Library + +open Internal.Utilities.Collections +open Internal.Utilities.Hashing type ISourceText = @@ -29,6 +34,11 @@ type ISourceText = abstract GetSubTextFromRange: range: range -> string +type ISourceTextNew = + inherit ISourceText + + abstract GetChecksum: unit -> System.Collections.Immutable.ImmutableArray + [] type StringText(str: string) = @@ -66,7 +76,7 @@ type StringText(str: string) = override _.ToString() = str - interface ISourceText with + interface ISourceTextNew with member _.Item with get index = str[index] @@ -97,7 +107,7 @@ type StringText(str: string) = if lastIndex <= startIndex || lastIndex >= str.Length then invalidArg "target" "Too big." - str.IndexOf(target, startIndex, target.Length) <> -1 + str.IndexOfOrdinal(target, startIndex, target.Length) <> -1 member _.Length = str.Length @@ -144,9 +154,45 @@ type StringText(str: string) = let lastLine = sourceText.GetLineString(range.EndLine - 1) sb.Append(lastLine.Substring(0, range.EndColumn)).ToString() + member _.GetChecksum() = + str |> Md5Hasher.hashString |> ImmutableArray.Create + module SourceText = let ofString str = StringText(str) :> ISourceText + +module SourceTextNew = + + let ofString str = StringText(str) :> ISourceTextNew + + let ofISourceText (sourceText: ISourceText) = + { new ISourceTextNew with + member _.Item + with get index = sourceText[index] + + member _.GetLineString(x) = sourceText.GetLineString(x) + + member _.GetLineCount() = sourceText.GetLineCount() + + member _.GetLastCharacterPosition() = sourceText.GetLastCharacterPosition() + + member _.GetSubTextString(x, y) = sourceText.GetSubTextString(x, y) + + member _.SubTextEquals(x, y) = sourceText.SubTextEquals(x, y) + + member _.Length = sourceText.Length + + member _.ContentEquals(x) = sourceText.ContentEquals(x) + + member _.CopyTo(a, b, c, d) = sourceText.CopyTo(a, b, c, d) + + member _.GetSubTextFromRange(x) = sourceText.GetSubTextFromRange(x) + + member _.GetChecksum() = + // TODO: something better... + sourceText.ToString() |> Md5Hasher.hashString |> ImmutableArray.Create + } + // NOTE: the code in this file is a drop-in replacement runtime for Lexing.fs from the FsLexYacc repository namespace Internal.Utilities.Text.Lexing diff --git a/src/Compiler/Facilities/prim-lexing.fsi b/src/Compiler/Facilities/prim-lexing.fsi index 6e5f6da4f25..ff13f96c9e1 100644 --- a/src/Compiler/Facilities/prim-lexing.fsi +++ b/src/Compiler/Facilities/prim-lexing.fsi @@ -39,12 +39,23 @@ type ISourceText = /// Throws an exception when the input range is outside the file boundaries. abstract GetSubTextFromRange: range: range -> string +/// Just like ISourceText, but with a checksum. Added as a separate type to avoid breaking changes. +type ISourceTextNew = + inherit ISourceText + + abstract GetChecksum: unit -> System.Collections.Immutable.ImmutableArray + /// Functions related to ISourceText objects module SourceText = /// Creates an ISourceText object from the given string val ofString: string -> ISourceText +module SourceTextNew = + + val ofString: string -> ISourceTextNew + val ofISourceText: ISourceText -> ISourceTextNew + // // NOTE: the code in this file is a drop-in replacement runtime for Lexing.fsi from the FsLexYacc repository // and is referenced by generated code for the three FsLex generated lexers in the F# compiler. diff --git a/src/Compiler/Interactive/fsi.fs b/src/Compiler/Interactive/fsi.fs index 040ad43e407..9ed34abfaac 100644 --- a/src/Compiler/Interactive/fsi.fs +++ b/src/Compiler/Interactive/fsi.fs @@ -933,12 +933,12 @@ type DiagnosticsLogger with /// Get the directory name from a string, with some defaults if it doesn't have one let internal directoryName (s: string) = - if s = "" then + if String.IsNullOrEmpty(s) then "." else match Path.GetDirectoryName s with | null -> if FileSystem.IsPathRootedShim s then s else "." - | res -> if res = "" then "." else res + | res -> if String.IsNullOrEmpty(res) then "." else res //---------------------------------------------------------------------------- // cmd line - state for options @@ -1526,7 +1526,7 @@ let ConvReflectionTypeToILTypeRef (reflectionTy: Type) = let scoref = ILScopeRef.Assembly aref let fullName = reflectionTy.FullName - let index = fullName.IndexOf("[") + let index = fullName.IndexOfOrdinal("[") let fullName = if index = -1 then @@ -4089,7 +4089,6 @@ type FsiInteractionProcessor ?cancellationToken: CancellationToken ) = let cancellationToken = defaultArg cancellationToken CancellationToken.None - use _ = Cancellable.UsingToken(cancellationToken) if tokenizer.LexBuffer.IsPastEndOfStream then let stepStatus = @@ -4218,7 +4217,6 @@ type FsiInteractionProcessor member _.EvalInteraction(ctok, sourceText, scriptFileName, diagnosticsLogger, ?cancellationToken) = let cancellationToken = defaultArg cancellationToken CancellationToken.None - use _ = Cancellable.UsingToken(cancellationToken) use _ = UseBuildPhase BuildPhase.Interactive use _ = UseDiagnosticsLogger diagnosticsLogger use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID @@ -4895,7 +4893,6 @@ type FsiEvaluationSession SpawnInteractiveServer(fsi, fsiOptions, fsiConsoleOutput) use _ = UseBuildPhase BuildPhase.Interactive - use _ = Cancellable.UsingToken(CancellationToken.None) if fsiOptions.Interact then // page in the type check env diff --git a/src/Compiler/Optimize/LowerStateMachines.fs b/src/Compiler/Optimize/LowerStateMachines.fs index 7c4835b3460..ef578e86064 100644 --- a/src/Compiler/Optimize/LowerStateMachines.fs +++ b/src/Compiler/Optimize/LowerStateMachines.fs @@ -114,7 +114,7 @@ let isExpandVar g (v: Val) = let isStateMachineBindingVar g (v: Val) = isExpandVar g v || (let nm = v.LogicalName - (nm.StartsWith "builder@" || v.IsMemberThisVal) && + (nm.StartsWithOrdinal("builder@") || v.IsMemberThisVal) && not v.IsCompiledAsTopLevel) type env = @@ -833,7 +833,7 @@ type LowerStateMachine(g: TcGlobals) = |> Result.Ok elif bind.Var.IsCompiledAsTopLevel || not (resBody.resumableVars.FreeLocals.Contains(bind.Var)) || - bind.Var.LogicalName.StartsWith stackVarPrefix then + bind.Var.LogicalName.StartsWithOrdinal(stackVarPrefix) then if sm_verbose then printfn "LetExpr (non-control-flow, rewrite rhs, RepresentBindingAsTopLevelOrLocal)" RepresentBindingAsTopLevelOrLocal bind resBody m |> Result.Ok diff --git a/src/Compiler/Optimize/Optimizer.fs b/src/Compiler/Optimize/Optimizer.fs index a1e01d4a58d..73ed2972ea0 100644 --- a/src/Compiler/Optimize/Optimizer.fs +++ b/src/Compiler/Optimize/Optimizer.fs @@ -230,20 +230,23 @@ type Summary<'Info> = // Note, this is a different notion of "size" to the one used for inlining heuristics //------------------------------------------------------------------------- -let rec SizeOfValueInfos (arr:_[]) = - if arr.Length <= 0 then 0 else max 0 (SizeOfValueInfo arr[0]) - -and SizeOfValueInfo x = - match x with - | SizeValue (vdepth, _v) -> vdepth // terminate recursion at CACHED size nodes - | ConstValue (_x, _) -> 1 - | UnknownValue -> 1 - | ValValue (_vr, vinfo) -> SizeOfValueInfo vinfo + 1 - | TupleValue vinfos - | RecdValue (_, vinfos) - | UnionCaseValue (_, vinfos) -> 1 + SizeOfValueInfos vinfos - | CurriedLambdaValue _ -> 1 - | ConstExprValue (_size, _) -> 1 +let SizeOfValueInfo valueInfo = + let rec loop acc valueInfo = + match valueInfo with + | SizeValue (vdepth, _v) -> assert (vdepth >= 0); acc + vdepth // terminate recursion at CACHED size nodes + | CurriedLambdaValue _ + | ConstExprValue _ + | ConstValue _ + | UnknownValue -> acc + 1 + | TupleValue vinfos + | RecdValue (_, vinfos) + | UnionCaseValue (_, vinfos) when vinfos.Length = 0 -> acc + 1 + | TupleValue vinfos + | RecdValue (_, vinfos) + | UnionCaseValue (_, vinfos) -> loop (acc + 1) vinfos[0] + | ValValue (_vr, vinfo) -> loop (acc + 1) vinfo + + loop 0 valueInfo let [] minDepthForASizeNode = 5 // for small vinfos do not record size info, save space @@ -1534,11 +1537,11 @@ let ValueOfExpr expr = let IsMutableStructuralBindingForTupleElement (vref: ValRef) = vref.IsCompilerGenerated && - vref.LogicalName.EndsWith suffixForTupleElementAssignmentTarget + vref.LogicalName.EndsWithOrdinal suffixForTupleElementAssignmentTarget let IsMutableForOutArg (vref: ValRef) = vref.IsCompilerGenerated && - vref.LogicalName.StartsWith(outArgCompilerGeneratedName) + vref.LogicalName.StartsWithOrdinal(outArgCompilerGeneratedName) let IsKnownOnlyMutableBeforeUse (vref: ValRef) = IsMutableStructuralBindingForTupleElement vref || @@ -1672,7 +1675,7 @@ let TryEliminateBinding cenv _env bind e2 _m = not vspec1.IsCompilerGenerated then None elif vspec1.IsFixed then None - elif vspec1.LogicalName.StartsWith stackVarPrefix || + elif vspec1.LogicalName.StartsWithOrdinal stackVarPrefix || vspec1.LogicalName.Contains suffixForVariablesThatMayNotBeEliminated then None else diff --git a/src/Compiler/Service/BackgroundCompiler.fs b/src/Compiler/Service/BackgroundCompiler.fs new file mode 100644 index 00000000000..f9f952dde70 --- /dev/null +++ b/src/Compiler/Service/BackgroundCompiler.fs @@ -0,0 +1,1680 @@ +namespace FSharp.Compiler.CodeAnalysis + +open FSharp.Compiler.Text +open FSharp.Compiler.BuildGraph + +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.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 +open FSharp.Compiler.CompilerImports +open FSharp.Compiler.CompilerOptions +open FSharp.Compiler.DependencyManager +open FSharp.Compiler.Diagnostics +open FSharp.Compiler.Driver +open FSharp.Compiler.DiagnosticsLogger +open FSharp.Compiler.IO +open FSharp.Compiler.ParseAndCheckInputs +open FSharp.Compiler.ScriptClosure +open FSharp.Compiler.Symbols +open FSharp.Compiler.Syntax +open FSharp.Compiler.Tokenization +open FSharp.Compiler.Text +open FSharp.Compiler.Text.Range +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.BuildGraph +open FSharp.Compiler.CodeAnalysis.ProjectSnapshot + +type SourceTextHash = int64 +type CacheStamp = int64 +type FileName = string +type FilePath = string +type ProjectPath = string +type FileVersion = int + +type FSharpProjectSnapshot = FSharp.Compiler.CodeAnalysis.ProjectSnapshot.FSharpProjectSnapshot + +type internal IBackgroundCompiler = + + /// Type-check the result obtained by parsing. Force the evaluation of the antecedent type checking context if needed. + abstract member CheckFileInProject: + parseResults: FSharpParseFileResults * + fileName: string * + fileVersion: int * + sourceText: ISourceText * + options: FSharpProjectOptions * + userOpName: string -> + NodeCode + + /// Type-check the result obtained by parsing, but only if the antecedent type checking context is available. + abstract member CheckFileInProjectAllowingStaleCachedResults: + parseResults: FSharpParseFileResults * + fileName: string * + fileVersion: int * + sourceText: ISourceText * + options: FSharpProjectOptions * + userOpName: string -> + NodeCode + + abstract member ClearCache: options: seq * userOpName: string -> unit + + abstract member ClearCache: projects: ProjectSnapshot.FSharpProjectIdentifier seq * userOpName: string -> unit + + abstract member ClearCaches: unit -> unit + + abstract member DownsizeCaches: unit -> unit + + abstract member FindReferencesInFile: + fileName: string * + options: FSharpProjectOptions * + symbol: FSharp.Compiler.Symbols.FSharpSymbol * + canInvalidateProject: bool * + userOpName: string -> + NodeCode> + + abstract member FindReferencesInFile: + fileName: string * projectSnapshot: FSharpProjectSnapshot * symbol: FSharp.Compiler.Symbols.FSharpSymbol * userOpName: string -> + NodeCode> + + abstract member GetAssemblyData: + options: FSharpProjectOptions * outputFileName: string * userOpName: string -> + NodeCode + + abstract member GetAssemblyData: + projectSnapshot: FSharpProjectSnapshot * outputFileName: string * userOpName: string -> + NodeCode + + /// Fetch the check information from the background compiler (which checks w.r.t. the FileSystem API) + abstract member GetBackgroundCheckResultsForFileInProject: + fileName: string * options: FSharpProjectOptions * userOpName: string -> NodeCode + + /// Fetch the parse information from the background compiler (which checks w.r.t. the FileSystem API) + abstract member GetBackgroundParseResultsForFileInProject: + fileName: string * options: FSharpProjectOptions * userOpName: string -> NodeCode + + abstract member GetCachedCheckFileResult: + builder: IncrementalBuilder * fileName: string * sourceText: ISourceText * options: FSharpProjectOptions -> + NodeCode<(FSharpParseFileResults * FSharpCheckFileResults) option> + + abstract member GetProjectOptionsFromScript: + fileName: string * + sourceText: ISourceText * + previewEnabled: bool option * + loadedTimeStamp: System.DateTime option * + otherFlags: string array option * + useFsiAuxLib: bool option * + useSdkRefs: bool option * + sdkDirOverride: string option * + assumeDotNetFramework: bool option * + optionsStamp: int64 option * + userOpName: string -> + Async + + abstract member GetSemanticClassificationForFile: + fileName: string * options: FSharpProjectOptions * userOpName: string -> + NodeCode + + abstract member GetSemanticClassificationForFile: + fileName: string * snapshot: FSharpProjectSnapshot * userOpName: string -> + NodeCode + + abstract member InvalidateConfiguration: options: FSharpProjectOptions * userOpName: string -> unit + + abstract member NotifyFileChanged: fileName: string * options: FSharpProjectOptions * userOpName: string -> NodeCode + + abstract member NotifyProjectCleaned: options: FSharpProjectOptions * userOpName: string -> Async + + /// Parses and checks the source file and returns untyped AST and check results. + abstract member ParseAndCheckFileInProject: + fileName: string * fileVersion: int * sourceText: ISourceText * options: FSharpProjectOptions * userOpName: string -> + NodeCode + + abstract member ParseAndCheckFileInProject: + fileName: string * projectSnapshot: FSharpProjectSnapshot * userOpName: string -> + NodeCode + + /// Parse and typecheck the whole project. + abstract member ParseAndCheckProject: options: FSharpProjectOptions * userOpName: string -> NodeCode + + abstract member ParseAndCheckProject: projectSnapshot: FSharpProjectSnapshot * userOpName: string -> NodeCode + + abstract member ParseFile: + fileName: string * sourceText: ISourceText * options: FSharpParsingOptions * cache: bool * flatErrors: bool * userOpName: string -> + Async + + abstract member ParseFile: + fileName: string * projectSnapshot: FSharpProjectSnapshot * userOpName: string -> Async + + /// Try to get recent approximate type check results for a file. + abstract member TryGetRecentCheckResultsForFile: + fileName: string * options: FSharpProjectOptions * sourceText: ISourceText option * userOpName: string -> + (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option + + abstract member BeforeBackgroundFileCheck: IEvent + + abstract member FileChecked: IEvent + + abstract member FileParsed: IEvent + + abstract member FrameworkImportsCache: FrameworkImportsCache + + abstract member ProjectChecked: IEvent + +type internal ParseCacheLockToken() = + interface LockToken + +type CheckFileCacheKey = FileName * SourceTextHash * FSharpProjectOptions +type CheckFileCacheValue = FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash * DateTime + +[] +module internal EnvMisc = + let braceMatchCacheSize = GetEnvInteger "FCS_BraceMatchCacheSize" 5 + let parseFileCacheSize = GetEnvInteger "FCS_ParseFileCacheSize" 2 + let checkFileInProjectCacheSize = GetEnvInteger "FCS_CheckFileInProjectCacheSize" 10 + + let projectCacheSizeDefault = GetEnvInteger "FCS_ProjectCacheSizeDefault" 3 + + let frameworkTcImportsCacheStrongSize = + GetEnvInteger "FCS_frameworkTcImportsCacheStrongSizeDefault" 8 + +[] +module internal 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)) = + (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)) = + fileName1 = fileName2 && options1 = options2 && source1Hash = source2Hash + + 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) + && 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) + + /// If a symbol is an attribute check if given set of names contains its name without the Attribute suffix + let rec NamesContainAttribute (symbol: FSharpSymbol) names = + match symbol with + | :? FSharpMemberOrFunctionOrValue as mofov -> + mofov.DeclaringEntity + |> Option.map (fun entity -> NamesContainAttribute entity names) + |> Option.defaultValue false + | :? FSharpEntity as entity when entity.IsAttributeType && symbol.DisplayNameCore.EndsWithOrdinal "Attribute" -> + let nameWithoutAttribute = String.dropSuffix symbol.DisplayNameCore "Attribute" + names |> Set.contains nameWithoutAttribute + | _ -> false + +// There is only one instance of this type, held in FSharpChecker +type internal BackgroundCompiler + ( + legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking, + parallelReferenceResolution, + captureIdentifiersWhenParsing, + getSource: (string -> Async) option, + useChangeNotifications, + useSyntaxTreeCache + ) as self = + + let beforeFileChecked = Event() + let fileParsed = Event() + let fileChecked = Event() + let projectChecked = Event() + + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.scriptClosureCache + /// Information about the derived script closure. + 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() + + 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(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 + let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData + return ProjectAssemblyDataResult.Available data + | _ -> + // 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 = delayedReader.OutputFile + } + + | FSharpReferencedProject.ILModuleReference(nm, getStamp, getReader) -> + { new IProjectReference with + member x.EvaluateRawContents() = + cancellable { + let ilReader = getReader () + let ilModuleDef, ilAsmRefs = ilReader.ILModuleDef, ilReader.ILAssemblyRefs + let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData + return ProjectAssemblyDataResult.Available data + } + |> NodeCode.FromCancellable + + member x.TryGetLogicalTimeStamp _ = getStamp () |> Some + member x.FileName = nm + } + ] + + /// 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 { + use _ = + Activity.start "BackgroundCompiler.CreateOneIncrementalBuilder" [| Activity.Tags.project, options.ProjectFileName |] + + 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, + parallelReferenceResolution, + captureIdentifiersWhenParsing, + getSource, + useChangeNotifications, + useSyntaxTreeCache + ) + + 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)) +#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) + } + + let parseCacheLock = Lock() + + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.parseFileInProjectCache. Most recently used cache for parsing files. + let parseFileCache = + MruCache( + parseFileCacheSize, + areSimilar = AreSimilarForParsing, + areSame = AreSameForParsing + ) + + // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.checkFileInProjectCache + // + /// Cache which holds recently seen type-checks. + /// This cache may hold out-of-date entries, in two senses + /// - there may be a more recent antecedent state available because the background build has made it available + /// - the source for the file may have changed + + // 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 + ) + + // 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 + ) + + let tryGetBuilderNode options = + incrementalBuildersCache.TryGet(AnyCallerThread, options) + + let tryGetBuilder options : NodeCode option = + tryGetBuilderNode options |> Option.map (fun x -> x.GetOrComputeValue()) + + let tryGetSimilarBuilder options : NodeCode option = + incrementalBuildersCache.TryGetSimilar(AnyCallerThread, options) + |> Option.map (fun x -> x.GetOrComputeValue()) + + let tryGetAnyBuilder options : NodeCode option = + incrementalBuildersCache.TryGetAny(AnyCallerThread, options) + |> Option.map (fun x -> x.GetOrComputeValue()) + + let createBuilderNode (options, userOpName, ct: CancellationToken) = + lock gate (fun () -> + if ct.IsCancellationRequested then + GraphNode.FromResult(None, [||]) + else + let getBuilderNode = GraphNode(CreateOneIncrementalBuilder(options, userOpName)) + incrementalBuildersCache.Set(AnyCallerThread, options, getBuilderNode) + getBuilderNode) + + let createAndGetBuilder (options, userOpName) = + node { + let! ct = NodeCode.CancellationToken + let getBuilderNode = createBuilderNode (options, userOpName, ct) + return! getBuilderNode.GetOrComputeValue() + } + + let getOrCreateBuilder (options, userOpName) : NodeCode = + match tryGetBuilder options with + | Some getBuilder -> + node { + match! getBuilder with + | builderOpt, creationDiags when builderOpt.IsNone || not builderOpt.Value.IsReferencesInvalidated -> + 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 -> + options.SourceFiles + |> Array.iter (fun sourceFile -> + let key = (sourceFile, 0L, options) + checkFileInProjectCache.RemoveAnySimilar(ltok, key))) + + return! createAndGetBuilder (options, userOpName) + } + | _ -> createAndGetBuilder (options, userOpName) + + let getSimilarOrCreateBuilder (options, userOpName) = + match tryGetSimilarBuilder options with + | Some res -> res + // The builder does not exist at all. Create it. + | None -> getOrCreateBuilder (options, userOpName) + + let getOrCreateBuilderWithInvalidationFlag (options, canInvalidateProject, userOpName) = + if canInvalidateProject then + getOrCreateBuilder (options, userOpName) + else + getSimilarOrCreateBuilder (options, userOpName) + + let getAnyBuilder (options, userOpName) = + match tryGetAnyBuilder options with + | Some getBuilder -> getBuilder + | _ -> 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) = + + // Here we lock for the creation of the node, not its execution + 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 + ) + + Interlocked.Increment(&actualCheckFileCount) |> ignore + return res + } + ) + + checkFileInProjectCache.Set(ltok, key, res) + res) + + member _.ParseFile + ( + fileName: string, + sourceText: ISourceText, + options: FSharpParsingOptions, + cache: bool, + flatErrors: bool, + userOpName: string + ) = + async { + use _ = + Activity.start + "BackgroundCompiler.ParseFile" + [| + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + Activity.Tags.cache, cache.ToString() + |] + + 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! ct = Async.CancellationToken + + let parseDiagnostics, parseTree, anyErrors = + ParseAndCheckFile.parseFile ( + sourceText, + fileName, + options, + userOpName, + suggestNamesForErrors, + flatErrors, + captureIdentifiersWhenParsing, + ct + ) + + let res = + FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, options.SourceFiles) + + parseCacheLock.AcquireLock(fun ltok -> parseFileCache.Set(ltok, (fileName, hash, options), res)) + return res + else + let! ct = Async.CancellationToken + + let parseDiagnostics, parseTree, anyErrors = + ParseAndCheckFile.parseFile ( + sourceText, + fileName, + options, + userOpName, + false, + flatErrors, + captureIdentifiersWhenParsing, + ct + ) + + 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 { + use _ = + Activity.start + "BackgroundCompiler.GetBackgroundParseResultsForFileInProject" + [| Activity.Tags.fileName, fileName; Activity.Tags.userOpName, userOpName |] + + 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, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName + + let parseDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + builder.TcConfig.diagnosticsOptions, + false, + fileName, + parseDiagnostics, + suggestNamesForErrors, + builder.TcConfig.flatErrors, + None + ) + + 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) = + node { + use _ = + Activity.start "BackgroundCompiler.GetCachedCheckFileResult" [| Activity.Tags.fileName, fileName |] + + let hash = sourceText.GetHashCode() |> int64 + let key = (fileName, hash, options) + + let cachedResultsOpt = + parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.TryGet(ltok, key)) + + 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) + | _ -> + parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.RemoveAnySimilar(ltok, key)) + return None + | _ -> return None + } + + member private _.CheckOneFileImplAux + ( + 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. + // For scripts, this will have been recorded by GetProjectOptionsFromScript. + let tcConfig = tcPrior.TcConfig + let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options) + + let! checkAnswer = + FSharpCheckFileResults.CheckOneFile( + parseResults, + sourceText, + fileName, + options.ProjectFileName, + tcConfig, + tcPrior.TcGlobals, + tcPrior.TcImports, + tcInfo.tcState, + tcInfo.moduleNamesDict, + loadClosure, + tcInfo.TcDiagnostics, + options.IsIncompleteTypeCheckEnvironment, + options, + Some builder, + Array.ofList tcInfo.tcDependencyFiles, + creationDiags, + parseResults.Diagnostics, + keepAssemblyContents, + 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 { + 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) + + 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 + ) = + node { + use _ = + Activity.start + "BackgroundCompiler.CheckFileInProjectAllowingStaleCachedResults" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + |] + + let! cachedResults = + node { + 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) + | _ -> 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 -> + match tcPrior.TryPeekTcInfo() with + | 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 + } + + /// 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 { + use _ = + Activity.start + "BackgroundCompiler.CheckFileInProject" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + |] + + let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | 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) + + match cachedResults with + | Some(_, checkResults) -> return FSharpCheckFileAnswer.Succeeded checkResults + | _ -> + let! tcPrior = builder.GetCheckResultsBeforeFileInProject fileName + let! tcInfo = tcPrior.GetOrComputeTcInfo() + + return! + bc.CheckOneFileImpl( + parseResults, + sourceText, + fileName, + options, + fileVersion, + builder, + tcPrior, + tcInfo, + creationDiags + ) + } + + /// Parses and checks the source file and returns untyped AST and check results. + member bc.ParseAndCheckFileInProject + ( + fileName: string, + fileVersion, + sourceText: ISourceText, + options: FSharpProjectOptions, + userOpName + ) = + node { + use _ = + Activity.start + "BackgroundCompiler.ParseAndCheckFileInProject" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + |] + + let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | None -> + let parseTree = EmptyParsedInput(fileName, (false, false)) + let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||]) + return (parseResults, FSharpCheckFileAnswer.Aborted) + + | Some builder -> + let! cachedResults = bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) + + match cachedResults with + | Some(parseResults, checkResults) -> return (parseResults, FSharpCheckFileAnswer.Succeeded checkResults) + | _ -> + let! tcPrior = builder.GetCheckResultsBeforeFileInProject fileName + let! tcInfo = tcPrior.GetOrComputeTcInfo() + // Do the parsing. + let parsingOptions = + FSharpParsingOptions.FromTcConfig( + builder.TcConfig, + Array.ofList builder.SourceFiles, + options.UseScriptResolutionRules + ) + + GraphNode.SetPreferredUILang tcPrior.TcConfig.preferredUiLang + let! ct = NodeCode.CancellationToken + + let parseDiagnostics, parseTree, anyErrors = + ParseAndCheckFile.parseFile ( + sourceText, + fileName, + parsingOptions, + userOpName, + suggestNamesForErrors, + builder.TcConfig.flatErrors, + captureIdentifiersWhenParsing, + ct + ) + + let parseResults = + FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, builder.AllDependenciesDeprecated) + + let! checkResults = + bc.CheckOneFileImpl( + parseResults, + sourceText, + fileName, + options, + fileVersion, + builder, + tcPrior, + tcInfo, + creationDiags + ) + + return (parseResults, checkResults) + } + + member _.NotifyFileChanged(fileName, options, userOpName) = + node { + use _ = + Activity.start + "BackgroundCompiler.NotifyFileChanged" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + |] + + let! builderOpt, _ = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | None -> return () + | Some builder -> do! builder.NotifyFileChanged(fileName, DateTime.UtcNow) + } + + /// Fetch the check information from the background compiler (which checks w.r.t. the FileSystem API) + member _.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName) = + node { + use _ = + Activity.start + "BackgroundCompiler.ParseAndCheckFileInProject" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + |] + + let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | None -> + let parseTree = EmptyParsedInput(fileName, (false, false)) + let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||]) + let typedResults = FSharpCheckFileResults.MakeEmpty(fileName, creationDiags, true) + return (parseResults, typedResults) + | Some builder -> + let parseTree, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName + let! tcProj = builder.GetFullCheckResultsAfterFileInProject fileName + + let! tcInfo, tcInfoExtras = tcProj.GetOrComputeTcInfoWithExtras() + + let tcResolutions = tcInfoExtras.tcResolutions + let tcSymbolUses = tcInfoExtras.tcSymbolUses + let tcOpenDeclarations = tcInfoExtras.tcOpenDeclarations + let latestCcuSigForFile = tcInfo.latestCcuSigForFile + let tcState = tcInfo.tcState + let tcEnvAtEnd = tcInfo.tcEnvAtEndOfFile + let latestImplementationFile = tcInfoExtras.latestImplFile + let tcDependencyFiles = tcInfo.tcDependencyFiles + let tcDiagnostics = tcInfo.TcDiagnostics + let diagnosticsOptions = builder.TcConfig.diagnosticsOptions + + let symbolEnv = + SymbolEnv(tcProj.TcGlobals, tcInfo.tcState.Ccu, Some tcInfo.tcState.CcuSig, tcProj.TcImports) + |> Some + + let parseDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + diagnosticsOptions, + false, + fileName, + parseDiagnostics, + suggestNamesForErrors, + builder.TcConfig.flatErrors, + None + ) + + let parseDiagnostics = [| yield! creationDiags; yield! parseDiagnostics |] + + let tcDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + diagnosticsOptions, + false, + fileName, + tcDiagnostics, + suggestNamesForErrors, + builder.TcConfig.flatErrors, + symbolEnv + ) + + 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, + Some 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 + ) = + node { + use _ = + Activity.start + "BackgroundCompiler.FindReferencesInFile" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + "symbol", symbol.FullName + |] + + let! builderOpt, _ = getOrCreateBuilderWithInvalidationFlag (options, canInvalidateProject, userOpName) + + match builderOpt with + | None -> return Seq.empty + | 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 + else + return Seq.empty + } + + member _.GetSemanticClassificationForFile(fileName: string, options: FSharpProjectOptions, userOpName: string) = + node { + use _ = + Activity.start + "BackgroundCompiler.GetSemanticClassificationForFile" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, userOpName + |] + + let! builderOpt, _ = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | None -> return None + | Some builder -> + let! checkResults = builder.GetFullCheckResultsAfterFileInProject fileName + let! scopt = checkResults.GetOrComputeSemanticClassificationIfEnabled() + + match scopt with + | None -> return None + | 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 + ) = + use _ = + Activity.start + "BackgroundCompiler.GetSemanticClassificationForFile" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.fileName, fileName + Activity.Tags.userOpName, _userOpName + |] + + match sourceText with + | Some sourceText -> + let hash = sourceText.GetHashCode() |> int64 + + 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 + + /// 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 -> + 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 symbolEnv = + SymbolEnv(tcProj.TcGlobals, tcInfo.tcState.Ccu, Some tcInfo.tcState.CcuSig, tcProj.TcImports) + |> Some + + let tcDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + diagnosticsOptions, + true, + fileName, + tcDiagnostics, + suggestNamesForErrors, + builder.TcConfig.flatErrors, + symbolEnv + ) + + 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 { + use _ = + Activity.start + "BackgroundCompiler.GetAssemblyData" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.userOpName, userOpName + |] + + let! builderOpt, _ = getOrCreateBuilder (options, userOpName) + + match builderOpt with + | None -> return ProjectAssemblyDataResult.Unavailable true + | Some builder -> + let! _, _, tcAssemblyDataOpt, _ = builder.GetCheckResultsAndImplementationsForProject() + return tcAssemblyDataOpt + } + + /// Get the timestamp that would be on the output if fully built immediately + member private _.TryGetLogicalTimeStampForProject(cache, options) = + match tryGetBuilderNode options with + | Some lazyWork -> + match lazyWork.TryPeekValue() with + | ValueSome(Some builder, _) -> Some(builder.GetLogicalTimeStampForProject(cache)) + | _ -> None + | _ -> None + + /// Parse and typecheck the whole project. + member bc.ParseAndCheckProject(options, userOpName) = + use _ = + Activity.start + "BackgroundCompiler.ParseAndCheckProject" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.userOpName, 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 + ) = + use _ = + Activity.start + "BackgroundCompiler.GetProjectOptionsFromScript" + [| Activity.Tags.fileName, fileName; Activity.Tags.userOpName, _userOpName |] + + cancellable { + // Do we add a reference to FSharp.Compiler.Interactive.Settings by default? + let useFsiAuxLib = defaultArg useFsiAuxLib 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! ct = Cancellable.token () + use _ = Cancellable.UsingToken(ct) + + let extraFlags = + if previewEnabled then + [| "--langversion:preview" |] + else + [||] + + let otherFlags = defaultArg otherFlags extraFlags + + use diagnostics = new DiagnosticsScope(otherFlags |> Array.contains "--flaterrors") + + let useSimpleResolution = + otherFlags |> Array.exists (fun x -> x = "--simpleresolution") + + 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 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 + |] + + 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 = [||] + IsIncompleteTypeCheckEnvironment = false + UseScriptResolutionRules = true + LoadTime = loadedTimeStamp + 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, + options.OtherOptions |> Array.contains "--flaterrors", + None + )) + + return options, (diags @ diagnostics.Diagnostics) + } + |> Cancellable.toAsync + + member bc.InvalidateConfiguration(options: FSharpProjectOptions, userOpName) = + use _ = + Activity.start + "BackgroundCompiler.InvalidateConfiguration" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.userOpName, userOpName + |] + + if incrementalBuildersCache.ContainsSimilarKey(AnyCallerThread, options) then + parseCacheLock.AcquireLock(fun ltok -> + for sourceFile in options.SourceFiles do + checkFileInProjectCache.RemoveAnySimilar(ltok, (sourceFile, 0L, options))) + + let _ = createBuilderNode (options, userOpName, CancellationToken.None) + () + + member bc.ClearCache(options: seq, _userOpName) = + use _ = + Activity.start "BackgroundCompiler.ClearCache" [| Activity.Tags.userOpName, _userOpName |] + + lock gate (fun () -> + options + |> Seq.iter (fun options -> + incrementalBuildersCache.RemoveAnySimilar(AnyCallerThread, options) + + parseCacheLock.AcquireLock(fun ltok -> + for sourceFile in options.SourceFiles do + checkFileInProjectCache.RemoveAnySimilar(ltok, (sourceFile, 0L, options))))) + + member _.NotifyProjectCleaned(options: FSharpProjectOptions, userOpName) = + use _ = + Activity.start + "BackgroundCompiler.NotifyProjectCleaned" + [| + Activity.Tags.project, options.ProjectFileName + Activity.Tags.userOpName, 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 + // builder, but costs some time. + if incrementalBuildersCache.ContainsSimilarKey(AnyCallerThread, options) then + let _ = createBuilderNode (options, userOpName, ct) + () + } + + member _.BeforeBackgroundFileCheck = beforeFileChecked.Publish + + member _.FileParsed = fileParsed.Publish + + member _.FileChecked = fileChecked.Publish + + member _.ProjectChecked = projectChecked.Publish + + member _.ClearCaches() = + use _ = Activity.startNoTags "BackgroundCompiler.ClearCaches" + + lock gate (fun () -> + parseCacheLock.AcquireLock(fun ltok -> + checkFileInProjectCache.Clear(ltok) + parseFileCache.Clear(ltok)) + + incrementalBuildersCache.Clear(AnyCallerThread) + frameworkTcImportsCache.Clear() + scriptClosureCache.Clear AnyCallerThread) + + member _.DownsizeCaches() = + use _ = Activity.startNoTags "BackgroundCompiler.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) + frameworkTcImportsCache.Downsize() + scriptClosureCache.Resize(AnyCallerThread, newKeepStrongly = 1, newKeepMax = 1)) + + member _.FrameworkImportsCache = frameworkTcImportsCache + + static member ActualParseFileCount = actualParseFileCount + + static member ActualCheckFileCount = actualCheckFileCount + + interface IBackgroundCompiler with + + member _.BeforeBackgroundFileCheck = self.BeforeBackgroundFileCheck + + member _.CheckFileInProject + ( + parseResults: FSharpParseFileResults, + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + self.CheckFileInProject(parseResults, fileName, fileVersion, sourceText, options, userOpName) + + member _.CheckFileInProjectAllowingStaleCachedResults + ( + parseResults: FSharpParseFileResults, + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + self.CheckFileInProjectAllowingStaleCachedResults(parseResults, fileName, fileVersion, sourceText, options, userOpName) + + member _.ClearCache(options: seq, userOpName: string) : unit = self.ClearCache(options, userOpName) + + member _.ClearCache(projects: ProjectSnapshot.FSharpProjectIdentifier seq, userOpName: string) = ignore (projects, userOpName) + + member _.ClearCaches() : unit = self.ClearCaches() + member _.DownsizeCaches() : unit = self.DownsizeCaches() + member _.FileChecked: IEvent = self.FileChecked + member _.FileParsed: IEvent = self.FileParsed + + member _.FindReferencesInFile + ( + fileName: string, + options: FSharpProjectOptions, + symbol: FSharpSymbol, + canInvalidateProject: bool, + userOpName: string + ) : NodeCode> = + self.FindReferencesInFile(fileName, options, symbol, canInvalidateProject, userOpName) + + member this.FindReferencesInFile(fileName, projectSnapshot, symbol, userOpName) = + this.FindReferencesInFile(fileName, projectSnapshot.ToOptions(), symbol, true, userOpName) + + member _.FrameworkImportsCache: FrameworkImportsCache = self.FrameworkImportsCache + + member _.GetAssemblyData + ( + options: FSharpProjectOptions, + _fileName: string, + userOpName: string + ) : NodeCode = + self.GetAssemblyData(options, userOpName) + + member _.GetAssemblyData + ( + projectSnapshot: FSharpProjectSnapshot, + _fileName: string, + userOpName: string + ) : NodeCode = + self.GetAssemblyData(projectSnapshot.ToOptions(), userOpName) + + member _.GetBackgroundCheckResultsForFileInProject + ( + fileName: string, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + self.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName) + + member _.GetBackgroundParseResultsForFileInProject + ( + fileName: string, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + self.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName) + + member _.GetCachedCheckFileResult + ( + builder: IncrementalBuilder, + fileName: string, + sourceText: ISourceText, + options: FSharpProjectOptions + ) : NodeCode<(FSharpParseFileResults * FSharpCheckFileResults) option> = + self.GetCachedCheckFileResult(builder, fileName, sourceText, options) + + member _.GetProjectOptionsFromScript + ( + fileName: string, + sourceText: ISourceText, + previewEnabled: bool option, + loadedTimeStamp: DateTime option, + otherFlags: string array option, + useFsiAuxLib: bool option, + useSdkRefs: bool option, + sdkDirOverride: string option, + assumeDotNetFramework: bool option, + optionsStamp: int64 option, + userOpName: string + ) : Async = + self.GetProjectOptionsFromScript( + fileName, + sourceText, + previewEnabled, + loadedTimeStamp, + otherFlags, + useFsiAuxLib, + useSdkRefs, + sdkDirOverride, + assumeDotNetFramework, + optionsStamp, + userOpName + ) + + member _.GetSemanticClassificationForFile + ( + fileName: string, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + self.GetSemanticClassificationForFile(fileName, options, userOpName) + + member _.GetSemanticClassificationForFile + ( + fileName: string, + snapshot: FSharpProjectSnapshot, + userOpName: string + ) : NodeCode = + self.GetSemanticClassificationForFile(fileName, snapshot.ToOptions(), userOpName) + + member _.InvalidateConfiguration(options: FSharpProjectOptions, userOpName: string) : unit = + self.InvalidateConfiguration(options, userOpName) + + member _.NotifyFileChanged(fileName: string, options: FSharpProjectOptions, userOpName: string) : NodeCode = + self.NotifyFileChanged(fileName, options, userOpName) + + member _.NotifyProjectCleaned(options: FSharpProjectOptions, userOpName: string) : Async = + self.NotifyProjectCleaned(options, userOpName) + + member _.ParseAndCheckFileInProject + ( + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + self.ParseAndCheckFileInProject(fileName, fileVersion, sourceText, options, userOpName) + + member _.ParseAndCheckFileInProject + ( + fileName: string, + projectSnapshot: FSharpProjectSnapshot, + userOpName: string + ) : NodeCode = + node { + let fileSnapshot = + projectSnapshot.ProjectSnapshot.SourceFiles + |> Seq.find (fun f -> f.FileName = fileName) + + let! sourceText = fileSnapshot.GetSource() |> NodeCode.AwaitTask + let options = projectSnapshot.ToOptions() + + return! self.ParseAndCheckFileInProject(fileName, 0, sourceText, options, userOpName) + } + + member _.ParseAndCheckProject(options: FSharpProjectOptions, userOpName: string) : NodeCode = + self.ParseAndCheckProject(options, userOpName) + + member _.ParseAndCheckProject(projectSnapshot: FSharpProjectSnapshot, userOpName: string) : NodeCode = + self.ParseAndCheckProject(projectSnapshot.ToOptions(), userOpName) + + member _.ParseFile + ( + fileName: string, + sourceText: ISourceText, + options: FSharpParsingOptions, + cache: bool, + flatErrors: bool, + userOpName: string + ) = + self.ParseFile(fileName, sourceText, options, cache, flatErrors, userOpName) + + member _.ParseFile(fileName: string, projectSnapshot: FSharpProjectSnapshot, userOpName: string) = + let options = projectSnapshot.ToOptions() + + self.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName) + |> Async.AwaitNodeCode + + member _.ProjectChecked: IEvent = self.ProjectChecked + + member _.TryGetRecentCheckResultsForFile + ( + fileName: string, + options: FSharpProjectOptions, + sourceText: ISourceText option, + userOpName: string + ) : (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option = + self.TryGetRecentCheckResultsForFile(fileName, options, sourceText, userOpName) diff --git a/src/Compiler/Service/BackgroundCompiler.fsi b/src/Compiler/Service/BackgroundCompiler.fsi new file mode 100644 index 00000000000..f3bf3c96ccc --- /dev/null +++ b/src/Compiler/Service/BackgroundCompiler.fsi @@ -0,0 +1,224 @@ +namespace FSharp.Compiler.CodeAnalysis + +open FSharp.Compiler.Text +open FSharp.Compiler.BuildGraph + +open System.Reflection +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CompilerConfig +open FSharp.Compiler.Diagnostics + +type SourceTextHash = int64 + +type CacheStamp = int64 + +type FileName = string + +type FilePath = string + +type ProjectPath = string + +type FileVersion = int + +type FSharpProjectSnapshot = ProjectSnapshot.FSharpProjectSnapshot + +type internal IBackgroundCompiler = + + /// Type-check the result obtained by parsing. Force the evaluation of the antecedent type checking context if needed. + abstract CheckFileInProject: + parseResults: FSharpParseFileResults * + fileName: string * + fileVersion: int * + sourceText: ISourceText * + options: FSharpProjectOptions * + userOpName: string -> + NodeCode + + /// Type-check the result obtained by parsing, but only if the antecedent type checking context is available. + abstract CheckFileInProjectAllowingStaleCachedResults: + parseResults: FSharpParseFileResults * + fileName: string * + fileVersion: int * + sourceText: ISourceText * + options: FSharpProjectOptions * + userOpName: string -> + NodeCode + + abstract ClearCache: options: FSharpProjectOptions seq * userOpName: string -> unit + + abstract ClearCache: projects: ProjectSnapshot.FSharpProjectIdentifier seq * userOpName: string -> unit + + abstract ClearCaches: unit -> unit + + abstract DownsizeCaches: unit -> unit + + abstract FindReferencesInFile: + fileName: string * + projectSnapshot: FSharpProjectSnapshot * + symbol: FSharp.Compiler.Symbols.FSharpSymbol * + userOpName: string -> + NodeCode + + abstract FindReferencesInFile: + fileName: string * + options: FSharpProjectOptions * + symbol: FSharp.Compiler.Symbols.FSharpSymbol * + canInvalidateProject: bool * + userOpName: string -> + NodeCode + + abstract GetAssemblyData: + projectSnapshot: FSharpProjectSnapshot * outputFileName: string * userOpName: string -> + NodeCode + + abstract GetAssemblyData: + options: FSharpProjectOptions * outputFileName: string * userOpName: string -> + NodeCode + + /// Fetch the check information from the background compiler (which checks w.r.t. the FileSystem API) + abstract GetBackgroundCheckResultsForFileInProject: + fileName: string * options: FSharpProjectOptions * userOpName: string -> + NodeCode + + /// Fetch the parse information from the background compiler (which checks w.r.t. the FileSystem API) + abstract GetBackgroundParseResultsForFileInProject: + fileName: string * options: FSharpProjectOptions * userOpName: string -> NodeCode + + abstract GetCachedCheckFileResult: + builder: IncrementalBuilder * fileName: string * sourceText: ISourceText * options: FSharpProjectOptions -> + NodeCode<(FSharpParseFileResults * FSharpCheckFileResults) option> + + abstract GetProjectOptionsFromScript: + fileName: string * + sourceText: ISourceText * + previewEnabled: bool option * + loadedTimeStamp: System.DateTime option * + otherFlags: string array option * + useFsiAuxLib: bool option * + useSdkRefs: bool option * + sdkDirOverride: string option * + assumeDotNetFramework: bool option * + optionsStamp: int64 option * + userOpName: string -> + Async + + abstract GetSemanticClassificationForFile: + fileName: string * snapshot: FSharpProjectSnapshot * userOpName: string -> + NodeCode + + abstract GetSemanticClassificationForFile: + fileName: string * options: FSharpProjectOptions * userOpName: string -> + NodeCode + + abstract InvalidateConfiguration: options: FSharpProjectOptions * userOpName: string -> unit + + abstract NotifyFileChanged: fileName: string * options: FSharpProjectOptions * userOpName: string -> NodeCode + + abstract NotifyProjectCleaned: options: FSharpProjectOptions * userOpName: string -> Async + + abstract ParseAndCheckFileInProject: + fileName: string * projectSnapshot: FSharpProjectSnapshot * userOpName: string -> + NodeCode + + /// Parses and checks the source file and returns untyped AST and check results. + abstract ParseAndCheckFileInProject: + fileName: string * + fileVersion: int * + sourceText: ISourceText * + options: FSharpProjectOptions * + userOpName: string -> + NodeCode + + abstract ParseAndCheckProject: + projectSnapshot: FSharpProjectSnapshot * userOpName: string -> NodeCode + + /// Parse and typecheck the whole project. + abstract ParseAndCheckProject: + options: FSharpProjectOptions * userOpName: string -> NodeCode + + abstract ParseFile: + fileName: string * projectSnapshot: FSharpProjectSnapshot * userOpName: string -> Async + + abstract ParseFile: + fileName: string * + sourceText: ISourceText * + options: FSharpParsingOptions * + cache: bool * + flatErrors: bool * + userOpName: string -> + Async + + /// Try to get recent approximate type check results for a file. + abstract TryGetRecentCheckResultsForFile: + fileName: string * options: FSharpProjectOptions * sourceText: ISourceText option * userOpName: string -> + (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option + + abstract BeforeBackgroundFileCheck: IEvent + + abstract FileChecked: IEvent + + abstract FileParsed: IEvent + + abstract FrameworkImportsCache: FrameworkImportsCache + + abstract ProjectChecked: IEvent + +[] +module internal EnvMisc = + + val braceMatchCacheSize: int + + val parseFileCacheSize: int + + val checkFileInProjectCacheSize: int + + val projectCacheSizeDefault: int + + val frameworkTcImportsCacheStrongSize: int + +[] +module internal Helpers = + + /// Determine whether two (fileName,options) keys are identical w.r.t. affect on checking + val AreSameForChecking2: (string * FSharpProjectOptions) * (string * FSharpProjectOptions) -> bool + + /// Determine whether two (fileName,options) keys should be identical w.r.t. resource usage + val AreSubsumable2: (string * FSharpProjectOptions) * (string * FSharpProjectOptions) -> bool + + /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. parsing + val AreSameForParsing: (string * int64 * 'a) * (string * int64 * 'a) -> bool when 'a: equality + + val AreSimilarForParsing: ('a * 'b * 'c) * ('a * 'd * 'e) -> bool when 'a: equality + + /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. checking + val AreSameForChecking3: (string * int64 * FSharpProjectOptions) * (string * int64 * FSharpProjectOptions) -> bool + + /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. resource usage + val AreSubsumable3: (string * 'a * FSharpProjectOptions) * (string * 'b * FSharpProjectOptions) -> bool + + /// If a symbol is an attribute check if given set of names contains its name without the Attribute suffix + val NamesContainAttribute: symbol: FSharp.Compiler.Symbols.FSharpSymbol -> names: Set -> bool + +type internal BackgroundCompiler = + interface IBackgroundCompiler + + new: + legacyReferenceResolver: LegacyReferenceResolver * + projectCacheSize: int * + keepAssemblyContents: bool * + keepAllBackgroundResolutions: bool * + tryGetMetadataSnapshot: FSharp.Compiler.AbstractIL.ILBinaryReader.ILReaderTryGetMetadataSnapshot * + suggestNamesForErrors: bool * + keepAllBackgroundSymbolUses: bool * + enableBackgroundItemKeyStoreAndSemanticClassification: bool * + enablePartialTypeChecking: bool * + parallelReferenceResolution: ParallelReferenceResolution * + captureIdentifiersWhenParsing: bool * + getSource: (string -> Async) option * + useChangeNotifications: bool * + useSyntaxTreeCache: bool -> + BackgroundCompiler + + static member ActualCheckFileCount: int + + static member ActualParseFileCount: int diff --git a/src/Compiler/Service/FSharpCheckerResults.fs b/src/Compiler/Service/FSharpCheckerResults.fs index 2b23d85a7ce..5f18a90968a 100644 --- a/src/Compiler/Service/FSharpCheckerResults.fs +++ b/src/Compiler/Service/FSharpCheckerResults.fs @@ -6,6 +6,7 @@ namespace FSharp.Compiler.CodeAnalysis open System +open System.Collections.Generic open System.Diagnostics open System.IO open System.Reflection @@ -53,6 +54,9 @@ open FSharp.Compiler.TypedTreeOps open Internal.Utilities open Internal.Utilities.Collections open FSharp.Compiler.AbstractIL.ILBinaryReader +open System.Threading.Tasks +open System.Runtime.CompilerServices +open Internal.Utilities.Hashing type FSharpUnresolvedReferencesSet = FSharpUnresolvedReferencesSet of UnresolvedAssemblyReference list @@ -483,6 +487,8 @@ type internal TypeCheckInfo // // 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(_, ItemOccurence.InvalidUse, _, _, _, _) :: _, _ -> NameResResult.Empty + | CNR(Item.Types(_, ty :: _), _, denv, nenv, ad, m) :: _, Some _ -> let targets = ResolveCompletionTargets.All(ConstraintSolver.IsApplicableMethApprox g amap m) @@ -891,7 +897,6 @@ type internal TypeCheckInfo let CompletionItem (ty: TyconRef voption) (assemblySymbol: AssemblySymbol voption) (item: ItemWithInst) = let kind = match item.Item with - | Item.FakeInterfaceCtor _ | Item.DelegateCtor _ | Item.CtorGroup _ -> CompletionItemKind.Method false | Item.MethodGroup(_, minfos, _) -> @@ -1802,7 +1807,6 @@ type internal TypeCheckInfo match d.Item with | Item.Types(_, AbbrevOrAppTy 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(AbbrevOrAppTy tcref) | Item.DelegateCtor(AbbrevOrAppTy 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 @@ -1822,7 +1826,6 @@ type internal TypeCheckInfo | Item.Types(_, AbbrevOrAppTy tcref :: _) | Item.ExnCase tcref -> tcref.LogicalName | Item.UnqualifiedType(tcref :: _) - | Item.FakeInterfaceCtor(AbbrevOrAppTy tcref) | Item.DelegateCtor(AbbrevOrAppTy tcref) -> tcref.CompiledName | Item.CtorGroup(_, cinfo :: _) -> cinfo.ApparentEnclosingTyconRef.CompiledName | _ -> d.Item.DisplayName) @@ -1909,7 +1912,7 @@ type internal TypeCheckInfo | Some(_, lines) -> let lines = lines - |> List.filter (fun line -> not (line.StartsWith("//")) && not (String.IsNullOrEmpty line)) + |> List.filter (fun line -> not (line.StartsWithOrdinal("//")) && not (String.IsNullOrEmpty line)) ToolTipText.ToolTipText [ @@ -2252,7 +2255,7 @@ type internal TypeCheckInfo | Some itemRange -> let projectDir = FileSystem.GetDirectoryNameShim( - if projectFileName = "" then + if String.IsNullOrEmpty(projectFileName) then mainInputFileName else projectFileName @@ -2516,6 +2519,11 @@ module internal ParseAndCheckFile = member _.AnyErrors = errorCount > 0 + member _.CollectedPhasedDiagnostics = + [| + for struct (diagnostic, severity) in diagnosticsCollector -> diagnostic, severity + |] + member _.CollectedDiagnostics(symbolEnv: SymbolEnv option) = [| for struct (diagnostic, severity) in diagnosticsCollector do @@ -3271,7 +3279,7 @@ type FSharpCheckFileResults tcConfig, tcGlobals, isIncompleteTypeCheckEnvironment: bool, - builder: IncrementalBuilder, + builder: IncrementalBuilder option, projectOptions, dependencyFiles, creationErrors: FSharpDiagnostic[], @@ -3312,7 +3320,7 @@ type FSharpCheckFileResults let errors = FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) - FSharpCheckFileResults(mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, keepAssemblyContents) + FSharpCheckFileResults(mainInputFileName, errors, Some tcFileInfo, dependencyFiles, builder, keepAssemblyContents) static member CheckOneFile ( @@ -3329,7 +3337,7 @@ type FSharpCheckFileResults backgroundDiagnostics: (PhasedDiagnostic * FSharpDiagnosticSeverity)[], isIncompleteTypeCheckEnvironment: bool, projectOptions: FSharpProjectOptions, - builder: IncrementalBuilder, + builder: IncrementalBuilder option, dependencyFiles: string[], creationErrors: FSharpDiagnostic[], parseErrors: FSharpDiagnostic[], @@ -3358,7 +3366,7 @@ type FSharpCheckFileResults FSharpCheckFileResults.JoinErrors(isIncompleteTypeCheckEnvironment, creationErrors, parseErrors, tcErrors) let results = - FSharpCheckFileResults(mainInputFileName, errors, Some tcFileInfo, dependencyFiles, Some builder, keepAssemblyContents) + FSharpCheckFileResults(mainInputFileName, errors, Some tcFileInfo, dependencyFiles, builder, keepAssemblyContents) return results } @@ -3376,7 +3384,7 @@ type FSharpCheckProjectResults TcImports * CcuThunk * ModuleOrNamespaceType * - Choice * + Choice> * TopAttribs option * (unit -> IRawFSharpAssemblyData option) * ILAssemblyRef * @@ -3414,6 +3422,7 @@ type FSharpCheckProjectResults FSharpAssemblySignature(tcGlobals, thisCcu, ccuSig, tcImports, topAttribs, ccuSig) + // TODO: Looks like we don't need this member _.TypedImplementationFiles = if not keepAssemblyContents then invalidOp @@ -3474,6 +3483,7 @@ type FSharpCheckProjectResults FSharpAssemblyContents(tcGlobals, thisCcu, Some ccuSig, tcImports, mimpls) // Not, this does not have to be a SyncOp, it can be called from any thread + // TODO: this should be async member _.GetUsesOfSymbol(symbol: FSharpSymbol, ?cancellationToken: CancellationToken) = let _, _, _, _, builderOrSymbolUses, _, _, _, _, _, _, _ = getDetails () @@ -3489,7 +3499,20 @@ type FSharpCheckProjectResults | Some(_, tcInfoExtras) -> tcInfoExtras.TcSymbolUses.GetUsesOfSymbol symbol.Item | _ -> [||] | _ -> [||]) - | Choice2Of2 tcSymbolUses -> tcSymbolUses.GetUsesOfSymbol symbol.Item + |> Array.toSeq + | Choice2Of2 task -> + Async.RunSynchronously( + async { + let! tcSymbolUses = task + + return + seq { + for symbolUses in tcSymbolUses do + yield! symbolUses.GetUsesOfSymbol symbol.Item + } + }, + ?cancellationToken = cancellationToken + ) results |> Seq.filter (fun symbolUse -> symbolUse.ItemOccurence <> ItemOccurence.RelatedText) @@ -3501,6 +3524,7 @@ type FSharpCheckProjectResults |> Seq.toArray // Not, this does not have to be a SyncOp, it can be called from any thread + // TODO: this should be async member _.GetAllUsesOfAllSymbols(?cancellationToken: CancellationToken) = let tcGlobals, tcImports, thisCcu, ccuSig, builderOrSymbolUses, _, _, _, _, _, _, _ = getDetails () @@ -3519,7 +3543,8 @@ type FSharpCheckProjectResults | Some(_, tcInfoExtras) -> tcInfoExtras.TcSymbolUses | _ -> TcSymbolUses.Empty | _ -> TcSymbolUses.Empty) - | Choice2Of2 tcSymbolUses -> [| tcSymbolUses |] + |> Array.toSeq + | Choice2Of2 tcSymbolUses -> Async.RunSynchronously(tcSymbolUses, ?cancellationToken = cancellationToken) [| for r in tcSymbolUses do @@ -3560,9 +3585,6 @@ type FsiInteractiveChecker(legacyReferenceResolver, tcConfig: TcConfig, tcGlobal member _.ParseAndCheckInteraction(sourceText: ISourceText, ?userOpName: string) = cancellable { - let! ct = Cancellable.token () - use _ = Cancellable.UsingToken(ct) - 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 @@ -3658,7 +3680,7 @@ type FsiInteractiveChecker(legacyReferenceResolver, tcConfig: TcConfig, tcGlobal tcImports, tcFileInfo.ThisCcu, tcFileInfo.CcuSigForFile, - Choice2Of2 tcFileInfo.ScopeSymbolUses, + Choice2Of2(tcFileInfo.ScopeSymbolUses |> Seq.singleton |> async.Return), None, (fun () -> None), mkSimpleAssemblyRef "stdin", diff --git a/src/Compiler/Service/FSharpCheckerResults.fsi b/src/Compiler/Service/FSharpCheckerResults.fsi index 8cdb304c18a..26781c4356e 100644 --- a/src/Compiler/Service/FSharpCheckerResults.fsi +++ b/src/Compiler/Service/FSharpCheckerResults.fsi @@ -3,8 +3,10 @@ namespace FSharp.Compiler.CodeAnalysis open System +open System.Collections.Generic open System.IO open System.Threading +open System.Threading.Tasks open Internal.Utilities.Library open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader @@ -26,6 +28,8 @@ open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TcGlobals open FSharp.Compiler.Text +open Internal.Utilities.Collections + /// Delays the creation of an ILModuleReader [] type DelayedILModuleReader = @@ -443,7 +447,7 @@ type public FSharpCheckFileResults = tcConfig: TcConfig * tcGlobals: TcGlobals * isIncompleteTypeCheckEnvironment: bool * - builder: IncrementalBuilder * + builder: IncrementalBuilder option * projectOptions: FSharpProjectOptions * dependencyFiles: string[] * creationErrors: FSharpDiagnostic[] * @@ -477,7 +481,7 @@ type public FSharpCheckFileResults = backgroundDiagnostics: (PhasedDiagnostic * FSharpDiagnosticSeverity)[] * isIncompleteTypeCheckEnvironment: bool * projectOptions: FSharpProjectOptions * - builder: IncrementalBuilder * + builder: IncrementalBuilder option * dependencyFiles: string[] * creationErrors: FSharpDiagnostic[] * parseErrors: FSharpDiagnostic[] * @@ -537,7 +541,7 @@ type public FSharpCheckProjectResults = TcImports * CcuThunk * ModuleOrNamespaceType * - Choice * + Choice> * TopAttribs option * (unit -> IRawFSharpAssemblyData option) * ILAssemblyRef * @@ -569,6 +573,29 @@ module internal ParseAndCheckFile = ct: CancellationToken -> (range * range)[] + /// Diagnostics handler for parsing & type checking while processing a single file + type DiagnosticsHandler = + new: + reportErrors: bool * + mainInputFileName: string * + diagnosticsOptions: FSharpDiagnosticOptions * + sourceText: ISourceText * + suggestNamesForErrors: bool * + flatErrors: bool -> + DiagnosticsHandler + + member DiagnosticsLogger: DiagnosticsLogger + + member ErrorCount: int + + member DiagnosticOptions: FSharpDiagnosticOptions with set + + member AnyErrors: bool + + member CollectedPhasedDiagnostics: (PhasedDiagnostic * FSharpDiagnosticSeverity) array + + member CollectedDiagnostics: symbolEnv: SymbolEnv option -> FSharpDiagnostic array + // An object to typecheck source in a given typechecking environment. // Used internally to provide intellisense over F# Interactive. type internal FsiInteractiveChecker = diff --git a/src/Compiler/Service/FSharpParseFileResults.fs b/src/Compiler/Service/FSharpParseFileResults.fs index 46a5753ba3f..baea32da816 100644 --- a/src/Compiler/Service/FSharpParseFileResults.fs +++ b/src/Compiler/Service/FSharpParseFileResults.fs @@ -6,7 +6,6 @@ open System open System.IO open System.Collections.Generic open System.Diagnostics -open Internal.Utilities.Library open FSharp.Compiler.Diagnostics open FSharp.Compiler.EditorServices open FSharp.Compiler.Syntax @@ -115,201 +114,118 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, | _ -> Some workingRange - 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) + (pos, input) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynBinding(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 + | _ -> None) member _.TryIdentOfPipelineContainingPosAndNumArgsApplied pos = - 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) + (pos, input) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.App( + funcExpr = SynExpr.App(_, true, SynExpr.LongIdent(longDotId = SynLongIdent(id = [ ident ])), _, _); argExpr = 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 + | _ -> None) member _.IsPosContainedInApplication pos = - 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 -> - traverseSynExpr expr - | SynExpr.App(_, _, _, _, range) when rangeContainsPos range pos -> Some range - | _ -> defaultTraverse expr - } - - let result = SyntaxTraversal.Traverse(pos, input, visitor) - result.IsSome + (pos, input) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.App(argExpr = SynExpr.ComputationExpr _) | SynExpr.TypeApp(expr = SynExpr.ComputationExpr _)) -> + false + | SyntaxNode.SynExpr(SynExpr.App(range = range) | SynExpr.TypeApp(range = range)) when rangeContainsPos range pos -> true + | _ -> false) member _.IsTypeName(range: range) = - let visitor = - { new SyntaxVisitorBase<_>() with - member _.VisitModuleDecl(_, _, synModuleDecl) = - match synModuleDecl with - | SynModuleDecl.Types(typeDefns, _) -> - typeDefns - |> Seq.exists (fun (SynTypeDefn(typeInfo, _, _, _, _, _)) -> typeInfo.Range = range) - |> Some - | _ -> None - } - - let result = SyntaxTraversal.Traverse(range.Start, input, visitor) - result |> Option.contains true + (range.Start, input) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn(SynTypeDefn(typeInfo = typeInfo)) -> typeInfo.Range = range + | _ -> false) 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.TypeApp(expr, _, _, _, _, _, _) -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos - - | SynExpr.App(_, _, funcExpr, argExpr, _) -> - match argExpr with - | SynExpr.App(_, _, _, _, range) when rangeContainsPos range pos -> - getIdentRangeForFuncExprInApp traverseSynExpr argExpr pos - - // Special case: `async { ... }` is actually a ComputationExpr inside of the argExpr of a SynExpr.App - | SynExpr.ComputationExpr(_, expr, range) - | SynExpr.Paren(expr, _, _, range) when rangeContainsPos range pos -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos - - // Yielding values in an array or list that is used as an argument: List.sum [ getVal a b; getVal b c ] - | SynExpr.ArrayOrListComputed(_, expr, range) when rangeContainsPos range pos -> - if rangeContainsPos expr.Range pos then - getIdentRangeForFuncExprInApp traverseSynExpr expr pos - else - (* - In cases like - - let test () = div [] [ - str "" - ; | - ] - - `ProvideParametersAsyncAux` currently works with the wrong symbol or - doesn't detect the previously applied arguments. - Until that is fixed, don't show any tooltips rather than the wrong signature. - *) - None - - | _ -> - match funcExpr with - | SynExpr.App(_, true, _, _, _) when rangeContainsPos argExpr.Range pos -> - // 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 - | _ -> - // Generally, we want to dive into the func expr to get the range - // of the identifier of the function we're after - getIdentRangeForFuncExprInApp traverseSynExpr funcExpr pos - - | SynExpr.Sequential(_, _, expr1, expr2, range) when rangeContainsPos range pos -> - if rangeContainsPos expr1.Range pos then - getIdentRangeForFuncExprInApp traverseSynExpr expr1 pos - else - getIdentRangeForFuncExprInApp traverseSynExpr expr2 pos - - | SynExpr.LetOrUse(bindings = bindings; body = body; range = range) when rangeContainsPos range pos -> - let binding = - 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 - - | 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 - getIdentRangeForFuncExprInApp traverseSynExpr thenExpr pos - else - match elseExpr with - | None -> None - | Some expr -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos + let rec (|FuncIdent|_|) (node, path) = + match node, path with + | SyntaxNode.SynExpr(DeepestIdentifiedFuncInAppChain range), _ -> Some range + | SyntaxNode.SynExpr PossibleBareArg, DeepestIdentifiedFuncInPath range -> Some range + | SyntaxNode.SynExpr(Identifier range), _ -> Some range + | _ -> None - | SynExpr.Match(expr = expr; clauses = clauses; range = range) when rangeContainsPos range pos -> + and (|DeepestIdentifiedFuncInAppChain|_|) expr = + let (|Contains|_|) pos (expr: SynExpr) = if rangeContainsPos expr.Range pos then - getIdentRangeForFuncExprInApp traverseSynExpr expr pos + Some Contains else - 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) -> - match whenExprOpt with - | 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 -> - let expr = exprs |> List.tryFind (fun expr -> rangeContainsPos expr.Range pos) - - match expr with - | None -> None - | 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 + None - | SynExpr.DotLambda(expr = body) when rangeContainsPos body.Range pos -> getIdentRangeForFuncExprInApp traverseSynExpr body pos - - | SynExpr.Do(expr, range) when rangeContainsPos range pos -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos + match expr with + | SynExpr.App(argExpr = Contains pos & DeepestIdentifiedFuncInAppChain range) -> Some range + | SynExpr.App(isInfix = false; funcExpr = Identifier range | DeepestIdentifiedFuncInAppChain range) -> Some range + | SynExpr.TypeApp(expr = Identifier range) -> Some range + | SynExpr.Paren(expr = Contains pos & DeepestIdentifiedFuncInAppChain range) -> Some range + | _ -> None - | SynExpr.Assert(expr, range) when rangeContainsPos range pos -> getIdentRangeForFuncExprInApp traverseSynExpr expr pos + and (|DeepestIdentifiedFuncInPath|_|) path = + match path with + | SyntaxNode.SynExpr(DeepestIdentifiedFuncInAppChain range) :: _ + | SyntaxNode.SynExpr PossibleBareArg :: DeepestIdentifiedFuncInPath range -> Some range + | _ -> None - | SynExpr.ArbitraryAfterError(_debugStr, range) when rangeContainsPos range pos -> Some range + and (|Identifier|_|) expr = + let (|Ident|) (ident: Ident) = ident.idRange - | expr -> traverseSynExpr expr + match expr with + | SynExpr.Ident(ident = Ident range) + | SynExpr.LongIdent(range = range) + | SynExpr.ArbitraryAfterError(range = range) -> Some range + | _ -> None - 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 - } + and (|PossibleBareArg|_|) expr = + match expr with + | SynExpr.App _ + | SynExpr.TypeApp _ + | SynExpr.Ident _ + | SynExpr.LongIdent _ + | SynExpr.Const _ + | SynExpr.Null _ + | SynExpr.InterpolatedString _ -> Some PossibleBareArg + + // f (g ‸) + | SynExpr.Paren(expr = SynExpr.Ident _ | SynExpr.LongIdent _; range = parenRange) when + rangeContainsPos parenRange pos + && not (expr.Range.End.IsAdjacentTo parenRange.End) + -> + None + + | SynExpr.Paren _ -> Some PossibleBareArg + | _ -> None - SyntaxTraversal.Traverse(pos, input, visitor) + match input |> ParsedInput.tryNode pos with + | Some(FuncIdent range) -> Some range + | Some _ -> None + | None -> + // The cursor is outside any existing node's range, + // so try to drill down into the nearest one. + (pos, input) + ||> ParsedInput.tryPickLast (fun path node -> + match node, path with + | FuncIdent range -> Some range + | _ -> None) member _.GetAllArgumentsForFunctionApplicationAtPosition pos = SynExprAppLocationsImpl.getAllCurriedArgsAtPosition pos input @@ -326,242 +242,161 @@ type FSharpParseFileResults(diagnostics: FSharpDiagnostic[], input: ParsedInput, false, SynExpr.App(ExprAtomicFlag.NonAtomic, true, Ident "op_EqualsGreater", actualParamListExpr, _), actualLambdaBodyExpr, - _) -> Some(actualParamListExpr, actualLambdaBodyExpr) + range) -> Some(range, 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 - } - ) + (opGreaterEqualPos, input) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Paren(expr = InfixAppOfOpEqualsGreater(range, lambdaArgs, lambdaBody))) + | SyntaxNode.SynBinding(SynBinding( + kind = SynBindingKind.Normal; expr = InfixAppOfOpEqualsGreater(range, lambdaArgs, lambdaBody))) -> + Some(range, lambdaArgs.Range, lambdaBody.Range) + | _ -> None) member _.TryRangeOfStringInterpolationContainingPos pos = - 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) + (pos, input) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.InterpolatedString(range = range)) when rangeContainsPos range pos -> Some range + | _ -> None) member _.TryRangeOfExprInYieldOrReturn pos = - 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) + (pos, input) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.YieldOrReturn(expr = expr; range = range) | SynExpr.YieldOrReturnFrom(expr = expr; range = range)) when + rangeContainsPos range pos + -> + Some expr.Range + | _ -> None) member _.TryRangeOfRecordExpressionContainingPos pos = - 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) + (pos, input) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Record(range = range)) when rangeContainsPos range pos -> Some range + | _ -> None) member _.TryRangeOfRefCellDereferenceContainingPos expressionPos = - 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) + (expressionPos, input) + ||> ParsedInput.tryPick (fun _path node -> + let (|Ident|) (ident: Ident) = ident.idText + + match node with + | SyntaxNode.SynExpr(SynExpr.App( + isInfix = false + funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent(id = [ funcIdent & Ident "op_Dereference" ])) + argExpr = argExpr)) when rangeContainsPos argExpr.Range expressionPos -> Some funcIdent.idRange + | _ -> None) member _.TryRangeOfExpressionBeingDereferencedContainingPos expressionPos = - 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 - } - - SyntaxTraversal.Traverse(expressionPos, input, visitor) + (expressionPos, input) + ||> ParsedInput.tryPick (fun _path node -> + let (|Ident|) (ident: Ident) = ident.idText + + match node with + | SyntaxNode.SynExpr(SynExpr.App( + isInfix = false; funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent(id = [ Ident "op_Dereference" ])); argExpr = argExpr)) when + rangeContainsPos argExpr.Range expressionPos + -> + Some argExpr.Range + | _ -> None) member _.TryRangeOfReturnTypeHint(symbolUseStart: pos, ?skipLambdas) = let skipLambdas = defaultArg skipLambdas true - SyntaxTraversal.Traverse( - symbolUseStart, - input, - { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, _traverseSynExpr, defaultTraverse, expr) = defaultTraverse expr + (symbolUseStart, input) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynBinding(SynBinding(expr = SynExpr.Lambda _)) + | SyntaxNode.SynBinding(SynBinding(expr = SynExpr.DotLambda _)) when skipLambdas -> None - override _.VisitBinding(_path, defaultTraverse, binding) = - match binding with - | SynBinding(expr = SynExpr.Lambda _) when skipLambdas -> defaultTraverse binding - | SynBinding(expr = SynExpr.DotLambda _) when skipLambdas -> defaultTraverse binding + // Skip manually type-annotated bindings + | SyntaxNode.SynBinding(SynBinding(returnInfo = Some(SynBindingReturnInfo _))) -> None - // Skip manually type-annotated bindings - | SynBinding(returnInfo = Some(SynBindingReturnInfo _)) -> defaultTraverse binding + // Let binding + | SyntaxNode.SynBinding(SynBinding(trivia = { EqualsRange = Some equalsRange }; range = range)) when + range.Start = symbolUseStart + -> + Some equalsRange.StartRange - // Let binding - | SynBinding(trivia = { EqualsRange = Some equalsRange }; range = range) when range.Start = symbolUseStart -> - Some equalsRange.StartRange + // Member binding + | SyntaxNode.SynBinding(SynBinding( + headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = _ :: ident :: _)); trivia = { EqualsRange = Some equalsRange })) when + ident.idRange.Start = symbolUseStart + -> + Some equalsRange.StartRange - // Member binding - | SynBinding( - headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = _ :: ident :: _)) - trivia = { EqualsRange = Some equalsRange }) when ident.idRange.Start = symbolUseStart -> - Some equalsRange.StartRange - - | _ -> defaultTraverse binding - } - ) + | _ -> None) member _.FindParameterLocations pos = ParameterLocations.Find(pos, input) member _.IsPositionContainedInACurriedParameter pos = - let visitor = - { new SyntaxVisitorBase<_>() with - member _.VisitExpr(_path, traverseSynExpr, defaultTraverse, expr) = defaultTraverse (expr) - - override _.VisitBinding(_path, _, binding) = - match binding with - | 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 - | _ -> () - - if found then Some range else None - | _ -> None - } - - let result = SyntaxTraversal.Traverse(pos, input, visitor) - result.IsSome + (pos, input) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynBinding(SynBinding(valData = valData; range = range)) when rangeContainsPos range pos -> + valData.SynValInfo.CurriedArgInfos + |> List.exists ( + List.exists (function + | SynArgInfo(ident = Some ident) -> rangeContainsPos ident.idRange pos + | _ -> false) + ) + + | _ -> false) member _.IsTypeAnnotationGivenAtPosition pos = - 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 - | _ -> defaultTraverse expr - - override _.VisitSimplePats(_path, pats) = - match pats with - | [] -> None - | _ -> - let exprFunc pat = - match pat with - // (s: string) - | 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 - | _ -> defaultTraverse pat + (pos, input) + ||> ParsedInput.exists (fun _path node -> + let rec (|Typed|_|) (pat: SynPat) = + if not (rangeContainsPos pat.Range pos) then + None + else + let (|AnyTyped|_|) = List.tryPick (|Typed|_|) - 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 - | _ -> defaultTraverse binding - } + match pat with + | SynPat.Typed(range = range) when Position.posEq range.Start pos -> Some Typed + | SynPat.Paren(pat = Typed) -> Some Typed + | SynPat.Tuple(elementPats = AnyTyped) -> Some Typed + | _ -> None - let result = SyntaxTraversal.Traverse(pos, input, visitor) - result.IsSome + match node with + | SyntaxNode.SynExpr(SynExpr.Typed(range = range)) + | SyntaxNode.SynPat(SynPat.Typed(range = range)) -> Position.posEq range.Start pos + | SyntaxNode.SynTypeDefn(SynTypeDefn(implicitConstructor = Some(SynMemberDefn.ImplicitCtor(ctorArgs = Typed)))) + | SyntaxNode.SynBinding(SynBinding( + headPat = SynPat.Named _; returnInfo = Some(SynBindingReturnInfo(typeName = SynType.LongIdent _)))) -> true + | _ -> false) member _.IsPositionWithinTypeDefinition pos = - let visitor = - { new SyntaxVisitorBase<_>() with - override _.VisitComponentInfo(path, _) = - let typeDefs = - path - |> List.filter (function - | SyntaxNode.SynModule(SynModuleDecl.Types _) -> true - | _ -> false) - - match typeDefs with - | [] -> None - | _ -> Some true - } - - let result = SyntaxTraversal.Traverse(pos, input, visitor) - result.IsSome + (pos, input) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn _ -> true + | _ -> false) 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 - | SynExpr.DotLambda _ -> Some range - | _ -> None - | _ -> defaultTraverse binding - } - - let result = SyntaxTraversal.Traverse(pos, input, visitor) - result.IsSome + (pos, input) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynBinding(SynBinding(expr = SynExpr.Lambda _; range = range)) + | SyntaxNode.SynBinding(SynBinding(expr = SynExpr.DotLambda _; range = range)) -> Position.posEq range.Start pos + | _ -> false) member _.IsPositionWithinRecordDefinition pos = let isWithin left right middle = Position.posGt right left && Position.posLt middle right - let visitor = - { new SyntaxVisitorBase<_>() with - override _.VisitRecordDefn(_, _, range) = - if pos |> isWithin range.Start range.End then - Some true - else - None - - override _.VisitTypeAbbrev(_, synType, range) = - match synType with - | SynType.AnonRecd _ when pos |> isWithin range.Start range.End -> Some true - | _ -> None - } - - let result = SyntaxTraversal.Traverse(pos, input, visitor) - result.IsSome + (pos, input) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn(SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record _, range))) + | SyntaxNode.SynTypeDefn(SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.TypeAbbrev _, range))) when + pos |> isWithin range.Start range.End + -> + true + | _ -> false) /// Get declared items and the selected item at the specified location member _.GetNavigationItemsImpl() = diff --git a/src/Compiler/Service/FSharpProjectSnapshot.fs b/src/Compiler/Service/FSharpProjectSnapshot.fs new file mode 100644 index 00000000000..259948dc706 --- /dev/null +++ b/src/Compiler/Service/FSharpProjectSnapshot.fs @@ -0,0 +1,626 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module FSharp.Compiler.CodeAnalysis.ProjectSnapshot + +open System +open System.Collections.Generic +open System.IO +open System.Reflection +open FSharp.Compiler.IO +open Internal.Utilities.Library.Extras +open FSharp.Core.Printf +open FSharp.Compiler.Text + +open Internal.Utilities.Collections +open System.Threading.Tasks +open Internal.Utilities.Hashing +open System.Collections.Immutable +open System.Runtime.CompilerServices +open FSharp.Compiler.Syntax +open FSharp.Compiler.Diagnostics +open FSharp.Compiler.DiagnosticsLogger + +type internal ProjectIdentifier = string * string + +/// A common interface for an F# source file snapshot that can be used accross all stages (lazy, source loaded, parsed) +type internal IFileSnapshot = + abstract member FileName: string + abstract member Version: byte array + abstract member IsSignatureFile: bool + +[] +module internal Helpers = + + let isSignatureFile (fileName: string) = + // TODO: is this robust enough? + fileName[fileName.Length - 1] = 'i' + + let addFileName (file: IFileSnapshot) = Md5Hasher.addString file.FileName + + let addFileNameAndVersion (file: IFileSnapshot) = + addFileName file >> Md5Hasher.addBytes file.Version + + let signatureHash projectCoreVersion (sourceFiles: IFileSnapshot seq) = + let mutable lastFile = "" + + ((projectCoreVersion, Set.empty), sourceFiles) + ||> Seq.fold (fun (res, sigs) file -> + if file.IsSignatureFile then + lastFile <- file.FileName + res |> addFileNameAndVersion file, sigs |> Set.add file.FileName + else + let sigFileName = $"{file.FileName}i" + + if sigs.Contains sigFileName then + res |> addFileName file, sigs |> Set.remove sigFileName + else + lastFile <- file.FileName + res |> addFileNameAndVersion file, sigs) + |> fst, + lastFile + + let findOutputFileName options = + options + |> Seq.tryFind (fun (x: string) -> x.StartsWith("-o:")) + |> Option.map (fun x -> x.Substring(3)) + +/// A snapshot of an F# source file. +[] +type FSharpFileSnapshot(FileName: string, Version: string, GetSource: unit -> Task) = + + static member Create(fileName: string, version: string, getSource: unit -> Task) = + FSharpFileSnapshot(fileName, version, getSource) + + static member CreateFromFileSystem(fileName: string) = + FSharpFileSnapshot( + fileName, + FileSystem.GetLastWriteTimeShim(fileName).Ticks.ToString(), + fun () -> + FileSystem.OpenFileForReadShim(fileName).ReadAllText() + |> SourceTextNew.ofString + |> Task.FromResult + ) + + member public _.FileName = FileName + member _.Version = Version + member _.GetSource() = GetSource() + + member val IsSignatureFile = FileName |> isSignatureFile + + member _.GetFileName() = FileName + + override this.Equals(o) = + match o with + | :? FSharpFileSnapshot as o -> o.FileName = this.FileName && o.Version = this.Version + | _ -> false + + override this.GetHashCode() = + this.FileName.GetHashCode() + this.Version.GetHashCode() + + interface IFileSnapshot with + member this.FileName = this.FileName + member this.Version = this.Version |> System.Text.Encoding.UTF8.GetBytes + member this.IsSignatureFile = this.IsSignatureFile + +/// A source file snapshot with loaded source text. +type internal FSharpFileSnapshotWithSource + (FileName: string, SourceHash: ImmutableArray, Source: ISourceText, IsLastCompiland: bool, IsExe: bool) = + + let version = lazy (SourceHash.ToBuilder().ToArray()) + let stringVersion = lazy (version.Value |> BitConverter.ToString) + + member val Version = version.Value + member val StringVersion = stringVersion.Value + member val IsSignatureFile = FileName |> isSignatureFile + + member _.FileName = FileName + member _.Source = Source + member _.IsLastCompiland = IsLastCompiland + member _.IsExe = IsExe + + interface IFileSnapshot with + member this.FileName = this.FileName + member this.Version = this.Version + member this.IsSignatureFile = this.IsSignatureFile + +/// A source file snapshot with parsed syntax tree +type internal FSharpParsedFile + ( + FileName: string, + SyntaxTreeHash: byte array, + SourceText: ISourceText, + ParsedInput: ParsedInput, + ParseErrors: (PhasedDiagnostic * FSharpDiagnosticSeverity)[] + ) = + + member _.FileName = FileName + member _.SourceText = SourceText + member _.ParsedInput = ParsedInput + member _.ParseErrors = ParseErrors + + member val IsSignatureFile = FileName |> isSignatureFile + + interface IFileSnapshot with + member this.FileName = this.FileName + member this.Version = SyntaxTreeHash + member this.IsSignatureFile = this.IsSignatureFile + +/// An on-disk reference needed for project compilation. +[] +type ReferenceOnDisk = + { Path: string; LastModified: DateTime } + +/// A snapshot of an F# project. The source file type can differ based on which stage of compilation the snapshot is used for. +type internal ProjectSnapshotBase<'T when 'T :> IFileSnapshot>(projectCore: ProjectCore, sourceFiles: 'T list) = + + let noFileVersionsHash = + lazy + (projectCore.Version + |> Md5Hasher.addStrings (sourceFiles |> Seq.map (fun x -> x.FileName))) + + let noFileVersionsKey = + lazy + ({ new ICacheKey<_, _> with + member _.GetLabel() = projectCore.Label + member _.GetKey() = projectCore.Identifier + + member _.GetVersion() = + noFileVersionsHash.Value |> Md5Hasher.toString + + }) + + let fullHash = + lazy + (projectCore.Version + |> Md5Hasher.addStrings ( + sourceFiles + |> Seq.collect (fun x -> + seq { + x.FileName + x.Version |> Md5Hasher.toString + }) + )) + + let fullKey = + lazy + ({ new ICacheKey<_, _> with + member _.GetLabel() = projectCore.Label + member _.GetKey() = projectCore.Identifier + member _.GetVersion() = fullHash.Value |> Md5Hasher.toString + }) + + let addHash (file: 'T) hash = + hash |> Md5Hasher.addString file.FileName |> Md5Hasher.addBytes file.Version + + let signatureHash = + lazy (signatureHash projectCore.Version (sourceFiles |> Seq.map (fun x -> x :> IFileSnapshot))) + + let signatureKey = + lazy (projectCore.CacheKeyWith("Signature", signatureHash.Value |> fst |> Md5Hasher.toString)) + + let lastFileHash = + lazy + (let lastFile = sourceFiles |> List.last + let sigHash, f = signatureHash.Value + + (if f = lastFile.FileName then + sigHash + else + sigHash |> Md5Hasher.addBytes lastFile.Version), + lastFile) + + let lastFileKey = + lazy + (let hash, f = lastFileHash.Value + + { new ICacheKey<_, _> with + member _.GetLabel() = $"{f.FileName} ({projectCore.Label})" + member _.GetKey() = f.FileName, projectCore.Identifier + member _.GetVersion() = hash |> Md5Hasher.toString + }) + + let sourceFileNames = lazy (sourceFiles |> List.map (fun x -> x.FileName)) + + member _.ProjectFileName = projectCore.ProjectFileName + member _.ProjectId = projectCore.ProjectId + member _.Identifier = projectCore.Identifier + member _.ReferencesOnDisk = projectCore.ReferencesOnDisk + member _.OtherOptions = projectCore.OtherOptions + member _.ReferencedProjects = projectCore.ReferencedProjects + + member _.IsIncompleteTypeCheckEnvironment = + projectCore.IsIncompleteTypeCheckEnvironment + + member _.UseScriptResolutionRules = projectCore.UseScriptResolutionRules + member _.LoadTime = projectCore.LoadTime + member _.UnresolvedReferences = projectCore.UnresolvedReferences + member _.OriginalLoadReferences = projectCore.OriginalLoadReferences + member _.Stamp = projectCore.Stamp + member _.CommandLineOptions = projectCore.CommandLineOptions + member _.ProjectDirectory = projectCore.ProjectDirectory + + member _.OutputFileName = projectCore.OutputFileName + + member _.ProjectCore = projectCore + + member _.SourceFiles = sourceFiles + + member _.SourceFileNames = sourceFileNames.Value + + member _.Label = projectCore.Label + + member _.IndexOf fileName = + sourceFiles + |> List.tryFindIndex (fun x -> x.FileName = fileName) + |> Option.defaultWith (fun () -> failwith (sprintf "Unable to find file %s in project %s" fileName projectCore.ProjectFileName)) + + member private _.With(sourceFiles: 'T list) = + ProjectSnapshotBase(projectCore, sourceFiles) + + /// Create a new snapshot with given source files replacing files in this snapshot with the same name. Other files remain unchanged. + member this.Replace(changedSourceFiles: 'T list) = + // TODO: validate if changed files are not present in the original list? + + let sourceFiles = + sourceFiles + |> List.map (fun x -> + match changedSourceFiles |> List.tryFind (fun y -> y.FileName = x.FileName) with + | Some y -> y + | None -> x) + + this.With sourceFiles + + /// Create a new snapshot with source files only up to the given index (inclusive) + member this.UpTo fileIndex = this.With sourceFiles[..fileIndex] + + /// Create a new snapshot with source files only up to the given file name (inclusive) + member this.UpTo fileName = this.UpTo(this.IndexOf fileName) + + /// Create a new snapshot with only source files at the given indexes + member this.OnlyWith fileIndexes = + this.With( + fileIndexes + |> Set.toList + |> List.sort + |> List.choose (fun x -> sourceFiles |> List.tryItem x) + ) + + override this.ToString() = + Path.GetFileNameWithoutExtension this.ProjectFileName + |> sprintf "FSharpProjectSnapshot(%s)" + + /// The newest last modified time of any file in this snapshot including the project file + member _.GetLastModifiedTimeOnDisk() = + seq { + projectCore.ProjectFileName + + yield! + sourceFiles + |> Seq.filter (fun x -> not (x.FileName.EndsWith(".AssemblyInfo.fs"))) // TODO: is this safe? any better way of doing this? + |> Seq.filter (fun x -> not (x.FileName.EndsWith(".AssemblyAttributes.fs"))) + |> Seq.map (fun x -> x.FileName) + } + |> Seq.map FileSystem.GetLastWriteTimeShim + |> Seq.max + + member _.FullVersion = fullHash.Value + member _.SignatureVersion = signatureHash.Value |> fst + member _.LastFileVersion = lastFileHash.Value |> fst + + /// Version for parsing - doesn't include any references because they don't affect parsing (...right?) + member _.ParsingVersion = projectCore.VersionForParsing |> Md5Hasher.toString + + /// A key for this snapshot but without file versions. So it will be the same across any in-file changes. + member _.NoFileVersionsKey = noFileVersionsKey.Value + + /// A full key for this snapshot, any change will cause this to change. + member _.FullKey = fullKey.Value + + /// A key including the public surface or signature for this snapshot + member _.SignatureKey = signatureKey.Value + + /// A key including the public surface or signature for this snapshot and the last file (even if it's not a signature file) + member _.LastFileKey = lastFileKey.Value + + //TODO: cache it here? + member this.FileKey(fileName: string) = this.UpTo(fileName).LastFileKey + member this.FileKey(index: FileIndex) = this.UpTo(index).LastFileKey + +/// Project snapshot with filenames and versions given as initial input +and internal ProjectSnapshot = ProjectSnapshotBase + +/// Project snapshot with file sources loaded +and internal ProjectSnapshotWithSources = ProjectSnapshotBase + +/// All required information for compiling a project except the source files. It's kept separate so it can be reused +/// for different stages of a project snapshot and also between changes to the source files. +and internal ProjectCore + ( + ProjectFileName: string, + ProjectId: string option, + ReferencesOnDisk: ReferenceOnDisk list, + OtherOptions: string list, + ReferencedProjects: FSharpReferencedProjectSnapshot list, + IsIncompleteTypeCheckEnvironment: bool, + UseScriptResolutionRules: bool, + LoadTime: DateTime, + UnresolvedReferences: FSharpUnresolvedReferencesSet option, + OriginalLoadReferences: (range * string * string) list, + Stamp: int64 option + ) as self = + + let hashForParsing = + lazy + (Md5Hasher.empty + |> Md5Hasher.addString ProjectFileName + |> Md5Hasher.addStrings OtherOptions + |> Md5Hasher.addBool IsIncompleteTypeCheckEnvironment + |> Md5Hasher.addBool UseScriptResolutionRules) + + let fullHash = + lazy + (hashForParsing.Value + |> Md5Hasher.addStrings (ReferencesOnDisk |> Seq.map (fun r -> r.Path)) + |> Md5Hasher.addDateTimes (ReferencesOnDisk |> Seq.map (fun r -> r.LastModified)) + |> Md5Hasher.addBytes' ( + ReferencedProjects + |> Seq.map (fun (FSharpReference(_name, p)) -> p.ProjectSnapshot.SignatureVersion) + )) + + let fullHashString = lazy (fullHash.Value |> Md5Hasher.toString) + + let commandLineOptions = + lazy + (seq { + for r in ReferencesOnDisk do + $"-r:{r.Path}" + + yield! OtherOptions + } + |> Seq.toList) + + let outputFileName = lazy (OtherOptions |> findOutputFileName) + + let key = lazy (ProjectFileName, outputFileName.Value |> Option.defaultValue "") + + let cacheKey = + lazy + ({ new ICacheKey<_, _> with + member _.GetLabel() = self.Label + member _.GetKey() = self.Identifier + member _.GetVersion() = fullHashString.Value + }) + + member val ProjectDirectory = Path.GetDirectoryName(ProjectFileName) + member _.OutputFileName = outputFileName.Value + member _.Identifier: ProjectIdentifier = key.Value + member _.Version = fullHash.Value + member _.Label = ProjectFileName |> shortPath + member _.VersionForParsing = hashForParsing.Value + + member _.CommandLineOptions = commandLineOptions.Value + + member _.ProjectFileName = ProjectFileName + member _.ProjectId = ProjectId + member _.ReferencesOnDisk = ReferencesOnDisk + member _.OtherOptions = OtherOptions + member _.ReferencedProjects = ReferencedProjects + member _.IsIncompleteTypeCheckEnvironment = IsIncompleteTypeCheckEnvironment + member _.UseScriptResolutionRules = UseScriptResolutionRules + member _.LoadTime = LoadTime + member _.UnresolvedReferences = UnresolvedReferences + member _.OriginalLoadReferences = OriginalLoadReferences + member _.Stamp = Stamp + + member _.CacheKeyWith(label, version) = + { new ICacheKey<_, _> with + member _.GetLabel() = $"{label} ({self.Label})" + member _.GetKey() = self.Identifier + member _.GetVersion() = fullHashString.Value, version + } + + member _.CacheKeyWith(label, key, version) = + { new ICacheKey<_, _> with + member _.GetLabel() = $"{label} ({self.Label})" + member _.GetKey() = key, self.Identifier + member _.GetVersion() = fullHashString.Value, version + } + + member _.CacheKey = cacheKey.Value + +and [] FSharpReferencedProjectSnapshot = + | FSharpReference of projectOutputFile: string * options: FSharpProjectSnapshot + //| PEReference of projectOutputFile: string * getStamp: (unit -> DateTime) * delayedReader: DelayedILModuleReader + //| ILModuleReference of + // projectOutputFile: string * + // getStamp: (unit -> DateTime) * + // getReader: (unit -> ILModuleReader) + + /// + /// The fully qualified path to the output of the referenced project. This should be the same value as the -r + /// reference in the project options for this referenced project. + /// + member this.OutputFile = + match this with + | FSharpReference(projectOutputFile, _) -> projectOutputFile + + /// + /// Creates a reference for an F# project. The physical data for it is stored/cached inside of the compiler service. + /// + /// The fully qualified path to the output of the referenced project. This should be the same value as the -r reference in the project options for this referenced project. + /// The project snapshot for this F# project + static member CreateFSharp(projectOutputFile, snapshot: FSharpProjectSnapshot) = + FSharpReference(projectOutputFile, snapshot) + + override this.Equals(o) = + match o with + | :? FSharpReferencedProjectSnapshot as o -> + match this, o with + | FSharpReference(projectOutputFile1, options1), FSharpReference(projectOutputFile2, options2) -> + projectOutputFile1 = projectOutputFile2 && options1 = options2 + + | _ -> false + + override this.GetHashCode() = this.OutputFile.GetHashCode() + +/// An identifier of an F# project. This serves to identify the same project as it changes over time and enables us to clear obsolete data from caches. +and [] FSharpProjectIdentifier = + | FSharpProjectIdentifier of projectFileName: string * outputFileName: string + +/// A snapshot of an F# project. This type contains all the necessary information for type checking a project. +and [] FSharpProjectSnapshot internal (projectSnapshot) = + + member internal _.ProjectSnapshot: ProjectSnapshot = projectSnapshot + + /// Create a new snapshot with given source files replacing files in this snapshot with the same name. Other files remain unchanged. + member _.Replace(changedSourceFiles: FSharpFileSnapshot list) = + projectSnapshot.Replace(changedSourceFiles) |> FSharpProjectSnapshot + + member _.Label = projectSnapshot.Label + member _.Identifier = FSharpProjectIdentifier projectSnapshot.ProjectCore.Identifier + + static member Create + ( + projectFileName: string, + projectId: string option, + sourceFiles: FSharpFileSnapshot list, + referencesOnDisk: ReferenceOnDisk list, + otherOptions: string list, + referencedProjects: FSharpReferencedProjectSnapshot list, + isIncompleteTypeCheckEnvironment: bool, + useScriptResolutionRules: bool, + loadTime: DateTime, + unresolvedReferences: FSharpUnresolvedReferencesSet option, + originalLoadReferences: (range * string * string) list, + stamp: int64 option + ) = + + let projectCore = + ProjectCore( + projectFileName, + projectId, + referencesOnDisk, + otherOptions, + referencedProjects, + isIncompleteTypeCheckEnvironment, + useScriptResolutionRules, + loadTime, + unresolvedReferences, + originalLoadReferences, + stamp + ) + + ProjectSnapshotBase(projectCore, sourceFiles) |> FSharpProjectSnapshot + + static member FromOptions(options: FSharpProjectOptions, getFileSnapshot, ?snapshotAccumulator) = + let snapshotAccumulator = defaultArg snapshotAccumulator (Dictionary()) + + async { + + // TODO: check if options is a good key here + if not (snapshotAccumulator.ContainsKey options) then + + let! sourceFiles = options.SourceFiles |> Seq.map (getFileSnapshot options) |> Async.Parallel + + let! referencedProjects = + options.ReferencedProjects + |> Seq.choose (function + | FSharpReferencedProject.FSharpReference(outputName, options) -> + Some( + async { + let! snapshot = FSharpProjectSnapshot.FromOptions(options, getFileSnapshot, snapshotAccumulator) + + return FSharpReferencedProjectSnapshot.FSharpReference(outputName, snapshot) + } + ) + // TODO: other types + | _ -> None) + |> Async.Sequential + + let referencesOnDisk, otherOptions = + options.OtherOptions + |> Array.partition (fun x -> x.StartsWith("-r:")) + |> map1Of2 ( + Array.map (fun x -> + let path = x.Substring(3) + + { + Path = path + LastModified = FileSystem.GetLastWriteTimeShim(path) + }) + ) + + let snapshot = + FSharpProjectSnapshot.Create( + projectFileName = options.ProjectFileName, + projectId = options.ProjectId, + sourceFiles = (sourceFiles |> List.ofArray), + referencesOnDisk = (referencesOnDisk |> List.ofArray), + otherOptions = (otherOptions |> List.ofArray), + referencedProjects = (referencedProjects |> List.ofArray), + isIncompleteTypeCheckEnvironment = options.IsIncompleteTypeCheckEnvironment, + useScriptResolutionRules = options.UseScriptResolutionRules, + loadTime = options.LoadTime, + unresolvedReferences = options.UnresolvedReferences, + originalLoadReferences = options.OriginalLoadReferences, + stamp = options.Stamp + ) + + snapshotAccumulator.Add(options, snapshot) + + return snapshotAccumulator[options] + } + + static member internal GetFileSnapshotFromDisk _ fileName = + FSharpFileSnapshot.CreateFromFileSystem fileName |> async.Return + + static member FromOptions(options: FSharpProjectOptions) = + FSharpProjectSnapshot.FromOptions(options, FSharpProjectSnapshot.GetFileSnapshotFromDisk) + + static member FromOptions(options: FSharpProjectOptions, fileName: string, fileVersion: int, sourceText: ISourceText) = + + let getFileSnapshot _ fName = + if fName = fileName then + FSharpFileSnapshot.Create( + fileName, + $"{fileVersion}{sourceText.GetHashCode().ToString()}", + fun () -> Task.FromResult(SourceTextNew.ofISourceText sourceText) + ) + else + FSharpFileSnapshot.CreateFromFileSystem fName + |> async.Return + + FSharpProjectSnapshot.FromOptions(options, getFileSnapshot) + +let rec internal snapshotToOptions (projectSnapshot: ProjectSnapshotBase<_>) = + { + ProjectFileName = projectSnapshot.ProjectFileName + ProjectId = projectSnapshot.ProjectId + SourceFiles = projectSnapshot.SourceFiles |> Seq.map (fun x -> x.FileName) |> Seq.toArray + OtherOptions = projectSnapshot.CommandLineOptions |> List.toArray + ReferencedProjects = + projectSnapshot.ReferencedProjects + |> Seq.map (function + | FSharpReference(name, opts) -> FSharpReferencedProject.FSharpReference(name, opts.ProjectSnapshot |> snapshotToOptions)) + |> Seq.toArray + IsIncompleteTypeCheckEnvironment = projectSnapshot.IsIncompleteTypeCheckEnvironment + UseScriptResolutionRules = projectSnapshot.UseScriptResolutionRules + LoadTime = projectSnapshot.LoadTime + UnresolvedReferences = projectSnapshot.UnresolvedReferences + OriginalLoadReferences = projectSnapshot.OriginalLoadReferences + Stamp = projectSnapshot.Stamp + } + +[] +type internal Extensions = + + [] + static member ToOptions(this: ProjectSnapshot) = this |> snapshotToOptions + + [] + static member ToOptions(this: FSharpProjectSnapshot) = + this.ProjectSnapshot |> snapshotToOptions + + [] + static member GetProjectIdentifier(this: FSharpProjectOptions) : ProjectIdentifier = + this.ProjectFileName, this.OtherOptions |> findOutputFileName |> Option.defaultValue "" diff --git a/src/Compiler/Service/IncrementalBuild.fs b/src/Compiler/Service/IncrementalBuild.fs index d37cd97671a..279de60274f 100644 --- a/src/Compiler/Service/IncrementalBuild.fs +++ b/src/Compiler/Service/IncrementalBuild.fs @@ -485,10 +485,19 @@ type BoundModel private ( syntaxTreeOpt ) - /// Global service state -type FrameworkImportsCacheKey = FrameworkImportsCacheKey of resolvedpath: string list * assemblyName: string * targetFrameworkDirectories: string list * fsharpBinaries: string * langVersion: decimal +type FrameworkImportsCacheKey = + | FrameworkImportsCacheKey of resolvedpath: string list * assemblyName: string * targetFrameworkDirectories: string list * fsharpBinaries: string * langVersion: decimal + + interface ICacheKey with + member this.GetKey() = + this |> function FrameworkImportsCacheKey(assemblyName=a) -> a + member this.GetLabel() = + this |> function FrameworkImportsCacheKey(assemblyName=a) -> a + + member this.GetVersion() = this + /// Represents a cache of 'framework' references that can be shared between multiple incremental builds type FrameworkImportsCache(size) = @@ -593,6 +602,7 @@ module Utilities = /// Constructs the build data (IRawFSharpAssemblyData) representing the assembly when used /// as a cross-assembly reference. Note the assembly has not been generated on disk, so this is /// a virtualized view of the assembly contents as computed by background checking. +[] type RawFSharpAssemblyDataBackedByLanguageService (tcConfig, tcGlobals, generatedCcu: CcuThunk, outfile, topAttrs, assemblyName, ilAssemRef) = let exportRemapping = MakeExportRemapping generatedCcu generatedCcu.Contents diff --git a/src/Compiler/Service/IncrementalBuild.fsi b/src/Compiler/Service/IncrementalBuild.fsi index b4e60d403f0..0dedfb02948 100644 --- a/src/Compiler/Service/IncrementalBuild.fsi +++ b/src/Compiler/Service/IncrementalBuild.fsi @@ -22,6 +22,17 @@ open FSharp.Compiler.TcGlobals open FSharp.Compiler.Text open FSharp.Compiler.TypedTree open FSharp.Compiler.BuildGraph +open Internal.Utilities.Collections + +type internal FrameworkImportsCacheKey = + | FrameworkImportsCacheKey of + resolvedpath: string list * + assemblyName: string * + targetFrameworkDirectories: string list * + fsharpBinaries: string * + langVersion: decimal + + interface ICacheKey /// Lookup the global static cache for building the FrameworkTcImports type internal FrameworkImportsCache = @@ -132,6 +143,20 @@ type internal PartialCheckResults = member TimeStamp: DateTime +[] +type internal RawFSharpAssemblyDataBackedByLanguageService = + new: + tcConfig: TcConfig * + tcGlobals: TcGlobals * + generatedCcu: CcuThunk * + outfile: string * + topAttrs: TopAttribs * + assemblyName: string * + ilAssemRef: FSharp.Compiler.AbstractIL.IL.ILAssemblyRef -> + RawFSharpAssemblyDataBackedByLanguageService + + interface IRawFSharpAssemblyData + /// Manages an incremental build graph for the build of an F# project [] type internal IncrementalBuilder = diff --git a/src/Compiler/Service/ItemKey.fs b/src/Compiler/Service/ItemKey.fs index daf6a28f544..7a904a235ed 100644 --- a/src/Compiler/Service/ItemKey.fs +++ b/src/Compiler/Service/ItemKey.fs @@ -562,7 +562,6 @@ and [] ItemKeyStoreBuilder(tcGlobals: TcGlobals) = // We should consider writing ItemKey for each of these | Item.OtherName _ -> () - | Item.FakeInterfaceCtor _ -> () | Item.CustomOperation _ -> () | Item.CustomBuilder _ -> () | Item.ImplicitOp _ -> () diff --git a/src/Compiler/Service/SemanticClassification.fs b/src/Compiler/Service/SemanticClassification.fs index 3697d781373..6ebbb3c8ae0 100644 --- a/src/Compiler/Service/SemanticClassification.fs +++ b/src/Compiler/Service/SemanticClassification.fs @@ -75,7 +75,7 @@ module TcResolutionsExtensions = && protectAssemblyExplorationNoReraise false false (fun () -> ExistsHeadTypeInEntireHierarchy g amap range0 ty g.tcref_System_IDisposable) - let isDiscard (str: string) = str.StartsWith("_") + let isDiscard (str: string) = str.StartsWithOrdinal("_") let isValRefDisposable g amap (vref: ValRef) = not (isDiscard vref.DisplayName) @@ -287,8 +287,6 @@ module TcResolutionsExtensions = | Item.DelegateCtor _, _, m -> add m SemanticClassificationType.ConstructorForReferenceType - | Item.FakeInterfaceCtor _, _, m -> add m SemanticClassificationType.ConstructorForReferenceType - | Item.MethodGroup(_, minfos, _), _, m -> match minfos with | [] -> add m SemanticClassificationType.Method diff --git a/src/Compiler/Service/ServiceAnalysis.fs b/src/Compiler/Service/ServiceAnalysis.fs index 777a9678769..29df63b1194 100644 --- a/src/Compiler/Service/ServiceAnalysis.fs +++ b/src/Compiler/Service/ServiceAnalysis.fs @@ -2,12 +2,12 @@ namespace FSharp.Compiler.EditorServices +open System open System.Collections.Generic open System.Runtime.CompilerServices open Internal.Utilities.Library open FSharp.Compiler.CodeAnalysis open FSharp.Compiler.Symbols -open FSharp.Compiler.Syntax open FSharp.Compiler.Syntax.PrettyNaming open FSharp.Compiler.Text open FSharp.Compiler.Text.Range @@ -296,12 +296,19 @@ module UnusedOpens = /// Async to allow cancellation. let getUnusedOpens (checkFileResults: FSharpCheckFileResults, getSourceLineStr: int -> string) : Async = async { - let! ct = Async.CancellationToken - let symbolUses = checkFileResults.GetAllUsesOfAllSymbolsInFile(ct) - let symbolUses = filterSymbolUses getSourceLineStr symbolUses - let symbolUses = splitSymbolUses symbolUses - let openStatements = getOpenStatements checkFileResults.OpenDeclarations - return! filterOpenStatements symbolUses openStatements + if checkFileResults.OpenDeclarations.Length = 0 then + return [] + else + let! ct = Async.CancellationToken + let symbolUses = checkFileResults.GetAllUsesOfAllSymbolsInFile(ct) + let symbolUses = filterSymbolUses getSourceLineStr symbolUses + let symbolUses = splitSymbolUses symbolUses + let openStatements = getOpenStatements checkFileResults.OpenDeclarations + + if openStatements.Length = 0 then + return [] + else + return! filterOpenStatements symbolUses openStatements } module SimplifyNames = @@ -332,7 +339,10 @@ module SimplifyNames = - partialName.PartialIdent.Length - (getPlidLength partialName.QualifyingIdents) - if partialName.PartialIdent = "" || List.isEmpty partialName.QualifyingIdents then + if + String.IsNullOrEmpty(partialName.PartialIdent) + || List.isEmpty partialName.QualifyingIdents + then None else Some(symbolUse, partialName.QualifyingIdents, plidStartCol, partialName.PartialIdent)) @@ -435,7 +445,7 @@ module UnusedDeclarations = su.IsFromDefinition && su.Symbol.DeclarationLocation.IsSome && (isScript || su.IsPrivateToFile) - && not (su.Symbol.DisplayName.StartsWith "_") + && not (su.Symbol.DisplayName.StartsWithOrdinal "_") && isPotentiallyUnusedDeclaration su.Symbol then Some(su, usages.Contains su.Symbol.DeclarationLocation.Value) @@ -452,1273 +462,3 @@ module UnusedDeclarations = let unusedRanges = getUnusedDeclarationRanges allSymbolUsesInFile isScriptFile return unusedRanges } - -module UnnecessaryParentheses = - open System - - let (|Ident|) (ident: Ident) = ident.idText - - /// Represents an expression's precedence, or, - /// for a few few types of expression whose exact - /// kind can be significant, the expression's exact kind. - /// - /// Use Precedence.sameKind to determine whether two expressions - /// have the same kind. Use Precedence.compare to compare two - /// expressions' precedence. Avoid using relational operators or the - /// built-in compare function on this type. - type Precedence = - /// yield, yield!, return, return! - | Low - - /// <- - | Set - - /// := - | ColonEquals - - /// , - | Comma - - /// or, || - /// - /// Refers to the exact operators or and ||. - /// Instances with leading dots or question marks or trailing characters are parsed as Bar instead. - | BarBar - - /// &, && - /// - /// Refers to the exact operators & and &&. - /// Instances with leading dots or question marks or trailing characters are parsed as Amp instead. - | AmpAmp - - /// :?> - | Downcast - - /// :> - | Upcast - - /// =… - | Eq - - /// |… - | Bar - - /// &… - | Amp - - /// $… - | Dollar - - /// >… - | Greater - - /// <… - | Less - - /// !=… - | BangEq - - /// ^… - | Hat - - /// @… - | At - - /// :: - | Cons - - /// :? - | TypeTest - - /// -… - | Sub - - /// +… - | Add - - /// %… - | Mod - - /// /… - | Div - - /// *… - | Mul - - /// **… - | Exp - - /// - x - | UnaryPrefix - - /// f x - | Apply - - /// -x, !… x, ~~… x - | High - - // x.y - | Dot - - module Precedence = - /// Returns true only if the two expressions are of the - /// exact same kind. E.g., Add = Add and Sub = Sub, - /// but Add <> Sub, even though their precedence compares equally. - let sameKind prec1 prec2 = prec1 = prec2 - - /// Compares two expressions' precedence. - let compare prec1 prec2 = - match prec1, prec2 with - | Dot, Dot -> 0 - | Dot, _ -> 1 - | _, Dot -> -1 - - | High, High -> 0 - | High, _ -> 1 - | _, High -> -1 - - | Apply, Apply -> 0 - | Apply, _ -> 1 - | _, Apply -> -1 - - | UnaryPrefix, UnaryPrefix -> 0 - | UnaryPrefix, _ -> 1 - | _, UnaryPrefix -> -1 - - | Exp, Exp -> 0 - | Exp, _ -> 1 - | _, Exp -> -1 - - | (Mod | Div | Mul), (Mod | Div | Mul) -> 0 - | (Mod | Div | Mul), _ -> 1 - | _, (Mod | Div | Mul) -> -1 - - | (Sub | Add), (Sub | Add) -> 0 - | (Sub | Add), _ -> 1 - | _, (Sub | Add) -> -1 - - | TypeTest, TypeTest -> 0 - | TypeTest, _ -> 1 - | _, TypeTest -> -1 - - | Cons, Cons -> 0 - | Cons, _ -> 1 - | _, Cons -> -1 - - | (Hat | At), (Hat | At) -> 0 - | (Hat | At), _ -> 1 - | _, (Hat | At) -> -1 - - | (Eq | Bar | Amp | Dollar | Greater | Less | BangEq), (Eq | Bar | Amp | Dollar | Greater | Less | BangEq) -> 0 - | (Eq | Bar | Amp | Dollar | Greater | Less | BangEq), _ -> 1 - | _, (Eq | Bar | Amp | Dollar | Greater | Less | BangEq) -> -1 - - | (Downcast | Upcast), (Downcast | Upcast) -> 0 - | (Downcast | Upcast), _ -> 1 - | _, (Downcast | Upcast) -> -1 - - | AmpAmp, AmpAmp -> 0 - | AmpAmp, _ -> 1 - | _, AmpAmp -> -1 - - | BarBar, BarBar -> 0 - | BarBar, _ -> 1 - | _, BarBar -> -1 - - | Comma, Comma -> 0 - | Comma, _ -> 1 - | _, Comma -> -1 - - | ColonEquals, ColonEquals -> 0 - | ColonEquals, _ -> 1 - | _, ColonEquals -> -1 - - | Set, Set -> 0 - | Set, _ -> 1 - | _, Set -> -1 - - | Low, Low -> 0 - - /// Associativity/association. - type Assoc = - /// Non-associative or no association. - | Non - - /// Left-associative or left-hand association. - | Left - - /// Right-associative or right-hand association. - | Right - - module Assoc = - let ofPrecedence precedence = - match precedence with - | Low -> Non - | Set -> Non - | ColonEquals -> Right - | Comma -> Non - | BarBar -> Left - | AmpAmp -> Left - | Upcast - | Downcast -> Right - | Eq - | Bar - | Amp - | Dollar - | Greater - | Less - | BangEq -> Left - | At - | Hat -> Right - | Cons -> Right - | TypeTest -> Non - | Add - | Sub -> Left - | Mul - | Div - | Mod -> Left - | Exp -> Right - | UnaryPrefix -> Left - | Apply -> Left - | High -> Left - | Dot -> Left - - /// Matches if the two expressions or patterns refer to the same object. - [] - let inline (|Is|_|) (inner1: 'a) (inner2: 'a) = - if obj.ReferenceEquals(inner1, inner2) then - ValueSome Is - else - ValueNone - - module SynExpr = - open FSharp.Compiler.SyntaxTrivia - - /// See atomicExprAfterType in pars.fsy. - [] - let (|AtomicExprAfterType|_|) expr = - match expr with - | SynExpr.Paren _ - | SynExpr.Quote _ - | SynExpr.Const _ - | SynExpr.Tuple(isStruct = true) - | SynExpr.Record _ - | SynExpr.AnonRecd _ - | SynExpr.InterpolatedString _ - | SynExpr.Null _ - | SynExpr.ArrayOrList(isArray = true) - | SynExpr.ArrayOrListComputed(isArray = true) -> ValueSome AtomicExprAfterType - | _ -> ValueNone - - /// Matches if the given expression represents a high-precedence - /// function application, e.g., - /// - /// f x - /// - /// (+) x y - [] - let (|HighPrecedenceApp|_|) expr = - match expr with - | SynExpr.App(isInfix = false; funcExpr = SynExpr.Ident _) - | SynExpr.App(isInfix = false; funcExpr = SynExpr.LongIdent _) - | SynExpr.App(isInfix = false; funcExpr = SynExpr.App(isInfix = false)) -> ValueSome HighPrecedenceApp - | _ -> ValueNone - - module FuncExpr = - /// Matches when the given funcExpr is a direct application - /// of a symbolic operator, e.g., -, _not_ (~-). - [] - let (|SymbolicOperator|_|) funcExpr = - match funcExpr with - | SynExpr.LongIdent(longDotId = SynLongIdent(trivia = trivia)) -> - let rec tryPick = - function - | [] -> ValueNone - | Some(IdentTrivia.OriginalNotation op) :: _ -> ValueSome op - | _ :: rest -> tryPick rest - - tryPick trivia - | _ -> ValueNone - - /// Matches when the given expression is a prefix operator application, e.g., - /// - /// -x - /// - /// ~~~x - [] - let (|PrefixApp|_|) expr : Precedence voption = - match expr with - | SynExpr.App(isInfix = false; funcExpr = funcExpr & FuncExpr.SymbolicOperator op; argExpr = argExpr) -> - if funcExpr.Range.IsAdjacentTo argExpr.Range then - ValueSome High - else - assert (op.Length > 0) - - match op[0] with - | '!' - | '~' -> ValueSome High - | _ -> ValueSome UnaryPrefix - - | SynExpr.AddressOf(expr = expr; opRange = opRange) -> - if opRange.IsAdjacentTo expr.Range then - ValueSome High - else - ValueSome UnaryPrefix - - | _ -> ValueNone - - /// Tries to parse the given original notation as a symbolic infix operator. - [] - let (|SymbolPrec|_|) (originalNotation: string) = - // Trim any leading dots or question marks from the given symbolic operator. - // Leading dots or question marks have no effect on operator precedence or associativity - // with the exception of &, &&, and ||. - let ignoredLeadingChars = ".?".AsSpan() - let trimmed = originalNotation.AsSpan().TrimStart ignoredLeadingChars - assert (trimmed.Length > 0) - - match trimmed[0], originalNotation with - | _, ":=" -> ValueSome ColonEquals - | _, ("||" | "or") -> ValueSome BarBar - | _, ("&" | "&&") -> ValueSome AmpAmp - | '|', _ -> ValueSome Bar - | '&', _ -> ValueSome Amp - | '<', _ -> ValueSome Less - | '>', _ -> ValueSome Greater - | '=', _ -> ValueSome Eq - | '$', _ -> ValueSome Dollar - | '!', _ when trimmed.Length > 1 && trimmed[1] = '=' -> ValueSome BangEq - | '^', _ -> ValueSome Hat - | '@', _ -> ValueSome At - | _, "::" -> ValueSome Cons - | '+', _ -> ValueSome Add - | '-', _ -> ValueSome Sub - | '/', _ -> ValueSome Div - | '%', _ -> ValueSome Mod - | '*', _ when trimmed.Length > 1 && trimmed[1] = '*' -> ValueSome Exp - | '*', _ -> ValueSome Mul - | _ -> ValueNone - - /// Any expressions in which the removal of parens would - /// lead to something like the following that would be - /// confused by the parser with a type parameter application: - /// - /// xz - /// - /// xz - [] - let rec (|ConfusableWithTypeApp|_|) synExpr = - match synExpr with - | SynExpr.Paren(expr = ConfusableWithTypeApp) - | SynExpr.App(funcExpr = ConfusableWithTypeApp) - | SynExpr.App(isInfix = true; funcExpr = FuncExpr.SymbolicOperator(SymbolPrec Greater); argExpr = ConfusableWithTypeApp) -> - ValueSome ConfusableWithTypeApp - | SynExpr.App(isInfix = true; funcExpr = funcExpr & FuncExpr.SymbolicOperator(SymbolPrec Less); argExpr = argExpr) when - argExpr.Range.IsAdjacentTo funcExpr.Range - -> - ValueSome ConfusableWithTypeApp - | SynExpr.Tuple(exprs = exprs) -> - let rec anyButLast = - function - | _ :: [] - | [] -> ValueNone - | ConfusableWithTypeApp :: _ -> ValueSome ConfusableWithTypeApp - | _ :: tail -> anyButLast tail - - anyButLast exprs - | _ -> ValueNone - - /// Matches when the expression represents the infix application of a symbolic operator. - /// - /// (x λ y) ρ z - /// - /// x λ (y ρ z) - [] - let (|InfixApp|_|) synExpr : struct (Precedence * Assoc) voption = - match synExpr with - | SynExpr.App(funcExpr = SynExpr.App(isInfix = true; funcExpr = FuncExpr.SymbolicOperator(SymbolPrec prec))) -> - ValueSome(prec, Right) - | SynExpr.App(isInfix = true; funcExpr = FuncExpr.SymbolicOperator(SymbolPrec prec)) -> ValueSome(prec, Left) - | SynExpr.Upcast _ -> ValueSome(Upcast, Left) - | SynExpr.Downcast _ -> ValueSome(Downcast, Left) - | SynExpr.TypeTest _ -> ValueSome(TypeTest, Left) - | _ -> ValueNone - - /// Returns the given expression's precedence and the side of the inner expression, - /// if applicable. - [] - let (|OuterBinaryExpr|_|) inner outer : struct (Precedence * Assoc) voption = - match outer with - | SynExpr.YieldOrReturn _ - | SynExpr.YieldOrReturnFrom _ -> ValueSome(Low, Right) - | SynExpr.Tuple(exprs = SynExpr.Paren(expr = Is inner) :: _) -> ValueSome(Comma, Left) - | SynExpr.Tuple _ -> ValueSome(Comma, Right) - | InfixApp(Cons, side) -> ValueSome(Cons, side) - | SynExpr.Assert _ - | SynExpr.Lazy _ - | SynExpr.InferredUpcast _ - | SynExpr.InferredDowncast _ -> ValueSome(Apply, Non) - | PrefixApp prec -> ValueSome(prec, Non) - | InfixApp(prec, side) -> ValueSome(prec, side) - | SynExpr.App(argExpr = SynExpr.ComputationExpr _) -> ValueSome(UnaryPrefix, Left) - | SynExpr.App(funcExpr = SynExpr.Paren(expr = SynExpr.App _)) -> ValueSome(Apply, Left) - | SynExpr.App _ -> ValueSome(Apply, Non) - | SynExpr.DotSet(targetExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left) - | SynExpr.DotSet(rhsExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right) - | SynExpr.DotIndexedSet(objectExpr = SynExpr.Paren(expr = Is inner)) - | SynExpr.DotNamedIndexedPropertySet(targetExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left) - | SynExpr.DotIndexedSet(valueExpr = SynExpr.Paren(expr = Is inner)) - | SynExpr.DotNamedIndexedPropertySet(rhsExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right) - | SynExpr.LongIdentSet(expr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right) - | SynExpr.Set _ -> ValueSome(Set, Non) - | SynExpr.DotGet _ -> ValueSome(Dot, Left) - | SynExpr.DotIndexedGet(objectExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left) - | _ -> ValueNone - - /// Matches a SynExpr.App nested in a sequence of dot-gets. - /// - /// x.M.N().O - [] - let (|NestedApp|_|) expr = - let rec loop = - function - | SynExpr.DotGet(expr = expr) - | SynExpr.DotIndexedGet(objectExpr = expr) -> loop expr - | SynExpr.App _ -> ValueSome NestedApp - | _ -> ValueNone - - loop expr - - /// Returns the given expression's precedence, if applicable. - [] - let (|InnerBinaryExpr|_|) expr : Precedence voption = - match expr with - | SynExpr.Tuple(isStruct = false) -> ValueSome Comma - | SynExpr.DotGet(expr = NestedApp) - | SynExpr.DotIndexedGet(objectExpr = NestedApp) -> ValueSome Apply - | SynExpr.DotGet _ - | SynExpr.DotIndexedGet _ -> ValueSome Dot - | PrefixApp prec -> ValueSome prec - | InfixApp(prec, _) -> ValueSome prec - | SynExpr.App _ - | SynExpr.Assert _ - | SynExpr.Lazy _ - | SynExpr.For _ - | SynExpr.ForEach _ - | SynExpr.While _ - | SynExpr.Do _ - | SynExpr.New _ - | SynExpr.InferredUpcast _ - | SynExpr.InferredDowncast _ -> ValueSome Apply - | SynExpr.DotIndexedSet _ - | SynExpr.DotNamedIndexedPropertySet _ - | SynExpr.DotSet _ -> ValueSome Set - | _ -> ValueNone - - module Dangling = - /// Returns the first matching nested right-hand target expression, if any. - let private dangling (target: SynExpr -> SynExpr option) = - let (|Target|_|) = target - let (|Last|) = List.last - - let rec loop expr = - match expr with - | Target expr -> ValueSome expr - | SynExpr.Tuple(isStruct = false; exprs = Last expr) - | SynExpr.App(argExpr = expr) - | SynExpr.IfThenElse(elseExpr = Some expr) - | SynExpr.IfThenElse(ifExpr = expr) - | SynExpr.Sequential(expr2 = expr) - | SynExpr.YieldOrReturn(expr = expr) - | SynExpr.YieldOrReturnFrom(expr = expr) - | SynExpr.Set(rhsExpr = expr) - | SynExpr.DotSet(rhsExpr = expr) - | SynExpr.DotNamedIndexedPropertySet(rhsExpr = expr) - | SynExpr.DotIndexedSet(valueExpr = expr) - | SynExpr.LongIdentSet(expr = expr) - | SynExpr.LetOrUse(body = expr) - | SynExpr.Lambda(body = expr) - | SynExpr.Match(clauses = Last(SynMatchClause(resultExpr = expr))) - | SynExpr.MatchLambda(matchClauses = Last(SynMatchClause(resultExpr = expr))) - | SynExpr.MatchBang(clauses = Last(SynMatchClause(resultExpr = expr))) - | SynExpr.TryWith(withCases = Last(SynMatchClause(resultExpr = expr))) - | SynExpr.TryFinally(finallyExpr = expr) -> loop expr - | _ -> ValueNone - - loop - - /// Matches a dangling if-then construct. - [] - let (|IfThen|_|) = - dangling (function - | SynExpr.IfThenElse _ as expr -> Some expr - | _ -> None) - - /// Matches a dangling sequential expression. - [] - let (|Sequential|_|) = - dangling (function - | SynExpr.Sequential _ as expr -> Some expr - | _ -> None) - - /// Matches a dangling try-with or try-finally construct. - [] - let (|Try|_|) = - dangling (function - | SynExpr.TryWith _ - | SynExpr.TryFinally _ as expr -> Some expr - | _ -> None) - - /// Matches a dangling match-like construct. - [] - let (|Match|_|) = - dangling (function - | SynExpr.Match _ - | SynExpr.MatchBang _ - | SynExpr.MatchLambda _ - | SynExpr.TryWith _ - | SynExpr.Lambda _ as expr -> Some expr - | _ -> None) - - /// Matches a nested dangling construct that could become problematic - /// if the surrounding parens were removed. - [] - let (|Problematic|_|) = - dangling (function - | SynExpr.Lambda _ - | SynExpr.MatchLambda _ - | SynExpr.Match _ - | SynExpr.MatchBang _ - | SynExpr.TryWith _ - | SynExpr.TryFinally _ - | SynExpr.IfThenElse _ - | SynExpr.Sequential _ - | SynExpr.LetOrUse _ - | SynExpr.Set _ - | SynExpr.LongIdentSet _ - | SynExpr.DotIndexedSet _ - | SynExpr.DotNamedIndexedPropertySet _ - | SynExpr.DotSet _ - | SynExpr.NamedIndexedPropertySet _ as expr -> Some expr - | _ -> None) - - /// If the given expression is a parenthesized expression and the parentheses - /// are unnecessary in the given context, returns the unnecessary parentheses' range. - let rec unnecessaryParentheses (getSourceLineStr: int -> string) expr path = - let unnecessaryParentheses = unnecessaryParentheses getSourceLineStr - - // Indicates whether the parentheses with the given range - // enclose an expression whose indentation would be invalid - // in context if it were not surrounded by parentheses. - let containsSensitiveIndentation outerOffsides (parenRange: range) = - let startLine = parenRange.StartLine - let endLine = parenRange.EndLine - - if startLine = endLine then - false - else - let rec loop offsides lineNo startCol = - if lineNo <= endLine then - let line = getSourceLineStr lineNo - - match offsides with - | ValueNone -> - let i = line.AsSpan(startCol).IndexOfAnyExcept(' ', ')') - - if i >= 0 then - let newOffsides = i + startCol - newOffsides <= outerOffsides || loop (ValueSome newOffsides) (lineNo + 1) 0 - else - loop offsides (lineNo + 1) 0 - - | ValueSome offsidesCol -> - let i = line.AsSpan(0, min offsidesCol line.Length).IndexOfAnyExcept(' ', ')') - - if i >= 0 && i < offsidesCol then - let slice = line.AsSpan(i, min (offsidesCol - i) (line.Length - i)) - let j = slice.IndexOfAnyExcept("*/%-+:^@><=!|0$.?".AsSpan()) - - let lo = i + (if j >= 0 && slice[j] = ' ' then j else 0) - lo < offsidesCol - 1 || lo <= outerOffsides || loop offsides (lineNo + 1) 0 - else - loop offsides (lineNo + 1) 0 - else - false - - loop ValueNone startLine (parenRange.StartColumn + 1) - - // Matches if the given expression starts with a symbol, e.g., <@ … @>, $"…", @"…", +1, -1… - let (|StartsWithSymbol|_|) = - let (|TextStartsWith|) (m: range) = - let line = getSourceLineStr m.StartLine - line[m.StartColumn] - - let (|StartsWith|) (s: string) = s[0] - - function - | SynExpr.Quote _ - | SynExpr.InterpolatedString _ - | SynExpr.Const(SynConst.String(synStringKind = SynStringKind.Verbatim), _) - | SynExpr.Const(SynConst.Byte _, TextStartsWith '+') - | SynExpr.Const(SynConst.UInt16 _, TextStartsWith '+') - | SynExpr.Const(SynConst.UInt32 _, TextStartsWith '+') - | SynExpr.Const(SynConst.UInt64 _, TextStartsWith '+') - | SynExpr.Const(SynConst.UIntPtr _, TextStartsWith '+') - | SynExpr.Const(SynConst.SByte _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.Int16 _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.Int32 _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.Int64 _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.IntPtr _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.Decimal _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.Double _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.Single _, TextStartsWith('-' | '+')) - | SynExpr.Const(SynConst.Measure(_, TextStartsWith('-' | '+'), _, _), _) - | SynExpr.Const(SynConst.UserNum(StartsWith('-' | '+'), _), _) -> Some StartsWithSymbol - | _ -> None - - // Matches if the given expression is a numeric literal - // that it is safe to "dot into," e.g., 1l, 0b1, 1e10, 1d, 1.0… - let (|DotSafeNumericLiteral|_|) = - /// 1l, 1d, 0b1, 0x1, 0o1, 1e10… - let (|TextContainsLetter|_|) (m: range) = - let line = getSourceLineStr m.StartLine - let span = line.AsSpan(m.StartColumn, m.EndColumn - m.StartColumn) - - if span.LastIndexOfAnyInRange('A', 'z') >= 0 then - Some TextContainsLetter - else - None - - // 1.0… - let (|TextEndsWithNumber|_|) (m: range) = - let line = getSourceLineStr m.StartLine - let span = line.AsSpan(m.StartColumn, m.EndColumn - m.StartColumn) - - if Char.IsDigit span[span.Length - 1] then - Some TextEndsWithNumber - else - None - - function - | SynExpr.Const(SynConst.Byte _, _) - | SynExpr.Const(SynConst.UInt16 _, _) - | SynExpr.Const(SynConst.UInt32 _, _) - | SynExpr.Const(SynConst.UInt64 _, _) - | SynExpr.Const(SynConst.UIntPtr _, _) - | SynExpr.Const(SynConst.SByte _, _) - | SynExpr.Const(SynConst.Int16 _, _) - | SynExpr.Const(SynConst.Int32 _, TextContainsLetter) - | SynExpr.Const(SynConst.Int64 _, _) - | SynExpr.Const(SynConst.IntPtr _, _) - | SynExpr.Const(SynConst.Decimal _, _) - | SynExpr.Const(SynConst.Double _, (TextEndsWithNumber | TextContainsLetter)) - | SynExpr.Const(SynConst.Single _, _) - | SynExpr.Const(SynConst.Measure _, _) - | SynExpr.Const(SynConst.UserNum _, _) -> Some DotSafeNumericLiteral - | _ -> None - - match expr, path with - // Check for nested matches, e.g., - // - // match … with … -> (…, match … with … -> … | … -> …) | … -> … - | SynExpr.Paren _, SyntaxNode.SynMatchClause _ :: path -> unnecessaryParentheses expr path - - // We always need parens for trait calls, e.g., - // - // let inline f x = (^a : (static member Parse : string -> ^a) x) - | SynExpr.Paren(expr = SynExpr.TraitCall _), _ -> ValueNone - - // Don't touch library-only stuff: - // - // (# "ldlen.multi 2 0" array : int #) - | SynExpr.Paren(expr = SynExpr.LibraryOnlyILAssembly _), _ - | SynExpr.Paren(expr = SynExpr.LibraryOnlyStaticOptimization _), _ - | SynExpr.Paren(expr = SynExpr.LibraryOnlyUnionCaseFieldGet _), _ - | SynExpr.Paren(expr = SynExpr.LibraryOnlyUnionCaseFieldSet _), _ -> ValueNone - - // Parens are required around the body expresion of a binding - // if the parenthesized expression would be invalid without its parentheses, e.g., - // - // let x = (x - // + y) - | SynExpr.Paren(rightParenRange = Some _; range = parenRange), - SyntaxNode.SynBinding(SynBinding(trivia = { LeadingKeyword = leadingKeyword })) :: _ when - containsSensitiveIndentation leadingKeyword.Range.StartColumn parenRange - -> - ValueNone - - // Parens are otherwise never required for binding bodies or for top-level expressions, e.g., - // - // let x = (…) - // _.member X = (…) - // (printfn "Hello, world.") - | SynExpr.Paren(rightParenRange = Some _; range = range), SyntaxNode.SynBinding _ :: _ - | SynExpr.Paren(rightParenRange = Some _; range = range), SyntaxNode.SynModule _ :: _ -> ValueSome range - - // Parens must be kept when there is a high-precedence function application - // before a prefix operator application before another expression that starts with a symbol, e.g., - // - // id -(-x) - // id -(-1y) - // id -($"") - // id -(@"") - // id -(<@ ValueNone @>) - // let (~+) _ = true in assert +($"{true}") - | SynExpr.Paren(expr = PrefixApp _ | StartsWithSymbol), - SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(HighPrecedenceApp | SynExpr.Assert _ | SynExpr.InferredUpcast _ | SynExpr.InferredDowncast _) :: _ -> - ValueNone - - // Parens are never required around suffixed or infixed numeric literals, e.g., - // - // (1l).ToString() - // (1uy).ToString() - // (0b1).ToString() - // (1e10).ToString() - // (1.0).ToString() - | SynExpr.Paren(expr = DotSafeNumericLiteral; rightParenRange = Some _; range = range), _ -> ValueSome range - - // Parens are required around bare decimal ints or doubles ending - // in dots when being dotted into, e.g., - // - // (1).ToString() - // (1.).ToString() - | SynExpr.Paren(expr = SynExpr.Const(constant = SynConst.Int32 _ | SynConst.Double _)), - SyntaxNode.SynExpr(SynExpr.DotGet _) :: _ -> ValueNone - - // Parens are required around join conditions: - // - // join … on (… = …) - | SynExpr.Paren(expr = SynExpr.App _), SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(SynExpr.JoinIn _) :: _ -> - ValueNone - - // Parens are not required around a few anointed expressions after inherit: - // - // inherit T(3) - // inherit T(null) - // inherit T("") - // … - | SynExpr.Paren(expr = AtomicExprAfterType; range = range), SyntaxNode.SynMemberDefn(SynMemberDefn.ImplicitInherit _) :: _ -> - ValueSome range - - // Parens are otherwise required in inherit T(x), etc. - | SynExpr.Paren _, SyntaxNode.SynMemberDefn(SynMemberDefn.ImplicitInherit _) :: _ -> ValueNone - - // We can't remove parens when they're required for fluent calls: - // - // x.M(y).N z - // x.M(y).[z] - // (f x)[z] - // (f(x))[z] - // x.M(y)[z] - | SynExpr.Paren _, SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(SynExpr.DotGet _ | SynExpr.DotIndexedGet _) :: _ - | SynExpr.Paren(expr = SynExpr.App _), - SyntaxNode.SynExpr(SynExpr.App(argExpr = SynExpr.ArrayOrListComputed(isArray = false))) :: _ - | SynExpr.Paren _, - SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(SynExpr.App(argExpr = SynExpr.ArrayOrListComputed(isArray = false))) :: _ -> - ValueNone - - // Parens must stay around binary equals expressions in argument - // position lest they be interpreted as named argument assignments: - // - // o.M((x = y)) - // o.N((x = y), z) - | SynExpr.Paren(expr = SynExpr.Paren(expr = InfixApp(Eq, _))), - SyntaxNode.SynExpr(SynExpr.App(funcExpr = SynExpr.LongIdent _)) :: _ - | SynExpr.Paren(expr = InfixApp(Eq, _)), - SyntaxNode.SynExpr(SynExpr.Paren _) :: SyntaxNode.SynExpr(SynExpr.App(funcExpr = SynExpr.LongIdent _)) :: _ - | SynExpr.Paren(expr = InfixApp(Eq, _)), - SyntaxNode.SynExpr(SynExpr.Tuple(isStruct = false)) :: SyntaxNode.SynExpr(SynExpr.Paren _) :: SyntaxNode.SynExpr(SynExpr.App( - funcExpr = SynExpr.LongIdent _)) :: _ -> ValueNone - - // The :: operator is parsed differently from other symbolic infix operators, - // so we need to give it special treatment. - - // Outer right: - // - // (x) :: xs - // (x * y) :: zs - // … - | SynExpr.Paren(rightParenRange = Some _), - SyntaxNode.SynExpr(SynExpr.Tuple(isStruct = false; exprs = [ SynExpr.Paren _; _ ])) :: (SyntaxNode.SynExpr(SynExpr.App( - isInfix = true)) :: _ as path) -> unnecessaryParentheses expr path - - // Outer left: - // - // x :: (xs) - // x :: (ys @ zs) - // … - | SynExpr.Paren(rightParenRange = Some _) as argExpr, - SyntaxNode.SynExpr(SynExpr.Tuple(isStruct = false; exprs = [ _; SynExpr.Paren _ ])) :: SyntaxNode.SynExpr(SynExpr.App( - isInfix = true) as outer) :: path -> - unnecessaryParentheses - expr - (SyntaxNode.SynExpr(SynExpr.App(ExprAtomicFlag.NonAtomic, false, outer, argExpr, outer.Range)) - :: path) - - // Ordinary nested expressions. - | SynExpr.Paren(expr = inner; leftParenRange = leftParenRange; rightParenRange = Some _ as rightParenRange; range = range), - SyntaxNode.SynExpr outer :: outerPath when not (containsSensitiveIndentation outer.Range.StartColumn range) -> - let dangling expr = - match expr with - | Dangling.Problematic subExpr -> - let parenzedSubExpr = SynExpr.Paren(subExpr, leftParenRange, rightParenRange, range) - - match outer with - | SynExpr.Tuple(exprs = exprs) -> not (obj.ReferenceEquals(subExpr, List.last exprs)) - | InfixApp(_, Left) -> true - | _ -> unnecessaryParentheses parenzedSubExpr outerPath |> ValueOption.isNone - - | _ -> false - - let problematic (exprRange: range) (delimiterRange: range) = - exprRange.EndLine = delimiterRange.EndLine - && exprRange.EndColumn < delimiterRange.StartColumn - - let anyProblematic matchOrTryRange clauses = - let rec loop = - function - | [] -> false - | SynMatchClause(trivia = trivia) :: clauses -> - trivia.BarRange |> Option.exists (problematic matchOrTryRange) - || trivia.ArrowRange |> Option.exists (problematic matchOrTryRange) - || loop clauses - - loop clauses - - match outer, inner with - | ConfusableWithTypeApp, _ -> ValueNone - - | SynExpr.IfThenElse _, Dangling.Sequential _ -> ValueNone - - | SynExpr.IfThenElse(trivia = trivia), Dangling.IfThen ifThenElse when - problematic ifThenElse.Range trivia.ThenKeyword - || trivia.ElseKeyword |> Option.exists (problematic ifThenElse.Range) - -> - ValueNone - - | SynExpr.TryFinally(trivia = trivia), Dangling.Try tryExpr when problematic tryExpr.Range trivia.FinallyKeyword -> - ValueNone - - | SynExpr.Match(clauses = clauses; trivia = { WithKeyword = withKeyword }), Dangling.Match matchOrTry when - problematic matchOrTry.Range withKeyword - || anyProblematic matchOrTry.Range clauses - -> - ValueNone - - | SynExpr.MatchBang(clauses = clauses; trivia = { WithKeyword = withKeyword }), Dangling.Match matchOrTry when - problematic matchOrTry.Range withKeyword - || anyProblematic matchOrTry.Range clauses - -> - ValueNone - - | SynExpr.MatchLambda(matchClauses = clauses), Dangling.Match matchOrTry when anyProblematic matchOrTry.Range clauses -> - ValueNone - - | SynExpr.TryWith(withCases = clauses; trivia = trivia), Dangling.Match matchOrTry when - problematic matchOrTry.Range trivia.WithKeyword - || anyProblematic matchOrTry.Range clauses - -> - ValueNone - - | SynExpr.Sequential(expr1 = SynExpr.Paren(expr = Is inner); expr2 = expr2), Dangling.Problematic _ when - problematic inner.Range expr2.Range - -> - ValueNone - - | SynExpr.Record(copyInfo = Some(SynExpr.Paren(expr = Is inner), _)), Dangling.Problematic _ - | SynExpr.AnonRecd(copyInfo = Some(SynExpr.Paren(expr = Is inner), _)), Dangling.Problematic _ -> ValueNone - - | SynExpr.Record(recordFields = recordFields), Dangling.Problematic _ -> - let rec loop recordFields = - match recordFields with - | [] -> ValueSome range - | SynExprRecordField(expr = Some(SynExpr.Paren(expr = Is inner)); blockSeparator = Some _) :: SynExprRecordField( - fieldName = SynLongIdent(id = id :: _), _) :: _ -> - if problematic inner.Range id.idRange then - ValueNone - else - ValueSome range - | _ :: recordFields -> loop recordFields - - loop recordFields - - | SynExpr.AnonRecd(recordFields = recordFields), Dangling.Problematic _ -> - let rec loop recordFields = - match recordFields with - | [] -> ValueSome range - | (_, Some _blockSeparator, SynExpr.Paren(expr = Is inner)) :: (SynLongIdent(id = id :: _), _, _) :: _ -> - if problematic inner.Range id.idRange then - ValueNone - else - ValueSome range - | _ :: recordFields -> loop recordFields - - loop recordFields - - | SynExpr.Paren _, SynExpr.Typed _ - | SynExpr.Quote _, SynExpr.Typed _ - | SynExpr.AnonRecd _, SynExpr.Typed _ - | SynExpr.Record _, SynExpr.Typed _ - | SynExpr.While(doExpr = SynExpr.Paren(expr = Is inner)), SynExpr.Typed _ - | SynExpr.WhileBang(doExpr = SynExpr.Paren(expr = Is inner)), SynExpr.Typed _ - | SynExpr.For(doBody = Is inner), SynExpr.Typed _ - | SynExpr.ForEach(bodyExpr = Is inner), SynExpr.Typed _ - | SynExpr.Match _, SynExpr.Typed _ - | SynExpr.Do _, SynExpr.Typed _ - | SynExpr.LetOrUse(body = Is inner), SynExpr.Typed _ - | SynExpr.TryWith _, SynExpr.Typed _ - | SynExpr.TryFinally _, SynExpr.Typed _ -> ValueSome range - | _, SynExpr.Typed _ -> ValueNone - - | OuterBinaryExpr inner (outerPrecedence, side), InnerBinaryExpr innerPrecedence -> - let ambiguous = - match Precedence.compare outerPrecedence innerPrecedence with - | 0 -> - match side, Assoc.ofPrecedence innerPrecedence with - | Non, _ - | _, Non - | Left, Right -> true - | Right, Right - | Left, Left -> false - | Right, Left -> - not (Precedence.sameKind outerPrecedence innerPrecedence) - || match innerPrecedence with - | Div - | Mod - | Sub -> true - | _ -> false - - | c -> c > 0 - - if ambiguous || dangling inner then - ValueNone - else - ValueSome range - - | OuterBinaryExpr inner (_, Right), (SynExpr.Sequential _ | SynExpr.LetOrUse(trivia = { InKeyword = None })) -> ValueNone - | OuterBinaryExpr inner (_, Right), inner -> if dangling inner then ValueNone else ValueSome range - - // new T(expr) - | SynExpr.New _, AtomicExprAfterType -> ValueSome range - | SynExpr.New _, _ -> ValueNone - - // { inherit T(expr); … } - | SynExpr.Record(baseInfo = Some(_, SynExpr.Paren(expr = Is inner), _, _, _)), AtomicExprAfterType -> ValueSome range - | SynExpr.Record(baseInfo = Some(_, SynExpr.Paren(expr = Is inner), _, _, _)), _ -> ValueNone - - | _, SynExpr.Paren _ - | _, SynExpr.Quote _ - | _, SynExpr.Const _ - | _, SynExpr.Tuple(isStruct = true) - | _, SynExpr.AnonRecd _ - | _, SynExpr.ArrayOrList _ - | _, SynExpr.Record _ - | _, SynExpr.ObjExpr _ - | _, SynExpr.ArrayOrListComputed _ - | _, SynExpr.ComputationExpr _ - | _, SynExpr.TypeApp _ - | _, SynExpr.Ident _ - | _, SynExpr.LongIdent _ - | _, SynExpr.DotGet _ - | _, SynExpr.DotLambda _ - | _, SynExpr.DotIndexedGet _ - | _, SynExpr.Null _ - | _, SynExpr.InterpolatedString _ - - | SynExpr.Paren _, _ - | SynExpr.Quote _, _ - | SynExpr.Typed _, _ - | SynExpr.AnonRecd _, _ - | SynExpr.Record _, _ - | SynExpr.ObjExpr _, _ - | SynExpr.While _, _ - | SynExpr.WhileBang _, _ - | SynExpr.For _, _ - | SynExpr.ForEach _, _ - | SynExpr.Lambda _, _ - | SynExpr.MatchLambda _, _ - | SynExpr.Match _, _ - | SynExpr.MatchBang _, _ - | SynExpr.LetOrUse _, _ - | SynExpr.LetOrUseBang _, _ - | SynExpr.Sequential _, _ - | SynExpr.Do _, _ - | SynExpr.DoBang _, _ - | SynExpr.IfThenElse _, _ - | SynExpr.TryWith _, _ - | SynExpr.TryFinally _, _ - | SynExpr.ComputationExpr _, _ - | SynExpr.InterpolatedString _, _ -> ValueSome range - - | _ -> ValueNone - - | _ -> ValueNone - - module SynPat = - let (|Last|) = List.last - - /// Matches if any pattern in the given list is a SynPat.Typed. - [] - let (|AnyTyped|_|) pats = - if - pats - |> List.exists (function - | SynPat.Typed _ -> true - | _ -> false) - then - ValueSome AnyTyped - else - ValueNone - - /// Matches if any member in the given list is an inherit - /// or implementation of an interface with generic type args. - [] - let (|AnyGenericInheritOrInterfaceImpl|_|) members = - if - members - |> List.exists (function - | SynMemberDefn.ImplicitInherit(inheritType = SynType.App(typeArgs = _ :: _)) - | SynMemberDefn.ImplicitInherit(inheritType = SynType.LongIdentApp(typeArgs = _ :: _)) - | SynMemberDefn.Interface(interfaceType = SynType.App(typeArgs = _ :: _)) - | SynMemberDefn.Interface(interfaceType = SynType.LongIdentApp(typeArgs = _ :: _)) -> true - | _ -> false) - then - ValueSome AnyGenericInheritOrInterfaceImpl - else - ValueNone - - /// Matches the rightmost potentially dangling nested pattern. - let rec (|Rightmost|) pat = - match pat with - | SynPat.Or(rhsPat = Rightmost pat) - | SynPat.ListCons(rhsPat = Rightmost pat) - | SynPat.As(rhsPat = Rightmost pat) - | SynPat.Ands(pats = Last(Rightmost pat)) - | SynPat.Tuple(isStruct = false; elementPats = Last(Rightmost pat)) -> pat - | pat -> pat - - /// Matches if the given pattern is atomic. - [] - let (|Atomic|_|) pat = - match pat with - | SynPat.Named _ - | SynPat.Wild _ - | SynPat.Paren _ - | SynPat.Tuple(isStruct = true) - | SynPat.Record _ - | SynPat.ArrayOrList _ - | SynPat.Const _ - | SynPat.LongIdent(argPats = SynArgPats.Pats []) - | SynPat.Null _ - | SynPat.QuoteExpr _ -> ValueSome Atomic - | _ -> ValueNone - - /// If the given pattern is a parenthesized pattern and the parentheses - /// are unnecessary in the given context, returns the unnecessary parentheses' range. - let unnecessaryParentheses pat path = - match pat, path with - // Parens are needed in: - // - // let (Pattern …) = … - // let (x: …, y…) = … - // let (x: …), (y: …) = … - // let! (x: …) = … - // and! (x: …) = … - // use! (x: …) = … - // _.member M(x: …) = … - // match … with (x: …) -> … - // match … with (x, y: …) -> … - // function (x: …) -> … - // fun (x, y, …) -> … - // fun (x: …) -> … - // fun (Pattern …) -> … - | SynPat.Paren(SynPat.Typed _, _), SyntaxNode.SynPat(Rightmost rightmost) :: SyntaxNode.SynMatchClause _ :: _ when - obj.ReferenceEquals(pat, rightmost) - -> - ValueNone - | SynPat.Paren(Rightmost(SynPat.Typed _), _), SyntaxNode.SynMatchClause _ :: _ - | SynPat.Paren(SynPat.Typed _, _), SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ - | SynPat.Paren(SynPat.Typed _, _), - SyntaxNode.SynPat(SynPat.Tuple(isStruct = false)) :: SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ - | SynPat.Paren(SynPat.Tuple(isStruct = false; elementPats = AnyTyped), _), SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ - | SynPat.Paren(SynPat.Typed _, _), SyntaxNode.SynPat(SynPat.Tuple(isStruct = false)) :: SyntaxNode.SynBinding _ :: _ - | SynPat.Paren(SynPat.Tuple(isStruct = false; elementPats = AnyTyped), _), SyntaxNode.SynBinding _ :: _ - | SynPat.Paren(SynPat.LongIdent(argPats = SynArgPats.Pats(_ :: _)), _), SyntaxNode.SynBinding _ :: _ - | SynPat.Paren(SynPat.LongIdent(argPats = SynArgPats.Pats(_ :: _)), _), SyntaxNode.SynExpr(SynExpr.Lambda _) :: _ - | SynPat.Paren(SynPat.Tuple(isStruct = false), _), SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some _)) :: _ - | SynPat.Paren(SynPat.Typed _, _), SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some _)) :: _ -> ValueNone - - // () is parsed as this. - | SynPat.Paren(SynPat.Const(SynConst.Unit, _), _), _ -> ValueNone - - // (()) is required when overriding a generic member - // where unit is the generic type argument: - // - // type C<'T> = abstract M : 'T -> unit - // let _ = { new C with override _.M (()) = () } - | SynPat.Paren(SynPat.Paren(SynPat.Const(SynConst.Unit, _), _), _), - SyntaxNode.SynPat(SynPat.LongIdent _) :: SyntaxNode.SynBinding _ :: SyntaxNode.SynExpr(SynExpr.ObjExpr( - objType = SynType.App(typeArgs = _ :: _) | SynType.LongIdentApp(typeArgs = _ :: _))) :: _ - | SynPat.Paren(SynPat.Paren(SynPat.Const(SynConst.Unit, _), _), _), - SyntaxNode.SynPat(SynPat.LongIdent _) :: SyntaxNode.SynBinding _ :: SyntaxNode.SynMemberDefn _ :: SyntaxNode.SynTypeDefn(SynTypeDefn( - typeRepr = SynTypeDefnRepr.ObjectModel(members = AnyGenericInheritOrInterfaceImpl))) :: _ -> ValueNone - - // Parens are required around the atomic argument of - // any additional `new` constructor that is not the last. - // - // type T … = - // new (x) = … - // new (x, y) = … - | SynPat.Paren(Atomic, range), - SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = [ Ident "new" ]))) :: SyntaxNode.SynBinding _ :: SyntaxNode.SynMemberDefn _ :: SyntaxNode.SynTypeDefn(SynTypeDefn( - typeRepr = SynTypeDefnRepr.ObjectModel(members = members))) :: _ -> - let lastNew = - (ValueNone, members) - ||> List.fold (fun lastNew ``member`` -> - match ``member`` with - | SynMemberDefn.Member( - memberDefn = SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = [ Ident "new" ])))) -> - ValueSome ``member`` - | _ -> lastNew) - - match lastNew with - | ValueSome(SynMemberDefn.Member(memberDefn = SynBinding(headPat = SynPat.LongIdent(argPats = SynArgPats.Pats [ Is pat ])))) -> - ValueSome range - | _ -> ValueNone - - // Parens are otherwise never needed in these cases: - // - // let (x: …) = … - // for (…) in (…) do … - // let! (…) = … - // and! (…) = … - // use! (…) = … - // match … with (…) -> … - // function (…) -> … - // function (Pattern …) -> … - // fun (x) -> … - | SynPat.Paren(_, range), SyntaxNode.SynBinding _ :: _ - | SynPat.Paren(_, range), SyntaxNode.SynExpr(SynExpr.ForEach _) :: _ - | SynPat.Paren(_, range), SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ - | SynPat.Paren(_, range), SyntaxNode.SynMatchClause _ :: _ - | SynPat.Paren(Atomic, range), SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some _)) :: _ -> ValueSome range - - // Nested patterns. - | SynPat.Paren(inner, range), SyntaxNode.SynPat outer :: _ -> - match outer, inner with - // (x :: xs) :: ys - // (x, xs) :: ys - | SynPat.ListCons(lhsPat = SynPat.Paren(pat = Is inner)), SynPat.ListCons _ - | SynPat.ListCons(lhsPat = SynPat.Paren(pat = Is inner)), SynPat.Tuple(isStruct = false) -> ValueNone - - // A as (B | C) - // A as (B & C) - // x as (y, z) - // xs as (y :: zs) - | SynPat.As(rhsPat = SynPat.Paren(pat = Is inner)), - (SynPat.Or _ | SynPat.Ands _ | SynPat.Tuple(isStruct = false) | SynPat.ListCons _) -> ValueNone - - // (A | B) :: xs - // (A & B) :: xs - // (x as y) :: xs - | SynPat.ListCons _, SynPat.Or _ - | SynPat.ListCons _, SynPat.Ands _ - | SynPat.ListCons _, SynPat.As _ -> ValueNone - - // Pattern (x = (…)) - | SynPat.LongIdent(argPats = SynArgPats.NamePatPairs _), _ -> ValueSome range - - // Pattern (x : int) - // Pattern ([] x) - // Pattern (:? int) - // Pattern (A :: _) - // Pattern (A | B) - // Pattern (A & B) - // Pattern (A as B) - // Pattern (A, B) - // Pattern1 (Pattern2 (x = A)) - // Pattern1 (Pattern2 x y) - | SynPat.LongIdent _, SynPat.Typed _ - | SynPat.LongIdent _, SynPat.Attrib _ - | SynPat.LongIdent _, SynPat.IsInst _ - | SynPat.LongIdent _, SynPat.ListCons _ - | SynPat.LongIdent _, SynPat.Or _ - | SynPat.LongIdent _, SynPat.Ands _ - | SynPat.LongIdent _, SynPat.As _ - | SynPat.LongIdent _, SynPat.Tuple(isStruct = false) - | SynPat.LongIdent _, SynPat.LongIdent(argPats = SynArgPats.NamePatPairs _) - | SynPat.LongIdent _, SynPat.LongIdent(argPats = SynArgPats.Pats(_ :: _)) - - // A | (B as C) - // A & (B as C) - // A, (B as C) - | SynPat.Or _, SynPat.As _ - | SynPat.Ands _, SynPat.As _ - | SynPat.Tuple _, SynPat.As _ - - // x, (y, z) - // x & (y, z) - // (x, y) & z - | SynPat.Tuple _, SynPat.Tuple(isStruct = false) - | SynPat.Ands _, SynPat.Tuple(isStruct = false) - - // A, (B | C) - // A & (B | C) - | SynPat.Tuple _, SynPat.Or _ - | SynPat.Ands _, SynPat.Or _ -> ValueNone - - // (x : int) & y - // x & (y : int) & z - | SynPat.Ands(Last(SynPat.Paren(pat = Is inner)), _), SynPat.Typed _ -> ValueSome range - | SynPat.Ands _, SynPat.Typed _ -> ValueNone - - | _, SynPat.Const _ - | _, SynPat.Wild _ - | _, SynPat.Named _ - | _, SynPat.Typed _ - | _, SynPat.LongIdent(argPats = SynArgPats.Pats []) - | _, SynPat.Tuple(isStruct = true) - | _, SynPat.Paren _ - | _, SynPat.ArrayOrList _ - | _, SynPat.Record _ - | _, SynPat.Null _ - | _, SynPat.OptionalVal _ - | _, SynPat.IsInst _ - | _, SynPat.QuoteExpr _ - - | SynPat.Or _, _ - | SynPat.ListCons _, _ - | SynPat.Ands _, _ - | SynPat.As _, _ - | SynPat.LongIdent _, _ - | SynPat.Tuple _, _ - | SynPat.Paren _, _ - | SynPat.ArrayOrList _, _ - | SynPat.Record _, _ -> ValueSome range - - | _ -> ValueNone - - | _ -> ValueNone - - let getUnnecessaryParentheses (getSourceLineStr: int -> string) (parsedInput: ParsedInput) : Async = - async { - let ranges = HashSet Range.comparer - - let visitor = - { new SyntaxVisitorBase() with - member _.VisitExpr(path, _, defaultTraverse, expr) = - SynExpr.unnecessaryParentheses getSourceLineStr expr path - |> ValueOption.iter (ranges.Add >> ignore) - - defaultTraverse expr - - member _.VisitPat(path, defaultTraverse, pat) = - SynPat.unnecessaryParentheses pat path - |> ValueOption.iter (ranges.Add >> ignore) - - defaultTraverse pat - } - - SyntaxTraversal.traverseAll visitor parsedInput - return ranges - } diff --git a/src/Compiler/Service/ServiceAnalysis.fsi b/src/Compiler/Service/ServiceAnalysis.fsi index 836bfce0c56..672cf088759 100644 --- a/src/Compiler/Service/ServiceAnalysis.fsi +++ b/src/Compiler/Service/ServiceAnalysis.fsi @@ -3,7 +3,6 @@ namespace FSharp.Compiler.EditorServices open FSharp.Compiler.CodeAnalysis -open FSharp.Compiler.Syntax open FSharp.Compiler.Text module public UnusedOpens = @@ -32,14 +31,3 @@ module public UnusedDeclarations = /// Get all unused declarations in a file val getUnusedDeclarations: checkFileResults: FSharpCheckFileResults * isScriptFile: bool -> Async> - -module public UnnecessaryParentheses = - - /// Gets the ranges of all unnecessary pairs of parentheses in a file. - /// - /// Note that this may include pairs of nested ranges each of whose - /// lack of necessity depends on the other's presence, such - /// that it is valid to remove either set of parentheses but not both, e.g.: - /// - /// (x.M(y)).N → (x.M y).N ↮ x.M(y).N - val getUnnecessaryParentheses: getSourceLineStr: (int -> string) -> parsedInput: ParsedInput -> Async diff --git a/src/Compiler/Service/ServiceDeclarationLists.fs b/src/Compiler/Service/ServiceDeclarationLists.fs index 5488baa107a..d8499132fdc 100644 --- a/src/Compiler/Service/ServiceDeclarationLists.fs +++ b/src/Compiler/Service/ServiceDeclarationLists.fs @@ -358,19 +358,7 @@ module DeclarationListHelpers = | Item.CtorGroup(_, minfos) | Item.MethodGroup(_, minfos, _) -> FormatOverloadsToList infoReader m denv item minfos symbol width - - // The 'fake' zero-argument constructors of .NET interfaces. - // This ideally should never appear in intellisense, but we do get here in repros like: - // type IFoo = abstract F : int - // type II = IFoo // remove 'type II = ' and quickly hover over IFoo before it gets squiggled for 'invalid use of interface type' - // and in that case we'll just show the interface type name. - | Item.FakeInterfaceCtor ty -> - let ty, _ = PrettyTypes.PrettifyType g ty - let layout = NicePrint.layoutTyconRef denv (tcrefOfAppTy g ty) - let layout = PrintUtilities.squashToWidth width layout - let layout = toArray layout - ToolTipElement.Single(layout, xml, ?symbol = symbol) - + // The 'fake' representation of constructors of .NET delegate types | Item.DelegateCtor delTy -> let delTy, _cxs = PrettyTypes.PrettifyType g delTy @@ -848,10 +836,6 @@ module internal DescriptionListsImpl = let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInstantiation [] retTy [], prettyRetTyL // no parameter data available for binary operators like 'zip', 'join' and 'groupJoin' since they use bespoke syntax - | Item.FakeInterfaceCtor ty -> - let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInstantiation [] ty - [], prettyRetTyL - | Item.DelegateCtor delTy -> let (SigOfFunctionForDelegate(_, _, _, delFuncTy)) = GetSigOfFunctionForDelegate infoReader delTy m AccessibleFromSomewhere @@ -940,7 +924,6 @@ module internal DescriptionListsImpl = | Item.Property _ -> FSharpGlyph.Property | Item.CtorGroup _ | Item.DelegateCtor _ - | Item.FakeInterfaceCtor _ | Item.CustomOperation _ -> FSharpGlyph.Method | Item.MethodGroup (_, minfos, _) when minfos |> List.forall (fun minfo -> minfo.IsExtensionMember) -> FSharpGlyph.ExtensionMethod | Item.MethodGroup _ -> FSharpGlyph.Method @@ -986,7 +969,6 @@ module internal DescriptionListsImpl = | Item.CtorGroup(nm, cinfos) -> List.map (fun minfo -> Item.CtorGroup(nm, [minfo])) cinfos | Item.Trait traitInfo -> if traitInfo.GetLogicalArgumentTypes(g).IsEmpty then [] else [item] - | Item.FakeInterfaceCtor _ | Item.DelegateCtor _ -> [item] | Item.NewDef _ | Item.ILField _ -> [] @@ -1107,9 +1089,9 @@ type DeclarationListInfo(declarations: DeclarationListItem[], isForType: bool, i items |> List.map (fun x -> match x.Item with + | Item.Types (_, TType_app(tcref, _, _) :: _) when isInterfaceTyconRef tcref -> { x with MinorPriority = 1000 + tcref.TyparsNoRange.Length } | Item.Types (_, TType_app(tcref, _, _) :: _) -> { x with MinorPriority = 1 + tcref.TyparsNoRange.Length } // Put delegate ctors after types, sorted by #typars. RemoveDuplicateItems will remove FakeInterfaceCtor and DelegateCtor if an earlier type is also reported with this name - | Item.FakeInterfaceCtor (TType_app(tcref, _, _)) | Item.DelegateCtor (TType_app(tcref, _, _)) -> { x with MinorPriority = 1000 + tcref.TyparsNoRange.Length } // Put type ctors after types, sorted by #typars. RemoveDuplicateItems will remove DefaultStructCtors if a type is also reported with this name | Item.CtorGroup (_, cinfo :: _) -> { x with MinorPriority = 1000 + 10 * cinfo.DeclaringTyconRef.TyparsNoRange.Length } diff --git a/src/Compiler/Service/ServiceNavigation.fs b/src/Compiler/Service/ServiceNavigation.fs index 7f912e07e09..03afe63b373 100755 --- a/src/Compiler/Service/ServiceNavigation.fs +++ b/src/Compiler/Service/ServiceNavigation.fs @@ -377,7 +377,14 @@ module NavigationImpl = | 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 newBaseName = + (if (String.IsNullOrEmpty(baseName)) then + "" + else + baseName + ".") + + (textOfLid lid) + let other = processNavigationTopLevelDeclarations (newBaseName, decls) let mBody = unionRangesChecked (rangeOfDecls nested) (moduleRange (rangeOfLid lid) other) @@ -587,7 +594,14 @@ module NavigationImpl = | 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 newBaseName = + (if String.IsNullOrEmpty(baseName) then + "" + else + baseName + ".") + + (textOfLid lid) + let other = processNavigationTopLevelSigDeclarations (newBaseName, decls) // Get nested modules and types (for the left dropdown) diff --git a/src/Compiler/Service/ServiceParseTreeWalk.fs b/src/Compiler/Service/ServiceParseTreeWalk.fs index e18c3cff03f..e358b2bf921 100644 --- a/src/Compiler/Service/ServiceParseTreeWalk.fs +++ b/src/Compiler/Service/ServiceParseTreeWalk.fs @@ -13,7 +13,6 @@ open FSharp.Compiler.Text open FSharp.Compiler.Text.Position open FSharp.Compiler.Text.Range -/// used to track route during traversal AST [] type SyntaxNode = | SynPat of SynPat @@ -31,6 +30,23 @@ type SyntaxNode = | SynTypeDefnSig of SynTypeDefnSig | SynMemberSig of SynMemberSig + member this.Range = + match this with + | SynPat pat -> pat.Range + | SynType ty -> ty.Range + | SynExpr expr -> expr.Range + | SynModule modul -> modul.Range + | SynModuleOrNamespace moduleOrNamespace -> moduleOrNamespace.Range + | SynTypeDefn tyDef -> tyDef.Range + | SynMemberDefn memberDef -> memberDef.Range + | SynMatchClause matchClause -> matchClause.Range + | SynBinding binding -> binding.RangeOfBindingWithRhs + | SynModuleOrNamespaceSig moduleOrNamespaceSig -> moduleOrNamespaceSig.Range + | SynModuleSigDecl moduleSigDecl -> moduleSigDecl.Range + | SynValSig(SynValSig.SynValSig(range = range)) -> range + | SynTypeDefnSig tyDefSig -> tyDefSig.Range + | SynMemberSig memberSig -> memberSig.Range + type SyntaxVisitorPath = SyntaxNode list [] @@ -163,10 +179,10 @@ type SyntaxVisitorBase<'T>() = None /// VisitSimplePats allows overriding behavior when visiting simple pats - abstract VisitSimplePats: path: SyntaxVisitorPath * synPats: SynSimplePat list -> 'T option + abstract VisitSimplePats: path: SyntaxVisitorPath * pat: SynPat -> 'T option - default _.VisitSimplePats(path, synPats) = - ignore (path, synPats) + default _.VisitSimplePats(path, pat) = + ignore (path, pat) None /// VisitPat allows overriding behavior when visiting patterns @@ -211,6 +227,15 @@ type SyntaxVisitorBase<'T>() = ignore path defaultTraverse valSig +[] +module private ParsedInputExtensions = + type ParsedInput with + + member parsedInput.Contents = + match parsedInput with + | ParsedInput.ImplFile file -> file.Contents |> List.map SyntaxNode.SynModuleOrNamespace + | ParsedInput.SigFile file -> file.Contents |> List.map SyntaxNode.SynModuleOrNamespaceSig + /// A range of utility functions to assist with traversing an AST module SyntaxTraversal = // treat ranges as though they are half-open: [,) @@ -304,7 +329,7 @@ module SyntaxTraversal = (pick: pos -> range -> obj -> (range * (unit -> 'T option)) list -> 'T option) (pos: pos) (visitor: SyntaxVisitorBase<'T>) - (parseTree: ParsedInput) + (ast: SyntaxNode list) : 'T option = let pick x = pick pos x @@ -749,15 +774,18 @@ module SyntaxTraversal = visitor.VisitPat(origPath, defaultTraverse, pat) - and traverseSynSimplePats origPath (pats: SynSimplePat list) = - match visitor.VisitSimplePats(origPath, pats) with + and traverseSynSimplePats origPath (pat: SynPat) = + match visitor.VisitSimplePats(origPath, pat) with | None -> - pats - |> List.tryPick (fun pat -> + let rec loop (pat: SynPat) = match pat with - | SynSimplePat.Attrib(attributes = attributes; range = m) -> - attributeApplicationDives origPath attributes |> pick m attributes - | _ -> None) + | SynPat.Paren(pat = pat) + | SynPat.Typed(pat = pat) -> loop pat + | SynPat.Tuple(elementPats = pats) -> List.tryPick loop pats + | SynPat.Attrib(_, attributes, m) -> attributeApplicationDives origPath attributes |> pick m attributes + | _ -> None + + loop pat | x -> x and traverseSynType origPath (StripParenTypes ty) = @@ -888,9 +916,8 @@ module SyntaxTraversal = traverseSynBinding path getBinding |> Option.orElseWith (fun () -> traverseSynBinding path setBinding) - | SynMemberDefn.ImplicitCtor(ctorArgs = simplePats) -> - match simplePats with - | SynSimplePats.SimplePats(pats = simplePats) -> traverseSynSimplePats path simplePats + | SynMemberDefn.ImplicitCtor(ctorArgs = pat) -> traverseSynSimplePats path pat + | SynMemberDefn.ImplicitInherit(synType, synExpr, _identOption, range) -> [ dive () synType.Range (fun () -> @@ -1062,40 +1089,377 @@ module SyntaxTraversal = attributeApplicationDives path attributes |> pick m.Range attributes | SynMemberSig.NestedType(nestedType = nestedType) -> traverseSynTypeDefnSig path nestedType - match parseTree with - | ParsedInput.ImplFile file -> - let l = file.Contents + let fileRange = + (range0, ast) ||> List.fold (fun acc node -> unionRanges acc node.Range) + + ast + |> List.map (fun node -> + match node with + | SyntaxNode.SynModuleOrNamespace moduleOrNamespace -> + dive moduleOrNamespace moduleOrNamespace.Range (traverseSynModuleOrNamespace []) + | SyntaxNode.SynModuleOrNamespaceSig moduleOrNamespaceSig -> + dive moduleOrNamespaceSig moduleOrNamespaceSig.Range (traverseSynModuleOrNamespaceSig []) + | SyntaxNode.SynPat pat -> dive pat pat.Range (traversePat []) + | SyntaxNode.SynType ty -> dive ty ty.Range (traverseSynType []) + | SyntaxNode.SynExpr expr -> dive expr expr.Range (traverseSynExpr []) + | SyntaxNode.SynModule modul -> dive modul modul.Range (traverseSynModuleDecl []) + | SyntaxNode.SynTypeDefn tyDef -> dive tyDef tyDef.Range (traverseSynTypeDefn []) + | SyntaxNode.SynMemberDefn memberDef -> dive memberDef memberDef.Range (traverseSynMemberDefn [] (fun _ -> None)) + | SyntaxNode.SynMatchClause matchClause -> dive matchClause matchClause.Range (traverseSynMatchClause []) + | SyntaxNode.SynBinding binding -> dive binding binding.RangeOfBindingWithRhs (traverseSynBinding []) + | SyntaxNode.SynModuleSigDecl moduleSigDecl -> dive moduleSigDecl moduleSigDecl.Range (traverseSynModuleSigDecl []) + | SyntaxNode.SynValSig(SynValSig.SynValSig(range = range) as valSig) -> dive valSig range (traverseSynValSig []) + | SyntaxNode.SynTypeDefnSig tyDefSig -> dive tyDefSig tyDefSig.Range (traverseSynTypeDefnSig []) + | SyntaxNode.SynMemberSig memberSig -> dive memberSig memberSig.Range (traverseSynMemberSig [])) + |> pick fileRange ast - let fileRange = -#if DEBUG - 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 -#endif - l - |> List.map (fun x -> dive x x.Range (traverseSynModuleOrNamespace [])) - |> pick fileRange l - | ParsedInput.SigFile sigFile -> - let l = sigFile.Contents + /// traverse an implementation file walking all the way down to SynExpr or TypeAbbrev at a particular location + /// + let Traverse (pos: pos, parseTree: ParsedInput, visitor: SyntaxVisitorBase<'T>) = + traverseUntil pick pos visitor parseTree.Contents - let fileRange = -#if DEBUG - 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 -#endif - l - |> List.map (fun x -> dive x x.Range (traverseSynModuleOrNamespaceSig [])) - |> pick fileRange l - - let traverseAll (visitor: SyntaxVisitorBase<'T>) (parseTree: ParsedInput) : unit = - let pick _ _ _ diveResults = - let rec loop = - function +[] +[] +module SyntaxNode = + let (|Attributes|) node = + let (|All|) = List.collect + let field (SynField(attributes = attributes)) = attributes + let unionCase (SynUnionCase(attributes = attributes)) = attributes + let enumCase (SynEnumCase(attributes = attributes)) = attributes + let typar (SynTyparDecl(attributes = attributes)) = attributes + + let (|SynComponentInfo|) componentInfo = + match componentInfo with + | SynComponentInfo(attributes = attributes; typeParams = Some(SynTyparDecls.PrefixList(decls = All typar attributes'))) + | SynComponentInfo(attributes = attributes; typeParams = Some(SynTyparDecls.PostfixList(decls = All typar attributes'))) + | SynComponentInfo( + attributes = attributes; typeParams = Some(SynTyparDecls.SinglePrefix(decl = SynTyparDecl(attributes = attributes')))) -> + attributes @ attributes' + | SynComponentInfo(attributes = attributes) -> attributes + + let (|SynBinding|) binding = + match binding with + | SynBinding(attributes = attributes; returnInfo = Some(SynBindingReturnInfo(attributes = attributes'))) -> + attributes @ attributes' + | SynBinding(attributes = attributes) -> attributes + + match node with + | SyntaxNode.SynModuleOrNamespace(SynModuleOrNamespace(attribs = attributes)) + | SyntaxNode.SynModuleOrNamespaceSig(SynModuleOrNamespaceSig(attribs = attributes)) + | SyntaxNode.SynModule(SynModuleDecl.Attributes(attributes = attributes)) + | SyntaxNode.SynTypeDefn(SynTypeDefn(typeInfo = SynComponentInfo attributes)) + | SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFields = All field attributes), _))) + | SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Union(unionCases = All unionCase attributes), _))) + | SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Enum(cases = All enumCase attributes), _))) + | SyntaxNode.SynMemberDefn(SynMemberDefn.AutoProperty(attributes = attributes)) + | SyntaxNode.SynMemberDefn(SynMemberDefn.AbstractSlot(slotSig = SynValSig(attributes = attributes))) + | SyntaxNode.SynMemberDefn(SynMemberDefn.ImplicitCtor(attributes = attributes)) + | SyntaxNode.SynBinding(SynBinding attributes) + | SyntaxNode.SynPat(SynPat.Attrib(attributes = attributes)) + | SyntaxNode.SynType(SynType.SignatureParameter(attributes = attributes)) + | SyntaxNode.SynValSig(SynValSig(attributes = attributes)) -> attributes + | _ -> [] + +[] +[] +module ParsedInput = + let fold folder state (parsedInput: ParsedInput) = + let mutable state = state + + let visitor = + { new SyntaxVisitorBase() with + member _.VisitExpr(path, _, defaultTraverse, expr) = + match path with + | SyntaxNode.SynMemberDefn _ as parent :: path -> state <- folder state path parent + | _ -> () + + state <- folder state path (SyntaxNode.SynExpr expr) + defaultTraverse expr + + member _.VisitPat(path, defaultTraverse, pat) = + state <- folder state path (SyntaxNode.SynPat pat) + defaultTraverse pat + + member _.VisitType(path, defaultTraverse, synType) = + match path with + | SyntaxNode.SynMemberDefn _ | SyntaxNode.SynMemberSig _ as parent :: path -> state <- folder state path parent + | _ -> () + + state <- folder state path (SyntaxNode.SynType synType) + defaultTraverse synType + + member _.VisitModuleDecl(path, defaultTraverse, synModuleDecl) = + state <- folder state path (SyntaxNode.SynModule synModuleDecl) + + match synModuleDecl with + | SynModuleDecl.Types(types, _) -> + let path = SyntaxNode.SynModule synModuleDecl :: path + + for ty in types do + state <- folder state path (SyntaxNode.SynTypeDefn ty) + + | _ -> () + + defaultTraverse synModuleDecl + + member _.VisitModuleOrNamespace(path, synModuleOrNamespace) = + state <- folder state path (SyntaxNode.SynModuleOrNamespace synModuleOrNamespace) + None + + member _.VisitMatchClause(path, defaultTraverse, matchClause) = + state <- folder state path (SyntaxNode.SynMatchClause matchClause) + defaultTraverse matchClause + + member _.VisitBinding(path, defaultTraverse, synBinding) = + match path with + | SyntaxNode.SynMemberDefn _ as parent :: path -> state <- folder state path parent + | _ -> () + + state <- folder state path (SyntaxNode.SynBinding synBinding) + defaultTraverse synBinding + + member _.VisitModuleOrNamespaceSig(path, synModuleOrNamespaceSig) = + state <- folder state path (SyntaxNode.SynModuleOrNamespaceSig synModuleOrNamespaceSig) + None + + member _.VisitModuleSigDecl(path, defaultTraverse, synModuleSigDecl) = + state <- folder state path (SyntaxNode.SynModuleSigDecl synModuleSigDecl) + + match synModuleSigDecl with + | SynModuleSigDecl.Types(types, _) -> + let path = SyntaxNode.SynModuleSigDecl synModuleSigDecl :: path + + for ty in types do + state <- folder state path (SyntaxNode.SynTypeDefnSig ty) + + | _ -> () + + defaultTraverse synModuleSigDecl + + member _.VisitValSig(path, defaultTraverse, valSig) = + match path with + | SyntaxNode.SynMemberSig _ as parent :: path -> state <- folder state path parent + | _ -> () + + state <- folder state path (SyntaxNode.SynValSig valSig) + defaultTraverse valSig + + member _.VisitSimplePats(path, _pat) = + match path with + | SyntaxNode.SynMemberDefn _ as node :: path -> state <- folder state path node + | _ -> () + + None + + member _.VisitInterfaceSynMemberDefnType(path, _synType) = + match path with + | SyntaxNode.SynMemberDefn _ as node :: path -> state <- folder state path node + | _ -> () + + None + } + + let pickAll _ _ _ diveResults = + let rec loop diveResults = + match diveResults with + | [] -> None + | (_, project) :: rest -> + ignore (project ()) + loop rest + + loop diveResults + + let ast = parsedInput.Contents + let m = (range0, ast) ||> List.fold (fun acc node -> unionRanges acc node.Range) + ignore (SyntaxTraversal.traverseUntil pickAll m.End visitor ast) + state + + let private foldWhileImpl pick pos folder state (ast: SyntaxNode list) = + let mutable state = state + + let visitor = + { new SyntaxVisitorBase() with + member _.VisitExpr(path, _, defaultTraverse, expr) = + match path with + | SyntaxNode.SynMemberDefn _ as parent :: path -> + match folder state path parent with + | Some state' -> + match folder state' path (SyntaxNode.SynExpr expr) with + | Some state' -> + state <- state' + defaultTraverse expr + | None -> Some() + | None -> Some() + | _ -> + match folder state path (SyntaxNode.SynExpr expr) with + | Some state' -> + state <- state' + defaultTraverse expr + | None -> Some() + + member _.VisitPat(path, defaultTraverse, pat) = + match folder state path (SyntaxNode.SynPat pat) with + | Some state' -> + state <- state' + defaultTraverse pat + | None -> Some() + + member _.VisitType(path, defaultTraverse, synType) = + match path with + | SyntaxNode.SynMemberDefn _ | SyntaxNode.SynMemberSig _ as parent :: path -> + match folder state path parent with + | Some state' -> + match folder state' path (SyntaxNode.SynType synType) with + | Some state' -> + state <- state' + defaultTraverse synType + | None -> Some() + | None -> Some() + | _ -> + match folder state path (SyntaxNode.SynType synType) with + | Some state' -> + state <- state' + defaultTraverse synType + | None -> Some() + + member _.VisitModuleDecl(path, defaultTraverse, synModuleDecl) = + match folder state path (SyntaxNode.SynModule synModuleDecl) with + | Some state' -> + state <- state' + + match synModuleDecl with + | SynModuleDecl.Types(types, _) -> + let path = SyntaxNode.SynModule synModuleDecl :: path + + let rec loop types = + match types with + | [] -> defaultTraverse synModuleDecl + | ty :: types -> + match folder state path (SyntaxNode.SynTypeDefn ty) with + | Some state' -> + state <- state' + loop types + | None -> Some() + + loop types + + | _ -> defaultTraverse synModuleDecl + + | None -> Some() + + member _.VisitModuleOrNamespace(path, synModuleOrNamespace) = + match folder state path (SyntaxNode.SynModuleOrNamespace synModuleOrNamespace) with + | Some state' -> + state <- state' + None + | None -> Some() + + member _.VisitMatchClause(path, defaultTraverse, matchClause) = + match folder state path (SyntaxNode.SynMatchClause matchClause) with + | Some state' -> + state <- state' + defaultTraverse matchClause + | None -> Some() + + member _.VisitBinding(path, defaultTraverse, synBinding) = + match path with + | SyntaxNode.SynMemberDefn _ as parent :: path -> + match folder state path parent with + | Some state' -> + match folder state' path (SyntaxNode.SynBinding synBinding) with + | Some state' -> + state <- state' + defaultTraverse synBinding + | None -> Some() + | None -> Some() + | _ -> + match folder state path (SyntaxNode.SynBinding synBinding) with + | Some state' -> + state <- state' + defaultTraverse synBinding + | None -> Some() + + member _.VisitModuleOrNamespaceSig(path, synModuleOrNamespaceSig) = + match folder state path (SyntaxNode.SynModuleOrNamespaceSig synModuleOrNamespaceSig) with + | Some state' -> + state <- state' + None + | None -> Some() + + member _.VisitModuleSigDecl(path, defaultTraverse, synModuleSigDecl) = + match folder state path (SyntaxNode.SynModuleSigDecl synModuleSigDecl) with + | Some state' -> + state <- state' + + match synModuleSigDecl with + | SynModuleSigDecl.Types(types, _) -> + let path = SyntaxNode.SynModuleSigDecl synModuleSigDecl :: path + + let rec loop types = + match types with + | [] -> defaultTraverse synModuleSigDecl + | ty :: types -> + match folder state path (SyntaxNode.SynTypeDefnSig ty) with + | Some state' -> + state <- state' + loop types + | None -> Some() + + loop types + + | _ -> defaultTraverse synModuleSigDecl + + | None -> Some() + + member _.VisitValSig(path, defaultTraverse, valSig) = + match path with + | SyntaxNode.SynMemberSig _ as parent :: path -> + match folder state path parent with + | Some state' -> + match folder state' path (SyntaxNode.SynValSig valSig) with + | Some state' -> + state <- state' + defaultTraverse valSig + | None -> Some() + | None -> Some() + | _ -> + match folder state path (SyntaxNode.SynValSig valSig) with + | Some state' -> + state <- state' + defaultTraverse valSig + | None -> Some() + + member _.VisitSimplePats(path, _pat) = + match path with + | SyntaxNode.SynMemberDefn _ as node :: path -> + match folder state path node with + | Some state' -> + state <- state' + None + | None -> Some() + | _ -> None + + member _.VisitInterfaceSynMemberDefnType(path, _synType) = + match path with + | SyntaxNode.SynMemberDefn _ as node :: path -> + match folder state path node with + | Some state' -> + state <- state' + None + | None -> Some() + | _ -> None + } + + ignore (SyntaxTraversal.traverseUntil pick pos visitor ast) + state + + let foldWhile folder state (parsedInput: ParsedInput) = + let pickAll _ _ _ diveResults = + let rec loop diveResults = + match diveResults with | [] -> None | (_, project) :: rest -> ignore (project ()) @@ -1103,9 +1467,105 @@ module SyntaxTraversal = loop diveResults - ignore<'T option> (traverseUntil pick parseTree.Range.End visitor parseTree) + let ast = parsedInput.Contents + let m = (range0, ast) ||> List.fold (fun acc node -> unionRanges acc node.Range) + foldWhileImpl pickAll m.End folder state ast + + let tryPick chooser position (parsedInput: ParsedInput) = + let visitor = + { new SyntaxVisitorBase<'T>() with + member _.VisitExpr(path, _, defaultTraverse, expr) = + (match path with + | SyntaxNode.SynMemberDefn _ as parent :: parentPath -> chooser parentPath parent + | _ -> None) + |> Option.orElseWith (fun () -> chooser path (SyntaxNode.SynExpr expr)) + |> Option.orElseWith (fun () -> defaultTraverse expr) + + member _.VisitPat(path, defaultTraverse, pat) = + chooser path (SyntaxNode.SynPat pat) + |> Option.orElseWith (fun () -> defaultTraverse pat) + + member _.VisitType(path, defaultTraverse, synType) = + (match path with + | SyntaxNode.SynMemberDefn _ | SyntaxNode.SynMemberSig _ as parent :: parentPath -> chooser parentPath parent + | _ -> None) + |> Option.orElseWith (fun () -> chooser path (SyntaxNode.SynType synType)) + |> Option.orElseWith (fun () -> defaultTraverse synType) + + member _.VisitModuleDecl(path, defaultTraverse, synModuleDecl) = + chooser path (SyntaxNode.SynModule synModuleDecl) + |> Option.orElseWith (fun () -> + match synModuleDecl with + | SynModuleDecl.Types(types, _) -> + let path = SyntaxNode.SynModule synModuleDecl :: path + types |> List.tryPick (SyntaxNode.SynTypeDefn >> chooser path) + | _ -> None) + |> Option.orElseWith (fun () -> defaultTraverse synModuleDecl) + + member _.VisitModuleOrNamespace(path, synModuleOrNamespace) = + chooser path (SyntaxNode.SynModuleOrNamespace synModuleOrNamespace) + + member _.VisitMatchClause(path, defaultTraverse, matchClause) = + chooser path (SyntaxNode.SynMatchClause matchClause) + |> Option.orElseWith (fun () -> defaultTraverse matchClause) + + member _.VisitBinding(path, defaultTraverse, synBinding) = + (match path with + | SyntaxNode.SynMemberDefn _ as parent :: parentPath -> chooser parentPath parent + | _ -> None) + |> Option.orElseWith (fun () -> chooser path (SyntaxNode.SynBinding synBinding)) + |> Option.orElseWith (fun () -> defaultTraverse synBinding) + + member _.VisitModuleOrNamespaceSig(path, synModuleOrNamespaceSig) = + chooser path (SyntaxNode.SynModuleOrNamespaceSig synModuleOrNamespaceSig) + + member _.VisitModuleSigDecl(path, defaultTraverse, synModuleSigDecl) = + chooser path (SyntaxNode.SynModuleSigDecl synModuleSigDecl) + |> Option.orElseWith (fun () -> + match synModuleSigDecl with + | SynModuleSigDecl.Types(types, _) -> + let path = SyntaxNode.SynModuleSigDecl synModuleSigDecl :: path + types |> List.tryPick (SyntaxNode.SynTypeDefnSig >> chooser path) + | _ -> None) + |> Option.orElseWith (fun () -> defaultTraverse synModuleSigDecl) + + member _.VisitValSig(path, defaultTraverse, valSig) = + (match path with + | SyntaxNode.SynMemberSig _ as parent :: parentPath -> chooser parentPath parent + | _ -> None) + |> Option.orElseWith (fun () -> chooser path (SyntaxNode.SynValSig valSig)) + |> Option.orElseWith (fun () -> defaultTraverse valSig) + + member _.VisitSimplePats(path, _pat) = + match path with + | SyntaxNode.SynMemberDefn _ as node :: path -> chooser path node + | _ -> None - /// 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>) = - traverseUntil pick pos visitor parseTree + member _.VisitInterfaceSynMemberDefnType(path, _synType) = + match path with + | SyntaxNode.SynMemberDefn _ as node :: path -> chooser path node + | _ -> None + } + + SyntaxTraversal.traverseUntil SyntaxTraversal.pick position visitor parsedInput.Contents + + let tryPickLast chooser position (parsedInput: ParsedInput) = + (None, parsedInput.Contents) + ||> foldWhileImpl SyntaxTraversal.pick position (fun prev path node -> + match chooser path node with + | Some _ as next -> Some next + | None -> Some prev) + + let tryNode position (parsedInput: ParsedInput) = + let Matching = Some + + (None, parsedInput.Contents) + ||> foldWhileImpl SyntaxTraversal.pick position (fun _prev path node -> + if rangeContainsPos node.Range position then + Some(Matching(node, path)) + else + None) + + let exists predicate position parsedInput = + tryPick (fun path node -> if predicate path node then Some() else None) position parsedInput + |> Option.isSome diff --git a/src/Compiler/Service/ServiceParseTreeWalk.fsi b/src/Compiler/Service/ServiceParseTreeWalk.fsi index ef118baf12e..86ca17380ee 100644 --- a/src/Compiler/Service/ServiceParseTreeWalk.fsi +++ b/src/Compiler/Service/ServiceParseTreeWalk.fsi @@ -5,7 +5,7 @@ namespace FSharp.Compiler.Syntax open FSharp.Compiler.Syntax open FSharp.Compiler.Text -/// Used to track route during traversal of syntax using SyntaxTraversal.Traverse +/// Represents a major syntax node in the untyped abstract syntax tree. [] type SyntaxNode = | SynPat of SynPat @@ -23,6 +23,11 @@ type SyntaxNode = | SynTypeDefnSig of SynTypeDefnSig | SynMemberSig of SynMemberSig + /// The range of the syntax node, inclusive of its contents. + member Range: range + +/// Represents the set of ancestor nodes traversed before reaching +/// the current node in a traversal of the untyped abstract syntax tree. type SyntaxVisitorPath = SyntaxNode list [] @@ -152,8 +157,8 @@ type SyntaxVisitorBase<'T> = default VisitRecordField: path: SyntaxVisitorPath * copyOpt: SynExpr option * recordField: SynLongIdent option -> 'T option - abstract VisitSimplePats: path: SyntaxVisitorPath * synPats: SynSimplePat list -> 'T option - default VisitSimplePats: path: SyntaxVisitorPath * synPats: SynSimplePat list -> 'T option + abstract VisitSimplePats: path: SyntaxVisitorPath * pat: SynPat -> 'T option + default VisitSimplePats: path: SyntaxVisitorPath * pat: SynPat -> 'T option abstract VisitType: path: SyntaxVisitorPath * defaultTraverse: (SynType -> 'T option) * synType: SynType -> 'T option @@ -199,6 +204,157 @@ module public SyntaxTraversal = val internal pick: pos: pos -> outerRange: range -> debugObj: obj -> diveResults: (range * (unit -> 'a option)) list -> 'a option - val internal traverseAll: visitor: SyntaxVisitorBase<'T> -> parseTree: ParsedInput -> unit - val Traverse: pos: pos * parseTree: ParsedInput * visitor: SyntaxVisitorBase<'T> -> 'T option + +/// +/// Holds operations for working with s +/// in the untyped abstract syntax tree (AST). +/// +[] +[] +module SyntaxNode = + /// + /// Extracts the , if any, + /// from the given . + /// + val (|Attributes|): node: SyntaxNode -> SynAttributes + +/// +/// Holds operations for working with the +/// untyped abstract syntax tree (). +/// +[] +[] +module ParsedInput = + /// + /// Applies the given predicate to each node of the AST and its context (path) + /// down to a given position, returning true if a matching node is found, otherwise false. + /// Traversal is short-circuited if no matching node is found through the given position. + /// + /// The predicate to match each node against. + /// The position in the input file down to which to apply the function. + /// The AST to search. + /// True if a matching node is found, or false if no matching node is found. + /// + /// + /// let isInTypeDefn = + /// (pos, parsedInput) + /// ||> ParsedInput.exists (fun _path node -> + /// match node with + /// | SyntaxNode.SynTypeDefn _ -> true + /// | _ -> false) + /// + /// + val exists: + predicate: (SyntaxVisitorPath -> SyntaxNode -> bool) -> position: pos -> parsedInput: ParsedInput -> bool + + /// + /// Applies a function to each node of the AST and its context (path), + /// threading an accumulator through the computation. + /// + /// The function to use to update the state given each node and its context. + /// The initial state. + /// The AST to fold over. + /// The final state. + /// + /// + /// let unnecessaryParentheses = + /// (HashSet Range.comparer, parsedInput) ||> ParsedInput.fold (fun acc path node -> + /// match node with + /// | SyntaxNode.SynExpr (SynExpr.Paren (expr = inner; rightParenRange = Some _; range = range)) when + /// not (SynExpr.shouldBeParenthesizedInContext getLineString path inner) + /// -> + /// ignore (acc.Add range) + /// acc + /// + /// | SyntaxNode.SynPat (SynPat.Paren (inner, range)) when + /// not (SynPat.shouldBeParenthesizedInContext path inner) + /// -> + /// ignore (acc.Add range) + /// acc + /// + /// | _ -> acc) + /// + /// + val fold: + folder: ('State -> SyntaxVisitorPath -> SyntaxNode -> 'State) -> + state: 'State -> + parsedInput: ParsedInput -> + 'State + + /// + /// Applies a function to each node of the AST and its context (path) + /// until the folder returns None, threading an accumulator through the computation. + /// + /// The function to use to update the state given each node and its context, or to stop traversal by returning None. + /// The initial state. + /// The AST to fold over. + /// The final state. + val foldWhile: + folder: ('State -> SyntaxVisitorPath -> SyntaxNode -> 'State option) -> + state: 'State -> + parsedInput: ParsedInput -> + 'State + + /// + /// Dives to the deepest node that contains the given position, + /// returning the node and its path if found, or None if no + /// node contains the position. + /// + /// The position in the input file down to which to dive. + /// The AST to search. + /// The deepest node containing the given position, along with the path taken through the node's ancestors to find it. + val tryNode: position: pos -> parsedInput: ParsedInput -> (SyntaxNode * SyntaxVisitorPath) option + + /// + /// Applies the given function to each node of the AST and its context (path) + /// down to a given position, returning Some x for the first node + /// for which the function returns Some x for some value x, otherwise None. + /// Traversal is short-circuited if no matching node is found through the given position. + /// + /// The function to apply to each node and its context to derive an optional value. + /// The position in the input file down to which to apply the function. + /// The AST to search. + /// The first value for which the function returns Some, or None if no matching node is found. + /// + /// + /// let range = + /// (pos, parsedInput) ||> ParsedInput.tryPick (fun _path node -> + /// match node with + /// | SyntaxNode.SynExpr (SynExpr.InterpolatedString (range = range)) when + /// rangeContainsPos range pos + /// -> Some range + /// | _ -> None) + /// + /// + val tryPick: + chooser: (SyntaxVisitorPath -> SyntaxNode -> 'T option) -> + position: pos -> + parsedInput: ParsedInput -> + 'T option + + /// + /// Applies the given function to each node of the AST and its context (path) + /// down to a given position, returning Some x for the last (deepest) node + /// for which the function returns Some x for some value x, otherwise None. + /// Traversal is short-circuited if no matching node is found through the given position. + /// + /// The function to apply to each node and its context to derive an optional value. + /// The position in the input file down to which to apply the function. + /// The AST to search. + /// The last (deepest) value for which the function returns Some, or None if no matching node is found. + /// + /// + /// let range = + /// (pos, parsedInput) + /// ||> ParsedInput.tryPickLast (fun path node -> + /// match node, path with + /// | FuncIdent range -> Some range + /// | _ -> None) + /// + /// + val tryPickLast: + chooser: (SyntaxVisitorPath -> SyntaxNode -> 'T option) -> + position: pos -> + parsedInput: ParsedInput -> + 'T option diff --git a/src/Compiler/Service/ServiceParsedInputOps.fs b/src/Compiler/Service/ServiceParsedInputOps.fs index 421ccc3fb0d..617cd2bdf00 100644 --- a/src/Compiler/Service/ServiceParsedInputOps.fs +++ b/src/Compiler/Service/ServiceParsedInputOps.fs @@ -891,9 +891,8 @@ module ParsedInput = | None, Some binding -> walkBinding binding | Some getBinding, Some setBinding -> walkBinding getBinding |> Option.orElseWith (fun () -> walkBinding setBinding) - | SynMemberDefn.ImplicitCtor(attributes = Attributes attrs; ctorArgs = SynSimplePats.SimplePats(pats = simplePats)) -> - List.tryPick walkAttribute attrs - |> Option.orElseWith (fun () -> List.tryPick walkSimplePat simplePats) + | SynMemberDefn.ImplicitCtor(attributes = Attributes attrs; ctorArgs = pat) -> + List.tryPick walkAttribute attrs |> Option.orElseWith (fun _ -> walkPat pat) | SynMemberDefn.ImplicitInherit(t, e, _, _) -> walkType t |> Option.orElseWith (fun () -> walkExpr e) @@ -1580,25 +1579,36 @@ module ParsedInput = | [] when range.StartLine = pos.Line -> Some CompletionContext.Invalid | _ -> None - member _.VisitSimplePats(_, pats) = + member _.VisitSimplePats(_, pat) = // Lambdas and their patterns are processed above in VisitExpr, // so VisitSimplePats is only called for primary constructors - pats - |> List.tryPick (fun pat -> - match pat with - // type C (x| ) - | SynSimplePat.Id(range = range) when rangeContainsPos range pos -> Some CompletionContext.Invalid - | SynSimplePat.Typed(pat = SynSimplePat.Id(range = idRange); targetType = synType) -> - // type C (x|: int) -> - if rangeContainsPos idRange pos then - Some CompletionContext.Invalid - // type C (x: int|) -> - elif rangeContainsPos synType.Range pos then - Some CompletionContext.Type - else - None - | _ -> None) + let rec loop (pat: SynPat) = + if not (rangeContainsPos pat.Range pos) then + None + else + + match pat with + // type C (x{caret} ) + | SynPat.Named _ + | SynPat.Const(SynConst.Unit, _) -> Some CompletionContext.Invalid + + | SynPat.Attrib(pat, _, _) + | SynPat.Paren(pat, _) -> loop pat + + | SynPat.Tuple(_, pats, _, _) -> List.tryPick loop pats + + | SynPat.Typed(pat, synType, _) -> + // type C (x: int{caret}) -> + if rangeContainsPos synType.Range pos then + Some CompletionContext.Type + else + // type C (x{caret}: int) -> + loop pat + + | _ -> None + + loop pat member _.VisitPat(_, defaultTraverse, pat) = TryGetCompletionContextInPattern false pat None pos @@ -2091,9 +2101,9 @@ module ParsedInput = | SynMemberDefn.GetSetMember(getBinding, setBinding, _, _) -> Option.iter walkBinding getBinding Option.iter walkBinding setBinding - | SynMemberDefn.ImplicitCtor(attributes = Attributes attrs; ctorArgs = SynSimplePats.SimplePats(pats = simplePats)) -> + | SynMemberDefn.ImplicitCtor(attributes = Attributes attrs; ctorArgs = pat) -> List.iter walkAttribute attrs - List.iter walkSimplePat simplePats + walkPat pat | SynMemberDefn.ImplicitInherit(t, e, _, _) -> walkType t walkExpr e diff --git a/src/Compiler/Service/SynExpr.fs b/src/Compiler/Service/SynExpr.fs new file mode 100644 index 00000000000..0df9a1a1c17 --- /dev/null +++ b/src/Compiler/Service/SynExpr.fs @@ -0,0 +1,931 @@ +namespace FSharp.Compiler.Syntax + +open System +open FSharp.Compiler.SyntaxTrivia +open FSharp.Compiler.Text + +[] +[] +module SynExpr = + let (|Last|) = List.last + + /// Matches if the two values refer to the same object. + [] + let inline (|Is|_|) (inner1: 'a) (inner2: 'a) = + if obj.ReferenceEquals(inner1, inner2) then + ValueSome Is + else + ValueNone + + /// Represents a symbolic infix operator with the precedence of *, /, or %. + /// All instances of this type are considered equal. + [] + type MulDivMod = + | Mul + | Div + | Mod + + member _.CompareTo(_other: MulDivMod) = 0 + override this.Equals obj = this.CompareTo(unbox obj) = 0 + override _.GetHashCode() = 0 + + interface IComparable with + member this.CompareTo obj = this.CompareTo(unbox obj) + + /// Represents a symbolic infix operator with the precedence of + or -. + /// All instances of this type are considered equal. + [] + type AddSub = + | Add + | Sub + + member _.CompareTo(_other: AddSub) = 0 + override this.Equals obj = this.CompareTo(unbox obj) = 0 + override _.GetHashCode() = 0 + + interface IComparable with + member this.CompareTo obj = this.CompareTo(unbox obj) + + /// Holds a symbolic operator's original notation. + /// Equality is based on the contents of the string. + /// Comparison always returns 0. + [] + type OriginalNotation = + | OriginalNotation of string + + member _.CompareTo(_other: OriginalNotation) = 0 + + override this.Equals obj = + match this, obj with + | OriginalNotation this, (:? OriginalNotation as OriginalNotation other) -> String.Equals(this, other, StringComparison.Ordinal) + | _ -> false + + override this.GetHashCode() = + match this with + | OriginalNotation notation -> notation.GetHashCode() + + interface IComparable with + member this.CompareTo obj = this.CompareTo(unbox obj) + + /// Represents an expression's precedence. + /// Comparison is based only on the precedence case. + /// Equality considers the embedded original notation, if any. + /// + /// For example: + /// + /// compare (AddSub (Add, OriginalNotation "+")) (AddSub (Add, OriginalNotation "++")) = 0 + /// + /// but + /// + /// AddSub (Add, OriginalNotation "+") <> AddSub (Add, OriginalNotation "++") + type Precedence = + /// yield, yield!, return, return! + | Low + + /// <- + | Set + + /// := + | ColonEquals + + /// , + | Comma + + /// or, || + /// + /// Refers to the exact operators or and ||. + /// Instances with leading dots or question marks or trailing characters are parsed as Bar instead. + | BarBar of OriginalNotation + + /// &, && + /// + /// Refers to the exact operators & and &&. + /// Instances with leading dots or question marks or trailing characters are parsed as Amp instead. + | AmpAmp of OriginalNotation + + /// :>, :?> + | UpcastDowncast + + /// =…, |…, &…, $…, >…, <…, !=… + | Relational of OriginalNotation + + /// ^…, @… + | HatAt + + /// :: + | Cons + + /// :? + | TypeTest + + /// +…, -… + | AddSub of AddSub * OriginalNotation + + /// *…, /…, %… + | MulDivMod of MulDivMod * OriginalNotation + + /// **… + | Exp + + /// - x + | UnaryPrefix + + /// f x + | Apply + + /// -x, !… x, ~~… x + | High + + // x.y + | Dot + + /// Associativity/association. + type Assoc = + /// Non-associative or no association. + | Non + + /// Left-associative or left-hand association. + | Left + + /// Right-associative or right-hand association. + | Right + + module Assoc = + let ofPrecedence precedence = + match precedence with + | Low -> Non + | Set -> Non + | ColonEquals -> Right + | Comma -> Non + | BarBar _ -> Left + | AmpAmp _ -> Left + | UpcastDowncast -> Right + | Relational _ -> Left + | HatAt -> Right + | Cons -> Right + | TypeTest -> Non + | AddSub _ -> Left + | MulDivMod _ -> Left + | Exp -> Right + | UnaryPrefix -> Left + | Apply -> Left + | High -> Left + | Dot -> Left + + /// See atomicExprAfterType in pars.fsy. + [] + let (|AtomicExprAfterType|_|) expr = + match expr with + | SynExpr.Paren _ + | SynExpr.Quote _ + | SynExpr.Const _ + | SynExpr.Tuple(isStruct = true) + | SynExpr.Record _ + | SynExpr.AnonRecd _ + | SynExpr.InterpolatedString _ + | SynExpr.Null _ + | SynExpr.ArrayOrList(isArray = true) + | SynExpr.ArrayOrListComputed(isArray = true) -> ValueSome AtomicExprAfterType + | _ -> ValueNone + + /// Matches if the given expression represents a high-precedence + /// function application, e.g., + /// + /// f x + /// + /// (+) x y + [] + let (|HighPrecedenceApp|_|) expr = + match expr with + | SynExpr.App(isInfix = false; funcExpr = SynExpr.Ident _) + | SynExpr.App(isInfix = false; funcExpr = SynExpr.LongIdent _) + | SynExpr.App(isInfix = false; funcExpr = SynExpr.App(isInfix = false)) -> ValueSome HighPrecedenceApp + | _ -> ValueNone + + module FuncExpr = + /// Matches when the given funcExpr is a direct application + /// of a symbolic operator, e.g., -, _not_ (~-). + [] + let (|SymbolicOperator|_|) funcExpr = + match funcExpr with + | SynExpr.LongIdent(longDotId = SynLongIdent(trivia = trivia)) -> + let rec tryPick = + function + | [] -> ValueNone + | Some(IdentTrivia.OriginalNotation op) :: _ -> ValueSome op + | _ :: rest -> tryPick rest + + tryPick trivia + | _ -> ValueNone + + /// Matches when the given expression is a prefix operator application, e.g., + /// + /// -x + /// + /// ~~~x + [] + let (|PrefixApp|_|) expr : Precedence voption = + match expr with + | SynExpr.App(isInfix = false; funcExpr = funcExpr & FuncExpr.SymbolicOperator op; argExpr = argExpr) -> + if funcExpr.Range.IsAdjacentTo argExpr.Range then + ValueSome High + else + assert (op.Length > 0) + + match op[0] with + | '!' + | '~' -> ValueSome High + | _ -> ValueSome UnaryPrefix + + | SynExpr.AddressOf(expr = expr; opRange = opRange) -> + if opRange.IsAdjacentTo expr.Range then + ValueSome High + else + ValueSome UnaryPrefix + + | _ -> ValueNone + + /// Tries to parse the given original notation as a symbolic infix operator. + [] + let (|SymbolPrec|_|) (originalNotation: string) = + // Trim any leading dots or question marks from the given symbolic operator. + // Leading dots or question marks have no effect on operator precedence or associativity + // with the exception of &, &&, and ||. + let ignoredLeadingChars = ".?".AsSpan() + let trimmed = originalNotation.AsSpan().TrimStart ignoredLeadingChars + assert (trimmed.Length > 0) + + match trimmed[0], originalNotation with + | _, ":=" -> ValueSome ColonEquals + | _, ("||" | "or") -> ValueSome(BarBar(OriginalNotation originalNotation)) + | _, ("&" | "&&") -> ValueSome(AmpAmp(OriginalNotation originalNotation)) + | '|', _ + | '&', _ + | '<', _ + | '>', _ + | '=', _ + | '$', _ -> ValueSome(Relational(OriginalNotation originalNotation)) + | '!', _ when trimmed.Length > 1 && trimmed[1] = '=' -> ValueSome(Relational(OriginalNotation originalNotation)) + | '^', _ + | '@', _ -> ValueSome HatAt + | _, "::" -> ValueSome Cons + | '+', _ -> ValueSome(AddSub(Add, OriginalNotation originalNotation)) + | '-', _ -> ValueSome(AddSub(Sub, OriginalNotation originalNotation)) + | '/', _ -> ValueSome(MulDivMod(Div, OriginalNotation originalNotation)) + | '%', _ -> ValueSome(MulDivMod(Mod, OriginalNotation originalNotation)) + | '*', _ when trimmed.Length > 1 && trimmed[1] = '*' -> ValueSome Exp + | '*', _ -> ValueSome(MulDivMod(Mul, OriginalNotation originalNotation)) + | _ -> ValueNone + + [] + let (|Contains|_|) (c: char) (s: string) = + if s.IndexOf c >= 0 then ValueSome Contains else ValueNone + + /// Any expressions in which the removal of parens would + /// lead to something like the following that would be + /// confused by the parser with a type parameter application: + /// + /// xz + /// + /// xz + [] + let rec (|ConfusableWithTypeApp|_|) synExpr = + match synExpr with + | SynExpr.Paren(expr = ConfusableWithTypeApp) + | SynExpr.App(funcExpr = ConfusableWithTypeApp) + | SynExpr.App(isInfix = true; funcExpr = FuncExpr.SymbolicOperator(Contains '>'); argExpr = ConfusableWithTypeApp) -> + ValueSome ConfusableWithTypeApp + | SynExpr.App(isInfix = true; funcExpr = funcExpr & FuncExpr.SymbolicOperator(Contains '<'); argExpr = argExpr) when + argExpr.Range.IsAdjacentTo funcExpr.Range + -> + ValueSome ConfusableWithTypeApp + | SynExpr.Tuple(exprs = exprs) -> + let rec anyButLast = + function + | _ :: [] + | [] -> ValueNone + | ConfusableWithTypeApp :: _ -> ValueSome ConfusableWithTypeApp + | _ :: tail -> anyButLast tail + + anyButLast exprs + | _ -> ValueNone + + /// Matches when the expression represents the infix application of a symbolic operator. + /// + /// (x λ y) ρ z + /// + /// x λ (y ρ z) + [] + let (|InfixApp|_|) synExpr : struct (Precedence * Assoc) voption = + match synExpr with + | SynExpr.App(funcExpr = SynExpr.App(isInfix = true; funcExpr = FuncExpr.SymbolicOperator(SymbolPrec prec))) -> + ValueSome(prec, Right) + | SynExpr.App(isInfix = true; funcExpr = FuncExpr.SymbolicOperator(SymbolPrec prec)) -> ValueSome(prec, Left) + | SynExpr.Upcast _ + | SynExpr.Downcast _ -> ValueSome(UpcastDowncast, Left) + | SynExpr.TypeTest _ -> ValueSome(TypeTest, Left) + | _ -> ValueNone + + /// Returns the given expression's precedence and the side of the inner expression, + /// if applicable. + [] + let (|OuterBinaryExpr|_|) inner outer : struct (Precedence * Assoc) voption = + match outer with + | SynExpr.YieldOrReturn _ + | SynExpr.YieldOrReturnFrom _ -> ValueSome(Low, Right) + | SynExpr.Tuple(exprs = SynExpr.Paren(expr = Is inner) :: _) -> ValueSome(Comma, Left) + | SynExpr.Tuple _ -> ValueSome(Comma, Right) + | InfixApp(Cons, side) -> ValueSome(Cons, side) + | SynExpr.Assert _ + | SynExpr.Lazy _ + | SynExpr.InferredUpcast _ + | SynExpr.InferredDowncast _ -> ValueSome(Apply, Non) + | PrefixApp prec -> ValueSome(prec, Non) + | InfixApp(prec, side) -> ValueSome(prec, side) + | SynExpr.App(argExpr = SynExpr.ComputationExpr _) -> ValueSome(UnaryPrefix, Left) + | SynExpr.App(funcExpr = SynExpr.Paren(expr = SynExpr.App _)) -> ValueSome(Apply, Left) + | SynExpr.App _ -> ValueSome(Apply, Non) + | SynExpr.DotSet(targetExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left) + | SynExpr.DotSet(rhsExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right) + | SynExpr.DotIndexedSet(objectExpr = SynExpr.Paren(expr = Is inner)) + | SynExpr.DotNamedIndexedPropertySet(targetExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left) + | SynExpr.DotIndexedSet(valueExpr = SynExpr.Paren(expr = Is inner)) + | SynExpr.DotNamedIndexedPropertySet(rhsExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right) + | SynExpr.LongIdentSet(expr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right) + | SynExpr.Set _ -> ValueSome(Set, Non) + | SynExpr.DotGet _ -> ValueSome(Dot, Left) + | SynExpr.DotIndexedGet(objectExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left) + | _ -> ValueNone + + /// Matches a SynExpr.App nested in a sequence of dot-gets. + /// + /// x.M.N().O + [] + let (|NestedApp|_|) expr = + let rec loop = + function + | SynExpr.DotGet(expr = expr) + | SynExpr.DotIndexedGet(objectExpr = expr) -> loop expr + | SynExpr.App _ -> ValueSome NestedApp + | _ -> ValueNone + + loop expr + + /// Returns the given expression's precedence, if applicable. + [] + let (|InnerBinaryExpr|_|) expr : Precedence voption = + match expr with + | SynExpr.Tuple(isStruct = false) -> ValueSome Comma + | SynExpr.DotGet(expr = NestedApp) + | SynExpr.DotIndexedGet(objectExpr = NestedApp) -> ValueSome Apply + | SynExpr.DotGet _ + | SynExpr.DotIndexedGet _ -> ValueSome Dot + | PrefixApp prec -> ValueSome prec + | InfixApp(prec, _) -> ValueSome prec + | SynExpr.App _ + | SynExpr.Assert _ + | SynExpr.Lazy _ + | SynExpr.For _ + | SynExpr.ForEach _ + | SynExpr.While _ + | SynExpr.Do _ + | SynExpr.New _ + | SynExpr.InferredUpcast _ + | SynExpr.InferredDowncast _ -> ValueSome Apply + | SynExpr.DotIndexedSet _ + | SynExpr.DotNamedIndexedPropertySet _ + | SynExpr.DotSet _ -> ValueSome Set + | _ -> ValueNone + + module Dangling = + /// Returns the first matching nested right-hand target expression, if any. + let private dangling (target: SynExpr -> SynExpr option) = + let (|Target|_|) = target + + let rec loop expr = + match expr with + | Target expr -> ValueSome expr + | SynExpr.Tuple(isStruct = false; exprs = Last expr) + | SynExpr.App(argExpr = expr) + | SynExpr.IfThenElse(elseExpr = Some expr) + | SynExpr.IfThenElse(ifExpr = expr) + | SynExpr.Sequential(expr2 = expr) + | SynExpr.YieldOrReturn(expr = expr) + | SynExpr.YieldOrReturnFrom(expr = expr) + | SynExpr.Set(rhsExpr = expr) + | SynExpr.DotSet(rhsExpr = expr) + | SynExpr.DotNamedIndexedPropertySet(rhsExpr = expr) + | SynExpr.DotIndexedSet(valueExpr = expr) + | SynExpr.LongIdentSet(expr = expr) + | SynExpr.LetOrUse(body = expr) + | SynExpr.Lambda(body = expr) + | SynExpr.Match(clauses = Last(SynMatchClause(resultExpr = expr))) + | SynExpr.MatchLambda(matchClauses = Last(SynMatchClause(resultExpr = expr))) + | SynExpr.MatchBang(clauses = Last(SynMatchClause(resultExpr = expr))) + | SynExpr.TryWith(withCases = Last(SynMatchClause(resultExpr = expr))) + | SynExpr.TryFinally(finallyExpr = expr) -> loop expr + | _ -> ValueNone + + loop + + /// Matches a dangling if-then construct. + [] + let (|IfThen|_|) = + dangling (function + | SynExpr.IfThenElse _ as expr -> Some expr + | _ -> None) + + /// Matches a dangling sequential expression. + [] + let (|Sequential|_|) = + dangling (function + | SynExpr.Sequential _ as expr -> Some expr + | _ -> None) + + /// Matches a dangling try-with or try-finally construct. + [] + let (|Try|_|) = + dangling (function + | SynExpr.TryWith _ + | SynExpr.TryFinally _ as expr -> Some expr + | _ -> None) + + /// Matches a dangling match-like construct. + [] + let (|Match|_|) = + dangling (function + | SynExpr.Match _ + | SynExpr.MatchBang _ + | SynExpr.MatchLambda _ + | SynExpr.TryWith _ + | SynExpr.Lambda _ as expr -> Some expr + | _ -> None) + + /// Matches a nested dangling construct that could become problematic + /// if the surrounding parens were removed. + [] + let (|Problematic|_|) = + dangling (function + | SynExpr.Lambda _ + | SynExpr.MatchLambda _ + | SynExpr.Match _ + | SynExpr.MatchBang _ + | SynExpr.TryWith _ + | SynExpr.TryFinally _ + | SynExpr.IfThenElse _ + | SynExpr.Sequential _ + | SynExpr.LetOrUse _ + | SynExpr.Set _ + | SynExpr.LongIdentSet _ + | SynExpr.DotIndexedSet _ + | SynExpr.DotNamedIndexedPropertySet _ + | SynExpr.DotSet _ + | SynExpr.NamedIndexedPropertySet _ as expr -> Some expr + | _ -> None) + + /// Indicates whether the expression with the given range + /// includes indentation that would be invalid + /// in context if it were not wrapped in parentheses. + let containsSensitiveIndentation (getSourceLineStr: int -> string) outerOffsidesColumn (range: range) = + let startLine = range.StartLine + let endLine = range.EndLine + + if startLine = endLine then + range.StartColumn <= outerOffsidesColumn + else + let rec loop offsides lineNo startCol = + if lineNo <= endLine then + let line = getSourceLineStr lineNo + + match offsides with + | ValueNone -> + let i = line.AsSpan(startCol).IndexOfAnyExcept(' ', ')') + + if i >= 0 then + let newOffsides = i + startCol + + newOffsides <= outerOffsidesColumn + || loop (ValueSome newOffsides) (lineNo + 1) 0 + else + loop offsides (lineNo + 1) 0 + + | ValueSome offsidesCol -> + let i = line.AsSpan(0, min offsidesCol line.Length).IndexOfAnyExcept(' ', ')') + + if i >= 0 && i < offsidesCol then + let slice = line.AsSpan(i, min (offsidesCol - i) (line.Length - i)) + let j = slice.IndexOfAnyExcept("*/%-+:^@><=!|0$.?".AsSpan()) + + let lo = i + (if j >= 0 && slice[j] = ' ' then j else 0) + + lo < offsidesCol - 1 + || lo <= outerOffsidesColumn + || loop offsides (lineNo + 1) 0 + else + loop offsides (lineNo + 1) 0 + else + false + + loop ValueNone startLine range.StartColumn + + let rec shouldBeParenthesizedInContext (getSourceLineStr: int -> string) path expr : bool = + let shouldBeParenthesizedInContext = shouldBeParenthesizedInContext getSourceLineStr + let containsSensitiveIndentation = containsSensitiveIndentation getSourceLineStr + + // Matches if the given expression starts with a symbol, e.g., <@ … @>, $"…", @"…", +1, -1… + let (|StartsWithSymbol|_|) = + let (|TextStartsWith|) (m: range) = + let line = getSourceLineStr m.StartLine + line[m.StartColumn] + + let (|StartsWith|) (s: string) = s[0] + + function + | SynExpr.Quote _ + | SynExpr.InterpolatedString _ + | SynExpr.Const(SynConst.String(synStringKind = SynStringKind.Verbatim), _) + | SynExpr.Const(SynConst.Byte _, TextStartsWith '+') + | SynExpr.Const(SynConst.UInt16 _, TextStartsWith '+') + | SynExpr.Const(SynConst.UInt32 _, TextStartsWith '+') + | SynExpr.Const(SynConst.UInt64 _, TextStartsWith '+') + | SynExpr.Const(SynConst.UIntPtr _, TextStartsWith '+') + | SynExpr.Const(SynConst.SByte _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.Int16 _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.Int32 _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.Int64 _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.IntPtr _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.Decimal _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.Double _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.Single _, TextStartsWith('-' | '+')) + | SynExpr.Const(SynConst.Measure(_, TextStartsWith('-' | '+'), _, _), _) + | SynExpr.Const(SynConst.UserNum(StartsWith('-' | '+'), _), _) -> Some StartsWithSymbol + | _ -> None + + // Matches if the given expression is a numeric literal + // that it is safe to "dot into," e.g., 1l, 0b1, 1e10, 1d, 1.0… + let (|DotSafeNumericLiteral|_|) = + /// 1l, 1d, 0b1, 0x1, 0o1, 1e10… + let (|TextContainsLetter|_|) (m: range) = + let line = getSourceLineStr m.StartLine + let span = line.AsSpan(m.StartColumn, m.EndColumn - m.StartColumn) + + if span.LastIndexOfAnyInRange('A', 'z') >= 0 then + Some TextContainsLetter + else + None + + // 1.0… + let (|TextEndsWithNumber|_|) (m: range) = + let line = getSourceLineStr m.StartLine + let span = line.AsSpan(m.StartColumn, m.EndColumn - m.StartColumn) + + if Char.IsDigit span[span.Length - 1] then + Some TextEndsWithNumber + else + None + + function + | SynExpr.Const(SynConst.Byte _, _) + | SynExpr.Const(SynConst.UInt16 _, _) + | SynExpr.Const(SynConst.UInt32 _, _) + | SynExpr.Const(SynConst.UInt64 _, _) + | SynExpr.Const(SynConst.UIntPtr _, _) + | SynExpr.Const(SynConst.SByte _, _) + | SynExpr.Const(SynConst.Int16 _, _) + | SynExpr.Const(SynConst.Int32 _, TextContainsLetter) + | SynExpr.Const(SynConst.Int64 _, _) + | SynExpr.Const(SynConst.IntPtr _, _) + | SynExpr.Const(SynConst.Decimal _, _) + | SynExpr.Const(SynConst.Double _, (TextEndsWithNumber | TextContainsLetter)) + | SynExpr.Const(SynConst.Single _, _) + | SynExpr.Const(SynConst.Measure _, _) + | SynExpr.Const(SynConst.UserNum _, _) -> Some DotSafeNumericLiteral + | _ -> None + + match expr, path with + // Parens must stay around binary equals expressions in argument + // position lest they be interpreted as named argument assignments: + // + // o.M((x = y)) + // o.N((x = y), z) + | SynExpr.Paren(expr = InfixApp(Relational(OriginalNotation "="), _)), + SyntaxNode.SynExpr(SynExpr.App(funcExpr = SynExpr.LongIdent _)) :: _ + | InfixApp(Relational(OriginalNotation "="), _), + SyntaxNode.SynExpr(SynExpr.Paren _) :: SyntaxNode.SynExpr(SynExpr.App(funcExpr = SynExpr.LongIdent _)) :: _ + | InfixApp(Relational(OriginalNotation "="), _), + SyntaxNode.SynExpr(SynExpr.Tuple(isStruct = false)) :: SyntaxNode.SynExpr(SynExpr.Paren _) :: SyntaxNode.SynExpr(SynExpr.App( + funcExpr = SynExpr.LongIdent _)) :: _ -> true + + // Already parenthesized. + | _, SyntaxNode.SynExpr(SynExpr.Paren _) :: _ -> false + + // Parens must stay around indentation that would otherwise be invalid: + // + // let _ = (x + // +y) + | _, SyntaxNode.SynBinding(SynBinding(trivia = trivia)) :: _ when + containsSensitiveIndentation trivia.LeadingKeyword.Range.StartColumn expr.Range + -> + true + + // Parens must stay around indentation that would otherwise be invalid: + // + // return ( + // x + // ) + | _, SyntaxNode.SynExpr outer :: _ when containsSensitiveIndentation outer.Range.StartColumn expr.Range -> true + + // Check for nested matches, e.g., + // + // match … with … -> (…, match … with … -> … | … -> …) | … -> … + | _, SyntaxNode.SynMatchClause _ :: path -> shouldBeParenthesizedInContext path expr + + // We always need parens for trait calls, e.g., + // + // let inline f x = (^a : (static member Parse : string -> ^a) x) + | SynExpr.TraitCall _, _ -> true + + // Don't touch library-only stuff: + // + // (# "ldlen.multi 2 0" array : int #) + | SynExpr.LibraryOnlyILAssembly _, _ + | SynExpr.LibraryOnlyStaticOptimization _, _ + | SynExpr.LibraryOnlyUnionCaseFieldGet _, _ + | SynExpr.LibraryOnlyUnionCaseFieldSet _, _ -> true + + // Parens are otherwise never required for binding bodies or for top-level expressions, e.g., + // + // let x = (…) + // _.member X = (…) + // (printfn "Hello, world.") + | _, SyntaxNode.SynBinding _ :: _ + | _, SyntaxNode.SynModule _ :: _ -> false + + // Parens must be kept when there is a high-precedence function application + // before a prefix operator application before another expression that starts with a symbol, e.g., + // + // id -(-x) + // id -(-1y) + // id -($"") + // id -(@"") + // id -(<@ ValueNone @>) + // let (~+) _ = true in assert +($"{true}") + | (PrefixApp _ | StartsWithSymbol), + SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(HighPrecedenceApp | SynExpr.Assert _ | SynExpr.InferredUpcast _ | SynExpr.InferredDowncast _) :: _ -> + true + + // Parens are never required around suffixed or infixed numeric literals, e.g., + // + // (1l).ToString() + // (1uy).ToString() + // (0b1).ToString() + // (1e10).ToString() + // (1.0).ToString() + | DotSafeNumericLiteral, _ -> false + + // Parens are required around bare decimal ints or doubles ending + // in dots when being dotted into, e.g., + // + // (1).ToString() + // (1.).ToString() + | SynExpr.Const(constant = SynConst.Int32 _ | SynConst.Double _), SyntaxNode.SynExpr(SynExpr.DotGet _) :: _ -> true + + // Parens are required around join conditions: + // + // join … on (… = …) + | SynExpr.App _, SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(SynExpr.JoinIn _) :: _ -> true + + // Parens are not required around a few anointed expressions after inherit: + // + // inherit T(3) + // inherit T(null) + // inherit T("") + // … + | AtomicExprAfterType, SyntaxNode.SynMemberDefn(SynMemberDefn.ImplicitInherit _) :: _ -> false + + // Parens are otherwise required in inherit T(x), etc. + | _, SyntaxNode.SynMemberDefn(SynMemberDefn.ImplicitInherit _) :: _ -> true + + // We can't remove parens when they're required for fluent calls: + // + // x.M(y).N z + // x.M(y).[z] + // _.M(x) + // (f x)[z] + // (f(x))[z] + // x.M(y)[z] + | _, SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(SynExpr.DotGet _ | SynExpr.DotIndexedGet _ | SynExpr.DotLambda _) :: _ + | SynExpr.App _, SyntaxNode.SynExpr(SynExpr.App(argExpr = SynExpr.ArrayOrListComputed(isArray = false))) :: _ + | _, + SyntaxNode.SynExpr(SynExpr.App _) :: SyntaxNode.SynExpr(SynExpr.App(argExpr = SynExpr.ArrayOrListComputed(isArray = false))) :: _ -> + true + + // The :: operator is parsed differently from other symbolic infix operators, + // so we need to give it special treatment. + + // Outer right: + // + // (x) :: xs + // (x * y) :: zs + // … + | _, + SyntaxNode.SynExpr(SynExpr.Tuple(isStruct = false; exprs = [ SynExpr.Paren _; _ ])) :: (SyntaxNode.SynExpr(SynExpr.App( + isInfix = true)) :: _ as path) -> shouldBeParenthesizedInContext path expr + + // Outer left: + // + // x :: (xs) + // x :: (ys @ zs) + // … + | argExpr, + SyntaxNode.SynExpr(SynExpr.Tuple(isStruct = false; exprs = [ _; SynExpr.Paren _ ])) :: SyntaxNode.SynExpr(SynExpr.App( + isInfix = true) as outer) :: path -> + shouldBeParenthesizedInContext + (SyntaxNode.SynExpr(SynExpr.App(ExprAtomicFlag.NonAtomic, false, outer, argExpr, outer.Range)) + :: path) + expr + + // Ordinary nested expressions. + | inner, SyntaxNode.SynExpr outer :: outerPath -> + let dangling expr = + match expr with + | Dangling.Problematic subExpr -> + match outer with + | SynExpr.Tuple(exprs = exprs) -> not (obj.ReferenceEquals(subExpr, List.last exprs)) + | InfixApp(_, Left) -> true + | _ -> shouldBeParenthesizedInContext outerPath subExpr + + | _ -> false + + let problematic (exprRange: range) (delimiterRange: range) = + exprRange.EndLine = delimiterRange.EndLine + && exprRange.EndColumn < delimiterRange.StartColumn + + let anyProblematic matchOrTryRange clauses = + let rec loop = + function + | [] -> false + | SynMatchClause(trivia = trivia) :: clauses -> + trivia.BarRange |> Option.exists (problematic matchOrTryRange) + || trivia.ArrowRange |> Option.exists (problematic matchOrTryRange) + || loop clauses + + loop clauses + + match outer, inner with + | ConfusableWithTypeApp, _ -> true + + | SynExpr.IfThenElse _, Dangling.Sequential _ -> true + + | SynExpr.IfThenElse(trivia = trivia), Dangling.IfThen ifThenElse when + problematic ifThenElse.Range trivia.ThenKeyword + || trivia.ElseKeyword |> Option.exists (problematic ifThenElse.Range) + -> + true + + | SynExpr.TryFinally(trivia = trivia), Dangling.Try tryExpr when problematic tryExpr.Range trivia.FinallyKeyword -> true + + | SynExpr.Match(clauses = clauses; trivia = { WithKeyword = withKeyword }), Dangling.Match matchOrTry when + problematic matchOrTry.Range withKeyword + || anyProblematic matchOrTry.Range clauses + -> + true + + | SynExpr.MatchBang(clauses = clauses; trivia = { WithKeyword = withKeyword }), Dangling.Match matchOrTry when + problematic matchOrTry.Range withKeyword + || anyProblematic matchOrTry.Range clauses + -> + true + + | SynExpr.MatchLambda(matchClauses = clauses), Dangling.Match matchOrTry when anyProblematic matchOrTry.Range clauses -> true + + | SynExpr.TryWith(withCases = clauses; trivia = trivia), Dangling.Match matchOrTry when + problematic matchOrTry.Range trivia.WithKeyword + || anyProblematic matchOrTry.Range clauses + -> + true + + | SynExpr.Sequential(expr1 = SynExpr.Paren(expr = Is inner); expr2 = expr2), Dangling.Problematic _ when + problematic inner.Range expr2.Range + -> + true + + | SynExpr.Record(copyInfo = Some(SynExpr.Paren(expr = Is inner), _)), Dangling.Problematic _ + | SynExpr.AnonRecd(copyInfo = Some(SynExpr.Paren(expr = Is inner), _)), Dangling.Problematic _ -> true + + | SynExpr.Record(recordFields = recordFields), Dangling.Problematic _ -> + let rec loop recordFields = + match recordFields with + | [] -> false + | SynExprRecordField(expr = Some(SynExpr.Paren(expr = Is inner)); blockSeparator = Some _) :: SynExprRecordField( + fieldName = SynLongIdent(id = id :: _), _) :: _ -> problematic inner.Range id.idRange + | _ :: recordFields -> loop recordFields + + loop recordFields + + | SynExpr.AnonRecd(recordFields = recordFields), Dangling.Problematic _ -> + let rec loop recordFields = + match recordFields with + | [] -> false + | (_, Some _blockSeparator, SynExpr.Paren(expr = Is inner)) :: (SynLongIdent(id = id :: _), _, _) :: _ -> + problematic inner.Range id.idRange + | _ :: recordFields -> loop recordFields + + loop recordFields + + | SynExpr.Paren _, SynExpr.Typed _ + | SynExpr.Quote _, SynExpr.Typed _ + | SynExpr.AnonRecd _, SynExpr.Typed _ + | SynExpr.Record _, SynExpr.Typed _ + | SynExpr.While(doExpr = SynExpr.Paren(expr = Is inner)), SynExpr.Typed _ + | SynExpr.WhileBang(doExpr = SynExpr.Paren(expr = Is inner)), SynExpr.Typed _ + | SynExpr.For(doBody = Is inner), SynExpr.Typed _ + | SynExpr.ForEach(bodyExpr = Is inner), SynExpr.Typed _ + | SynExpr.Match _, SynExpr.Typed _ + | SynExpr.Do _, SynExpr.Typed _ + | SynExpr.LetOrUse(body = Is inner), SynExpr.Typed _ + | SynExpr.TryWith _, SynExpr.Typed _ + | SynExpr.TryFinally _, SynExpr.Typed _ -> false + | _, SynExpr.Typed _ -> true + + | OuterBinaryExpr inner (outerPrecedence, side), InnerBinaryExpr innerPrecedence -> + let ambiguous = + match compare outerPrecedence innerPrecedence with + | 0 -> + match side, Assoc.ofPrecedence innerPrecedence with + | Non, _ + | _, Non + | Left, Right -> true + | Right, Right + | Left, Left -> false + | Right, Left -> + outerPrecedence <> innerPrecedence + || match outerPrecedence, innerPrecedence with + | _, MulDivMod(Div, _) + | _, MulDivMod(Mod, _) + | _, AddSub(Sub, _) -> true + | Relational _, Relational _ -> true + | _ -> false + + | c -> c > 0 + + ambiguous || dangling inner + + | OuterBinaryExpr inner (_, Right), (SynExpr.Sequential _ | SynExpr.LetOrUse(trivia = { InKeyword = None })) -> true + | OuterBinaryExpr inner (_, Right), inner -> dangling inner + + // new T(expr) + | SynExpr.New _, AtomicExprAfterType -> false + | SynExpr.New _, _ -> true + + // { inherit T(expr); … } + | SynExpr.Record(baseInfo = Some(_, SynExpr.Paren(expr = Is inner), _, _, _)), AtomicExprAfterType -> false + | SynExpr.Record(baseInfo = Some(_, SynExpr.Paren(expr = Is inner), _, _, _)), _ -> true + + | _, SynExpr.Paren _ + | _, SynExpr.Quote _ + | _, SynExpr.Const _ + | _, SynExpr.Tuple(isStruct = true) + | _, SynExpr.AnonRecd _ + | _, SynExpr.ArrayOrList _ + | _, SynExpr.Record _ + | _, SynExpr.ObjExpr _ + | _, SynExpr.ArrayOrListComputed _ + | _, SynExpr.ComputationExpr _ + | _, SynExpr.TypeApp _ + | _, SynExpr.Ident _ + | _, SynExpr.LongIdent _ + | _, SynExpr.DotGet _ + | _, SynExpr.DotLambda _ + | _, SynExpr.DotIndexedGet _ + | _, SynExpr.Null _ + | _, SynExpr.InterpolatedString _ + + | SynExpr.Paren _, _ + | SynExpr.Quote _, _ + | SynExpr.Typed _, _ + | SynExpr.AnonRecd _, _ + | SynExpr.Record _, _ + | SynExpr.ObjExpr _, _ + | SynExpr.While _, _ + | SynExpr.WhileBang _, _ + | SynExpr.For _, _ + | SynExpr.ForEach _, _ + | SynExpr.Lambda _, _ + | SynExpr.MatchLambda _, _ + | SynExpr.Match _, _ + | SynExpr.MatchBang _, _ + | SynExpr.LetOrUse _, _ + | SynExpr.LetOrUseBang _, _ + | SynExpr.Sequential _, _ + | SynExpr.Do _, _ + | SynExpr.DoBang _, _ + | SynExpr.IfThenElse _, _ + | SynExpr.TryWith _, _ + | SynExpr.TryFinally _, _ + | SynExpr.ComputationExpr _, _ + | SynExpr.InterpolatedString _, _ -> false + + | _ -> true + + | _ -> true diff --git a/src/Compiler/Service/SynExpr.fsi b/src/Compiler/Service/SynExpr.fsi new file mode 100644 index 00000000000..9e74ce6c1e9 --- /dev/null +++ b/src/Compiler/Service/SynExpr.fsi @@ -0,0 +1,15 @@ +namespace FSharp.Compiler.Syntax + +[] +[] +module public SynExpr = + + /// + /// Returns true if the given expression should be parenthesized in the given context, otherwise false. + /// + /// A function for getting the text of a given source line. + /// The expression's ancestor nodes. + /// The expression to check. + /// True if the given expression should be parenthesized in the given context, otherwise false. + val shouldBeParenthesizedInContext: + getSourceLineStr: (int -> string) -> path: SyntaxVisitorPath -> expr: SynExpr -> bool diff --git a/src/Compiler/Service/SynPat.fs b/src/Compiler/Service/SynPat.fs new file mode 100644 index 00000000000..53212cf17dc --- /dev/null +++ b/src/Compiler/Service/SynPat.fs @@ -0,0 +1,253 @@ +namespace FSharp.Compiler.Syntax + +[] +[] +module SynPat = + let (|Last|) = List.last + + /// Matches if the two values refer to the same object. + [] + let inline (|Is|_|) (inner1: 'a) (inner2: 'a) = + if obj.ReferenceEquals(inner1, inner2) then + ValueSome Is + else + ValueNone + + let (|Ident|) (ident: Ident) = ident.idText + + /// Matches if any pattern in the given list is a SynPat.Typed. + [] + let (|AnyTyped|_|) pats = + if + pats + |> List.exists (function + | SynPat.Typed _ -> true + | _ -> false) + then + ValueSome AnyTyped + else + ValueNone + + /// Matches if any member in the given list is an inherit + /// or implementation of an interface with generic type args. + [] + let (|AnyGenericInheritOrInterfaceImpl|_|) members = + if + members + |> List.exists (function + | SynMemberDefn.ImplicitInherit(inheritType = SynType.App(typeArgs = _ :: _)) + | SynMemberDefn.ImplicitInherit(inheritType = SynType.LongIdentApp(typeArgs = _ :: _)) + | SynMemberDefn.Interface(interfaceType = SynType.App(typeArgs = _ :: _)) + | SynMemberDefn.Interface(interfaceType = SynType.LongIdentApp(typeArgs = _ :: _)) -> true + | _ -> false) + then + ValueSome AnyGenericInheritOrInterfaceImpl + else + ValueNone + + /// Matches the rightmost potentially dangling nested pattern. + let rec (|Rightmost|) pat = + match pat with + | SynPat.Or(rhsPat = Rightmost pat) + | SynPat.ListCons(rhsPat = Rightmost pat) + | SynPat.As(rhsPat = Rightmost pat) + | SynPat.Ands(pats = Last(Rightmost pat)) + | SynPat.Tuple(isStruct = false; elementPats = Last(Rightmost pat)) -> pat + | pat -> pat + + /// Matches if the given pattern is atomic. + [] + let (|Atomic|_|) pat = + match pat with + | SynPat.Named _ + | SynPat.Wild _ + | SynPat.Paren _ + | SynPat.Tuple(isStruct = true) + | SynPat.Record _ + | SynPat.ArrayOrList _ + | SynPat.Const _ + | SynPat.LongIdent(argPats = SynArgPats.Pats []) + | SynPat.Null _ + | SynPat.QuoteExpr _ -> ValueSome Atomic + | _ -> ValueNone + + let shouldBeParenthesizedInContext path pat : bool = + match pat, path with + // Parens are needed in: + // + // let (Pattern …) = … + // let (x: …, y…) = … + // let (x: …), (y: …) = … + // let! (x: …) = … + // and! (x: …) = … + // use! (x: …) = … + // _.member M(x: …) = … + // match … with (x: …) -> … + // match … with (x, y: …) -> … + // function (x: …) -> … + // fun (x, y, …) -> … + // fun (x: …) -> … + // fun (Pattern …) -> … + | SynPat.Typed _, SyntaxNode.SynPat(Rightmost(SynPat.Paren(Is pat, _))) :: SyntaxNode.SynMatchClause _ :: _ + | Rightmost(SynPat.Typed _), SyntaxNode.SynMatchClause _ :: _ + | SynPat.Typed _, SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ + | SynPat.Typed _, SyntaxNode.SynPat(SynPat.Tuple(isStruct = false)) :: SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ + | SynPat.Tuple(isStruct = false; elementPats = AnyTyped), SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ + | SynPat.Typed _, SyntaxNode.SynPat(SynPat.Tuple(isStruct = false)) :: SyntaxNode.SynBinding _ :: _ + | SynPat.Tuple(isStruct = false; elementPats = AnyTyped), SyntaxNode.SynBinding _ :: _ + | SynPat.LongIdent(argPats = SynArgPats.Pats(_ :: _)), SyntaxNode.SynBinding _ :: _ + | SynPat.LongIdent(argPats = SynArgPats.Pats(_ :: _)), SyntaxNode.SynExpr(SynExpr.Lambda _) :: _ + | SynPat.Tuple(isStruct = false), SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some _)) :: _ + | SynPat.Typed _, SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some _)) :: _ -> true + + // () is parsed as this. + | SynPat.Const(SynConst.Unit, _), _ -> true + + // (()) is required when overriding a generic member + // where unit is the generic type argument: + // + // type C<'T> = abstract M : 'T -> unit + // let _ = { new C with override _.M (()) = () } + | SynPat.Paren(SynPat.Const(SynConst.Unit, _), _), + SyntaxNode.SynPat(SynPat.LongIdent _) :: SyntaxNode.SynBinding _ :: SyntaxNode.SynExpr(SynExpr.ObjExpr( + objType = SynType.App(typeArgs = _ :: _) | SynType.LongIdentApp(typeArgs = _ :: _))) :: _ + | SynPat.Paren(SynPat.Const(SynConst.Unit, _), _), + SyntaxNode.SynPat(SynPat.LongIdent _) :: SyntaxNode.SynBinding _ :: SyntaxNode.SynMemberDefn _ :: SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.ObjectModel(members = AnyGenericInheritOrInterfaceImpl))) :: _ -> true + + // Parens are required around the atomic argument of + // any additional `new` constructor that is not the last. + // + // type T … = + // new (x) = … + // new (x, y) = … + | Atomic, + SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = [ Ident "new" ]))) :: SyntaxNode.SynBinding _ :: SyntaxNode.SynMemberDefn _ :: SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.ObjectModel(members = members))) :: _ -> + let lastNew = + (ValueNone, members) + ||> List.fold (fun lastNew ``member`` -> + match ``member`` with + | SynMemberDefn.Member( + memberDefn = SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = [ Ident "new" ])))) -> + ValueSome ``member`` + | _ -> lastNew) + + match lastNew with + | ValueSome(SynMemberDefn.Member( + memberDefn = SynBinding(headPat = SynPat.LongIdent(argPats = SynArgPats.Pats [ SynPat.Paren(Is pat, _) ])))) -> false + | _ -> true + + // Parens are otherwise never needed in these cases: + // + // let (x: …) = … + // for (…) in (…) do … + // let! (…) = … + // and! (…) = … + // use! (…) = … + // match … with (…) -> … + // function (…) -> … + // function (Pattern …) -> … + // fun (x) -> … + | _, SyntaxNode.SynBinding _ :: _ + | _, SyntaxNode.SynExpr(SynExpr.ForEach _) :: _ + | _, SyntaxNode.SynExpr(SynExpr.LetOrUseBang _) :: _ + | _, SyntaxNode.SynMatchClause _ :: _ + | Atomic, SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some _)) :: _ -> false + + // Nested patterns. + | inner, SyntaxNode.SynPat outer :: _ -> + match outer, inner with + // (x :: xs) :: ys + // (x, xs) :: ys + | SynPat.ListCons(lhsPat = SynPat.Paren(pat = Is inner)), SynPat.ListCons _ + | SynPat.ListCons(lhsPat = SynPat.Paren(pat = Is inner)), SynPat.Tuple(isStruct = false) -> true + + // A as (B | C) + // A as (B & C) + // x as (y, z) + // xs as (y :: zs) + | SynPat.As(rhsPat = SynPat.Paren(pat = Is inner)), + (SynPat.Or _ | SynPat.Ands _ | SynPat.Tuple(isStruct = false) | SynPat.ListCons _) -> true + + // (A | B) :: xs + // (A & B) :: xs + // (x as y) :: xs + | SynPat.ListCons _, SynPat.Or _ + | SynPat.ListCons _, SynPat.Ands _ + | SynPat.ListCons _, SynPat.As _ -> true + + // Pattern (x = (…)) + | SynPat.LongIdent(argPats = SynArgPats.NamePatPairs _), _ -> false + + // Pattern (x : int) + // Pattern ([] x) + // Pattern (:? int) + // Pattern (A :: _) + // Pattern (A | B) + // Pattern (A & B) + // Pattern (A as B) + // Pattern (A, B) + // Pattern1 (Pattern2 (x = A)) + // Pattern1 (Pattern2 x y) + | SynPat.LongIdent _, SynPat.Typed _ + | SynPat.LongIdent _, SynPat.Attrib _ + | SynPat.LongIdent _, SynPat.IsInst _ + | SynPat.LongIdent _, SynPat.ListCons _ + | SynPat.LongIdent _, SynPat.Or _ + | SynPat.LongIdent _, SynPat.Ands _ + | SynPat.LongIdent _, SynPat.As _ + | SynPat.LongIdent _, SynPat.Tuple(isStruct = false) + | SynPat.LongIdent _, SynPat.LongIdent(argPats = SynArgPats.NamePatPairs _) + | SynPat.LongIdent _, SynPat.LongIdent(argPats = SynArgPats.Pats(_ :: _)) + + // A | (B as C) + // A & (B as C) + // A, (B as C) + | SynPat.Or _, SynPat.As _ + | SynPat.Ands _, SynPat.As _ + | SynPat.Tuple _, SynPat.As _ + + // x, (y, z) + // x & (y, z) + // (x, y) & z + | SynPat.Tuple _, SynPat.Tuple(isStruct = false) + | SynPat.Ands _, SynPat.Tuple(isStruct = false) + + // A, (B | C) + // A & (B | C) + | SynPat.Tuple _, SynPat.Or _ + | SynPat.Ands _, SynPat.Or _ -> true + + // (x : int) & y + // x & (y : int) & z + | SynPat.Ands(Last(SynPat.Paren(pat = Is inner)), _), SynPat.Typed _ -> false + | SynPat.Ands _, SynPat.Typed _ -> true + + | _, SynPat.Const _ + | _, SynPat.Wild _ + | _, SynPat.Named _ + | _, SynPat.Typed _ + | _, SynPat.LongIdent(argPats = SynArgPats.Pats []) + | _, SynPat.Tuple(isStruct = true) + | _, SynPat.Paren _ + | _, SynPat.ArrayOrList _ + | _, SynPat.Record _ + | _, SynPat.Null _ + | _, SynPat.OptionalVal _ + | _, SynPat.IsInst _ + | _, SynPat.QuoteExpr _ + + | SynPat.Or _, _ + | SynPat.ListCons _, _ + | SynPat.Ands _, _ + | SynPat.As _, _ + | SynPat.LongIdent _, _ + | SynPat.Tuple _, _ + | SynPat.Paren _, _ + | SynPat.ArrayOrList _, _ + | SynPat.Record _, _ -> false + + | _ -> true + + | _ -> true diff --git a/src/Compiler/Service/SynPat.fsi b/src/Compiler/Service/SynPat.fsi new file mode 100644 index 00000000000..77bcd9c600c --- /dev/null +++ b/src/Compiler/Service/SynPat.fsi @@ -0,0 +1,13 @@ +namespace FSharp.Compiler.Syntax + +[] +[] +module public SynPat = + + /// + /// Returns true if the given pattern should be parenthesized in the given context, otherwise false. + /// + /// The pattern's ancestor nodes. + /// The pattern to check. + /// True if the given pattern should be parenthesized in the given context, otherwise false. + val shouldBeParenthesizedInContext: path: SyntaxVisitorPath -> pat: SynPat -> bool diff --git a/src/Compiler/Service/TransparentCompiler.fs b/src/Compiler/Service/TransparentCompiler.fs new file mode 100644 index 00000000000..298c0e6b627 --- /dev/null +++ b/src/Compiler/Service/TransparentCompiler.fs @@ -0,0 +1,2071 @@ +namespace FSharp.Compiler.CodeAnalysis.TransparentCompiler + +open System +open System.Collections.Generic +open System.Runtime.CompilerServices +open System.Diagnostics +open System.IO + +open Internal.Utilities.Collections +open Internal.Utilities.Library + +open FSharp.Compiler +open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.ILBinaryReader +open FSharp.Compiler.BuildGraph +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CompilerConfig +open FSharp.Compiler.CompilerImports +open FSharp.Compiler.CompilerOptions +open FSharp.Compiler.CheckBasics +open FSharp.Compiler.DependencyManager +open FSharp.Compiler.Diagnostics +open FSharp.Compiler.DiagnosticsLogger +open FSharp.Compiler.IO +open FSharp.Compiler.ScriptClosure +open FSharp.Compiler.Symbols +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text +open FSharp.Compiler.Text.Range +open FSharp.Compiler.Xml +open System.Threading.Tasks +open FSharp.Compiler.ParseAndCheckInputs +open FSharp.Compiler.GraphChecking +open FSharp.Compiler.Syntax +open FSharp.Compiler.CompilerDiagnostics +open FSharp.Compiler.NameResolution +open Internal.Utilities.Library.Extras +open FSharp.Compiler.TypedTree +open FSharp.Compiler.CheckDeclarations +open FSharp.Compiler.EditorServices +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CreateILModule +open FSharp.Compiler.TypedTreeOps +open System.Threading +open Internal.Utilities.Hashing + +open FSharp.Compiler.CodeAnalysis.ProjectSnapshot + +/// Accumulated results of type checking. The minimum amount of state in order to continue type-checking following files. +[] +type internal TcInfo = + { + tcState: TcState + tcEnvAtEndOfFile: TcEnv + + /// Disambiguation table for module names + moduleNamesDict: ModuleNamesDict + + topAttribs: TopAttribs option + + latestCcuSigForFile: ModuleOrNamespaceType option + + /// Accumulated diagnostics, last file first + tcDiagnosticsRev: (PhasedDiagnostic * FSharpDiagnosticSeverity)[] list + + tcDependencyFiles: string list + + sigNameOpt: (string * QualifiedNameOfFile) option + + graphNode: NodeToTypeCheck option + + stateContainsNodes: Set + + sink: TcResultsSinkImpl list + } + + member x.TcDiagnostics = Array.concat (List.rev x.tcDiagnosticsRev) + +[] +type internal TcIntermediate = + { + finisher: Finisher + //tcEnvAtEndOfFile: TcEnv + + /// Disambiguation table for module names + moduleNamesDict: ModuleNamesDict + + /// Accumulated diagnostics, last file first + tcDiagnosticsRev: (PhasedDiagnostic * FSharpDiagnosticSeverity)[] list + + tcDependencyFiles: string list + + sink: TcResultsSinkImpl + } + +/// Things we need to start parsing and checking files for a given project snapshot +type internal BootstrapInfo = + { + // Each instance gets an Id on creation, unfortunately partial type check results using different instances are not compatible + // So if this needs to be recreated for whatever reason then we need to re type check all files + Id: int + + AssemblyName: string + OutFile: string + TcConfig: TcConfig + TcImports: TcImports + TcGlobals: TcGlobals + InitialTcInfo: TcInfo + + // TODO: Figure out how these work and if they need to be added to the snapshot... + LoadedSources: (range * FSharpFileSnapshot) list + + // TODO: Might be a bit more complicated if we want to support adding files to the project via OtherOptions + // ExtraSourceFilesAfter: FSharpFileSnapshot list + + LoadClosure: LoadClosure option + LastFileName: string + } + +type internal TcIntermediateResult = TcInfo * TcResultsSinkImpl * CheckedImplFile option * string + +[] +type internal DependencyGraphType = + /// A dependency graph for a single file - it will be missing files which this file does not depend on + | File + /// A dependency graph for a project - it will contain all files in the project + | Project + +[] +type internal Extensions = + [] + static member Key<'T when 'T :> IFileSnapshot>(fileSnapshots: 'T list, ?extraKeyFlag) = + + { new ICacheKey<_, _> with + member _.GetLabel() = + let lastFile = + fileSnapshots + |> List.tryLast + |> Option.map (fun f -> f.FileName |> shortPath) + |> Option.defaultValue "[no file]" + + $"%d{fileSnapshots.Length} files ending with {lastFile}" + + member _.GetKey() = + Md5Hasher.empty + |> Md5Hasher.addStrings (fileSnapshots |> Seq.map (fun f -> f.FileName)) + |> pair extraKeyFlag + + member _.GetVersion() = + Md5Hasher.empty + |> Md5Hasher.addBytes' (fileSnapshots |> Seq.map (fun f -> f.Version)) + |> Md5Hasher.toString + } + +[] +module private TypeCheckingGraphProcessing = + open FSharp.Compiler.GraphChecking.GraphProcessing + + // TODO Do we need to suppress some error logging if we + // TODO apply the same partial results multiple times? + // TODO Maybe we can enable logging only for the final fold + /// + /// Combine type-checking results of dependencies needed to type-check a 'higher' node in the graph + /// + /// Initial state + /// Direct dependencies of a node + /// Transitive dependencies of a node + /// A way to fold a single result into existing state + let private combineResults + (emptyState: TcInfo) + (deps: ProcessedNode> array) + (transitiveDeps: ProcessedNode> array) + (folder: TcInfo -> Finisher -> TcInfo) + : TcInfo = + match deps with + | [||] -> emptyState + | _ -> + // Instead of starting with empty state, + // reuse state produced by the dependency with the biggest number of transitive dependencies. + // This is to reduce the number of folds required to achieve the final state. + let biggestDependency = + let sizeMetric (node: ProcessedNode<_, _>) = node.Info.TransitiveDeps.Length + deps |> Array.maxBy sizeMetric + + let firstState = biggestDependency.Result |> fst + + // Find items not already included in the state. + let itemsPresent = + set + [| + yield! biggestDependency.Info.TransitiveDeps + yield biggestDependency.Info.Item + |] + + let resultsToAdd = + transitiveDeps + |> Array.filter (fun dep -> itemsPresent.Contains dep.Info.Item = false) + |> Array.distinctBy (fun dep -> dep.Info.Item) + |> Array.sortWith (fun a b -> + // We preserve the order in which items are folded to the state. + match a.Info.Item, b.Info.Item with + | NodeToTypeCheck.PhysicalFile aIdx, NodeToTypeCheck.PhysicalFile bIdx + | NodeToTypeCheck.ArtificialImplFile aIdx, NodeToTypeCheck.ArtificialImplFile bIdx -> aIdx.CompareTo bIdx + | NodeToTypeCheck.PhysicalFile _, NodeToTypeCheck.ArtificialImplFile _ -> -1 + | NodeToTypeCheck.ArtificialImplFile _, NodeToTypeCheck.PhysicalFile _ -> 1) + |> Array.map (fun dep -> dep.Result |> snd) + + // Fold results not already included and produce the final state + let state = Array.fold folder firstState resultsToAdd + state + + /// + /// Process a graph of items. + /// A version of 'GraphProcessing.processGraph' with a signature specific to type-checking. + /// + let processTypeCheckingGraph + (graph: Graph) + (work: NodeToTypeCheck -> TcInfo -> Async>) + (emptyState: TcInfo) + : Async<(int * PartialResult) list * TcInfo> = + async { + + let workWrapper + (getProcessedNode: + NodeToTypeCheck -> ProcessedNode>) + (node: NodeInfo) + : Async> = + async { + let folder (state: TcInfo) (Finisher(finisher = finisher)) : TcInfo = finisher state |> snd + let deps = node.Deps |> Array.except [| node.Item |] |> Array.map getProcessedNode + + let transitiveDeps = + node.TransitiveDeps + |> Array.except [| node.Item |] + |> Array.map getProcessedNode + + let inputState = combineResults emptyState deps transitiveDeps folder + + let! singleRes = work node.Item inputState + let state = folder inputState singleRes + return state, singleRes + } + + let! results = processGraphAsync graph workWrapper + + let finalFileResults, state = + (([], emptyState), + results + |> Array.choose (fun (item, res) -> + match item with + | NodeToTypeCheck.ArtificialImplFile _ -> None + | NodeToTypeCheck.PhysicalFile file -> Some(file, res))) + ||> Array.fold (fun (fileResults, state) (item, (_, Finisher(finisher = finisher))) -> + let fileResult, state = finisher state + (item, fileResult) :: fileResults, state) + + return finalFileResults, state + } + +type internal CompilerCaches(sizeFactor: int) = + + let sf = sizeFactor + + member _.SizeFactor = sf + + member val ParseFile = AsyncMemoize(keepStrongly = 50 * sf, keepWeakly = 20 * sf, name = "ParseFile") + + member val ParseAndCheckFileInProject = AsyncMemoize(sf, 2 * sf, name = "ParseAndCheckFileInProject") + + member val ParseAndCheckAllFilesInProject = AsyncMemoizeDisabled(sf, 2 * sf, name = "ParseAndCheckFullProject") + + member val ParseAndCheckProject = AsyncMemoize(sf, 2 * sf, name = "ParseAndCheckProject") + + member val FrameworkImports = AsyncMemoize(sf, 2 * sf, name = "FrameworkImports") + + member val BootstrapInfoStatic = AsyncMemoize(sf, 2 * sf, name = "BootstrapInfoStatic") + + member val BootstrapInfo = AsyncMemoize(sf, 2 * sf, name = "BootstrapInfo") + + member val TcLastFile = AsyncMemoizeDisabled(sf, 2 * sf, name = "TcLastFile") + + member val TcIntermediate = AsyncMemoize(20 * sf, 20 * sf, name = "TcIntermediate") + + member val DependencyGraph = AsyncMemoize(sf, 2 * sf, name = "DependencyGraph") + + member val ProjectExtras = AsyncMemoizeDisabled(sf, 2 * sf, name = "ProjectExtras") + + member val AssemblyData = AsyncMemoize(sf, 2 * sf, name = "AssemblyData") + + member val SemanticClassification = AsyncMemoize(sf, 2 * sf, name = "SemanticClassification") + + member val ItemKeyStore = AsyncMemoize(sf, 2 * sf, name = "ItemKeyStore") + + member this.Clear(projects: Set) = + let shouldClear project = projects |> Set.contains project + + this.ParseFile.Clear(fst >> shouldClear) + this.ParseAndCheckFileInProject.Clear(snd >> shouldClear) + this.ParseAndCheckProject.Clear(shouldClear) + this.BootstrapInfoStatic.Clear(shouldClear) + this.BootstrapInfo.Clear(shouldClear) + this.TcIntermediate.Clear(snd >> shouldClear) + this.AssemblyData.Clear(shouldClear) + this.SemanticClassification.Clear(snd >> shouldClear) + this.ItemKeyStore.Clear(snd >> shouldClear) + +type internal TransparentCompiler + ( + legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking, + parallelReferenceResolution, + captureIdentifiersWhenParsing, + getSource: (string -> Async) option, + useChangeNotifications, + useSyntaxTreeCache + ) as self = + + // Is having just one of these ok? + let lexResourceManager = Lexhelp.LexResourceManager() + + // Mutable so we can easily clear them by creating a new instance + let mutable caches = CompilerCaches(100) + + // TODO: do we need this? + //let maxTypeCheckingParallelism = max 1 (Environment.ProcessorCount / 2) + //let maxParallelismSemaphore = new SemaphoreSlim(maxTypeCheckingParallelism) + + // 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() + + // Legacy events, they're used in tests... eventually they should go away + let beforeFileChecked = Event() + let fileParsed = Event() + let fileChecked = Event() + let projectChecked = Event() + + // use this to process not-yet-implemented tasks + let backgroundCompiler = + BackgroundCompiler( + legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking, + parallelReferenceResolution, + captureIdentifiersWhenParsing, + getSource, + useChangeNotifications, + useSyntaxTreeCache + ) + :> IBackgroundCompiler + + let ComputeFrameworkImports (tcConfig: TcConfig) frameworkDLLs nonFrameworkResolutions = + let frameworkDLLsKey = + frameworkDLLs + |> List.map (fun ar -> ar.resolvedPath) // The cache key. Just the minimal data. + |> List.sort // Sort to promote cache hits. + + // 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 = + FrameworkImportsCacheKey( + frameworkDLLsKey, + tcConfig.primaryAssembly.Name, + tcConfig.GetTargetFrameworkDirectories(), + tcConfig.fsharpBinariesDir, + tcConfig.langVersion.SpecifiedVersion + ) + + caches.FrameworkImports.Get( + key, + node { + use _ = Activity.start "ComputeFrameworkImports" [] + let tcConfigP = TcConfigProvider.Constant tcConfig + + return! TcImports.BuildFrameworkTcImports(tcConfigP, frameworkDLLs, nonFrameworkResolutions) + } + ) + + // Link all the assemblies together and produce the input typecheck accumulator + let CombineImportedAssembliesTask + ( + assemblyName, + tcConfig: TcConfig, + tcConfigP, + tcGlobals, + frameworkTcImports, + nonFrameworkResolutions, + unresolvedReferences, + dependencyProvider, + loadClosureOpt: LoadClosure option, + basicDependencies, + importsInvalidatedByTypeProvider: Event + ) = + + node { + let diagnosticsLogger = + CompilationDiagnosticLogger("CombineImportedAssembliesTask", tcConfig.diagnosticsOptions) + + use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Parameter) + + let! tcImports = + node { + try + let! tcImports = + TcImports.BuildNonFrameworkTcImports( + tcConfigP, + frameworkTcImports, + nonFrameworkResolutions, + unresolvedReferences, + dependencyProvider + ) +#if !NO_TYPEPROVIDERS + // TODO: review and handle the event + tcImports.GetCcusExcludingBase() + |> Seq.iter (fun ccu -> + // When a CCU reports an invalidation, merge them together and just report a + // general "imports invalidated". This triggers a rebuild. + // + // We are explicit about what the handler closure captures to help reason about the + // lifetime of captured objects, especially in case the type provider instance gets leaked + // or keeps itself alive mistakenly, e.g. via some global state in the type provider instance. + // + // The handler only captures + // 1. a weak reference to the importsInvalidated event. + // + // The IncrementalBuilder holds the strong reference the importsInvalidated event. + // + // In the invalidation handler we use a weak reference to allow the IncrementalBuilder to + // be collected if, for some reason, a TP instance is not disposed or not GC'd. + let capturedImportsInvalidated = WeakReference<_>(importsInvalidatedByTypeProvider) + + ccu.Deref.InvalidateEvent.Add(fun _ -> + match capturedImportsInvalidated.TryGetTarget() with + | true, tg -> tg.Trigger() + | _ -> ())) +#endif +#if NO_TYPEPROVIDERS + ignore importsInvalidatedByTypeProvider +#endif + return tcImports + with + | :? OperationCanceledException -> + // if it's been canceled then it shouldn't be needed anymore + return frameworkTcImports + | exn -> + Debug.Assert(false, sprintf "Could not BuildAllReferencedDllTcImports %A" exn) + diagnosticsLogger.Warning exn + return frameworkTcImports + } + + let tcInitial, openDecls0 = + GetInitialTcEnv(assemblyName, rangeStartup, tcConfig, tcImports, tcGlobals) + + let tcState = + GetInitialTcState(rangeStartup, assemblyName, tcConfig, tcGlobals, tcImports, tcInitial, openDecls0) + + let loadClosureErrors = + [ + match loadClosureOpt with + | None -> () + | Some loadClosure -> + for inp in loadClosure.Inputs do + yield! inp.MetaCommandDiagnostics + ] + + let initialErrors = + Array.append (Array.ofList loadClosureErrors) (diagnosticsLogger.GetDiagnostics()) + + let tcInfo = + { + tcState = tcState + tcEnvAtEndOfFile = tcInitial + topAttribs = None + latestCcuSigForFile = None + tcDiagnosticsRev = [ initialErrors ] + moduleNamesDict = Map.empty + tcDependencyFiles = basicDependencies + sigNameOpt = None + graphNode = None + stateContainsNodes = Set.empty + sink = [] + } + + return tcImports, tcInfo + } + + let getProjectReferences (project: ProjectSnapshotBase<_>) userOpName = + [ + for r in project.ReferencedProjects do + + match r with + | FSharpReferencedProjectSnapshot.FSharpReference(nm, projectSnapshot) -> + // 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( + projectSnapshot.ProjectSnapshot, + nm, + userOpName + ".CheckReferencedProject(" + nm + ")" + ) + } + + member x.TryGetLogicalTimeStamp(cache) = + // TODO: + None + + member x.FileName = nm + } + ] + + let ComputeTcConfigBuilder (projectSnapshot: ProjectSnapshotBase<_>) = + + let useSimpleResolutionSwitch = "--simpleresolution" + let commandLineArgs = projectSnapshot.CommandLineOptions + let defaultFSharpBinariesDir = FSharpCheckerResultsSettings.defaultFSharpBinariesDir + let useScriptResolutionRules = projectSnapshot.UseScriptResolutionRules + + let projectReferences = + getProjectReferences projectSnapshot "ComputeTcConfigBuilder" + + // TODO: script support + let loadClosureOpt: LoadClosure option = None + + let getSwitchValue (switchString: string) = + match commandLineArgs |> List.tryFindIndex (fun s -> s.StartsWithOrdinal switchString) with + | Some idx -> Some(commandLineArgs[idx].Substring(switchString.Length)) + | _ -> None + + let sdkDirOverride = + match loadClosureOpt with + | None -> None + | Some loadClosure -> loadClosure.SdkDirOverride + + // see also fsc.fs: runFromCommandLineToImportingAssemblies(), as there are many similarities to where the PS creates a tcConfigB + let tcConfigB = + TcConfigBuilder.CreateNew( + legacyReferenceResolver, + defaultFSharpBinariesDir, + implicitIncludeDir = projectSnapshot.ProjectDirectory, + reduceMemoryUsage = ReduceMemoryFlag.Yes, + isInteractive = useScriptResolutionRules, + isInvalidationSupported = true, + defaultCopyFSharpCore = CopyFSharpCoreFlag.No, + tryGetMetadataSnapshot = tryGetMetadataSnapshot, + sdkDirOverride = sdkDirOverride, + rangeForErrors = range0 + ) + + tcConfigB.primaryAssembly <- + match loadClosureOpt with + | None -> PrimaryAssembly.Mscorlib + | Some loadClosure -> + if loadClosure.UseDesktopFramework then + PrimaryAssembly.Mscorlib + else + PrimaryAssembly.System_Runtime + + tcConfigB.resolutionEnvironment <- (LegacyResolutionEnvironment.EditingOrCompilation true) + + tcConfigB.conditionalDefines <- + let define = + if useScriptResolutionRules then + "INTERACTIVE" + else + "COMPILED" + + define :: tcConfigB.conditionalDefines + + tcConfigB.projectReferences <- projectReferences + + tcConfigB.useSimpleResolution <- (getSwitchValue useSimpleResolutionSwitch) |> Option.isSome + + // Apply command-line arguments and collect more source files if they are in the arguments + let sourceFilesNew = + ApplyCommandLineArgs(tcConfigB, projectSnapshot.SourceFileNames, commandLineArgs) + + // Never open PDB files for the language service, even if --standalone is specified + tcConfigB.openDebugInformationForLaterStaticLinking <- false + + tcConfigB.xmlDocInfoLoader <- + { new IXmlDocumentationInfoLoader with + /// Try to load xml documentation associated with an assembly by the same file path with the extension ".xml". + member _.TryLoad(assemblyFileName) = + let xmlFileName = Path.ChangeExtension(assemblyFileName, ".xml") + + // REVIEW: File IO - Will eventually need to change this to use a file system interface of some sort. + XmlDocumentationInfo.TryCreateFromFile(xmlFileName) + } + |> Some + + tcConfigB.parallelReferenceResolution <- parallelReferenceResolution + tcConfigB.captureIdentifiersWhenParsing <- captureIdentifiersWhenParsing + + tcConfigB, sourceFilesNew, loadClosureOpt + + let mutable BootstrapInfoIdCounter = 0 + + /// Bootstrap info that does not depend source files + let ComputeBootstrapInfoStatic (projectSnapshot: ProjectCore, tcConfig: TcConfig, assemblyName: string, loadClosureOpt) = + + caches.BootstrapInfoStatic.Get( + projectSnapshot.CacheKeyWith("BootstrapInfoStatic", assemblyName), + node { + use _ = + Activity.start + "ComputeBootstrapInfoStatic" + [| + Activity.Tags.project, projectSnapshot.ProjectFileName |> Path.GetFileName + "references", projectSnapshot.ReferencedProjects.Length.ToString() + |] + + // Resolve assemblies and create the framework TcImports. This caches a level of "system" references. No type providers are + // included in these references. + + let frameworkDLLs, nonFrameworkResolutions, unresolvedReferences = + TcAssemblyResolutions.SplitNonFoundationalResolutions(tcConfig) + + // Prepare the frameworkTcImportsCache + let! tcGlobals, frameworkTcImports = ComputeFrameworkImports tcConfig frameworkDLLs nonFrameworkResolutions + + // Note we are not calling diagnosticsLogger.GetDiagnostics() anywhere for this task. + // This is ok because not much can actually go wrong here. + let diagnosticsLogger = + CompilationDiagnosticLogger("nonFrameworkAssemblyInputs", tcConfig.diagnosticsOptions) + + use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Parameter) + + let tcConfigP = TcConfigProvider.Constant tcConfig + + let importsInvalidatedByTypeProvider = Event() + + let basicDependencies = + [ + for UnresolvedAssemblyReference(referenceText, _) in unresolvedReferences do + // Exclude things that are definitely not a file name + if not (FileSystem.IsInvalidPathShim referenceText) then + let file = + if FileSystem.IsPathRootedShim referenceText then + referenceText + else + Path.Combine(projectSnapshot.ProjectDirectory, referenceText) + + yield file + + for r in nonFrameworkResolutions do + yield r.resolvedPath + ] + + // For scripts, the dependency provider is already available. + // For projects create a fresh one for the project. + let dependencyProvider = + if projectSnapshot.UseScriptResolutionRules then + dependencyProviderForScripts + else + new DependencyProvider() + + let! tcImports, initialTcInfo = + CombineImportedAssembliesTask( + assemblyName, + tcConfig, + tcConfigP, + tcGlobals, + frameworkTcImports, + nonFrameworkResolutions, + unresolvedReferences, + dependencyProvider, + loadClosureOpt, + basicDependencies, + importsInvalidatedByTypeProvider + ) + + let bootstrapId = Interlocked.Increment &BootstrapInfoIdCounter + + return bootstrapId, tcImports, tcGlobals, initialTcInfo, importsInvalidatedByTypeProvider + } + ) + + let computeBootstrapInfoInner (projectSnapshot: ProjectSnapshot) = + node { + + let tcConfigB, sourceFiles, loadClosureOpt = ComputeTcConfigBuilder projectSnapshot + + // If this is a builder for a script, re-apply the settings inferred from the + // script and its load closure to the configuration. + // + // NOTE: it would probably be cleaner and more accurate to re-run the load closure at this point. + let setupConfigFromLoadClosure () = + match loadClosureOpt with + | Some loadClosure -> + let dllReferences = + [ + for reference in tcConfigB.referencedDLLs do + // If there's (one or more) resolutions of closure references then yield them all + match + loadClosure.References + |> List.tryFind (fun (resolved, _) -> resolved = reference.Text) + with + | Some(resolved, closureReferences) -> + for closureReference in closureReferences do + yield AssemblyReference(closureReference.originalReference.Range, resolved, None) + | None -> yield reference + ] + + tcConfigB.referencedDLLs <- [] + + tcConfigB.primaryAssembly <- + (if loadClosure.UseDesktopFramework then + PrimaryAssembly.Mscorlib + else + PrimaryAssembly.System_Runtime) + // Add one by one to remove duplicates + dllReferences + |> List.iter (fun dllReference -> tcConfigB.AddReferencedAssemblyByPath(dllReference.Range, dllReference.Text)) + + tcConfigB.knownUnresolvedReferences <- loadClosure.UnresolvedReferences + | None -> () + + setupConfigFromLoadClosure () + + let tcConfig = TcConfig.Create(tcConfigB, validate = true) + let outFile, _, assemblyName = tcConfigB.DecideNames sourceFiles + + let! bootstrapId, tcImports, tcGlobals, initialTcInfo, _importsInvalidatedByTypeProvider = + ComputeBootstrapInfoStatic(projectSnapshot.ProjectCore, tcConfig, assemblyName, loadClosureOpt) + + // Check for the existence of loaded sources and prepend them to the sources list if present. + let loadedSources = + tcConfig.GetAvailableLoadedSources() + |> List.map (fun (m, fileName) -> m, FSharpFileSnapshot.CreateFromFileSystem(fileName)) + + return + Some + { + Id = bootstrapId + AssemblyName = assemblyName + OutFile = outFile + TcConfig = tcConfig + TcImports = tcImports + TcGlobals = tcGlobals + InitialTcInfo = initialTcInfo + LoadedSources = loadedSources + LoadClosure = loadClosureOpt + LastFileName = sourceFiles |> List.last + //ImportsInvalidatedByTypeProvider = importsInvalidatedByTypeProvider + } + } + + let ComputeBootstrapInfo (projectSnapshot: ProjectSnapshot) = + + caches.BootstrapInfo.Get( + projectSnapshot.NoFileVersionsKey, + node { + use _ = + Activity.start "ComputeBootstrapInfo" [| Activity.Tags.project, projectSnapshot.ProjectFileName |> Path.GetFileName |] + + // Trap and report diagnostics from creation. + let delayedLogger = CapturingDiagnosticsLogger("IncrementalBuilderCreation") + use _ = new CompilationGlobalsScope(delayedLogger, BuildPhase.Parameter) + + let! bootstrapInfoOpt = + node { + try + return! computeBootstrapInfoInner projectSnapshot + with exn -> + errorRecoveryNoRange exn + return None + } + + let diagnostics = + match bootstrapInfoOpt with + | Some bootstrapInfo -> + let diagnosticsOptions = bootstrapInfo.TcConfig.diagnosticsOptions + + let diagnosticsLogger = + CompilationDiagnosticLogger("IncrementalBuilderCreation", diagnosticsOptions) + + delayedLogger.CommitDelayedDiagnostics diagnosticsLogger + diagnosticsLogger.GetDiagnostics() + | _ -> Array.ofList delayedLogger.Diagnostics + |> Array.map (fun (diagnostic, severity) -> + let flatErrors = + bootstrapInfoOpt + |> Option.map (fun bootstrapInfo -> bootstrapInfo.TcConfig.flatErrors) + |> Option.defaultValue false // TODO: do we need to figure this out? + + FSharpDiagnostic.CreateFromException(diagnostic, severity, range.Zero, suggestNamesForErrors, flatErrors, None)) + + return bootstrapInfoOpt, diagnostics + } + ) + + // TODO: Not sure if we should cache this. For VS probably not. Maybe it can be configurable by FCS user. + let LoadSource (file: FSharpFileSnapshot) isExe isLastCompiland = + node { + let! source = file.GetSource() |> NodeCode.AwaitTask + + return + FSharpFileSnapshotWithSource( + FileName = file.FileName, + Source = source, + SourceHash = source.GetChecksum(), + IsLastCompiland = isLastCompiland, + IsExe = isExe + ) + } + + let LoadSources (bootstrapInfo: BootstrapInfo) (projectSnapshot: ProjectSnapshot) = + node { + let isExe = bootstrapInfo.TcConfig.target.IsExe + + let! sources = + projectSnapshot.SourceFiles + |> Seq.map (fun f -> LoadSource f isExe (f.FileName = bootstrapInfo.LastFileName)) + |> NodeCode.Parallel + + return ProjectSnapshotWithSources(projectSnapshot.ProjectCore, sources |> Array.toList) + + } + + let ComputeParseFile (projectSnapshot: ProjectSnapshotBase<_>) (tcConfig: TcConfig) (file: FSharpFileSnapshotWithSource) = + + let key = + { new ICacheKey<_, _> with + member _.GetLabel() = file.FileName |> shortPath + + member _.GetKey() = + projectSnapshot.ProjectCore.Identifier, file.FileName + + member _.GetVersion() = + projectSnapshot.ParsingVersion, + file.StringVersion, + // TODO: is there a situation where this is not enough and we need to have them separate? + file.IsLastCompiland && file.IsExe + } + + caches.ParseFile.Get( + key, + node { + use _ = + Activity.start + "ComputeParseFile" + [| + Activity.Tags.fileName, file.FileName |> shortPath + Activity.Tags.version, file.StringVersion + |] + + let diagnosticsLogger = + CompilationDiagnosticLogger("Parse", tcConfig.diagnosticsOptions) + // Return the disposable object that cleans up + use _holder = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Parse) + + let flags = file.IsLastCompiland, file.IsExe + let fileName = file.FileName + let sourceText = file.Source + + let input = + ParseOneInputSourceText(tcConfig, lexResourceManager, fileName, flags, diagnosticsLogger, sourceText) + + // TODO: Hashing of syntax tree + let inputHash = file.Version + + fileParsed.Trigger(fileName, Unchecked.defaultof<_>) + + return FSharpParsedFile(fileName, inputHash, sourceText, input, diagnosticsLogger.GetDiagnostics()) + } + ) + + // In case we don't want to use any parallel processing + let mkLinearGraph count : Graph = + seq { + 0, [||] + + yield! + [ 0 .. count - 1 ] + |> Seq.rev + |> Seq.pairwise + |> Seq.map (fun (a, b) -> a, [| b |]) + } + |> Graph.make + + let computeDependencyGraph (tcConfig: TcConfig) parsedInputs (processGraph: Graph -> Graph) = + node { + let sourceFiles: FileInProject array = + parsedInputs + |> Seq.toArray + |> Array.mapi (fun idx (input: ParsedInput) -> + { + Idx = idx + FileName = input.FileName + ParsedInput = input + }) + + use _ = + Activity.start "ComputeDependencyGraph" [| Activity.Tags.fileName, (sourceFiles |> Array.last).FileName |] + + let filePairs = FilePairMap(sourceFiles) + + // TODO: we will probably want to cache and re-use larger graphs if available + + let graph = + if tcConfig.compilingFSharpCore then + mkLinearGraph sourceFiles.Length + else + DependencyResolution.mkGraph filePairs sourceFiles |> fst |> processGraph + + let nodeGraph = TransformDependencyGraph(graph, filePairs) + + let fileNames = + parsedInputs + |> Seq.mapi (fun idx input -> idx, Path.GetFileName input.FileName) + |> Map.ofSeq + + let debugGraph = + nodeGraph + |> Graph.map (function + | NodeToTypeCheck.PhysicalFile i -> i, $"[{i}] {fileNames[i]}" + | NodeToTypeCheck.ArtificialImplFile i -> -(i + 1), $"AIF [{i}] : {fileNames[i]}") + |> Graph.serialiseToMermaid + + //Trace.TraceInformation("\n" + debugGraph) + + if Activity.Current <> null then + Activity.Current.AddTag("graph", debugGraph) |> ignore + + return nodeGraph, graph + } + + let removeImplFilesThatHaveSignatures (projectSnapshot: ProjectSnapshot) (graph: Graph) = + + let removeIndexes = + projectSnapshot.SourceFileNames + |> Seq.mapi pair + |> Seq.groupBy ( + snd + >> (fun fileName -> + if fileName.EndsWith(".fsi") then + fileName.Substring(0, fileName.Length - 1) + else + fileName) + ) + |> Seq.map (snd >> (Seq.toList)) + |> Seq.choose (function + | [ idx1, _; idx2, _ ] -> max idx1 idx2 |> Some + | _ -> None) + |> Set + + graph + |> Seq.filter (fun x -> not (removeIndexes.Contains x.Key)) + |> Seq.map (fun x -> x.Key, x.Value |> Array.filter (fun node -> not (removeIndexes.Contains node))) + |> Graph.make + + let removeImplFilesThatHaveSignaturesExceptLastOne (projectSnapshot: ProjectSnapshotBase<_>) (graph: Graph) = + + let removeIndexes = + projectSnapshot.SourceFileNames + |> Seq.mapi pair + |> Seq.groupBy ( + snd + >> (fun fileName -> + if fileName.EndsWith(".fsi") then + fileName.Substring(0, fileName.Length - 1) + else + fileName) + ) + |> Seq.map (snd >> (Seq.toList)) + |> Seq.choose (function + | [ idx1, _; idx2, _ ] -> max idx1 idx2 |> Some + | _ -> None) + |> Set + // Don't remove the last file + |> Set.remove (projectSnapshot.SourceFiles.Length - 1) + + graph + |> Seq.filter (fun x -> not (removeIndexes.Contains x.Key)) + |> Seq.map (fun x -> x.Key, x.Value |> Array.filter (fun node -> not (removeIndexes.Contains node))) + |> Graph.make + + let ComputeDependencyGraphForFile (tcConfig: TcConfig) (priorSnapshot: ProjectSnapshotBase) = + let key = priorSnapshot.SourceFiles.Key(DependencyGraphType.File) + //let lastFileIndex = (parsedInputs |> Array.length) - 1 + //caches.DependencyGraph.Get(key, computeDependencyGraph parsedInputs (Graph.subGraphFor lastFileIndex)) + caches.DependencyGraph.Get( + key, + computeDependencyGraph + tcConfig + (priorSnapshot.SourceFiles |> Seq.map (fun f -> f.ParsedInput)) + (removeImplFilesThatHaveSignaturesExceptLastOne priorSnapshot) + ) + + let ComputeDependencyGraphForProject (tcConfig: TcConfig) (projectSnapshot: ProjectSnapshotBase) = + + let key = projectSnapshot.SourceFiles.Key(DependencyGraphType.Project) + //caches.DependencyGraph.Get(key, computeDependencyGraph parsedInputs (removeImplFilesThatHaveSignatures projectSnapshot)) + caches.DependencyGraph.Get( + key, + computeDependencyGraph tcConfig (projectSnapshot.SourceFiles |> Seq.map (fun f -> f.ParsedInput)) id + ) + + let ComputeTcIntermediate + (projectSnapshot: ProjectSnapshotBase) + (dependencyGraph: Graph) + (index: FileIndex) + (nodeToCheck: NodeToTypeCheck) + bootstrapInfo + (prevTcInfo: TcInfo) + = + + ignore dependencyGraph + + let key = projectSnapshot.FileKey(index).WithExtraVersion(bootstrapInfo.Id) + + let _label, _k, _version = key.GetLabel(), key.GetKey(), key.GetVersion() + + caches.TcIntermediate.Get( + key, + node { + + let file = projectSnapshot.SourceFiles[index] + + let input = file.ParsedInput + let fileName = file.FileName + + use _ = + Activity.start + "ComputeTcIntermediate" + [| + Activity.Tags.fileName, fileName |> Path.GetFileName + "key", key.GetLabel() + "version", "-" // key.GetVersion() + |] + + beforeFileChecked.Trigger(fileName, Unchecked.defaultof<_>) + + let tcConfig = bootstrapInfo.TcConfig + let tcGlobals = bootstrapInfo.TcGlobals + let tcImports = bootstrapInfo.TcImports + + let mainInputFileName = file.FileName + let sourceText = file.SourceText + let parsedMainInput = file.ParsedInput + + // Initialize the error handler + let errHandler = + ParseAndCheckFile.DiagnosticsHandler( + true, + mainInputFileName, + tcConfig.diagnosticsOptions, + sourceText, + suggestNamesForErrors, + tcConfig.flatErrors + ) + + use _ = + new CompilationGlobalsScope(errHandler.DiagnosticsLogger, 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 + + let diagnosticsLogger = errHandler.DiagnosticsLogger + + //let capturingDiagnosticsLogger = CapturingDiagnosticsLogger("TypeCheck") + + //let diagnosticsLogger = + // GetDiagnosticsLoggerFilteringByScopedPragmas( + // false, + // input.ScopedPragmas, + // tcConfig.diagnosticsOptions, + // capturingDiagnosticsLogger + // ) + + //use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.TypeCheck) + + //beforeFileChecked.Trigger fileName + + ApplyMetaCommandsFromInputToTcConfig(tcConfig, input, Path.GetDirectoryName fileName, tcImports.DependencyProvider) + |> ignore + + let sink = TcResultsSinkImpl(tcGlobals) + + let hadParseErrors = not (Array.isEmpty file.ParseErrors) + + let input, moduleNamesDict = + DeduplicateParsedInputModuleName prevTcInfo.moduleNamesDict input + + //let! ct = NodeCode.CancellationToken + + try + //do! maxParallelismSemaphore.WaitAsync(ct) |> NodeCode.AwaitTask + + let! finisher = + CheckOneInputWithCallback + nodeToCheck + ((fun () -> hadParseErrors || diagnosticsLogger.ErrorCount > 0), + tcConfig, + tcImports, + tcGlobals, + None, + TcResultsSink.WithSink sink, + prevTcInfo.tcState, + input, + true) + |> Cancellable.toAsync + |> NodeCode.AwaitAsync + + //fileChecked.Trigger fileName + + let newErrors = + Array.append file.ParseErrors (errHandler.CollectedPhasedDiagnostics) + + fileChecked.Trigger(fileName, Unchecked.defaultof<_>) + + return + { + finisher = finisher + moduleNamesDict = moduleNamesDict + tcDiagnosticsRev = [ newErrors ] + tcDependencyFiles = [ fileName ] + sink = sink + } + finally + () + //maxParallelismSemaphore.Release() |> ignore + } + ) + + let processGraphNode projectSnapshot bootstrapInfo dependencyFiles collectSinks (fileNode: NodeToTypeCheck) tcInfo = + // TODO: should this be node? + async { + match fileNode with + | NodeToTypeCheck.PhysicalFile index -> + + let! tcIntermediate = + ComputeTcIntermediate projectSnapshot dependencyFiles index fileNode bootstrapInfo tcInfo + |> Async.AwaitNodeCode + + let (Finisher(node = node; finisher = finisher)) = tcIntermediate.finisher + + return + Finisher( + node, + (fun tcInfo -> + + if tcInfo.stateContainsNodes |> Set.contains fileNode then + failwith $"Oops!" + + //if + // tcInfo.stateContainsNodes + // Signature files don't have to be right above the impl file... if we need this check then + // we need to do it differently + // |> Set.contains (NodeToTypeCheck.ArtificialImplFile(index - 1)) + //then + // failwith $"Oops???" + + let partialResult, tcState = finisher tcInfo.tcState + + let tcEnv, topAttribs, _checkImplFileOpt, ccuSigForFile = partialResult + + let tcEnvAtEndOfFile = + if keepAllBackgroundResolutions then + tcEnv + else + tcState.TcEnvFromImpls + + partialResult, + { tcInfo with + tcState = tcState + tcEnvAtEndOfFile = tcEnvAtEndOfFile + moduleNamesDict = tcIntermediate.moduleNamesDict + topAttribs = Some topAttribs + tcDiagnosticsRev = tcIntermediate.tcDiagnosticsRev @ tcInfo.tcDiagnosticsRev + tcDependencyFiles = tcIntermediate.tcDependencyFiles @ tcInfo.tcDependencyFiles + latestCcuSigForFile = Some ccuSigForFile + graphNode = Some node + stateContainsNodes = tcInfo.stateContainsNodes |> Set.add node + sink = + if collectSinks then + tcIntermediate.sink :: tcInfo.sink + else + [ tcIntermediate.sink ] + }) + ) + + | NodeToTypeCheck.ArtificialImplFile index -> + return + Finisher( + fileNode, + (fun tcInfo -> + + if tcInfo.stateContainsNodes |> Set.contains fileNode then + failwith $"Oops!" + + if + tcInfo.stateContainsNodes + |> Set.contains (NodeToTypeCheck.PhysicalFile(index + 1)) + then + failwith $"Oops!!!" + + let parsedInput = projectSnapshot.SourceFiles[index].ParsedInput + let prefixPathOpt = None + // Retrieve the type-checked signature information and add it to the TcEnvFromImpls. + let partialResult, tcState = + AddSignatureResultToTcImplEnv + (bootstrapInfo.TcImports, + bootstrapInfo.TcGlobals, + prefixPathOpt, + TcResultsSink.NoSink, + tcInfo.tcState, + parsedInput) + tcInfo.tcState + + let tcEnv, topAttribs, _checkImplFileOpt, ccuSigForFile = partialResult + + let tcEnvAtEndOfFile = + if keepAllBackgroundResolutions then + tcEnv + else + tcState.TcEnvFromImpls + + partialResult, + { tcInfo with + tcState = tcState + tcEnvAtEndOfFile = tcEnvAtEndOfFile + topAttribs = Some topAttribs + latestCcuSigForFile = Some ccuSigForFile + graphNode = Some fileNode + stateContainsNodes = tcInfo.stateContainsNodes |> Set.add fileNode + }) + ) + + } + + let parseSourceFiles (projectSnapshot: ProjectSnapshotWithSources) tcConfig = + node { + let! parsedInputs = + projectSnapshot.SourceFiles + |> Seq.map (ComputeParseFile projectSnapshot tcConfig) + |> NodeCode.Parallel + + return ProjectSnapshotBase<_>(projectSnapshot.ProjectCore, parsedInputs |> Array.toList) + } + + // Type check file and all its dependencies + let ComputeTcLastFile (bootstrapInfo: BootstrapInfo) (projectSnapshot: ProjectSnapshotWithSources) = + let fileName = projectSnapshot.SourceFiles |> List.last |> (fun f -> f.FileName) + + caches.TcLastFile.Get( + projectSnapshot.FileKey fileName, + node { + let file = projectSnapshot.SourceFiles |> List.last + + use _ = + Activity.start "ComputeTcLastFile" [| Activity.Tags.fileName, file.FileName |> Path.GetFileName |] + + let! projectSnapshot = parseSourceFiles projectSnapshot bootstrapInfo.TcConfig + + let! graph, dependencyFiles = ComputeDependencyGraphForFile bootstrapInfo.TcConfig projectSnapshot + + let! results, tcInfo = + processTypeCheckingGraph + graph + (processGraphNode projectSnapshot bootstrapInfo dependencyFiles false) + bootstrapInfo.InitialTcInfo + |> NodeCode.AwaitAsync + + let lastResult = results |> List.head |> snd + + return lastResult, tcInfo + } + ) + + let getParseResult (projectSnapshot: ProjectSnapshot) creationDiags file (tcConfig: TcConfig) = + node { + let! parsedFile = ComputeParseFile projectSnapshot tcConfig file + + let parseDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + tcConfig.diagnosticsOptions, + false, + file.FileName, + parsedFile.ParseErrors, + suggestNamesForErrors, + tcConfig.flatErrors, + None + ) + + let diagnostics = [| yield! creationDiags; yield! parseDiagnostics |] + + return + FSharpParseFileResults( + diagnostics = diagnostics, + input = parsedFile.ParsedInput, + parseHadErrors = (parseDiagnostics.Length > 0), + // TODO: check if we really need this in parse results + dependencyFiles = [||] + ) + } + + let emptyParseResult fileName diagnostics = + let parseTree = EmptyParsedInput(fileName, (false, false)) + FSharpParseFileResults(diagnostics, parseTree, true, [||]) + + let ComputeParseAndCheckFileInProject (fileName: string) (projectSnapshot: ProjectSnapshot) = + caches.ParseAndCheckFileInProject.Get( + projectSnapshot.FileKey fileName, + node { + + use _ = + Activity.start "ComputeParseAndCheckFileInProject" [| Activity.Tags.fileName, fileName |> Path.GetFileName |] + + match! ComputeBootstrapInfo projectSnapshot with + | None, creationDiags -> return emptyParseResult fileName creationDiags, FSharpCheckFileAnswer.Aborted + + | Some bootstrapInfo, creationDiags -> + + let priorSnapshot = projectSnapshot.UpTo fileName + let! snapshotWithSources = LoadSources bootstrapInfo priorSnapshot + let file = snapshotWithSources.SourceFiles |> List.last + + let! parseResults = getParseResult projectSnapshot creationDiags file bootstrapInfo.TcConfig + + let! result, tcInfo = ComputeTcLastFile bootstrapInfo snapshotWithSources + + let (tcEnv, _topAttribs, checkedImplFileOpt, ccuSigForFile) = result + + let tcState = tcInfo.tcState + + let sink = tcInfo.sink.Head // TODO: don't use head + + let tcResolutions = sink.GetResolutions() + let tcSymbolUses = sink.GetSymbolUses() + let tcOpenDeclarations = sink.GetOpenDeclarations() + + let tcDependencyFiles = [] // TODO add as a set to TcIntermediate + + // TODO: Apparently creating diagnostics can produce further diagnostics. So let's capture those too. Hopefully there is a more elegant solution... + // Probably diagnostics need to be evaluated during typecheck anyway for proper formatting, which might take care of this too. + let extraLogger = CapturingDiagnosticsLogger("DiagnosticsWhileCreatingDiagnostics") + use _ = new CompilationGlobalsScope(extraLogger, BuildPhase.TypeCheck) + + // Apply nowarns to tcConfig (may generate errors, so ensure diagnosticsLogger is installed) + let tcConfig = + ApplyNoWarnsToTcConfig(bootstrapInfo.TcConfig, parseResults.ParseTree, Path.GetDirectoryName fileName) + + let diagnosticsOptions = tcConfig.diagnosticsOptions + + let symbolEnv = + SymbolEnv(bootstrapInfo.TcGlobals, tcState.Ccu, Some tcState.CcuSig, bootstrapInfo.TcImports) + + let tcDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + diagnosticsOptions, + false, + fileName, + tcInfo.TcDiagnostics, + suggestNamesForErrors, + bootstrapInfo.TcConfig.flatErrors, + Some symbolEnv + ) + + let extraDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + diagnosticsOptions, + false, + fileName, + extraLogger.Diagnostics, + suggestNamesForErrors, + bootstrapInfo.TcConfig.flatErrors, + Some symbolEnv + ) + + let tcDiagnostics = + [| yield! creationDiags; yield! extraDiagnostics; yield! tcDiagnostics |] + + let loadClosure = None // TODO: script support + + let typedResults = + FSharpCheckFileResults.Make( + fileName, + projectSnapshot.ProjectFileName, + bootstrapInfo.TcConfig, + bootstrapInfo.TcGlobals, + projectSnapshot.IsIncompleteTypeCheckEnvironment, + None, + projectSnapshot.ToOptions(), + Array.ofList tcDependencyFiles, + creationDiags, + parseResults.Diagnostics, + tcDiagnostics, + keepAssemblyContents, + ccuSigForFile, + tcState.Ccu, + bootstrapInfo.TcImports, + tcEnv.AccessRights, + tcResolutions, + tcSymbolUses, + tcEnv.NameEnv, + loadClosure, + checkedImplFileOpt, + tcOpenDeclarations + ) + + return (parseResults, FSharpCheckFileAnswer.Succeeded typedResults) + } + ) + + let ComputeParseAndCheckAllFilesInProject (bootstrapInfo: BootstrapInfo) (projectSnapshot: ProjectSnapshotWithSources) = + caches.ParseAndCheckAllFilesInProject.Get( + projectSnapshot.FullKey, + node { + use _ = + Activity.start + "ComputeParseAndCheckAllFilesInProject" + [| Activity.Tags.project, projectSnapshot.ProjectFileName |> Path.GetFileName |] + + let! projectSnapshot = parseSourceFiles projectSnapshot bootstrapInfo.TcConfig + + let! graph, dependencyFiles = ComputeDependencyGraphForProject bootstrapInfo.TcConfig projectSnapshot + + return! + processTypeCheckingGraph + graph + (processGraphNode projectSnapshot bootstrapInfo dependencyFiles true) + bootstrapInfo.InitialTcInfo + |> NodeCode.AwaitAsync + } + ) + + let ComputeProjectExtras (bootstrapInfo: BootstrapInfo) (projectSnapshot: ProjectSnapshotWithSources) = + caches.ProjectExtras.Get( + projectSnapshot.SignatureKey, + node { + + let! results, finalInfo = ComputeParseAndCheckAllFilesInProject bootstrapInfo projectSnapshot + + let assemblyName = bootstrapInfo.AssemblyName + let tcConfig = bootstrapInfo.TcConfig + let tcGlobals = bootstrapInfo.TcGlobals + + let results = results |> Seq.sortBy fst |> Seq.map snd |> Seq.toList + + // Finish the checking + let (_tcEnvAtEndOfLastFile, topAttrs, checkedImplFiles, _), tcState = + CheckMultipleInputsFinish(results, finalInfo.tcState) + + let tcState, _, ccuContents = CheckClosedInputSetFinish([], tcState) + + let generatedCcu = tcState.Ccu.CloneWithFinalizedContents(ccuContents) + + // Compute the identity of the generated assembly based on attributes, options etc. + // Some of this is duplicated from fsc.fs + let ilAssemRef = + let publicKey = + try + let signingInfo = ValidateKeySigningAttributes(tcConfig, tcGlobals, topAttrs) + + match GetStrongNameSigner signingInfo with + | None -> None + | Some s -> Some(PublicKey.KeyAsToken(s.PublicKey)) + with exn -> + errorRecoveryNoRange exn + None + + let locale = + TryFindFSharpStringAttribute + tcGlobals + (tcGlobals.FindSysAttrib "System.Reflection.AssemblyCultureAttribute") + topAttrs.assemblyAttrs + + let assemVerFromAttrib = + TryFindFSharpStringAttribute + tcGlobals + (tcGlobals.FindSysAttrib "System.Reflection.AssemblyVersionAttribute") + topAttrs.assemblyAttrs + |> Option.bind (fun v -> + try + Some(parseILVersion v) + with _ -> + None) + + let ver = + match assemVerFromAttrib with + | None -> tcConfig.version.GetVersionInfo(tcConfig.implicitIncludeDir) + | Some v -> v + + ILAssemblyRef.Create(assemblyName, None, publicKey, false, Some ver, locale) + + let assemblyDataResult = + try + // Assemblies containing type provider components can not successfully be used via cross-assembly references. + // We return 'None' for the assembly portion of the cross-assembly reference + let hasTypeProviderAssemblyAttrib = + topAttrs.assemblyAttrs + |> List.exists (fun (Attrib(tcref, _, _, _, _, _, _)) -> + let nm = tcref.CompiledRepresentationForNamedType.BasicQualifiedName + + nm = typeof.FullName) + + if tcState.CreatesGeneratedProvidedTypes || hasTypeProviderAssemblyAttrib then + ProjectAssemblyDataResult.Unavailable true + else + ProjectAssemblyDataResult.Available( + RawFSharpAssemblyDataBackedByLanguageService( + bootstrapInfo.TcConfig, + bootstrapInfo.TcGlobals, + generatedCcu, + bootstrapInfo.OutFile, + topAttrs, + bootstrapInfo.AssemblyName, + ilAssemRef + ) + :> IRawFSharpAssemblyData + ) + with exn -> + errorRecoveryNoRange exn + ProjectAssemblyDataResult.Unavailable true + + return finalInfo, ilAssemRef, assemblyDataResult, checkedImplFiles + } + ) + + let ComputeAssemblyData (projectSnapshot: ProjectSnapshot) fileName = + caches.AssemblyData.Get( + projectSnapshot.SignatureKey, + node { + + try + + let availableOnDiskModifiedTime = + if FileSystem.FileExistsShim fileName then + Some <| FileSystem.GetLastWriteTimeShim fileName + else + None + + // TODO: This kinda works, but the problem is that in order to switch a project to "in-memory" mode + // - some file needs to be edited (this tirggers a re-check, but LastModifiedTimeOnDisk won't change) + // - saved (this will not trigger anything) + // - and then another change has to be made (to any file buffer) - so that recheck is triggered and we get here again + // Until that sequence happens the project will be used from disk (if available). + // To get around it we probably need to detect changes made in the editor and record a timestamp for them. + let shouldUseOnDisk = + availableOnDiskModifiedTime + |> Option.exists (fun t -> t >= projectSnapshot.GetLastModifiedTimeOnDisk()) + + let name = projectSnapshot.ProjectFileName |> Path.GetFileNameWithoutExtension + + if shouldUseOnDisk then + Trace.TraceInformation($"Using assembly on disk: {name}") + return ProjectAssemblyDataResult.Unavailable true + else + match! ComputeBootstrapInfo projectSnapshot with + | None, _ -> + Trace.TraceInformation($"Using assembly on disk (unintentionally): {name}") + return ProjectAssemblyDataResult.Unavailable true + | Some bootstrapInfo, _creationDiags -> + + let! snapshotWithSources = LoadSources bootstrapInfo projectSnapshot + + let! _, _, assemblyDataResult, _ = ComputeProjectExtras bootstrapInfo snapshotWithSources + Trace.TraceInformation($"Using in-memory project reference: {name}") + + return assemblyDataResult + with + | TaskCancelled ex -> return raise ex + | ex -> + errorR (exn ($"Error while computing assembly data for project {projectSnapshot.Label}: {ex}")) + return ProjectAssemblyDataResult.Unavailable true + } + ) + + let ComputeParseAndCheckProject (projectSnapshot: ProjectSnapshot) = + caches.ParseAndCheckProject.Get( + projectSnapshot.FullKey, + node { + + match! ComputeBootstrapInfo projectSnapshot with + | None, creationDiags -> + return FSharpCheckProjectResults(projectSnapshot.ProjectFileName, None, keepAssemblyContents, creationDiags, None) + | Some bootstrapInfo, creationDiags -> + + let! snapshotWithSources = LoadSources bootstrapInfo projectSnapshot + + let! tcInfo, ilAssemRef, assemblyDataResult, checkedImplFiles = ComputeProjectExtras bootstrapInfo snapshotWithSources + + let diagnosticsOptions = bootstrapInfo.TcConfig.diagnosticsOptions + let fileName = DummyFileNameForRangesWithoutASpecificLocation + + let topAttribs = tcInfo.topAttribs + let tcState = tcInfo.tcState + let tcEnvAtEnd = tcInfo.tcEnvAtEndOfFile + let tcDiagnostics = tcInfo.TcDiagnostics + let tcDependencyFiles = tcInfo.tcDependencyFiles + + let symbolEnv = + SymbolEnv(bootstrapInfo.TcGlobals, tcInfo.tcState.Ccu, Some tcInfo.tcState.CcuSig, bootstrapInfo.TcImports) + |> Some + + let tcDiagnostics = + DiagnosticHelpers.CreateDiagnostics( + diagnosticsOptions, + true, + fileName, + tcDiagnostics, + suggestNamesForErrors, + bootstrapInfo.TcConfig.flatErrors, + symbolEnv + ) + + let diagnostics = [| yield! creationDiags; yield! tcDiagnostics |] + + let getAssemblyData () = + match assemblyDataResult with + | ProjectAssemblyDataResult.Available data -> Some data + | _ -> None + + let symbolUses = tcInfo.sink |> Seq.map (fun sink -> sink.GetSymbolUses()) + + let details = + (bootstrapInfo.TcGlobals, + bootstrapInfo.TcImports, + tcState.Ccu, + tcState.CcuSig, + Choice2Of2(async.Return symbolUses), + topAttribs, + getAssemblyData, + ilAssemRef, + tcEnvAtEnd.AccessRights, + Some checkedImplFiles, + Array.ofList tcDependencyFiles, + projectSnapshot.ToOptions()) + + let results = + FSharpCheckProjectResults( + projectSnapshot.ProjectFileName, + Some bootstrapInfo.TcConfig, + keepAssemblyContents, + diagnostics, + Some details + ) + + return results + } + ) + + let tryGetSink (fileName: string) (projectSnapshot: ProjectSnapshot) = + node { + match! ComputeBootstrapInfo projectSnapshot with + | None, _ -> return None + | Some bootstrapInfo, _creationDiags -> + + let! snapshotWithSources = projectSnapshot.UpTo fileName |> LoadSources bootstrapInfo + + let! _, tcInfo = ComputeTcLastFile bootstrapInfo snapshotWithSources + + return tcInfo.sink |> List.tryHead |> Option.map (fun sink -> sink, bootstrapInfo) + } + + let ComputeSemanticClassification (fileName: string, projectSnapshot: ProjectSnapshot) = + caches.SemanticClassification.Get( + projectSnapshot.FileKey fileName, + node { + use _ = + Activity.start "ComputeSemanticClassification" [| Activity.Tags.fileName, fileName |> Path.GetFileName |] + + let! sinkOpt = tryGetSink fileName projectSnapshot + + return + sinkOpt + |> Option.bind (fun (sink, bootstrapInfo) -> + let sResolutions = sink.GetResolutions() + + let semanticClassification = + sResolutions.GetSemanticClassification( + bootstrapInfo.TcGlobals, + bootstrapInfo.TcImports.GetImportMap(), + sink.GetFormatSpecifierLocations(), + None + ) + + let sckBuilder = SemanticClassificationKeyStoreBuilder() + sckBuilder.WriteAll semanticClassification + + sckBuilder.TryBuildAndReset()) + |> Option.map (fun sck -> sck.GetView()) + } + ) + + let ComputeItemKeyStore (fileName: string, projectSnapshot: ProjectSnapshot) = + caches.ItemKeyStore.Get( + projectSnapshot.FileKey fileName, + node { + use _ = + Activity.start "ComputeItemKeyStore" [| Activity.Tags.fileName, fileName |> Path.GetFileName |] + + let! sinkOpt = tryGetSink fileName projectSnapshot + + return + sinkOpt + |> Option.bind (fun (sink, { TcGlobals = g }) -> + let sResolutions = sink.GetResolutions() + + let builder = ItemKeyStoreBuilder(g) + + let preventDuplicates = + HashSet( + { new IEqualityComparer with + member _.Equals((s1, e1): struct (pos * pos), (s2, e2): struct (pos * pos)) = + Position.posEq s1 s2 && Position.posEq e1 e2 + + member _.GetHashCode o = o.GetHashCode() + } + ) + + sResolutions.CapturedNameResolutions + |> Seq.iter (fun cnr -> + let r = cnr.Range + + if preventDuplicates.Add struct (r.Start, r.End) then + builder.Write(cnr.Range, cnr.Item)) + + builder.TryBuildAndReset()) + } + ) + + member _.ParseFile(fileName, projectSnapshot: ProjectSnapshot, _userOpName) = + node { + //use _ = + // Activity.start "ParseFile" [| Activity.Tags.fileName, fileName |> Path.GetFileName |] + + // TODO: might need to deal with exceptions here: + let tcConfigB, sourceFileNames, _ = ComputeTcConfigBuilder projectSnapshot + + let tcConfig = TcConfig.Create(tcConfigB, validate = true) + + let _index, fileSnapshot = + projectSnapshot.SourceFiles + |> Seq.mapi pair + |> Seq.tryFind (fun (_, f) -> f.FileName = fileName) + |> Option.defaultWith (fun () -> failwith $"File not found: {fileName}") + + let isExe = tcConfig.target.IsExe + let isLastCompiland = fileName = (sourceFileNames |> List.last) + + let! file = LoadSource fileSnapshot isExe isLastCompiland + let! parseResult = getParseResult projectSnapshot Seq.empty file tcConfig + return parseResult + } + + member _.ParseAndCheckFileInProject(fileName: string, projectSnapshot: ProjectSnapshot, userOpName: string) = + ignore userOpName + ComputeParseAndCheckFileInProject fileName projectSnapshot + + member _.FindReferencesInFile(fileName: string, projectSnapshot: ProjectSnapshot, symbol: FSharpSymbol, userOpName: string) = + ignore userOpName + + node { + match! ComputeItemKeyStore(fileName, projectSnapshot) with + | None -> return Seq.empty + | Some itemKeyStore -> return itemKeyStore.FindAll symbol.Item + } + + member _.GetAssemblyData(projectSnapshot: ProjectSnapshot, fileName, _userOpName) = + ComputeAssemblyData projectSnapshot fileName + + member _.Caches = caches + + member _.SetCacheSizeFactor(sizeFactor: int) = + if sizeFactor <> caches.SizeFactor then + caches <- CompilerCaches(sizeFactor) + + interface IBackgroundCompiler with + + member this.CheckFileInProject + ( + parseResults: FSharpParseFileResults, + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + node { + let! snapshot = + FSharpProjectSnapshot.FromOptions(options, fileName, fileVersion, sourceText) + |> NodeCode.AwaitAsync + + ignore parseResults + + let! _, result = this.ParseAndCheckFileInProject(fileName, snapshot.ProjectSnapshot, userOpName) + + return result + } + + member this.CheckFileInProjectAllowingStaleCachedResults + ( + parseResults: FSharpParseFileResults, + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + node { + let! snapshot = + FSharpProjectSnapshot.FromOptions(options, fileName, fileVersion, sourceText) + |> NodeCode.AwaitAsync + + ignore parseResults + + let! _, result = this.ParseAndCheckFileInProject(fileName, snapshot.ProjectSnapshot, userOpName) + + return Some result + } + + member this.ClearCache(projects: FSharpProjectIdentifier seq, userOpName: string) : unit = + use _ = + Activity.start "TransparentCompiler.ClearCache" [| Activity.Tags.userOpName, userOpName |] + + this.Caches.Clear( + projects + |> Seq.map (function + | FSharpProjectIdentifier(x, y) -> (x, y)) + |> Set + ) + + member this.ClearCache(options: seq, userOpName: string) : unit = + use _ = + Activity.start "TransparentCompiler.ClearCache" [| Activity.Tags.userOpName, userOpName |] + + backgroundCompiler.ClearCache(options, userOpName) + this.Caches.Clear(options |> Seq.map (fun o -> o.GetProjectIdentifier()) |> Set) + + member _.ClearCaches() : unit = + backgroundCompiler.ClearCaches() + caches <- CompilerCaches(100) // TODO: check + + member _.DownsizeCaches() : unit = backgroundCompiler.DownsizeCaches() + + member _.BeforeBackgroundFileCheck = beforeFileChecked.Publish + + member _.FileParsed = fileParsed.Publish + + member _.FileChecked = fileChecked.Publish + + member _.ProjectChecked = projectChecked.Publish + + member this.FindReferencesInFile + ( + fileName: string, + options: FSharpProjectOptions, + symbol: FSharpSymbol, + canInvalidateProject: bool, + userOpName: string + ) : NodeCode> = + node { + ignore canInvalidateProject + let! snapshot = FSharpProjectSnapshot.FromOptions options |> NodeCode.AwaitAsync + + return! this.FindReferencesInFile(fileName, snapshot.ProjectSnapshot, symbol, userOpName) + } + + member this.FindReferencesInFile(fileName, projectSnapshot, symbol, userOpName) = + this.FindReferencesInFile(fileName, projectSnapshot.ProjectSnapshot, symbol, userOpName) + + member _.FrameworkImportsCache: FrameworkImportsCache = + backgroundCompiler.FrameworkImportsCache + + member this.GetAssemblyData(options: FSharpProjectOptions, fileName, userOpName: string) : NodeCode = + node { + let! snapshot = FSharpProjectSnapshot.FromOptions options |> NodeCode.AwaitAsync + return! this.GetAssemblyData(snapshot.ProjectSnapshot, fileName, userOpName) + } + + member this.GetAssemblyData + ( + projectSnapshot: FSharpProjectSnapshot, + fileName, + userOpName: string + ) : NodeCode = + this.GetAssemblyData(projectSnapshot.ProjectSnapshot, fileName, userOpName) + + member this.GetBackgroundCheckResultsForFileInProject + ( + fileName: string, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + node { + let! snapshot = FSharpProjectSnapshot.FromOptions options |> NodeCode.AwaitAsync + + match! this.ParseAndCheckFileInProject(fileName, snapshot.ProjectSnapshot, userOpName) with + | parseResult, FSharpCheckFileAnswer.Succeeded checkResult -> return parseResult, checkResult + | parseResult, FSharpCheckFileAnswer.Aborted -> return parseResult, FSharpCheckFileResults.MakeEmpty(fileName, [||], true) + } + + member this.GetBackgroundParseResultsForFileInProject + ( + fileName: string, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + node { + let! snapshot = FSharpProjectSnapshot.FromOptions options |> NodeCode.AwaitAsync + return! this.ParseFile(fileName, snapshot.ProjectSnapshot, userOpName) + } + + member this.GetCachedCheckFileResult + ( + builder: IncrementalBuilder, + fileName: string, + sourceText: ISourceText, + options: FSharpProjectOptions + ) : NodeCode<(FSharpParseFileResults * FSharpCheckFileResults) option> = + node { + ignore builder + + let! snapshot = + FSharpProjectSnapshot.FromOptions(options, fileName, 1, sourceText) + |> NodeCode.AwaitAsync + + match! this.ParseAndCheckFileInProject(fileName, snapshot.ProjectSnapshot, "GetCachedCheckFileResult") with + | parseResult, FSharpCheckFileAnswer.Succeeded checkResult -> return Some(parseResult, checkResult) + | _, FSharpCheckFileAnswer.Aborted -> return None + } + + member this.GetProjectOptionsFromScript + ( + fileName: string, + sourceText: ISourceText, + previewEnabled: bool option, + loadedTimeStamp: DateTime option, + otherFlags: string array option, + useFsiAuxLib: bool option, + useSdkRefs: bool option, + sdkDirOverride: string option, + assumeDotNetFramework: bool option, + optionsStamp: int64 option, + userOpName: string + ) : Async = + backgroundCompiler.GetProjectOptionsFromScript( + fileName, + sourceText, + previewEnabled, + loadedTimeStamp, + otherFlags, + useFsiAuxLib, + useSdkRefs, + sdkDirOverride, + assumeDotNetFramework, + optionsStamp, + userOpName + ) + + member this.GetSemanticClassificationForFile(fileName: string, snapshot: FSharpProjectSnapshot, userOpName: string) = + node { + ignore userOpName + return! ComputeSemanticClassification(fileName, snapshot.ProjectSnapshot) + } + + member this.GetSemanticClassificationForFile + ( + fileName: string, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + node { + ignore userOpName + let! snapshot = FSharpProjectSnapshot.FromOptions options |> NodeCode.AwaitAsync + return! ComputeSemanticClassification(fileName, snapshot.ProjectSnapshot) + } + + member this.InvalidateConfiguration(options: FSharpProjectOptions, userOpName: string) : unit = + backgroundCompiler.InvalidateConfiguration(options, userOpName) + + member this.NotifyFileChanged(fileName: string, options: FSharpProjectOptions, userOpName: string) : NodeCode = + backgroundCompiler.NotifyFileChanged(fileName, options, userOpName) + + member this.NotifyProjectCleaned(options: FSharpProjectOptions, userOpName: string) : Async = + backgroundCompiler.NotifyProjectCleaned(options, userOpName) + + member this.ParseAndCheckFileInProject + ( + fileName: string, + fileVersion: int, + sourceText: ISourceText, + options: FSharpProjectOptions, + userOpName: string + ) : NodeCode = + node { + let! snapshot = + FSharpProjectSnapshot.FromOptions(options, fileName, fileVersion, sourceText) + |> NodeCode.AwaitAsync + + return! this.ParseAndCheckFileInProject(fileName, snapshot.ProjectSnapshot, userOpName) + } + + member this.ParseAndCheckFileInProject(fileName: string, projectSnapshot: FSharpProjectSnapshot, userOpName: string) = + this.ParseAndCheckFileInProject(fileName, projectSnapshot.ProjectSnapshot, userOpName) + + member this.ParseAndCheckProject(options: FSharpProjectOptions, userOpName: string) : NodeCode = + node { + ignore userOpName + let! snapshot = FSharpProjectSnapshot.FromOptions options |> NodeCode.AwaitAsync + return! ComputeParseAndCheckProject snapshot.ProjectSnapshot + } + + member this.ParseAndCheckProject(projectSnapshot: FSharpProjectSnapshot, userOpName: string) : NodeCode = + node { + ignore userOpName + return! ComputeParseAndCheckProject projectSnapshot.ProjectSnapshot + } + + member this.ParseFile(fileName, projectSnapshot, userOpName) = + this.ParseFile(fileName, projectSnapshot.ProjectSnapshot, userOpName) + |> Async.AwaitNodeCode + + member this.ParseFile + ( + fileName: string, + sourceText: ISourceText, + options: FSharpParsingOptions, + cache: bool, + flatErrors: bool, + userOpName: string + ) = + backgroundCompiler.ParseFile(fileName, sourceText, options, cache, flatErrors, userOpName) + + member this.TryGetRecentCheckResultsForFile + ( + fileName: string, + options: FSharpProjectOptions, + sourceText: ISourceText option, + userOpName: string + ) : (FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash) option = + backgroundCompiler.TryGetRecentCheckResultsForFile(fileName, options, sourceText, userOpName) diff --git a/src/Compiler/Service/TransparentCompiler.fsi b/src/Compiler/Service/TransparentCompiler.fsi new file mode 100644 index 00000000000..00167ccc67f --- /dev/null +++ b/src/Compiler/Service/TransparentCompiler.fsi @@ -0,0 +1,175 @@ +namespace FSharp.Compiler.CodeAnalysis.TransparentCompiler + +open Internal.Utilities.Collections + +open FSharp.Compiler.AbstractIL.ILBinaryReader +open FSharp.Compiler.BuildGraph +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CompilerConfig +open FSharp.Compiler.CompilerImports +open FSharp.Compiler.CheckBasics +open FSharp.Compiler.Diagnostics +open FSharp.Compiler.DiagnosticsLogger +open FSharp.Compiler.ScriptClosure +open FSharp.Compiler.Symbols +open FSharp.Compiler.TcGlobals +open FSharp.Compiler.Text +open FSharp.Compiler.ParseAndCheckInputs +open FSharp.Compiler.GraphChecking +open FSharp.Compiler.Syntax +open FSharp.Compiler.NameResolution +open FSharp.Compiler.TypedTree +open FSharp.Compiler.CheckDeclarations +open FSharp.Compiler.EditorServices + +/// Accumulated results of type checking. The minimum amount of state in order to continue type-checking following files. +[] +type internal TcInfo = + { + tcState: TcState + tcEnvAtEndOfFile: TcEnv + + /// Disambiguation table for module names + moduleNamesDict: ModuleNamesDict + + topAttribs: TopAttribs option + + latestCcuSigForFile: ModuleOrNamespaceType option + + /// Accumulated diagnostics, last file first + tcDiagnosticsRev: (PhasedDiagnostic * FSharpDiagnosticSeverity)[] list + + tcDependencyFiles: string list + + sigNameOpt: (string * QualifiedNameOfFile) option + + graphNode: NodeToTypeCheck option + + stateContainsNodes: Set + + sink: TcResultsSinkImpl list + } + +[] +type internal TcIntermediate = + { + finisher: Finisher + + /// Disambiguation table for module names + moduleNamesDict: ModuleNamesDict + + /// Accumulated diagnostics, last file first + tcDiagnosticsRev: (PhasedDiagnostic * FSharpDiagnosticSeverity) array list + tcDependencyFiles: string list + sink: TcResultsSinkImpl + } + +/// Things we need to start parsing and checking files for a given project snapshot +type internal BootstrapInfo = + { Id: int + AssemblyName: string + OutFile: string + TcConfig: TcConfig + TcImports: TcImports + TcGlobals: TcGlobals + InitialTcInfo: TcInfo + LoadedSources: (range * ProjectSnapshot.FSharpFileSnapshot) list + LoadClosure: LoadClosure option + LastFileName: string } + +type internal TcIntermediateResult = TcInfo * TcResultsSinkImpl * CheckedImplFile option * string + +[] +type internal DependencyGraphType = + + /// A dependency graph for a single file - it will be missing files which this file does not depend on + | File + + /// A dependency graph for a project - it will contain all files in the project + | Project + +[] +type internal Extensions = + + [] + static member Key: + fileSnapshots: #ProjectSnapshot.IFileSnapshot list * ?extraKeyFlag: DependencyGraphType -> + ICacheKey<(DependencyGraphType option * byte array), string> + +type internal CompilerCaches = + + new: sizeFactor: int -> CompilerCaches + + member AssemblyData: AsyncMemoize<(string * string), (string * string), ProjectAssemblyDataResult> + + member BootstrapInfo: AsyncMemoize<(string * string), string, (BootstrapInfo option * FSharpDiagnostic array)> + + member BootstrapInfoStatic: + AsyncMemoize<(string * string), (string * string), (int * TcImports * TcGlobals * TcInfo * Event)> + + member DependencyGraph: + AsyncMemoize<(DependencyGraphType option * byte array), string, (Graph * Graph)> + + member FrameworkImports: AsyncMemoize + + member ItemKeyStore: AsyncMemoize<(string * (string * string)), string, ItemKeyStore option> + + member ParseAndCheckAllFilesInProject: AsyncMemoizeDisabled + + member ParseAndCheckFileInProject: + AsyncMemoize<(string * (string * string)), string, (FSharpParseFileResults * FSharpCheckFileAnswer)> + + member ParseAndCheckProject: AsyncMemoize<(string * string), string, FSharpCheckProjectResults> + + member ParseFile: + AsyncMemoize<((string * string) * string), (string * string * bool), ProjectSnapshot.FSharpParsedFile> + + member ProjectExtras: AsyncMemoizeDisabled + + member SemanticClassification: AsyncMemoize<(string * (string * string)), string, SemanticClassificationView option> + + member SizeFactor: int + + member TcIntermediate: AsyncMemoize<(string * (string * string)), (string * int), TcIntermediate> + + member TcLastFile: AsyncMemoizeDisabled + +type internal TransparentCompiler = + interface IBackgroundCompiler + + new: + legacyReferenceResolver: LegacyReferenceResolver * + projectCacheSize: int * + keepAssemblyContents: bool * + keepAllBackgroundResolutions: bool * + tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot * + suggestNamesForErrors: bool * + keepAllBackgroundSymbolUses: bool * + enableBackgroundItemKeyStoreAndSemanticClassification: bool * + enablePartialTypeChecking: bool * + parallelReferenceResolution: ParallelReferenceResolution * + captureIdentifiersWhenParsing: bool * + getSource: (string -> Async) option * + useChangeNotifications: bool * + useSyntaxTreeCache: bool -> + TransparentCompiler + + member FindReferencesInFile: + fileName: string * projectSnapshot: ProjectSnapshot.ProjectSnapshot * symbol: FSharpSymbol * userOpName: string -> + NodeCode + + member GetAssemblyData: + projectSnapshot: ProjectSnapshot.ProjectSnapshot * fileName: string * _userOpName: string -> + NodeCode + + member ParseAndCheckFileInProject: + fileName: string * projectSnapshot: ProjectSnapshot.ProjectSnapshot * userOpName: string -> + NodeCode + + member ParseFile: + fileName: string * projectSnapshot: ProjectSnapshot.ProjectSnapshot * _userOpName: 'a -> + NodeCode + + member SetCacheSizeFactor: sizeFactor: int -> unit + + member Caches: CompilerCaches diff --git a/src/Compiler/Service/service.fs b/src/Compiler/Service/service.fs index c5b6e64ffdc..492ff2da497 100644 --- a/src/Compiler/Service/service.fs +++ b/src/Compiler/Service/service.fs @@ -17,6 +17,7 @@ open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.AbstractIL.ILBinaryReader open FSharp.Compiler.AbstractIL.ILDynamicAssemblyWriter open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CodeAnalysis.TransparentCompiler open FSharp.Compiler.CompilerConfig open FSharp.Compiler.CompilerDiagnostics open FSharp.Compiler.CompilerImports @@ -36,19 +37,6 @@ open FSharp.Compiler.Text.Range open FSharp.Compiler.TcGlobals open FSharp.Compiler.BuildGraph -[] -module EnvMisc = - let braceMatchCacheSize = GetEnvInteger "FCS_BraceMatchCacheSize" 5 - let parseFileCacheSize = GetEnvInteger "FCS_ParseFileCacheSize" 2 - let checkFileInProjectCacheSize = GetEnvInteger "FCS_CheckFileInProjectCacheSize" 10 - - let projectCacheSizeDefault = GetEnvInteger "FCS_ProjectCacheSizeDefault" 3 - let frameworkTcImportsCacheStrongSize = GetEnvInteger "FCS_frameworkTcImportsCacheStrongSizeDefault" 8 - -//---------------------------------------------------------------------------- -// BackgroundCompiler -// - [] type DocumentSource = | FileSystem @@ -58,46 +46,6 @@ type DocumentSource = [] type IsResultObsolete = IsResultObsolete of (unit -> bool) -[] -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)) = - (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)) = - fileName1 = fileName2 && options1 = options2 && source1Hash = source2Hash - - 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) - && 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) - - /// If a symbol is an attribute check if given set of names contains its name without the Attribute suffix - let rec NamesContainAttribute (symbol: FSharpSymbol) names = - match symbol with - | :? FSharpMemberOrFunctionOrValue as mofov -> - mofov.DeclaringEntity - |> Option.map (fun entity -> NamesContainAttribute entity names) - |> Option.defaultValue false - | :? FSharpEntity as entity when entity.IsAttributeType && symbol.DisplayNameCore.EndsWithOrdinal "Attribute" -> - let nameWithoutAttribute = String.dropSuffix symbol.DisplayNameCore "Attribute" - names |> Set.contains nameWithoutAttribute - | _ -> false - module CompileHelpers = let mkCompilationDiagnosticsHandlers (flatErrors) = let diagnostics = ResizeArray<_>() @@ -165,1190 +113,6 @@ module CompileHelpers = Console.SetError error | None -> () -type SourceTextHash = int64 -type CacheStamp = int64 -type FileName = string -type FilePath = string -type ProjectPath = string -type FileVersion = int - -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, - parallelReferenceResolution, - captureIdentifiersWhenParsing, - getSource: (string -> Async) option, - useChangeNotifications, - useSyntaxTreeCache - ) as self = - - let beforeFileChecked = Event() - let fileParsed = Event() - let fileChecked = Event() - let projectChecked = Event() - - // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.scriptClosureCache - /// Information about the derived script closure. - 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() - - 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(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 - let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData - return ProjectAssemblyDataResult.Available data - | _ -> - // 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 = delayedReader.OutputFile - } - - | FSharpReferencedProject.ILModuleReference(nm, getStamp, getReader) -> - { new IProjectReference with - member x.EvaluateRawContents() = - cancellable { - let ilReader = getReader () - let ilModuleDef, ilAsmRefs = ilReader.ILModuleDef, ilReader.ILAssemblyRefs - let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData - return ProjectAssemblyDataResult.Available data - } - |> NodeCode.FromCancellable - - member x.TryGetLogicalTimeStamp _ = getStamp () |> Some - member x.FileName = nm - } - ] - - /// 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 { - use _ = - Activity.start "BackgroundCompiler.CreateOneIncrementalBuilder" [| Activity.Tags.project, options.ProjectFileName |] - - 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, - parallelReferenceResolution, - captureIdentifiersWhenParsing, - getSource, - useChangeNotifications, - useSyntaxTreeCache - ) - - 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)) -#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) - } - - let parseCacheLock = Lock() - - // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.parseFileInProjectCache. Most recently used cache for parsing files. - let parseFileCache = - MruCache(parseFileCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing) - - // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.checkFileInProjectCache - // - /// Cache which holds recently seen type-checks. - /// This cache may hold out-of-date entries, in two senses - /// - there may be a more recent antecedent state available because the background build has made it available - /// - the source for the file may have changed - - // 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 - ) - - // 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 - ) - - let tryGetBuilderNode options = - incrementalBuildersCache.TryGet(AnyCallerThread, options) - - let tryGetBuilder options : NodeCode option = - tryGetBuilderNode options |> Option.map (fun x -> x.GetOrComputeValue()) - - let tryGetSimilarBuilder options : NodeCode option = - incrementalBuildersCache.TryGetSimilar(AnyCallerThread, options) - |> Option.map (fun x -> x.GetOrComputeValue()) - - let tryGetAnyBuilder options : NodeCode option = - incrementalBuildersCache.TryGetAny(AnyCallerThread, options) - |> Option.map (fun x -> x.GetOrComputeValue()) - - let createBuilderNode (options, userOpName, ct: CancellationToken) = - lock gate (fun () -> - if ct.IsCancellationRequested then - GraphNode.FromResult(None, [||]) - else - let getBuilderNode = GraphNode(CreateOneIncrementalBuilder(options, userOpName)) - incrementalBuildersCache.Set(AnyCallerThread, options, getBuilderNode) - getBuilderNode) - - let createAndGetBuilder (options, userOpName) = - node { - let! ct = NodeCode.CancellationToken - let getBuilderNode = createBuilderNode (options, userOpName, ct) - return! getBuilderNode.GetOrComputeValue() - } - - let getOrCreateBuilder (options, userOpName) : NodeCode = - match tryGetBuilder options with - | Some getBuilder -> - node { - match! getBuilder with - | builderOpt, creationDiags when builderOpt.IsNone || not builderOpt.Value.IsReferencesInvalidated -> 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 -> - options.SourceFiles - |> Array.iter (fun sourceFile -> - let key = (sourceFile, 0L, options) - checkFileInProjectCache.RemoveAnySimilar(ltok, key))) - - return! createAndGetBuilder (options, userOpName) - } - | _ -> createAndGetBuilder (options, userOpName) - - let getSimilarOrCreateBuilder (options, userOpName) = - match tryGetSimilarBuilder options with - | Some res -> res - // The builder does not exist at all. Create it. - | None -> getOrCreateBuilder (options, userOpName) - - let getOrCreateBuilderWithInvalidationFlag (options, canInvalidateProject, userOpName) = - if canInvalidateProject then - getOrCreateBuilder (options, userOpName) - else - getSimilarOrCreateBuilder (options, userOpName) - - let getAnyBuilder (options, userOpName) = - match tryGetAnyBuilder options with - | Some getBuilder -> getBuilder - | _ -> 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) = - - // Here we lock for the creation of the node, not its execution - 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) - Interlocked.Increment(&actualCheckFileCount) |> ignore - return res - } - ) - - checkFileInProjectCache.Set(ltok, key, res) - res) - - member _.ParseFile(fileName: string, sourceText: ISourceText, options: FSharpParsingOptions, cache: bool, flatErrors: bool, userOpName: string) = - async { - use _ = - Activity.start - "BackgroundCompiler.ParseFile" - [| - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - Activity.Tags.cache, cache.ToString() - |] - - let! ct = Async.CancellationToken - use _ = Cancellable.UsingToken(ct) - - 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! ct = Async.CancellationToken - - let parseDiagnostics, parseTree, anyErrors = - ParseAndCheckFile.parseFile ( - sourceText, - fileName, - options, - userOpName, - suggestNamesForErrors, - flatErrors, - captureIdentifiersWhenParsing, - ct - ) - - let res = FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, options.SourceFiles) - parseCacheLock.AcquireLock(fun ltok -> parseFileCache.Set(ltok, (fileName, hash, options), res)) - return res - else - let! ct = Async.CancellationToken - - let parseDiagnostics, parseTree, anyErrors = - ParseAndCheckFile.parseFile (sourceText, fileName, options, userOpName, false, flatErrors, captureIdentifiersWhenParsing, ct) - - 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 { - use _ = - Activity.start - "BackgroundCompiler.GetBackgroundParseResultsForFileInProject" - [| Activity.Tags.fileName, fileName; Activity.Tags.userOpName, userOpName |] - - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - 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, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName - - let parseDiagnostics = - DiagnosticHelpers.CreateDiagnostics( - builder.TcConfig.diagnosticsOptions, - false, - fileName, - parseDiagnostics, - suggestNamesForErrors, - builder.TcConfig.flatErrors, - None - ) - - 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) = - node { - use _ = - Activity.start "BackgroundCompiler.GetCachedCheckFileResult" [| Activity.Tags.fileName, fileName |] - - let hash = sourceText.GetHashCode() |> int64 - let key = (fileName, hash, options) - let cachedResultsOpt = parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.TryGet(ltok, key)) - - 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) - | _ -> - parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.RemoveAnySimilar(ltok, key)) - return None - | _ -> return None - } - - member private _.CheckOneFileImplAux - ( - 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. - // For scripts, this will have been recorded by GetProjectOptionsFromScript. - let tcConfig = tcPrior.TcConfig - let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options) - - let! checkAnswer = - FSharpCheckFileResults.CheckOneFile( - parseResults, - sourceText, - fileName, - options.ProjectFileName, - tcConfig, - tcPrior.TcGlobals, - tcPrior.TcImports, - tcInfo.tcState, - tcInfo.moduleNamesDict, - loadClosure, - tcInfo.TcDiagnostics, - options.IsIncompleteTypeCheckEnvironment, - options, - builder, - Array.ofList tcInfo.tcDependencyFiles, - creationDiags, - parseResults.Diagnostics, - keepAssemblyContents, - 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 { - 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) - - 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 - ) = - node { - use _ = - Activity.start - "BackgroundCompiler.CheckFileInProjectAllowingStaleCachedResults" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - |] - - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - let! cachedResults = - node { - 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) - | _ -> 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 -> - match tcPrior.TryPeekTcInfo() with - | 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 - } - - /// 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 { - use _ = - Activity.start - "BackgroundCompiler.CheckFileInProject" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - |] - - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) - - match builderOpt with - | 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) - - match cachedResults with - | Some(_, checkResults) -> return FSharpCheckFileAnswer.Succeeded checkResults - | _ -> - let! tcPrior = builder.GetCheckResultsBeforeFileInProject fileName - let! tcInfo = tcPrior.GetOrComputeTcInfo() - return! bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) - } - - /// Parses and checks the source file and returns untyped AST and check results. - member bc.ParseAndCheckFileInProject(fileName: string, fileVersion, sourceText: ISourceText, options: FSharpProjectOptions, userOpName) = - node { - use _ = - Activity.start - "BackgroundCompiler.ParseAndCheckFileInProject" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - |] - - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) - - match builderOpt with - | None -> - let parseTree = EmptyParsedInput(fileName, (false, false)) - let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||]) - return (parseResults, FSharpCheckFileAnswer.Aborted) - - | Some builder -> - let! cachedResults = bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) - - match cachedResults with - | Some(parseResults, checkResults) -> return (parseResults, FSharpCheckFileAnswer.Succeeded checkResults) - | _ -> - let! tcPrior = builder.GetCheckResultsBeforeFileInProject fileName - let! tcInfo = tcPrior.GetOrComputeTcInfo() - // Do the parsing. - let parsingOptions = - FSharpParsingOptions.FromTcConfig(builder.TcConfig, Array.ofList builder.SourceFiles, options.UseScriptResolutionRules) - - GraphNode.SetPreferredUILang tcPrior.TcConfig.preferredUiLang - let! ct = NodeCode.CancellationToken - - let parseDiagnostics, parseTree, anyErrors = - ParseAndCheckFile.parseFile ( - sourceText, - fileName, - parsingOptions, - userOpName, - suggestNamesForErrors, - builder.TcConfig.flatErrors, - captureIdentifiersWhenParsing, - ct - ) - - let parseResults = - FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, builder.AllDependenciesDeprecated) - - let! checkResults = - bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags) - - return (parseResults, checkResults) - } - - member _.NotifyFileChanged(fileName, options, userOpName) = - node { - use _ = - Activity.start - "BackgroundCompiler.NotifyFileChanged" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - |] - - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - let! builderOpt, _ = getOrCreateBuilder (options, userOpName) - - match builderOpt with - | None -> return () - | Some builder -> do! builder.NotifyFileChanged(fileName, DateTime.UtcNow) - } - - /// Fetch the check information from the background compiler (which checks w.r.t. the FileSystem API) - member _.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName) = - node { - use _ = - Activity.start - "BackgroundCompiler.ParseAndCheckFileInProject" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - |] - - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName) - - match builderOpt with - | None -> - let parseTree = EmptyParsedInput(fileName, (false, false)) - let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||]) - let typedResults = FSharpCheckFileResults.MakeEmpty(fileName, creationDiags, true) - return (parseResults, typedResults) - | Some builder -> - let parseTree, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName - let! tcProj = builder.GetFullCheckResultsAfterFileInProject fileName - - let! tcInfo, tcInfoExtras = tcProj.GetOrComputeTcInfoWithExtras() - - let tcResolutions = tcInfoExtras.tcResolutions - let tcSymbolUses = tcInfoExtras.tcSymbolUses - let tcOpenDeclarations = tcInfoExtras.tcOpenDeclarations - let latestCcuSigForFile = tcInfo.latestCcuSigForFile - let tcState = tcInfo.tcState - let tcEnvAtEnd = tcInfo.tcEnvAtEndOfFile - let latestImplementationFile = tcInfoExtras.latestImplFile - let tcDependencyFiles = tcInfo.tcDependencyFiles - let tcDiagnostics = tcInfo.TcDiagnostics - let diagnosticsOptions = builder.TcConfig.diagnosticsOptions - - let symbolEnv = - SymbolEnv(tcProj.TcGlobals, tcInfo.tcState.Ccu, Some tcInfo.tcState.CcuSig, tcProj.TcImports) - |> Some - - let parseDiagnostics = - DiagnosticHelpers.CreateDiagnostics( - diagnosticsOptions, - false, - fileName, - parseDiagnostics, - suggestNamesForErrors, - builder.TcConfig.flatErrors, - None - ) - - let parseDiagnostics = [| yield! creationDiags; yield! parseDiagnostics |] - - let tcDiagnostics = - DiagnosticHelpers.CreateDiagnostics( - diagnosticsOptions, - false, - fileName, - tcDiagnostics, - suggestNamesForErrors, - builder.TcConfig.flatErrors, - symbolEnv - ) - - 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 - ) - - return (parseResults, typedResults) - } - - member _.FindReferencesInFile - ( - fileName: string, - options: FSharpProjectOptions, - symbol: FSharpSymbol, - canInvalidateProject: bool, - userOpName: string - ) = - node { - use _ = - Activity.start - "BackgroundCompiler.FindReferencesInFile" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - "symbol", symbol.FullName - |] - - let! builderOpt, _ = getOrCreateBuilderWithInvalidationFlag (options, canInvalidateProject, userOpName) - - match builderOpt with - | None -> return Seq.empty - | 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 - else - return Seq.empty - } - - member _.GetSemanticClassificationForFile(fileName: string, options: FSharpProjectOptions, userOpName: string) = - node { - use _ = - Activity.start - "BackgroundCompiler.GetSemanticClassificationForFile" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, userOpName - |] - - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - let! builderOpt, _ = getOrCreateBuilder (options, userOpName) - - match builderOpt with - | None -> return None - | Some builder -> - let! checkResults = builder.GetFullCheckResultsAfterFileInProject fileName - let! scopt = checkResults.GetOrComputeSemanticClassificationIfEnabled() - - match scopt with - | None -> return None - | 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) = - use _ = - Activity.start - "BackgroundCompiler.GetSemanticClassificationForFile" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.fileName, fileName - Activity.Tags.userOpName, _userOpName - |] - - match sourceText with - | Some sourceText -> - let hash = sourceText.GetHashCode() |> int64 - - 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 - - /// Parse and typecheck the whole project (the implementation, called recursively as project graph is evaluated) - member private _.ParseAndCheckProjectImpl(options, userOpName) = - node { - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - - 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 symbolEnv = - SymbolEnv(tcProj.TcGlobals, tcInfo.tcState.Ccu, Some tcInfo.tcState.CcuSig, tcProj.TcImports) - |> Some - - let tcDiagnostics = - DiagnosticHelpers.CreateDiagnostics( - diagnosticsOptions, - true, - fileName, - tcDiagnostics, - suggestNamesForErrors, - builder.TcConfig.flatErrors, - symbolEnv - ) - - 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 { - use _ = - Activity.start - "BackgroundCompiler.GetAssemblyData" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.userOpName, userOpName - |] - - let! builderOpt, _ = getOrCreateBuilder (options, userOpName) - - match builderOpt with - | None -> return ProjectAssemblyDataResult.Unavailable true - | Some builder -> - let! _, _, tcAssemblyDataOpt, _ = builder.GetCheckResultsAndImplementationsForProject() - return tcAssemblyDataOpt - } - - /// Get the timestamp that would be on the output if fully built immediately - member private _.TryGetLogicalTimeStampForProject(cache, options) = - match tryGetBuilderNode options with - | Some lazyWork -> - match lazyWork.TryPeekValue() with - | ValueSome(Some builder, _) -> Some(builder.GetLogicalTimeStampForProject(cache)) - | _ -> None - | _ -> None - - /// Parse and typecheck the whole project. - member bc.ParseAndCheckProject(options, userOpName) = - use _ = - Activity.start - "BackgroundCompiler.ParseAndCheckProject" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.userOpName, 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 - ) = - use _ = - Activity.start - "BackgroundCompiler.GetProjectOptionsFromScript" - [| Activity.Tags.fileName, fileName; Activity.Tags.userOpName, _userOpName |] - - cancellable { - // Do we add a reference to FSharp.Compiler.Interactive.Settings by default? - let useFsiAuxLib = defaultArg useFsiAuxLib 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! ct = Cancellable.token () - use _ = Cancellable.UsingToken(ct) - - let extraFlags = - if previewEnabled then - [| "--langversion:preview" |] - else - [||] - - let otherFlags = defaultArg otherFlags extraFlags - - use diagnostics = new DiagnosticsScope(otherFlags |> Array.contains "--flaterrors") - - let useSimpleResolution = otherFlags |> Array.exists (fun x -> x = "--simpleresolution") - - 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 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 - |] - - 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 = [||] - IsIncompleteTypeCheckEnvironment = false - UseScriptResolutionRules = true - LoadTime = loadedTimeStamp - 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, - options.OtherOptions |> Array.contains "--flaterrors", - None - )) - - return options, (diags @ diagnostics.Diagnostics) - } - |> Cancellable.toAsync - - member bc.InvalidateConfiguration(options: FSharpProjectOptions, userOpName) = - use _ = - Activity.start - "BackgroundCompiler.InvalidateConfiguration" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.userOpName, userOpName - |] - - if incrementalBuildersCache.ContainsSimilarKey(AnyCallerThread, options) then - parseCacheLock.AcquireLock(fun ltok -> - for sourceFile in options.SourceFiles do - checkFileInProjectCache.RemoveAnySimilar(ltok, (sourceFile, 0L, options))) - - let _ = createBuilderNode (options, userOpName, CancellationToken.None) - () - - member bc.ClearCache(options: seq, _userOpName) = - use _ = Activity.start "BackgroundCompiler.ClearCache" [| Activity.Tags.userOpName, _userOpName |] - - lock gate (fun () -> - options - |> Seq.iter (fun options -> - incrementalBuildersCache.RemoveAnySimilar(AnyCallerThread, options) - - parseCacheLock.AcquireLock(fun ltok -> - for sourceFile in options.SourceFiles do - checkFileInProjectCache.RemoveAnySimilar(ltok, (sourceFile, 0L, options))))) - - member _.NotifyProjectCleaned(options: FSharpProjectOptions, userOpName) = - use _ = - Activity.start - "BackgroundCompiler.NotifyProjectCleaned" - [| - Activity.Tags.project, options.ProjectFileName - Activity.Tags.userOpName, userOpName - |] - - async { - let! ct = Async.CancellationToken - use _ = Cancellable.UsingToken(ct) - - 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 - // builder, but costs some time. - if incrementalBuildersCache.ContainsSimilarKey(AnyCallerThread, options) then - let _ = createBuilderNode (options, userOpName, ct) - () - } - - member _.BeforeBackgroundFileCheck = beforeFileChecked.Publish - - member _.FileParsed = fileParsed.Publish - - member _.FileChecked = fileChecked.Publish - - member _.ProjectChecked = projectChecked.Publish - - member _.ClearCaches() = - use _ = Activity.startNoTags "BackgroundCompiler.ClearCaches" - - lock gate (fun () -> - parseCacheLock.AcquireLock(fun ltok -> - checkFileInProjectCache.Clear(ltok) - parseFileCache.Clear(ltok)) - - incrementalBuildersCache.Clear(AnyCallerThread) - frameworkTcImportsCache.Clear() - scriptClosureCache.Clear AnyCallerThread) - - member _.DownsizeCaches() = - use _ = Activity.startNoTags "BackgroundCompiler.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) - frameworkTcImportsCache.Downsize() - 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 @@ -1366,26 +130,47 @@ type FSharpChecker captureIdentifiersWhenParsing, getSource, useChangeNotifications, - useSyntaxTreeCache + useSyntaxTreeCache, + useTransparentCompiler ) = let backgroundCompiler = - BackgroundCompiler( - legacyReferenceResolver, - projectCacheSize, - keepAssemblyContents, - keepAllBackgroundResolutions, - tryGetMetadataSnapshot, - suggestNamesForErrors, - keepAllBackgroundSymbolUses, - enableBackgroundItemKeyStoreAndSemanticClassification, - enablePartialTypeChecking, - parallelReferenceResolution, - captureIdentifiersWhenParsing, - getSource, - useChangeNotifications, - useSyntaxTreeCache - ) + if useTransparentCompiler = Some true then + TransparentCompiler( + legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking, + parallelReferenceResolution, + captureIdentifiersWhenParsing, + getSource, + useChangeNotifications, + useSyntaxTreeCache + ) + :> IBackgroundCompiler + else + BackgroundCompiler( + legacyReferenceResolver, + projectCacheSize, + keepAssemblyContents, + keepAllBackgroundResolutions, + tryGetMetadataSnapshot, + suggestNamesForErrors, + keepAllBackgroundSymbolUses, + enableBackgroundItemKeyStoreAndSemanticClassification, + enablePartialTypeChecking, + parallelReferenceResolution, + captureIdentifiersWhenParsing, + getSource, + useChangeNotifications, + useSyntaxTreeCache + ) + :> IBackgroundCompiler static let globalInstance = lazy FSharpChecker.Create() @@ -1429,7 +214,8 @@ type FSharpChecker ?parallelReferenceResolution: bool, ?captureIdentifiersWhenParsing: bool, ?documentSource: DocumentSource, - ?useSyntaxTreeCache: bool + ?useSyntaxTreeCache: bool, + ?useTransparentCompiler: bool ) = use _ = Activity.startNoTags "FSharpChecker.Create" @@ -1480,9 +266,19 @@ type FSharpChecker | Some(DocumentSource.Custom f) -> Some f | _ -> None), useChangeNotifications, - useSyntaxTreeCache + useSyntaxTreeCache, + useTransparentCompiler ) + member _.UsesTransparentCompiler = useTransparentCompiler = Some true + + member _.TransparentCompiler = + match useTransparentCompiler with + | Some true -> backgroundCompiler :?> TransparentCompiler + | _ -> failwith "Transparent Compiler is not enabled." + + member this.Caches = this.TransparentCompiler.Caches + member _.ReferenceResolver = legacyReferenceResolver member _.MatchBraces(fileName, sourceText: ISourceText, options: FSharpParsingOptions, ?userOpName: string) = @@ -1521,6 +317,11 @@ type FSharpChecker let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.ParseFile(fileName, sourceText, options, cache, false, userOpName) + member _.ParseFile(fileName, projectSnapshot, ?userOpName) = + let userOpName = defaultArg userOpName "Unknown" + + backgroundCompiler.ParseFile(fileName, projectSnapshot, userOpName) + 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) @@ -1547,9 +348,6 @@ type FSharpChecker use _ = Activity.start "FSharpChecker.Compile" [| Activity.Tags.userOpName, _userOpName |] async { - let! ct = Async.CancellationToken - use _ = Cancellable.UsingToken(ct) - let ctok = CompilationThreadToken() return CompileHelpers.compileFromArgs (ctok, argv, legacyReferenceResolver, None, None) } @@ -1564,7 +362,6 @@ type FSharpChecker backgroundCompiler.ClearCaches() ClearAllILModuleReaderCache() - // This is for unit testing only member ic.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() = use _ = Activity.startNoTags "FsharpChecker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients" @@ -1585,6 +382,10 @@ type FSharpChecker let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.ClearCache(options, userOpName) + member _.ClearCache(projects: ProjectSnapshot.FSharpProjectIdentifier seq, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + backgroundCompiler.ClearCache(projects, userOpName) + /// 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" @@ -1650,12 +451,24 @@ type FSharpChecker backgroundCompiler.ParseAndCheckFileInProject(fileName, fileVersion, sourceText, options, userOpName) |> Async.AwaitNodeCode - member _.ParseAndCheckProject(options, ?userOpName: string) = + member _.ParseAndCheckFileInProject(fileName: string, projectSnapshot: FSharpProjectSnapshot, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + + backgroundCompiler.ParseAndCheckFileInProject(fileName, projectSnapshot, userOpName) + |> Async.AwaitNodeCode + + member _.ParseAndCheckProject(options: FSharpProjectOptions, ?userOpName: string) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.ParseAndCheckProject(options, userOpName) |> Async.AwaitNodeCode + member _.ParseAndCheckProject(projectSnapshot: FSharpProjectSnapshot, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + + backgroundCompiler.ParseAndCheckProject(projectSnapshot, userOpName) + |> Async.AwaitNodeCode + member _.FindBackgroundReferencesInFile ( fileName: string, @@ -1669,9 +482,6 @@ type FSharpChecker let userOpName = defaultArg userOpName "Unknown" node { - let! ct = NodeCode.CancellationToken - use _ = Cancellable.UsingToken(ct) - if fastCheck <> Some true || not captureIdentifiersWhenParsing then return! backgroundCompiler.FindReferencesInFile(fileName, options, symbol, canInvalidateProject, userOpName) else @@ -1687,12 +497,36 @@ type FSharpChecker } |> Async.AwaitNodeCode + member _.FindBackgroundReferencesInFile(fileName: string, projectSnapshot: FSharpProjectSnapshot, symbol: FSharpSymbol, ?userOpName: string) = + let userOpName = defaultArg userOpName "Unknown" + + node { + let! parseResults = + backgroundCompiler.ParseFile(fileName, projectSnapshot, userOpName) + |> NodeCode.AwaitAsync + + if + parseResults.ParseTree.Identifiers |> Set.contains symbol.DisplayNameCore + || parseResults.ParseTree.Identifiers |> NamesContainAttribute symbol + then + return! backgroundCompiler.FindReferencesInFile(fileName, projectSnapshot, symbol, userOpName) + else + return Seq.empty + } + |> Async.AwaitNodeCode + member _.GetBackgroundSemanticClassificationForFile(fileName: string, options: FSharpProjectOptions, ?userOpName) = let userOpName = defaultArg userOpName "Unknown" backgroundCompiler.GetSemanticClassificationForFile(fileName, options, userOpName) |> Async.AwaitNodeCode + member _.GetBackgroundSemanticClassificationForFile(fileName: string, snapshot: FSharpProjectSnapshot, ?userOpName) = + let userOpName = defaultArg userOpName "Unknown" + + backgroundCompiler.GetSemanticClassificationForFile(fileName, snapshot, userOpName) + |> Async.AwaitNodeCode + /// For a given script file, get the ProjectOptions implied by the #load closure member _.GetProjectOptionsFromScript ( diff --git a/src/Compiler/Service/service.fsi b/src/Compiler/Service/service.fsi index 297d7b367bc..14124fbda6b 100644 --- a/src/Compiler/Service/service.fsi +++ b/src/Compiler/Service/service.fsi @@ -6,8 +6,11 @@ namespace FSharp.Compiler.CodeAnalysis open System open System.IO +open System.Threading +open System.Threading.Tasks open FSharp.Compiler.AbstractIL.ILBinaryReader open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CodeAnalysis.TransparentCompiler open FSharp.Compiler.CompilerConfig open FSharp.Compiler.Diagnostics open FSharp.Compiler.EditorServices @@ -42,6 +45,7 @@ type public FSharpChecker = /// When set to true we create a set of all identifiers for each parsed file which can be used to speed up finding references. /// Default: FileSystem. You can use Custom source to provide a function that will return the source for a given file path instead of reading it from the file system. Note that with this option the FSharpChecker will also not monitor the file system for file changes. It will expect to be notified of changes via the NotifyFileChanged method. /// Default: true. Indicates whether to keep parsing results in a cache. + /// Default: false. Indicates whether we use a new experimental background compiler. This does not yet support all features static member Create: ?projectCacheSize: int * ?keepAssemblyContents: bool * @@ -57,9 +61,13 @@ type public FSharpChecker = [] ?documentSource: DocumentSource * [] ?useSyntaxTreeCache: + bool * + [] ?useTransparentCompiler: bool -> FSharpChecker + member internal UsesTransparentCompiler: bool + /// /// Parse a source code file, returning information about brace matching in the file. /// Return an enumeration of the matching parenthetical tokens in the file. @@ -100,6 +108,10 @@ type public FSharpChecker = fileName: string * sourceText: ISourceText * options: FSharpParsingOptions * ?cache: bool * ?userOpName: string -> Async + [] + member ParseFile: + fileName: string * projectSnapshot: FSharpProjectSnapshot * ?userOpName: string -> Async + /// /// Parses a source code for a file. Returns an AST that can be traversed for various features. /// @@ -193,6 +205,11 @@ type public FSharpChecker = ?userOpName: string -> Async + [] + member ParseAndCheckFileInProject: + fileName: string * projectSnapshot: FSharpProjectSnapshot * ?userOpName: string -> + Async + /// /// Parse and typecheck all files in a project. /// All files are read from the FileSystem API @@ -203,6 +220,10 @@ type public FSharpChecker = /// An optional string used for tracing compiler operations associated with this request. member ParseAndCheckProject: options: FSharpProjectOptions * ?userOpName: string -> Async + [] + member ParseAndCheckProject: + projectSnapshot: FSharpProjectSnapshot * ?userOpName: string -> Async + /// /// For a given script file, get the FSharpProjectOptions implied by the #load closure. /// All files are read from the FileSystem API, except the file being checked. @@ -323,6 +344,11 @@ type public FSharpChecker = ?userOpName: string -> Async + [] + member FindBackgroundReferencesInFile: + fileName: string * projectSnapshot: FSharpProjectSnapshot * symbol: FSharpSymbol * ?userOpName: string -> + Async + /// /// Get semantic classification for a file. /// All files are read from the FileSystem API, including the file being checked. @@ -336,6 +362,18 @@ type public FSharpChecker = fileName: string * options: FSharpProjectOptions * ?userOpName: string -> Async + /// + /// Get semantic classification for a file. + /// + /// + /// The file name for the file. + /// The project snapshot for which we want to get the semantic classification. + /// An optional string used for tracing compiler operations associated with this request. + [] + member GetBackgroundSemanticClassificationForFile: + fileName: string * snapshot: FSharpProjectSnapshot * ?userOpName: string -> + Async + /// /// Compile using the given flags. Source files names are resolved via the FileSystem API. /// The output file must be given by a -o flag. @@ -377,6 +415,8 @@ type public FSharpChecker = /// An optional string used for tracing compiler operations associated with this request. member ClearCache: options: FSharpProjectOptions seq * ?userOpName: string -> unit + member ClearCache: projects: ProjectSnapshot.FSharpProjectIdentifier seq * ?userOpName: string -> unit + /// Report a statistic for testability static member ActualParseFileCount: int @@ -421,6 +461,10 @@ type public FSharpChecker = /// The event may be raised on a background thread. member ProjectChecked: IEvent + member internal TransparentCompiler: TransparentCompiler + + member internal Caches: CompilerCaches + [] static member Instance: FSharpChecker diff --git a/src/Compiler/Symbols/Exprs.fs b/src/Compiler/Symbols/Exprs.fs index 5ad053b2d9f..dfdfb782e46 100644 --- a/src/Compiler/Symbols/Exprs.fs +++ b/src/Compiler/Symbols/Exprs.fs @@ -899,12 +899,12 @@ module FSharpExprConvert = let typR = ConvType cenv (mkAppTy tycr tyargs) E.UnionCaseTag(ConvExpr cenv env arg1, typR) - | TOp.TraitCall (TTrait(tys, nm, memFlags, argTys, _retTy, _solution)), _, _ -> - let tysR = ConvTypes cenv tys + | TOp.TraitCall traitInfo, _, _ -> + let tysR = ConvTypes cenv traitInfo.SupportTypes let tyargsR = ConvTypes cenv tyargs - let argTysR = ConvTypes cenv argTys + let argTysR = ConvTypes cenv traitInfo.CompiledObjectAndArgumentTypes let argsR = ConvExprs cenv env args - E.TraitCall(tysR, nm, memFlags, argTysR, tyargsR, argsR) + E.TraitCall(tysR, traitInfo.MemberLogicalName, traitInfo.MemberFlags, argTysR, tyargsR, argsR) | TOp.RefAddrGet readonly, [ty], [e] -> let replExpr = mkRecdFieldGetAddrViaExprAddr(readonly, e, mkRefCellContentsRef g, [ty], m) diff --git a/src/Compiler/Symbols/SymbolHelpers.fs b/src/Compiler/Symbols/SymbolHelpers.fs index 8e69702800c..940f97a3e6f 100644 --- a/src/Compiler/Symbols/SymbolHelpers.fs +++ b/src/Compiler/Symbols/SymbolHelpers.fs @@ -2,6 +2,7 @@ namespace FSharp.Compiler.Symbols +open System open System.IO open Internal.Utilities.Library @@ -117,8 +118,7 @@ module internal SymbolHelpers = | Item.ImplicitOp (_, {contents = Some(TraitConstraintSln.FSMethSln(vref=vref))}) -> Some vref.Range | Item.ImplicitOp _ -> None | Item.UnqualifiedType tcrefs -> tcrefs |> List.tryPick (rangeOfEntityRef preferFlag >> Some) - | Item.DelegateCtor ty - | Item.FakeInterfaceCtor ty -> ty |> tryNiceEntityRefOfTyOption |> Option.map (rangeOfEntityRef preferFlag) + | Item.DelegateCtor ty -> ty |> tryNiceEntityRefOfTyOption |> Option.map (rangeOfEntityRef preferFlag) | Item.NewDef _ -> None // Provided type definitions do not have a useful F# CCU for the purposes of goto-definition. @@ -189,7 +189,6 @@ module internal SymbolHelpers = | Item.Types(_, tys) -> tys |> List.tryPick (tryNiceEntityRefOfTyOption >> Option.bind computeCcuOfTyconRef) - | Item.FakeInterfaceCtor(ty) | Item.DelegateCtor(ty) -> ty |> tryNiceEntityRefOfTyOption |> Option.bind computeCcuOfTyconRef @@ -282,7 +281,6 @@ module internal SymbolHelpers = | Item.ILField finfo -> mkXmlComment (GetXmlDocSigOfILFieldInfo infoReader m finfo) - | Item.FakeInterfaceCtor ty | Item.DelegateCtor ty | Item.Types(_, ty :: _) -> match ty with @@ -362,7 +360,6 @@ module internal SymbolHelpers = match item with | Item.DelegateCtor ty | Item.CtorGroup(_, [DefaultStructCtor(_, ty)]) - | Item.FakeInterfaceCtor ty | Item.Types(_, [ty]) -> Some ty | _ -> None @@ -397,7 +394,6 @@ module internal SymbolHelpers = | Item.ActivePatternResult _ | Item.AnonRecdField _ | Item.OtherName _ - | Item.FakeInterfaceCtor _ | Item.ImplicitOp _ | Item.NewDef _ | Item.UnionCaseField _ @@ -503,7 +499,6 @@ module internal SymbolHelpers = | Item.ActivePatternResult _ | Item.AnonRecdField _ | Item.OtherName _ - | Item.FakeInterfaceCtor _ | Item.ImplicitOp _ | Item.NewDef _ | Item.UnionCaseField _ @@ -571,7 +566,6 @@ module internal SymbolHelpers = | Item.MethodGroup(_, _, Some minfo) -> buildString (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef; bprintf os ".%s" minfo.DisplayName) | Item.MethodGroup(_, minfo :: _, _) -> buildString (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef; bprintf os ".%s" minfo.DisplayName) | Item.UnqualifiedType (tcref :: _) -> buildString (fun os -> NicePrint.outputTyconRef denv os tcref) - | Item.FakeInterfaceCtor ty | Item.DelegateCtor ty | Item.Types(_, ty :: _) -> match tryTcrefOfAppTy g ty with @@ -716,7 +710,6 @@ module internal SymbolHelpers = | Item.ActivePatternResult _ | Item.NewDef _ | Item.ILField _ - | Item.FakeInterfaceCtor _ | Item.DelegateCtor _ -> //| _ -> GetXmlCommentForItemAux None infoReader m item @@ -848,7 +841,6 @@ module internal SymbolHelpers = #endif | Item.Types(_, AppTy g (tcref, _) :: _) | Item.DelegateCtor(AppTy g (tcref, _)) - | Item.FakeInterfaceCtor(AppTy g (tcref, _)) | Item.UnqualifiedType (tcref :: _) | Item.ExnCase tcref -> // strip off any abbreviation @@ -859,7 +851,6 @@ module internal SymbolHelpers = // Pathological cases of the above | Item.Types _ | Item.DelegateCtor _ - | Item.FakeInterfaceCtor _ | Item.UnqualifiedType [] -> None @@ -876,7 +867,7 @@ module internal SymbolHelpers = // works similar to generation of xml-docs at tastops.fs, probably too similar // TODO: check if this code can be implemented using xml-doc generation functionality let prefix = path.AccessPath |> Seq.map fst |> String.concat "." - let fullName = if prefix = "" then modref.CompiledName else prefix + "." + modref.CompiledName + let fullName = if String.IsNullOrEmpty(prefix) then modref.CompiledName else prefix + "." + modref.CompiledName Some fullName ) #endif @@ -958,7 +949,6 @@ module internal SymbolHelpers = minfos |> List.map (fun minfo -> { Item = Item.MethodGroup(nm, [minfo], orig); TyparInstantiation = item.TyparInstantiation }) | Item.CtorGroup(nm, cinfos) -> cinfos |> List.map (fun minfo -> { Item = Item.CtorGroup(nm, [minfo]); TyparInstantiation = item.TyparInstantiation }) - | Item.FakeInterfaceCtor _ | Item.DelegateCtor _ -> [item] | Item.NewDef _ | Item.ILField _ -> [] diff --git a/src/Compiler/Symbols/Symbols.fs b/src/Compiler/Symbols/Symbols.fs index bc8ffaf1b1f..6527baf8f2d 100644 --- a/src/Compiler/Symbols/Symbols.fs +++ b/src/Compiler/Symbols/Symbols.fs @@ -331,7 +331,6 @@ type FSharpSymbol(cenv: SymbolEnv, item: unit -> Item, access: FSharpSymbol -> C // TODO: the following don't currently return any interesting subtype | Item.ImplicitOp _ | Item.ILField _ - | Item.FakeInterfaceCtor _ | Item.NewDef _ -> dflt() // These cases cover unreachable cases | Item.CustomOperation (_, _, None) @@ -1461,18 +1460,18 @@ type FSharpGenericParameterMemberConstraint(cenv, info: TraitConstraintInfo) = (fun () -> Item.Trait(info)), (fun _ _ _ad -> true)) - let (TTrait(tys, nm, flags, atys, retTy, _)) = info member _.MemberSources = - tys |> List.map (fun ty -> FSharpType(cenv, ty)) |> makeReadOnlyCollection + info.SupportTypes |> List.map (fun ty -> FSharpType(cenv, ty)) |> makeReadOnlyCollection - member _.MemberName = nm + member _.MemberName = info.MemberLogicalName - member _.MemberIsStatic = not flags.IsInstance + member _.MemberIsStatic = not info.MemberFlags.IsInstance - member _.MemberArgumentTypes = atys |> List.map (fun ty -> FSharpType(cenv, ty)) |> makeReadOnlyCollection + member _.MemberArgumentTypes = + info.CompiledObjectAndArgumentTypes |> List.map (fun ty -> FSharpType(cenv, ty)) |> makeReadOnlyCollection member _.MemberReturnType = - match retTy with + match info.CompiledReturnType with | None -> FSharpType(cenv, cenv.g.unit_ty) | Some ty -> FSharpType(cenv, ty) override x.ToString() = "" diff --git a/src/Compiler/SyntaxTree/LexFilter.fs b/src/Compiler/SyntaxTree/LexFilter.fs index 397eb0651b5..63e0ab3516a 100644 --- a/src/Compiler/SyntaxTree/LexFilter.fs +++ b/src/Compiler/SyntaxTree/LexFilter.fs @@ -4,6 +4,7 @@ /// Implements the offside rule and a couple of other lexical transformations. module internal FSharp.Compiler.LexFilter +open System open System.Collections.Generic open Internal.Utilities.Text.Lexing open FSharp.Compiler @@ -537,7 +538,7 @@ let (|TyparsCloseOp|_|) (txt: string) = | "$" -> Some DOLLAR | "%" -> Some (PERCENT_OP("%") ) | "%%" -> Some (PERCENT_OP("%%")) - | "" -> None + | s when String.IsNullOrEmpty(s) -> None | s -> match List.ofSeq afterAngles with | '=' :: _ diff --git a/src/Compiler/SyntaxTree/ParseHelpers.fs b/src/Compiler/SyntaxTree/ParseHelpers.fs index bb2e7755767..cd4b41787e1 100644 --- a/src/Compiler/SyntaxTree/ParseHelpers.fs +++ b/src/Compiler/SyntaxTree/ParseHelpers.fs @@ -1159,7 +1159,7 @@ let mkSynField let mType, mStart = idOpt - |> Option.map _.idRange + |> Option.map (fun x -> x.idRange) |> Option.orElseWith (fun _ -> vis |> Option.map (fun v -> v.Range)) |> Option.orElse isMutable |> Option.orElseWith (fun _ -> leadingKeyword |> Option.map (fun k -> k.Range)) diff --git a/src/Compiler/SyntaxTree/PrettyNaming.fs b/src/Compiler/SyntaxTree/PrettyNaming.fs index 1e67b7166b1..62f4ce8476c 100755 --- a/src/Compiler/SyntaxTree/PrettyNaming.fs +++ b/src/Compiler/SyntaxTree/PrettyNaming.fs @@ -1034,7 +1034,7 @@ let MangleProvidedTypeName (typeLogicalName, nonDefaultArgs) = let nonDefaultArgsText = nonDefaultArgs |> Array.map mangleStaticStringArg |> String.concat "," - if nonDefaultArgsText = "" then + if String.IsNullOrEmpty(nonDefaultArgsText) then typeLogicalName else typeLogicalName + "," + nonDefaultArgsText diff --git a/src/Compiler/SyntaxTree/SyntaxTree.fs b/src/Compiler/SyntaxTree/SyntaxTree.fs index d47b2620b44..aae54549038 100644 --- a/src/Compiler/SyntaxTree/SyntaxTree.fs +++ b/src/Compiler/SyntaxTree/SyntaxTree.fs @@ -1193,7 +1193,7 @@ type SynTypeDefnSimpleRepr = fields: SynField list * isConcrete: bool * isIncrClass: bool * - implicitCtorSynPats: SynSimplePats option * + implicitCtorSynPats: SynPat option * range: range | LibraryOnlyILAssembly of @@ -1442,7 +1442,7 @@ type SynMemberDefn = | ImplicitCtor of accessibility: SynAccess option * attributes: SynAttributes * - ctorArgs: SynSimplePats * + ctorArgs: SynPat * selfIdentifier: Ident option * xmlDoc: PreXmlDoc * range: range * diff --git a/src/Compiler/SyntaxTree/SyntaxTree.fsi b/src/Compiler/SyntaxTree/SyntaxTree.fsi index 63ebdc6e448..0c278067a80 100644 --- a/src/Compiler/SyntaxTree/SyntaxTree.fsi +++ b/src/Compiler/SyntaxTree/SyntaxTree.fsi @@ -1351,7 +1351,7 @@ type SynTypeDefnSimpleRepr = fields: SynField list * isConcrete: bool * isIncrClass: bool * - implicitCtorSynPats: SynSimplePats option * + implicitCtorSynPats: SynPat option * range: range /// A type defined by using an IL assembly representation. Only used in FSharp.Core. @@ -1622,7 +1622,7 @@ type SynMemberDefn = | ImplicitCtor of accessibility: SynAccess option * attributes: SynAttributes * - ctorArgs: SynSimplePats * + ctorArgs: SynPat * selfIdentifier: Ident option * xmlDoc: PreXmlDoc * range: range * diff --git a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs index 4f259854614..d44395dbcc1 100644 --- a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs +++ b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs @@ -409,7 +409,10 @@ let opNameQMark = CompileOpName qmark let mkSynOperator (opm: range) (oper: string) = let trivia = - if oper.StartsWith("~") && ((opm.EndColumn - opm.StartColumn) = (oper.Length - 1)) then + if + oper.StartsWithOrdinal("~") + && ((opm.EndColumn - opm.StartColumn) = (oper.Length - 1)) + then // PREFIX_OP token where the ~ was actually absent IdentTrivia.OriginalNotation(string (oper.[1..])) else diff --git a/src/Compiler/SyntaxTree/XmlDoc.fs b/src/Compiler/SyntaxTree/XmlDoc.fs index 0bfb9c09f48..74135a6ba33 100644 --- a/src/Compiler/SyntaxTree/XmlDoc.fs +++ b/src/Compiler/SyntaxTree/XmlDoc.fs @@ -23,7 +23,7 @@ type XmlDoc(unprocessedLines: string[], range: range) = | lineA :: rest as lines -> let lineAT = lineA.TrimStart([| ' ' |]) - if lineAT = "" then + if String.IsNullOrEmpty(lineAT) then processLines rest elif lineAT.StartsWithOrdinal("<") then lines diff --git a/src/Compiler/TypedTree/TcGlobals.fs b/src/Compiler/TypedTree/TcGlobals.fs index 152ab480dfd..cc67a69edab 100644 --- a/src/Compiler/TypedTree/TcGlobals.fs +++ b/src/Compiler/TypedTree/TcGlobals.fs @@ -1559,7 +1559,6 @@ type TcGlobals( member val attrib_CompilerFeatureRequiredAttribute = findSysAttrib "System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute" member val attrib_SetsRequiredMembersAttribute = findSysAttrib "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute" member val attrib_RequiredMemberAttribute = findSysAttrib "System.Runtime.CompilerServices.RequiredMemberAttribute" - member val attrib_TailCallAttribute = mk_MFCore_attrib "TailCallAttribute" member g.improveType tcref tinst = improveTy tcref tinst @@ -1880,11 +1879,11 @@ type TcGlobals( member _.DebuggerBrowsableNeverAttribute = debuggerBrowsableNeverAttribute - member _.mkDebuggableAttributeV2(jitTracking, jitOptimizerDisabled, enableEnC) = + member _.mkDebuggableAttributeV2(jitTracking, jitOptimizerDisabled) = let debuggingMode = + 0x3 (* Default ||| IgnoreSymbolStoreSequencePoints *) ||| (if jitTracking then 1 else 0) ||| - (if jitOptimizerDisabled then 256 else 0) ||| - (if enableEnC then 4 else 0) + (if jitOptimizerDisabled then 256 else 0) let tref_DebuggableAttribute_DebuggingModes = mkILTyRefInTyRef (tref_DebuggableAttribute, tname_DebuggableAttribute_DebuggingModes) mkILCustomAttribute (tref_DebuggableAttribute, [mkILNonGenericValueTy tref_DebuggableAttribute_DebuggingModes], @@ -1897,6 +1896,10 @@ type TcGlobals( member _.DebuggerNonUserCodeAttribute = debuggerNonUserCodeAttribute + member _.HasTailCallAttrib (attribs: Attribs) = + attribs + |> List.exists (fun a -> a.TyconRef.CompiledRepresentationForNamedType.FullName = "Microsoft.FSharp.Core.TailCallAttribute") + member _.MakeInternalsVisibleToAttribute(simpleAssemName) = mkILCustomAttribute (tref_InternalsVisibleToAttribute, [ilg.typ_String], [ILAttribElem.String (Some simpleAssemName)], []) @@ -1906,7 +1909,7 @@ type TcGlobals( let memberName = let nm = t.MemberLogicalName let coreName = - if nm.StartsWith "op_" then nm[3..] + if nm.StartsWithOrdinal "op_" then nm[3..] elif nm = "get_Zero" then "GenericZero" elif nm = "get_One" then "GenericOne" else nm diff --git a/src/Compiler/TypedTree/TypedTree.fs b/src/Compiler/TypedTree/TypedTree.fs index e377213c329..e9028ca32cd 100644 --- a/src/Compiler/TypedTree/TypedTree.fs +++ b/src/Compiler/TypedTree/TypedTree.fs @@ -2461,29 +2461,41 @@ type TraitWitnessInfo = type TraitConstraintInfo = /// Indicates the signature of a member constraint. Contains a mutable solution cell - /// to store the inferred solution of the constraint. - | TTrait of tys: TTypes * memberName: string * memberFlags: SynMemberFlags * objAndArgTys: TTypes * returnTyOpt: TType option * solution: TraitConstraintSln option ref + /// to store the inferred solution of the constraint. And a mutable source cell to store + /// the name of the type or member that defined the constraint. + | TTrait of + tys: TTypes * + memberName: string * + memberFlags: SynMemberFlags * + objAndArgTys: TTypes * + returnTyOpt: TType option * + source: string option ref * + solution: TraitConstraintSln option ref /// Get the types that may provide solutions for the traits - member x.SupportTypes = (let (TTrait(tys, _, _, _, _, _)) = x in tys) + member x.SupportTypes = (let (TTrait(tys = tys)) = x in tys) /// Get the logical member name associated with the member constraint. - member x.MemberLogicalName = (let (TTrait(_, nm, _, _, _, _)) = x in nm) + member x.MemberLogicalName = (let (TTrait(memberName = nm)) = x in nm) /// Get the member flags associated with the member constraint. - member x.MemberFlags = (let (TTrait(_, _, flags, _, _, _)) = x in flags) - - member x.CompiledObjectAndArgumentTypes = (let (TTrait(_, _, _, objAndArgTys, _, _)) = x in objAndArgTys) - - member x.WithMemberKind(kind) = (let (TTrait(a, b, c, d, e, f)) = x in TTrait(a, b, { c with MemberKind=kind }, d, e, f)) + member x.MemberFlags = (let (TTrait(memberFlags = flags)) = x in flags) + member x.CompiledObjectAndArgumentTypes = (let (TTrait(objAndArgTys = objAndArgTys)) = x in objAndArgTys) + /// Get the optional return type recorded in the member constraint. - member x.CompiledReturnType = (let (TTrait(_, _, _, _, retTy, _)) = x in retTy) - + member x.CompiledReturnType = (let (TTrait(returnTyOpt = retTy)) = x in retTy) + /// Get or set the solution of the member constraint during inference member x.Solution - with get() = (let (TTrait(_, _, _, _, _, sln)) = x in sln.Value) - and set v = (let (TTrait(_, _, _, _, _, sln)) = x in sln.Value <- v) + with get() = (let (TTrait(solution = sln)) = x in sln.Value) + and set v = (let (TTrait(solution = sln)) = x in sln.Value <- v) + + member x.WithMemberKind(kind) = (let (TTrait(a, b, c, d, e, f, g)) = x in TTrait(a, b, { c with MemberKind=kind }, d, e, f, g)) + + member x.WithSupportTypes(tys) = (let (TTrait(_, b, c, d, e, f, g)) = x in TTrait(tys, b, c, d, e, f, g)) + + member x.WithMemberName(name) = (let (TTrait(a, _, c, d, e, f, g)) = x in TTrait(a, name, c, d, e, f, g)) [] member x.DebugText = x.ToString() diff --git a/src/Compiler/TypedTree/TypedTree.fsi b/src/Compiler/TypedTree/TypedTree.fsi index a2f167130e6..f40713b2f3e 100644 --- a/src/Compiler/TypedTree/TypedTree.fsi +++ b/src/Compiler/TypedTree/TypedTree.fsi @@ -1681,13 +1681,15 @@ type TraitWitnessInfo = type TraitConstraintInfo = /// Indicates the signature of a member constraint. Contains a mutable solution cell - /// to store the inferred solution of the constraint. + /// to store the inferred solution of the constraint. And a mutable source cell to store + /// the name of the type or member that defined the constraint. | TTrait of tys: TTypes * memberName: string * memberFlags: Syntax.SynMemberFlags * objAndArgTys: TTypes * returnTyOpt: TType option * + source: string option ref * solution: TraitConstraintSln option ref override ToString: unit -> string @@ -1722,6 +1724,10 @@ type TraitConstraintInfo = /// the extension property MemberDisplayNameCore member WithMemberKind: SynMemberKind -> TraitConstraintInfo + member WithSupportTypes: TTypes -> TraitConstraintInfo + + member WithMemberName: string -> TraitConstraintInfo + /// Represents the solution of a member constraint during inference. [] type TraitConstraintSln = diff --git a/src/Compiler/TypedTree/TypedTreeOps.fs b/src/Compiler/TypedTree/TypedTreeOps.fs index 1af0df92d43..cf75136829d 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.fs @@ -3,6 +3,7 @@ /// Defines derived expression manipulation and construction functions. module internal FSharp.Compiler.TypedTreeOps +open System open System.CodeDom.Compiler open System.Collections.Generic open System.Collections.Immutable @@ -263,7 +264,7 @@ and remapTyparConstraintsAux tyenv cs = | TyparConstraint.IsReferenceType _ | TyparConstraint.RequiresDefaultConstructor _ -> Some x) -and remapTraitInfo tyenv (TTrait(tys, nm, flags, argTys, retTy, slnCell)) = +and remapTraitInfo tyenv (TTrait(tys, nm, flags, argTys, retTy, source, slnCell)) = let slnCell = match slnCell.Value with | None -> None @@ -299,7 +300,7 @@ and remapTraitInfo tyenv (TTrait(tys, nm, flags, argTys, retTy, slnCell)) = // in the same way as types let newSlnCell = ref slnCell - TTrait(tysR, nm, flags, argTysR, retTyR, newSlnCell) + TTrait(tysR, nm, flags, argTysR, retTyR, source, newSlnCell) and bindTypars tps tyargs tpinst = match tps with @@ -968,8 +969,8 @@ type TypeEquivEnv with TypeEquivEnv.Empty.BindEquivTypars tps1 tps2 let rec traitsAEquivAux erasureFlag g aenv traitInfo1 traitInfo2 = - let (TTrait(tys1, nm, mf1, argTys, retTy, _)) = traitInfo1 - let (TTrait(tys2, nm2, mf2, argTys2, retTy2, _)) = traitInfo2 + let (TTrait(tys1, nm, mf1, argTys, retTy, _, _)) = traitInfo1 + let (TTrait(tys2, nm2, mf2, argTys2, retTy2, _, _)) = traitInfo2 mf1.IsInstance = mf2.IsInstance && nm = nm2 && ListSet.equals (typeAEquivAux erasureFlag g aenv) tys1 tys2 && @@ -2315,7 +2316,7 @@ and accFreeInTyparConstraint opts tpc acc = | TyparConstraint.IsUnmanaged _ | TyparConstraint.RequiresDefaultConstructor _ -> acc -and accFreeInTrait opts (TTrait(tys, _, _, argTys, retTy, sln)) acc = +and accFreeInTrait opts (TTrait(tys, _, _, argTys, retTy, _, sln)) acc = Option.foldBack (accFreeInTraitSln opts) sln.Value (accFreeInTypes opts tys (accFreeInTypes opts argTys @@ -2451,7 +2452,7 @@ and accFreeInTyparConstraintLeftToRight g cxFlag thruFlag acc tpc = | TyparConstraint.IsReferenceType _ | TyparConstraint.RequiresDefaultConstructor _ -> acc -and accFreeInTraitLeftToRight g cxFlag thruFlag acc (TTrait(tys, _, _, argTys, retTy, _)) = +and accFreeInTraitLeftToRight g cxFlag thruFlag acc (TTrait(tys, _, _, argTys, retTy, _, _)) = let acc = accFreeInTypesLeftToRight g cxFlag thruFlag acc tys let acc = accFreeInTypesLeftToRight g cxFlag thruFlag acc argTys let acc = Option.fold (accFreeInTypeLeftToRight g cxFlag thruFlag) acc retTy @@ -2658,7 +2659,7 @@ type TraitConstraintInfo with /// Get the key associated with the member constraint. member traitInfo.GetWitnessInfo() = - let (TTrait(tys, nm, memFlags, objAndArgTys, rty, _)) = traitInfo + let (TTrait(tys, nm, memFlags, objAndArgTys, rty, _, _)) = traitInfo TraitWitnessInfo(tys, nm, memFlags, objAndArgTys, rty) /// Get information about the trait constraints for a set of typars. @@ -3209,7 +3210,7 @@ type DisplayEnv = ControlPath (splitNamespace ExtraTopLevelOperatorsName) ] -let (+.+) s1 s2 = if s1 = "" then s2 else s1+"."+s2 +let (+.+) s1 s2 = if String.IsNullOrEmpty(s1) then s2 else s1+"."+s2 let layoutOfPath p = sepListL SepL.dot (List.map (tagNamespace >> wordL) p) @@ -4078,7 +4079,7 @@ module DebugPrint = and auxTraitL env (ttrait: TraitConstraintInfo) = #if DEBUG - let (TTrait(tys, nm, memFlags, argTys, retTy, _)) = ttrait + let (TTrait(tys, nm, memFlags, argTys, retTy, _, _)) = ttrait match global_g with | None -> wordL (tagText "") | Some g -> @@ -5413,7 +5414,7 @@ and accFreeInOp opts op acc = | TOp.Reraise -> accUsesRethrow true acc - | TOp.TraitCall (TTrait(tys, _, _, argTys, retTy, sln)) -> + | TOp.TraitCall (TTrait(tys, _, _, argTys, retTy, _, sln)) -> Option.foldBack (accFreeVarsInTraitSln opts) sln.Value (accFreeVarsInTys opts tys (accFreeVarsInTys opts argTys @@ -8831,7 +8832,7 @@ let buildAccessPath (cp: CompilationPath option) = System.String.Join(".", ap) | None -> "Extension Type" -let prependPath path name = if path = "" then name else path + "." + name +let prependPath path name = if String.IsNullOrEmpty(path) then name else path + "." + name let XmlDocSigOfVal g full path (v: Val) = let parentTypars, methTypars, cxs, argInfos, retTy, prefix, path, name = @@ -10516,7 +10517,7 @@ let (|SequentialResumableCode|_|) (g: TcGlobals) expr = Some (e1, e2, m, (fun e1 e2 -> Expr.Sequential(e1, e2, NormalSeq, m))) // let __stack_step = e1 in e2 - | Expr.Let(bind, e2, m, _) when bind.Var.CompiledName(g.CompilerGlobalState).StartsWith(stackVarPrefix) -> + | Expr.Let(bind, e2, m, _) when bind.Var.CompiledName(g.CompilerGlobalState).StartsWithOrdinal(stackVarPrefix) -> Some (bind.Expr, e2, m, (fun e1 e2 -> mkLet bind.DebugPoint m bind.Var e1 e2)) | _ -> None @@ -10691,23 +10692,42 @@ let (|EmptyModuleOrNamespaces|_|) (moduleOrNamespaceContents: ModuleOrNamespaceC None | _ -> None -let tryAddExtensionAttributeIfNotAlreadyPresent +let tryFindExtensionAttribute (g: TcGlobals) (attribs: Attrib list): Attrib option = + attribs + |> List.tryFind (IsMatchingFSharpAttribute g g.attrib_ExtensionAttribute) + +let tryAddExtensionAttributeIfNotAlreadyPresentForModule + (g: TcGlobals) + (tryFindExtensionAttributeIn: (Attrib list -> Attrib option) -> Attrib option) + (moduleEntity: Entity) + : Entity + = + if Option.isSome (tryFindExtensionAttribute g moduleEntity.Attribs) then + moduleEntity + else + match tryFindExtensionAttributeIn (tryFindExtensionAttribute g) with + | None -> moduleEntity + | Some extensionAttrib -> + { moduleEntity with entity_attribs = extensionAttrib :: moduleEntity.Attribs } + +let tryAddExtensionAttributeIfNotAlreadyPresentForType + (g: TcGlobals) (tryFindExtensionAttributeIn: (Attrib list -> Attrib option) -> Attrib option) - (entity: Entity) + (moduleOrNamespaceTypeAccumulator: ModuleOrNamespaceType ref) + (typeEntity: Entity) : Entity = - let tryFindExtensionAttribute (attribs: Attrib list): Attrib option = - List.tryFind - (fun (a: Attrib) -> - a.TyconRef.CompiledRepresentationForNamedType.BasicQualifiedName = "System.Runtime.CompilerServices.ExtensionAttribute") - attribs - - if Option.isSome (tryFindExtensionAttribute entity.Attribs) then - entity + if Option.isSome (tryFindExtensionAttribute g typeEntity.Attribs) then + typeEntity else - match tryFindExtensionAttributeIn tryFindExtensionAttribute with - | None -> entity - | Some extensionAttrib -> { entity with entity_attribs = extensionAttrib :: entity.Attribs } + match tryFindExtensionAttributeIn (tryFindExtensionAttribute g) with + | None -> typeEntity + | Some extensionAttrib -> + moduleOrNamespaceTypeAccumulator.Value.AllEntitiesByLogicalMangledName.TryFind(typeEntity.LogicalName) + |> Option.iter (fun e -> + e.entity_attribs <- extensionAttrib :: e.Attribs + ) + typeEntity type TypedTreeNode = { diff --git a/src/Compiler/TypedTree/TypedTreeOps.fsi b/src/Compiler/TypedTree/TypedTreeOps.fsi index 7ad98c887e5..77b6347d983 100755 --- a/src/Compiler/TypedTree/TypedTreeOps.fsi +++ b/src/Compiler/TypedTree/TypedTreeOps.fsi @@ -2732,9 +2732,22 @@ type TraitConstraintInfo with val (|EmptyModuleOrNamespaces|_|): moduleOrNamespaceContents: ModuleOrNamespaceContents -> (ModuleOrNamespace list) option -/// Add an System.Runtime.CompilerServices.ExtensionAttribute to the Entity if found via predicate and not already present. -val tryAddExtensionAttributeIfNotAlreadyPresent: - tryFindExtensionAttributeIn: ((Attrib list -> Attrib option) -> Attrib option) -> entity: Entity -> Entity +val tryFindExtensionAttribute: g: TcGlobals -> attribs: Attrib list -> Attrib option + +/// Add an System.Runtime.CompilerServices.ExtensionAttribute to the module Entity if found via predicate and not already present. +val tryAddExtensionAttributeIfNotAlreadyPresentForModule: + g: TcGlobals -> + tryFindExtensionAttributeIn: ((Attrib list -> Attrib option) -> Attrib option) -> + moduleEntity: Entity -> + Entity + +/// Add an System.Runtime.CompilerServices.ExtensionAttribute to the type Entity if found via predicate and not already present. +val tryAddExtensionAttributeIfNotAlreadyPresentForType: + g: TcGlobals -> + tryFindExtensionAttributeIn: ((Attrib list -> Attrib option) -> Attrib option) -> + moduleOrNamespaceTypeAccumulator: ModuleOrNamespaceType ref -> + typeEntity: Entity -> + Entity /// Serialize an entity to a very basic json structure. val serializeEntity: path: string -> entity: Entity -> unit diff --git a/src/Compiler/TypedTree/TypedTreePickle.fs b/src/Compiler/TypedTree/TypedTreePickle.fs index 84ed2bf70d2..e855587e739 100644 --- a/src/Compiler/TypedTree/TypedTreePickle.fs +++ b/src/Compiler/TypedTree/TypedTreePickle.fs @@ -1516,7 +1516,7 @@ let p_trait_sln sln st = p_byte 7 st; p_tup4 p_ty (p_vref "trait") p_tys p_ty (a, b, c, d) st -let p_trait (TTrait(a, b, c, d, e, f)) st = +let p_trait (TTrait(a, b, c, d, e, _, f)) st = p_tup6 p_tys p_string p_MemberFlags p_tys (p_option p_ty) (p_option p_trait_sln) (a, b, c, d, e, f.Value) st let u_anonInfo_data st = @@ -1556,7 +1556,7 @@ let u_trait_sln st = let u_trait st = let a, b, c, d, e, f = u_tup6 u_tys u_string u_MemberFlags u_tys (u_option u_ty) (u_option u_trait_sln) st - TTrait (a, b, c, d, e, ref f) + TTrait (a, b, c, d, e, ref None, ref f) let p_rational q st = p_int32 (GetNumerator q) st; p_int32 (GetDenominator q) st diff --git a/src/Compiler/Utilities/Activity.fs b/src/Compiler/Utilities/Activity.fs index 22405544e2f..ed2ac738ed2 100644 --- a/src/Compiler/Utilities/Activity.fs +++ b/src/Compiler/Utilities/Activity.fs @@ -33,6 +33,7 @@ module internal Activity = let gc2 = "gc2" let outputDllFile = "outputDllFile" let buildPhase = "buildPhase" + let version = "version" let AllKnownTags = [| diff --git a/src/Compiler/Utilities/Activity.fsi b/src/Compiler/Utilities/Activity.fsi index 94784c97f00..afce0f3b554 100644 --- a/src/Compiler/Utilities/Activity.fsi +++ b/src/Compiler/Utilities/Activity.fsi @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - namespace FSharp.Compiler.Diagnostics open System @@ -29,6 +28,7 @@ module internal Activity = val length: string val cache: string val buildPhase: string + val version: string module Events = val cacheHit: string diff --git a/src/Compiler/Utilities/Cancellable.fs b/src/Compiler/Utilities/Cancellable.fs index c702e3b7a0b..59e7def4c10 100644 --- a/src/Compiler/Utilities/Cancellable.fs +++ b/src/Compiler/Utilities/Cancellable.fs @@ -2,32 +2,47 @@ namespace FSharp.Compiler open System open System.Threading +open Internal.Utilities.Library [] type Cancellable = [] - static val mutable private token: CancellationToken - - static member UsingToken(ct) = - let oldCt = Cancellable.token - - Cancellable.token <- ct + static val mutable private tokens: CancellationToken list + static let disposable = { new IDisposable with - member this.Dispose() = Cancellable.token <- oldCt + member this.Dispose() = + Cancellable.Tokens <- Cancellable.Tokens |> List.tail } - static member Token - with get () = Cancellable.token - and internal set v = Cancellable.token <- v + static member Tokens + with private get () = + match box Cancellable.tokens with + | Null -> [] + | _ -> Cancellable.tokens + and private set v = Cancellable.tokens <- v + + static member UsingToken(ct) = + Cancellable.Tokens <- ct :: Cancellable.Tokens + disposable + + static member Token = + match Cancellable.Tokens with + | [] -> CancellationToken.None + | token :: _ -> token + /// There may be multiple tokens if `UsingToken` is called multiple times, producing scoped structure. + /// We're interested in the current, i.e. the most recent, one. static member CheckAndThrow() = - Cancellable.token.ThrowIfCancellationRequested() + match Cancellable.Tokens with + | [] -> () + | token :: _ -> token.ThrowIfCancellationRequested() namespace Internal.Utilities.Library open System open System.Threading +open FSharp.Compiler #if !FSHARPCORE_USE_PACKAGE open FSharp.Core.CompilerServices.StateMachineHelpers @@ -48,6 +63,7 @@ module Cancellable = ValueOrCancelled.Cancelled(OperationCanceledException ct) else try + use _ = Cancellable.UsingToken(ct) oper ct with :? OperationCanceledException as e -> ValueOrCancelled.Cancelled(OperationCanceledException e.CancellationToken) diff --git a/src/Compiler/Utilities/Cancellable.fsi b/src/Compiler/Utilities/Cancellable.fsi index 6e36d7ecb6d..23515432bdd 100644 --- a/src/Compiler/Utilities/Cancellable.fsi +++ b/src/Compiler/Utilities/Cancellable.fsi @@ -7,7 +7,6 @@ open System.Threading type Cancellable = static member internal UsingToken: CancellationToken -> IDisposable static member Token: CancellationToken - static member internal Token: CancellationToken with set static member CheckAndThrow: unit -> unit namespace Internal.Utilities.Library diff --git a/src/Compiler/Utilities/FileSystem.fs b/src/Compiler/Utilities/FileSystem.fs index 5b555915e6c..8023eacb942 100644 --- a/src/Compiler/Utilities/FileSystem.fs +++ b/src/Compiler/Utilities/FileSystem.fs @@ -616,16 +616,16 @@ type DefaultFileSystem() as this = default _.IsInvalidPathShim(path: string) = let isInvalidPath (p: string MaybeNull) = - match p with - | Null - | "" -> true - | NonNull p -> p.IndexOfAny(Path.GetInvalidPathChars()) <> -1 + if String.IsNullOrEmpty(p) then + true + else + p.IndexOfAny(Path.GetInvalidPathChars()) <> -1 let isInvalidFilename (p: string MaybeNull) = - match p with - | Null - | "" -> true - | NonNull p -> p.IndexOfAny(Path.GetInvalidFileNameChars()) <> -1 + if String.IsNullOrEmpty(p) then + true + else + p.IndexOfAny(Path.GetInvalidFileNameChars()) <> -1 let isInvalidDirectory (d: string MaybeNull) = match d with @@ -645,7 +645,7 @@ type DefaultFileSystem() as this = default _.GetDirectoryNameShim(path: string) = FileSystemUtils.checkPathForIllegalChars path - if path = "" then + if String.IsNullOrEmpty(path) then "." else match Path.GetDirectoryName(path) with @@ -654,7 +654,7 @@ type DefaultFileSystem() as this = path else "." - | res -> if res = "" then "." else res + | res -> if String.IsNullOrEmpty(res) then "." else res abstract GetLastWriteTimeShim: fileName: string -> DateTime default _.GetLastWriteTimeShim(fileName: string) = File.GetLastWriteTimeUtc fileName diff --git a/src/Compiler/Utilities/LruCache.fs b/src/Compiler/Utilities/LruCache.fs new file mode 100644 index 00000000000..c75ed1d88cf --- /dev/null +++ b/src/Compiler/Utilities/LruCache.fs @@ -0,0 +1,273 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace Internal.Utilities.Collections + +open System +open System.Collections.Generic +open System.Diagnostics + +open Internal.Utilities.Library.Extras + +[] +type internal CacheEvent = + | Evicted + | Collected + | Weakened + | Strengthened + | Cleared + +[] +type internal ValueLink<'T when 'T: not struct> = + | Strong of 'T + | Weak of WeakReference<'T> + +[] +type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality and 'TValue: not struct> + (keepStrongly, ?keepWeakly, ?requiredToKeep, ?event) = + + let keepWeakly = defaultArg keepWeakly 100 + let requiredToKeep = defaultArg requiredToKeep (fun _ -> false) + let event = defaultArg event (fun _ _ -> ()) + + let dictionary = Dictionary<'TKey, Dictionary<'TVersion, _>>() + + // Lists to keep track of when items were last accessed. First item is most recently accessed. + let strongList = LinkedList<'TKey * 'TVersion * string * ValueLink<'TValue>>() + let weakList = LinkedList<'TKey * 'TVersion * string * ValueLink<'TValue>>() + + let rec removeCollected (node: LinkedListNode<_>) = + if node <> null then + let key, version, label, value = node.Value + + match value with + | Weak w -> + let next = node.Next + + match w.TryGetTarget() with + | false, _ -> + weakList.Remove node + dictionary[key].Remove version |> ignore + + if dictionary[key].Count = 0 then + dictionary.Remove key |> ignore + + event CacheEvent.Collected (label, key, version) + | _ -> () + + removeCollected next + | _ -> failwith "Illegal state, strong reference in weak list" + + let cutWeakListIfTooLong () = + if weakList.Count > keepWeakly then + removeCollected weakList.First + + let mutable node = weakList.Last + + while weakList.Count > keepWeakly && node <> null do + let previous = node.Previous + let key, version, label, _ = node.Value + weakList.Remove node + dictionary[key].Remove version |> ignore + + if dictionary[key].Count = 0 then + dictionary.Remove key |> ignore + + event CacheEvent.Evicted (label, key, version) + node <- previous + + let cutStrongListIfTooLong () = + let mutable node = strongList.Last + + let mutable anythingWeakened = false + + while strongList.Count > keepStrongly && node <> null do + let previous = node.Previous + + match node.Value with + | _, _, _, Strong v when requiredToKeep v -> () + | key, version, label, Strong v -> + strongList.Remove node + node.Value <- key, version, label, Weak(WeakReference<_> v) + weakList.AddFirst node + event CacheEvent.Weakened (label, key, version) + anythingWeakened <- true + | _key, _version, _label, _ -> failwith "Invalid state, weak reference in strong list" + + node <- previous + + if anythingWeakened then + cutWeakListIfTooLong () + + let pushNodeToTop (node: LinkedListNode<_>) = + match node.Value with + | _, _, _, Strong _ -> + strongList.AddFirst node + cutStrongListIfTooLong () + | _, _, _, Weak _ -> failwith "Invalid operation, pushing weak reference to strong list" + + let pushValueToTop key version label value = + strongList.AddFirst(value = (key, version, label, Strong value)) + + member _.DebuggerDisplay = $"Cache(S:{strongList.Count} W:{weakList.Count})" + + member _.Set(key, version, label, value) = + match dictionary.TryGetValue key with + | true, versionDict -> + + if versionDict.ContainsKey version then + // TODO this is normal for unversioned cache; + // failwith "Suspicious - overwriting existing version" + + let node: LinkedListNode<_> = versionDict[version] + + match node.Value with + | _, _, _, Strong _ -> strongList.Remove node + | _, _, _, Weak _ -> + weakList.Remove node + event CacheEvent.Strengthened (label, key, version) + + node.Value <- key, version, label, Strong value + pushNodeToTop node + + else + let node = pushValueToTop key version label value + versionDict[version] <- node + // weaken all other versions (unless they're required to be kept) + let versionsToWeaken = versionDict.Keys |> Seq.filter ((<>) version) |> Seq.toList + + let mutable anythingWeakened = false + + for otherVersion in versionsToWeaken do + let node = versionDict[otherVersion] + + match node.Value with + | _, _, _, Strong value when not (requiredToKeep value) -> + strongList.Remove node + node.Value <- key, otherVersion, label, Weak(WeakReference<_> value) + weakList.AddFirst node + event CacheEvent.Weakened (label, key, otherVersion) + anythingWeakened <- true + | _ -> () + + if anythingWeakened then + cutWeakListIfTooLong () + else + cutStrongListIfTooLong () + + | false, _ -> + let node = pushValueToTop key version label value + cutStrongListIfTooLong () + dictionary[key] <- Dictionary() + dictionary[key][version] <- node + + member this.Set(key, version, value) = + this.Set(key, version, "[no label]", value) + + member _.TryGet(key, version) = + + match dictionary.TryGetValue key with + | false, _ -> None + | true, versionDict -> + match versionDict.TryGetValue version with + | false, _ -> None + | true, node -> + match node.Value with + | _, _, _, Strong v -> + strongList.Remove node + pushNodeToTop node + Some v + + | _, _, label, Weak w -> + match w.TryGetTarget() with + | true, value -> + weakList.Remove node + let node = pushValueToTop key version label value + event CacheEvent.Strengthened (label, key, version) + cutStrongListIfTooLong () + versionDict[version] <- node + Some value + | _ -> + weakList.Remove node + versionDict.Remove version |> ignore + + if versionDict.Count = 0 then + dictionary.Remove key |> ignore + + event CacheEvent.Collected (label, key, version) + None + + /// Returns an option of a value for given key and version, and also a list of all other versions for given key + member this.GetAll(key, version) = + this.TryGet(key, version), + + match dictionary.TryGetValue key with + | false, _ -> [] + | true, versionDict -> + versionDict.Values + |> Seq.map (fun node -> node.Value) + |> Seq.filter (p24 >> ((<>) version)) + |> Seq.choose (function + | _, ver, _, Strong v -> Some(ver, v) + | _, ver, _, Weak r -> + match r.TryGetTarget() with + | true, x -> Some(ver, x) + | _ -> None) + |> Seq.toList + + member _.Remove(key, version) = + match dictionary.TryGetValue key with + | false, _ -> () + | true, versionDict -> + match versionDict.TryGetValue version with + | true, node -> + versionDict.Remove version |> ignore + + if versionDict.Count = 0 then + dictionary.Remove key |> ignore + + match node.Value with + | _, _, _, Strong _ -> strongList.Remove node + | _, _, _, Weak _ -> weakList.Remove node + | _ -> () + + member this.Set(key, value) = + this.Set(key, Unchecked.defaultof<_>, value) + + member this.TryGet(key) = + this.TryGet(key, Unchecked.defaultof<_>) + + member this.Remove(key) = + this.Remove(key, Unchecked.defaultof<_>) + + member _.Clear() = + dictionary.Clear() + strongList.Clear() + weakList.Clear() + + member _.Clear(predicate) = + let keysToRemove = dictionary.Keys |> Seq.filter predicate |> Seq.toList + + for key in keysToRemove do + match dictionary.TryGetValue key with + | true, versionDict -> + versionDict.Values + |> Seq.iter (fun node -> + match node.Value with + | _, _, _, Strong _ -> strongList.Remove node + | _, _, _, Weak _ -> weakList.Remove node + + match node.Value with + | key, version, label, _ -> event CacheEvent.Cleared (label, key, version)) + + dictionary.Remove key |> ignore + | _ -> () + + member _.GetValues() = + strongList + |> Seq.append weakList + |> Seq.choose (function + | _k, version, label, Strong value -> Some(label, version, value) + | _k, version, label, Weak w -> + match w.TryGetTarget() with + | true, value -> Some(label, version, value) + | _ -> None) diff --git a/src/Compiler/Utilities/LruCache.fsi b/src/Compiler/Utilities/LruCache.fsi new file mode 100644 index 00000000000..d9aefd2a240 --- /dev/null +++ b/src/Compiler/Utilities/LruCache.fsi @@ -0,0 +1,52 @@ +namespace Internal.Utilities.Collections + +[] +type internal CacheEvent = + | Evicted + | Collected + | Weakened + | Strengthened + | Cleared + +/// A cache where least recently used items are removed when the cache is full. +/// +/// It's also versioned, meaning each key can have multiple versions and only the latest one is kept strongly. +/// Older versions are kept weakly and can be collected by GC. +type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality and 'TValue: not struct> = + + /// Maximum number of strongly held results to keep in the cache + /// Maximum number of weakly held results to keep in the cache + /// A predicate that determines if a value should be kept strongly (no matter what) + /// An event that is called when an item is evicted, collected, weakened or strengthened + new: + keepStrongly: int * + ?keepWeakly: int * + ?requiredToKeep: ('TValue -> bool) * + ?event: (CacheEvent -> string * 'TKey * 'TVersion -> unit) -> + LruCache<'TKey, 'TVersion, 'TValue> + + member Clear: unit -> unit + + /// Clear any keys that match the given predicate + member Clear: predicate: ('TKey -> bool) -> unit + + /// Returns an option of a value for given key and version, and also a list of all other versions for given key + member GetAll: key: 'TKey * version: 'TVersion -> 'TValue option * ('TVersion * 'TValue) list + + member GetValues: unit -> (string * 'TVersion * 'TValue) seq + + member Remove: key: 'TKey -> unit + + member Remove: key: 'TKey * version: 'TVersion -> unit + + member Set: key: 'TKey * value: 'TValue -> unit + + member Set: key: 'TKey * version: 'TVersion * value: 'TValue -> unit + + member Set: key: 'TKey * version: 'TVersion * label: string * value: 'TValue -> unit + + member TryGet: key: 'TKey -> 'TValue option + + member TryGet: key: 'TKey * version: 'TVersion -> 'TValue option + + member DebuggerDisplay: string diff --git a/src/Compiler/Utilities/PathMap.fs b/src/Compiler/Utilities/PathMap.fs index f11edef6a82..50319ea7079 100644 --- a/src/Compiler/Utilities/PathMap.fs +++ b/src/Compiler/Utilities/PathMap.fs @@ -6,6 +6,7 @@ namespace Internal.Utilities open System open System.IO +open Internal.Utilities.Library open FSharp.Compiler.IO type PathMap = PathMap of Map @@ -22,7 +23,7 @@ module internal PathMap = let normalSrc = FileSystem.GetFullPathShim src let oldPrefix = - if normalSrc.EndsWith dirSepStr then + if normalSrc.EndsWithOrdinal dirSepStr then normalSrc else normalSrc + dirSepStr @@ -41,7 +42,7 @@ module internal PathMap = // oldPrefix always ends with a path separator, so there's no need // to check if it was a partial match // e.g. for the map /goo=/bar and file name /goooo - if filePath.StartsWith(oldPrefix, StringComparison.Ordinal) then + if filePath.StartsWithOrdinal oldPrefix then let replacement = replacementPrefix + filePath.Substring(oldPrefix.Length - 1) // Normalize the path separators if used uniformly in the replacement @@ -60,7 +61,7 @@ module internal PathMap = |> Option.defaultValue filePath let applyDir pathMap (dirName: string) : string = - if dirName.EndsWith dirSepStr then + if dirName.EndsWithOrdinal dirSepStr then apply pathMap dirName else let mapped = apply pathMap (dirName + dirSepStr) diff --git a/src/Compiler/Utilities/illib.fs b/src/Compiler/Utilities/illib.fs index 6bf85595108..c4ecd88533e 100644 --- a/src/Compiler/Utilities/illib.fs +++ b/src/Compiler/Utilities/illib.fs @@ -129,6 +129,15 @@ module internal PervasiveAutoOpens = member inline x.EndsWithOrdinalIgnoreCase value = x.EndsWith(value, StringComparison.OrdinalIgnoreCase) + member inline x.IndexOfOrdinal value = + x.IndexOf(value, StringComparison.Ordinal) + + member inline x.IndexOfOrdinal(value, startIndex) = + x.IndexOf(value, startIndex, StringComparison.Ordinal) + + member inline x.IndexOfOrdinal(value, startIndex, count) = + x.IndexOf(value, startIndex, count, StringComparison.Ordinal) + /// Get an initialization hole let getHole (r: _ ref) = match r.Value with @@ -806,7 +815,7 @@ module String = String digits |> function - | "" -> str, None + | x when String.IsNullOrEmpty(x) -> str, None | index -> str.Substring(0, str.Length - index.Length), Some(int index) /// Splits a string into substrings based on the strings in the array separators diff --git a/src/Compiler/Utilities/illib.fsi b/src/Compiler/Utilities/illib.fsi index 266f884fa01..2df0d9c0959 100644 --- a/src/Compiler/Utilities/illib.fsi +++ b/src/Compiler/Utilities/illib.fsi @@ -85,6 +85,12 @@ module internal PervasiveAutoOpens = member inline EndsWithOrdinalIgnoreCase: value: string -> bool + member inline IndexOfOrdinal: value: string -> int + + member inline IndexOfOrdinal: value: string * startIndex: int -> int + + member inline IndexOfOrdinal: value: string * startIndex: int * count: int -> int + type Async with /// Runs the computation synchronously, always starting on the current thread. diff --git a/src/Compiler/Utilities/sformat.fs b/src/Compiler/Utilities/sformat.fs index 834e0c56ed3..611c31235d9 100644 --- a/src/Compiler/Utilities/sformat.fs +++ b/src/Compiler/Utilities/sformat.fs @@ -286,13 +286,13 @@ module Layout = let isEmptyL layout = match layout with - | Leaf(true, s, true) -> s.Text = "" + | Leaf(true, s, true) -> String.IsNullOrEmpty(s.Text) | _ -> false #if COMPILER let rec endsWithL (text: string) layout = match layout with - | Leaf(_, s, _) -> s.Text.EndsWith(text) + | Leaf(_, s, _) -> s.Text.EndsWith(text, StringComparison.Ordinal) | Node(_, r, _) -> endsWithL text r | Attr(_, _, l) -> endsWithL text l | ObjLeaf _ -> false @@ -519,7 +519,7 @@ module ReflectUtils = FSharpValue.GetTupleFields obj |> Array.mapi (fun i v -> (v, tyArgs[i])) let tupleType = - if reprty.Name.StartsWith "ValueTuple" then + if reprty.Name.StartsWith("ValueTuple", StringComparison.Ordinal) then TupleType.Value else TupleType.Reference @@ -1129,7 +1129,7 @@ module Display = :: layouts match postText with - | "" -> + | _ when String.IsNullOrEmpty(postText) -> //We are done, build a space-delimited layout from the collection of layouts we've accumulated Some(spaceListL (List.rev newLayouts)) diff --git a/src/Compiler/Utilities/sr.fs b/src/Compiler/Utilities/sr.fs index b081dfb6083..840a9f4197c 100644 --- a/src/Compiler/Utilities/sr.fs +++ b/src/Compiler/Utilities/sr.fs @@ -2,6 +2,7 @@ namespace FSharp.Compiler +open System open Microsoft.FSharp.Core open Microsoft.FSharp.Collections open Microsoft.FSharp.Reflection @@ -132,7 +133,7 @@ module internal DiagnosticMessage = // strip any escaped % characters - yes, this will fail if given %%%... let s = s.Replace("%%", "") - if s = "" then + if String.IsNullOrEmpty(s) then 0 else let len = s.Length - 1 diff --git a/src/Compiler/pars.fsy b/src/Compiler/pars.fsy index 03e8c099e25..5737eba22f3 100644 --- a/src/Compiler/pars.fsy +++ b/src/Compiler/pars.fsy @@ -1614,7 +1614,7 @@ tyconDefn: SynTypeDefn($1, SynTypeDefnRepr.ObjectModel(SynTypeDefnKind.Augmentation mWithKwd, [], m), classDefns, None, m, trivia) } | typeNameInfo opt_attributes opt_access opt_HIGH_PRECEDENCE_APP opt_simplePatterns optAsSpec EQUALS tyconDefnRhsBlock - { let vis, spats, az = $3, $5, $6 + { let vis, pat, az = $3, $5, $6 let nameRange = rhs parseState 1 let (tcDefRepr, mWith, members) = $8 nameRange let (SynComponentInfo(_, _, _, lid, _, _, _, _)) = $1 @@ -1623,8 +1623,8 @@ tyconDefn: let xmlDoc = grabXmlDoc (parseState, $2, 2) let m = match lid with [] -> rhs parseState 1 | _ -> rangeOfLid lid let memberCtorPattern = - spats |> Option.map (fun spats -> - SynMemberDefn.ImplicitCtor(vis, $2, spats, Option.bind snd az, xmlDoc, m, { AsKeyword = Option.map fst az }) + pat |> Option.map (fun pat -> + SynMemberDefn.ImplicitCtor(vis, $2, pat, Option.bind snd az, xmlDoc, m, { AsKeyword = Option.map fst az }) ) let tcDefRepr = @@ -1659,16 +1659,16 @@ tyconDefn: SynTypeDefn($1, tcDefRepr, members, memberCtorPattern, mWhole, trivia) } | typeNameInfo opt_attributes opt_access opt_HIGH_PRECEDENCE_APP opt_simplePatterns optAsSpec recover - { let vis, spats, az = $3, $5, $6 + { let vis, pat, az = $3, $5, $6 let (SynComponentInfo(longId = lid)) = $1 // Gets the XML doc comments prior to the implicit constructor let xmlDoc = grabXmlDoc (parseState, $2, 2) let m = match lid with [] -> rhs parseState 1 | _ -> rangeOfLid lid let mName = $1.Range let members, mWhole = - match spats, vis, az with - | Some spats, _, _ -> - let memberCtorPattern = SynMemberDefn.ImplicitCtor(vis, $2, spats, Option.bind snd az, xmlDoc, m, { AsKeyword = Option.map fst az }) + match pat, vis, az with + | Some pat, _, _ -> + let memberCtorPattern = SynMemberDefn.ImplicitCtor(vis, $2, pat, Option.bind snd az, xmlDoc, m, { AsKeyword = Option.map fst az }) [memberCtorPattern], unionRanges mName memberCtorPattern.Range | _, _, Some(mAs, asId) -> let mAs = @@ -2716,6 +2716,16 @@ attrUnionCaseDecl: let mDecl = unionRangeWithXmlDoc xmlDoc mDecl Choice1Of2 (SynEnumCase ($1, $3, fst $5, xmlDoc, mDecl, trivia))) } + | opt_attributes opt_access unionCaseName EQUALS recover + { if Option.isSome $2 then errorR(Error(FSComp.SR.parsEnumFieldsCannotHaveVisibilityDeclarations(), rhs parseState 2)) + let mEquals = rhs parseState 4 + let expr = arbExpr ("attrUnionCaseDecl", mEquals.EndRange) + let mDecl = rhs2 parseState 1 4 + fun (xmlDoc, mBar) -> + let trivia: SynEnumCaseTrivia = { BarRange = Some mBar; EqualsRange = mEquals } + let mDecl = unionRangeWithXmlDoc xmlDoc mDecl + Choice1Of2 (SynEnumCase ($1, $3, expr, xmlDoc, mDecl, trivia)) } + /* The name of a union case */ unionCaseName: | nameop @@ -2745,6 +2755,14 @@ firstUnionCaseDeclOfMany: let mDecl = (rhs2 parseState 1 3) |> unionRangeWithXmlDoc xmlDoc Choice1Of2 (SynEnumCase ([], SynIdent($1, None), fst $3, xmlDoc, mDecl, trivia)) } + | ident EQUALS recover opt_OBLOCKSEP + { let mEquals = rhs parseState 2 + let expr = arbExpr ("firstUnionCaseDeclOfMany1", mEquals.EndRange) + let trivia: SynEnumCaseTrivia = { BarRange = None; EqualsRange = mEquals } + let xmlDoc = grabXmlDoc(parseState, [], 1) + let mDecl = (rhs2 parseState 1 2) |> unionRangeWithXmlDoc xmlDoc + Choice1Of2 (SynEnumCase ([], SynIdent($1, None), expr, xmlDoc, mDecl, trivia)) } + | firstUnionCaseDecl opt_OBLOCKSEP { $1 } @@ -2785,6 +2803,15 @@ firstUnionCaseDecl: let mDecl = rhs2 parseState 1 3 |> unionRangeWithXmlDoc xmlDoc Choice1Of2(SynEnumCase([], SynIdent($1, None), fst $3, xmlDoc, mDecl, trivia)) } + | ident EQUALS recover opt_OBLOCKSEP + { let mEquals = rhs parseState 2 + let expr = arbExpr ("firstUnionCaseDecl", mEquals.EndRange) + let trivia: SynEnumCaseTrivia = { BarRange = None; EqualsRange = mEquals } + let xmlDoc = grabXmlDoc (parseState, [], 1) + let mDecl = rhs2 parseState 1 2 |> unionRangeWithXmlDoc xmlDoc + Choice1Of2(SynEnumCase([], SynIdent($1, None), expr, xmlDoc, mDecl, trivia)) } + + unionCaseReprElements: | unionCaseReprElement STAR unionCaseReprElements { $1 :: $3 } @@ -3219,10 +3246,16 @@ localBinding: | opt_inline opt_mutable bindingPattern opt_topReturnTypeWithTypeConstraints recover { if not $5 then reportParseErrorAt (rhs parseState 5) (FSComp.SR.parsUnexpectedEndOfFileDefinition()) + let bindingPat, mBindLhs = $3 let optReturnType = $4 - let mWhole = rhs2 parseState 1 (match optReturnType with None -> 3 | _ -> 4) + let mWhole = + let mStart = rhs parseState 1 + let mEnd = + match optReturnType with + | None -> bindingPat.Range + | Some (_, returnInfo) -> returnInfo.Range + unionRanges mStart mEnd let mRhs = mWhole.EndRange // zero-width range at end of last good token - let bindingPat, mBindLhs = $3 let localBindingBuilder = (fun xmlDoc attrs vis (leadingKeyword: SynLeadingKeyword) -> let spBind = DebugPointAtBinding.Yes(unionRanges leadingKeyword.Range mRhs) @@ -3382,39 +3415,7 @@ constant: bindingPattern: | headBindingPattern - { $1, rhs parseState 1 } - -// Subset of patterns allowed to be used in implicit ctors. -// For a better error recovery we could replace these rules with the actual SynPat parsing -// and use allowed patterns only at a later analysis stage reporting errors along the way. -simplePattern: - | ident - { let m = rhs parseState 1 - SynPat.Named(SynIdent($1, None), false, None, m) } - - | QMARK ident - { SynPat.OptionalVal($2, rhs parseState 2) } - - | simplePattern COLON typeWithTypeConstraints - { SynPat.Typed($1, $3, lhs parseState) } - - | simplePattern COLON recover - { let mColon = rhs parseState 2 - let ty = SynType.FromParseError(mColon.EndRange) - SynPat.Typed($1, ty, unionRanges $1.Range mColon) } - - | attributes simplePattern %prec paren_pat_attribs - { SynPat.Attrib($2, $1, lhs parseState) } - -simplePatternCommaList: - | simplePattern - { $1 } - - | simplePattern COMMA simplePatternCommaList - { let mComma = rhs parseState 2 - match $3 with - | SynPat.Tuple(_, pats, commas, _) -> SynPat.Tuple(false, $1 :: pats, mComma :: commas, rhs2 parseState 1 3) - | _ -> SynPat.Tuple(false, [$1; $3], [mComma], rhs2 parseState 1 3) } + { $1, $1.Range } opt_simplePatterns: | simplePatterns @@ -3423,32 +3424,11 @@ opt_simplePatterns: | { None } simplePatterns: - | LPAREN simplePatternCommaList rparen - { let parenPat = SynPat.Paren($2, rhs2 parseState 1 3) - let simplePats, _ = SimplePatsOfPat parseState.SynArgNameGenerator parenPat - simplePats } + | LPAREN parenPattern rparen + { SynPat.Paren($2, rhs2 parseState 1 3) } | LPAREN rparen - { let pat = SynPat.Const(SynConst.Unit, rhs2 parseState 1 2) - let simplePats, _ = SimplePatsOfPat parseState.SynArgNameGenerator pat - simplePats } - - | LPAREN simplePatternCommaList recover - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let parenPat = SynPat.Paren(SynPat.Tuple(false, [], [], rhs2 parseState 1 2), rhs2 parseState 1 2) // todo: report parsed pats anyway? - let simplePats, _ = SimplePatsOfPat parseState.SynArgNameGenerator parenPat - simplePats } - - | LPAREN error rparen - { let parenPat = SynPat.Paren(SynPat.Wild(rhs parseState 2), rhs2 parseState 1 3) // silent recovery - let simplePats, _ = SimplePatsOfPat parseState.SynArgNameGenerator parenPat - simplePats } - - | LPAREN recover - { reportParseErrorAt (rhs parseState 1) (FSComp.SR.parsUnmatchedParen()) - let pat = SynPat.Wild(lhs parseState) - let simplePats, _ = SimplePatsOfPat parseState.SynArgNameGenerator pat - simplePats } + { SynPat.Const(SynConst.Unit, rhs2 parseState 1 2) } barCanBeRightBeforeNull: | BAR @@ -3461,6 +3441,17 @@ headBindingPattern: | headBindingPattern AS constrPattern %prec AS { SynPat.As($1, $3, rhs2 parseState 1 3) } + | headBindingPattern AS recover + { let mAs = rhs parseState 2 + let pat2 = SynPat.Wild(mAs.EndRange) + SynPat.As($1, pat2, rhs2 parseState 1 2) } + + | headBindingPattern AS + { let mAs = rhs parseState 2 + reportParseErrorAt mAs (FSComp.SR.parsExpectingPattern ()) + let pat2 = SynPat.Wild(mAs.EndRange) + SynPat.As($1, pat2, rhs2 parseState 1 2) } + | headBindingPattern barCanBeRightBeforeNull headBindingPattern %prec BAR { let mBar = rhs parseState 2 SynPat.Or($1, $3, rhs2 parseState 1 3, { BarRange = mBar }) } @@ -3735,6 +3726,11 @@ parenPattern: | parenPattern AS constrPattern %prec AS { SynPat.As($1, $3, rhs2 parseState 1 3) } + | parenPattern AS recover + { let mAs = rhs parseState 2 + let pat2 = SynPat.Wild(mAs.EndRange) + SynPat.As($1, pat2, rhs2 parseState 1 2) } + | parenPattern barCanBeRightBeforeNull parenPattern %prec BAR { let mBar = rhs parseState 2 SynPat.Or($1, $3, rhs2 parseState 1 3, { BarRange = mBar }) } diff --git a/src/Compiler/xlf/FSComp.txt.cs.xlf b/src/Compiler/xlf/FSComp.txt.cs.xlf index 2a8ada38b97..2090cc5883d 100644 --- a/src/Compiler/xlf/FSComp.txt.cs.xlf +++ b/src/Compiler/xlf/FSComp.txt.cs.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + Metoda getter a setter indexované vlastnosti musí mít stejný typ. Vlastnost{0} má metodu get typu {1}, ale metodu set typu {2}. @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Objektové výrazy nemohou implementovat rozhraní se statickými abstraktními členy ani deklarovat statické členy. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + Atribut TailCall by se měl použít jenom pro rekurzivní funkce. @@ -147,6 +147,11 @@ Dostupná přetížení:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + {0} nepodporuje typ {1}, protože tento typ postrádá požadovaný (skutečný nebo vestavěný) člen {2} + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. Obecná konstrukce vyžaduje, aby byl parametr obecného typu známý jako typ struct nebo reference. Zvažte možnost přidat anotaci typu. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Vyvolá upozornění, pokud je atribut TailCall použit u nerekurzivních funkcí. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + preferovat metodu rozšíření před prostými vlastnostmi @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Sdílení podkladových polí v rozlišeném sjednocení [<Struct>] za předpokladu, že mají stejný název a typ @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Vlastnosti testu případu sjednocení @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + Metoda getter a setter indexované vlastnosti musí mít stejný typ. @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Očekává se pole záznamu. @@ -987,9 +992,14 @@ Tento přístup člena je nejednoznačný. Při vytváření objektu použijte závorky, např. (new SomeType(args)).MemberName' + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Neúplná deklarace statického konstruktoru. Pro deklaraci použijte „static let“, „static do“, „static member“ nebo „static val“. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + Zkrácená syntaxe lambda je podporována pouze pro atomické výrazy, jako je metoda, vlastnost, pole nebo indexer v implicitní argumentu _. Příklad: let f = _. Length'. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Toto je definice funkce, která stínuje případ sjednocení. Pokud je to to, co chcete, toto upozornění ignorujte nebo potlačte. Pokud chcete, aby se jedná o dekonstrukci případu sjednocení, přidejte závorky. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Nenašla se žádný statický abstraktní člen, který by odpovídal tomuto přepsání. No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Nenašla se žádná statická abstraktní vlastnost, která by odpovídala tomuto přepsání. @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Pokud je typ sjednocení s více písmeny strukturou, musí být všechna pole se stejným názvem stejného typu. Toto pravidlo platí také pro vygenerovaný název Item v případě nepojmenovaných polí. @@ -1497,6 +1507,11 @@ Deklarování \"interfaces with static abstract methods\" (rozhraní se statickými abstraktními metodami) je pokročilá funkce. Pokyny najdete v https://aka.ms/fsharp-iwsams. Toto upozornění můžete zakázat pomocí #nowarn \"3535\" nebo '--nowarn:3535'. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + Typ {0} má příliš mnoho metod. Nalezeno:{1}, maximum:{2} + + Interface member '{0}' does not have a most specific implementation. Člen rozhraní {0} nemá nejvíce specifickou implementaci. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Je možné odebrat závorky. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - Pro F#7 a nižší se definice statických hodnot dají použít jenom v typech s primárním konstruktorem ('type X(args) = ...'). Pokud je chcete povolit ve všech ostatních typech, použijte jazykovou verzi „preview“. + Pro definice F#7 a nižší, „static let“, „do“ a „member val“ lze použít pouze v typech s primárním konstruktorem (typ X(args) = ...). Pokud je chcete povolit ve všech ostatních typech, použijte jazyk verze 8 nebo vyšší. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - Nejde volat metodu rozšíření byref {0}. První parametr vyžaduje, aby hodnota byla měnitelná nebo typu byref, která není jen pro čtení. + Nejde volat metodu rozšíření byref {0}. Parametr „this“ vyžaduje, aby hodnota byla měnitelná nebo typu byref, která není jen pro čtení. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - Klíč správce balíčků „{0}“ nebyl v {1} zaregistrován. Aktuálně zaregistrováno: {2}. Další informace o rozšířeních najdete tady: https://aka.ms/dotnetdepmanager + Klíč správce balíčků „{0}“ nebyl v {1} zaregistrován. Aktuálně zaregistrováno: {2}. Cesty navíc můžete zadat tak, že do příkazového řádku předáte --compilertool:<extensionsfolder>. Další informace o rozšířeních najdete tady: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.de.xlf b/src/Compiler/xlf/FSComp.txt.de.xlf index d62f45e4cd7..8457960a3b0 100644 --- a/src/Compiler/xlf/FSComp.txt.de.xlf +++ b/src/Compiler/xlf/FSComp.txt.de.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + Getter und Setter einer indizierten Eigenschaft müssen denselben Typ aufweisen. Eigenschaft "{0}" hat einen Getter vom Typ "{1}", jedoch einen Setter vom Typ "{2}". @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Objektausdrücke können keine Schnittstellen mit statischen abstrakten Membern implementieren oder statische Member deklarieren. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + Das Attribut "TailCall" darf nur auf rekursive Funktionen angewendet werden. @@ -147,6 +147,11 @@ Verfügbare Überladungen:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + "{0}" unterstützt den Typ "{1}" nicht, da letzteres nicht das erforderliche (echte oder integrierte) Element "{2}" aufweist. + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. Für ein generisches Konstrukt muss ein generischer Typparameter als Struktur- oder Verweistyp bekannt sein. Erwägen Sie das Hinzufügen einer Typanmerkung. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Löst Warnungen aus, wenn das Attribut "TailCall" für nicht rekursive Funktionen verwendet wird. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + Erweiterungsmethode gegenüber plain-Eigenschaft bevorzugen @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Teilen sie zugrunde liegende Felder in einen [<Struct>]-diskriminierten Union, solange sie denselben Namen und Typ aufweisen. @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Eigenschaften von Union-Falltests @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + Getter und Setter für indizierte Eigenschaften müssen denselben Typ aufweisen. @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Datensatzfeld wird erwartet @@ -987,9 +992,14 @@ Dieser Memberzugriff ist mehrdeutig. Setzen Sie Klammern um die Objekterstellung, z. B. "(new SomeType(args)). MemberName“ + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Unvollständige Deklaration eines statischen Konstrukts. Verwenden Sie "static let", "static do", "static member" oder "static val" für die Deklaration. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + Die Lambdasyntax der Kurzform wird nur für atomische Ausdrücke wie Methode, Eigenschaft, Feld oder Indexer für das implizite Argument "_" unterstützt. Beispiel: "let f = _. Länge". @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Dies ist eine Funktionsdefinition, die einen Union-Fall überschatten kann. Wenn Sie dies wünschen, ignorieren oder unterdrücken Sie diese Warnung. Wenn es sich um eine Dekonstruktion des Union-Falls handelt, fügen Sie Klammern hinzu. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Es wurde kein abstrakter Member gefunden, der dieser Überschreibung entspricht. No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Es wurde keine statische abstrakte Eigenschaft gefunden, die dieser Überschreibung entspricht. @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Wenn ein Union-Typ mit mehreren Großbuchstaben eine Struktur ist, müssen alle Felder mit demselben Namen denselben Typ aufweisen. Diese Regel gilt auch für den generierten Elementnamen bei unbenannten Feldern. @@ -1497,6 +1507,11 @@ Das Deklarieren von \"Schnittstellen mit statischen abstrakten Methoden\" ist ein erweitertes Feature. Anleitungen finden Sie unter https://aka.ms/fsharp-iwsams. Sie können diese Warnung deaktivieren, indem Sie „#nowarn \"3535\"“ or „--nowarn:3535“ verwenden. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + Der Typ "{0}" weist zu viele Methoden auf. Gefunden: "{1}", Maximum: "{2}" + + Interface member '{0}' does not have a most specific implementation. Der Schnittstellenmember "{0}" weist keine spezifischste Implementierung auf. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Klammern können entfernt werden. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - Für F# 7 und früher dürfen statische Wertdefinitionen nur in Typen mit einem primären Konstruktor verwendet werden (type X(args) = ...). Um sie in anderen Typen zu aktivieren, verwenden Sie die Sprachversion "preview". + Für F# 7 und früher dürfen die statische Definitionen "let", "do" und "member" nur in Typen mit einem primären Konstruktor verwendet werden (type X(args) = ...). Um sie in anderen Typen zu aktivieren, verwenden Sie die Sprachversion "8" oder höher. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - Die ByRef-Erweiterungsmethode "{0}" kann nicht aufgerufen werden. Für den ersten Parameter muss der Wert änderbar sein oder einem nicht schreibgeschützten ByRef-Typ entsprechen. + Die ByRef-Erweiterungsmethode "{0}" kann nicht aufgerufen werden. Für den Parameter „this“ muss der Wert änderbar sein oder einem nicht schreibgeschützten ByRef-Typ entsprechen. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - Der Paket-Manager-Schlüssel "{0}" wurde nicht in "{1}" registriert. Zurzeit registriert: {2}. Weitere Informationen zu Erweiterungen finden Sie unter: https://aka.ms/dotnetdepmanager + Der Paket-Manager-Schlüssel "{0}" wurde nicht in "{1}" registriert. Zurzeit registriert: {2}. Sie können zusätzliche Pfade angeben, indem Sie "--compilertool:<extensionsfolder>" an die Befehlszeile übergeben. Weitere Informationen zu Erweiterungen finden Sie unter: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.es.xlf b/src/Compiler/xlf/FSComp.txt.es.xlf index 08bf1b59b23..02c83adf195 100644 --- a/src/Compiler/xlf/FSComp.txt.es.xlf +++ b/src/Compiler/xlf/FSComp.txt.es.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + El captador y el establecedor de una propiedad indexada deben tener el mismo tipo. La propiedad '{0}' tiene un captador de tipo '{1}', pero el establecedor es de tipo '{2}'. @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Las expresiones de objeto no pueden implementar interfaces con miembros abstractos estáticos ni declarar miembros estáticos. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + El atributo TailCall solo se debe aplicar a funciones recursivas. @@ -147,6 +147,11 @@ Sobrecargas disponibles:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + '{0}' no admite el tipo '{1}', porque a este último le falta el '{2}' de miembro necesario (real o integrado) + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. Una construcción genérica requiere que un parámetro de tipo genérico se conozca como tipo de referencia o estructura. Puede agregar una anotación de tipo. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Genera advertencias si el atributo 'TailCall' se usa en funciones no recursivas. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + preferir método de extensión sobre propiedad sin formato @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Compartir campos subyacentes en una unión discriminada [<Struct>] siempre y cuando tengan el mismo nombre y tipo @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Propiedades de prueba de caso de unión @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + El captador y el establecedor de propiedades indexadas deben tener el mismo tipo. @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Se espera un campo de registro @@ -987,9 +992,14 @@ Este acceso de miembro es ambiguo. Use paréntesis alrededor de la creación del objeto, por ejemplo, '(nuevo AlgúnTipo(args)).NombreMiembro' + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Declaración incompleta de una construcción estática. Use "static let", "static do", "static member" o "static val" para la declaración. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + La sintaxis lambda abreviada solo se admite para expresiones atómicas, como el método, la propiedad, el campo o el indexador en el argumento '_' implícito. Por ejemplo: 'let f = _.Length'. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Esta es una definición de función que oculta un caso de unión. Si esto es lo que desea, omita o suprima esta advertencia. Si desea que sea una desconstrucción de caso de unión, agregue paréntesis. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + No se encontró ningún miembro abstracto estático que corresponda a esta invalidación. No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + No se encontró ninguna propiedad abstracta estática que corresponda a esta invalidación. @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Si un tipo de unión multicase es un struct, todos los campos con el mismo nombre deben ser del mismo tipo. Esta regla se aplica también al nombre "Item" generado en el caso de campos sin nombre. @@ -1497,6 +1507,11 @@ Declarar \"interfaces con métodos abstractos estáticos\" es una característica avanzada. Consulte https://aka.ms/fsharp-iwsams para obtener instrucciones. Puede deshabilitar esta advertencia con "#nowarn \"3535\"" o "--nowarn:3535". + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + El tipo '{0}' tiene demasiados métodos. Encontrado: '{1}', máximo: '{2}' + + Interface member '{0}' does not have a most specific implementation. El miembro de interfaz "{0}" no tiene una implementación más específica. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Los paréntesis se pueden quitar. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - Para F#7 y versiones anteriores, las definiciones de valores estáticos solo se pueden usar en tipos con un constructor principal ('type X(args) = ...'). Para habilitarlos en todos los demás tipos, use la versión de idioma "preview". + Para F#7 y versiones anteriores, las definiciones estáticas 'let','do' y 'member val' solo se pueden usar en tipos con un constructor principal ('type X(args) = ...'). Para habilitarlos en todos los demás tipos, use la versión de idioma "8" o una versión posterior. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - No se puede llamar al método de extensión de byref "{0}". El primer parámetro requiere que el valor sea mutable o un tipo de byref que no sea de solo lectura. + No se puede llamar al método de extensión de byref "{0}". El parámetro 'this' requiere que el valor sea mutable o un tipo byref no de solo lectura. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - La clave del administrador de paquetes "{0}" no se registró en {1}. Registrado actualmente: {2}. Para obtener más información sobre las extensiones, visite https://aka.ms/dotnetdepmanager + La clave del administrador de paquetes "{0}" no se registró en {1}. Registrado actualmente: {2}. Puede proporcionar rutas adicionales pasando '--compilertool:<extensionsfolder>' a la línea de comando. Para obtener más información sobre las extensiones, visite https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.fr.xlf b/src/Compiler/xlf/FSComp.txt.fr.xlf index 5089523c330..7680237f22d 100644 --- a/src/Compiler/xlf/FSComp.txt.fr.xlf +++ b/src/Compiler/xlf/FSComp.txt.fr.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + Les méthodes getter et setter d’une propriété indexée doivent avoir le même type. La propriété « {0} » a une méthode getter de type « {1} » alors que sa méthode setter est de type « {2} ». @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Les expressions d’objet ne peuvent pas implémenter des interfaces avec des membres abstraits statiques ou déclarer des membres statiques. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + L’attribut TailCall ne doit être appliqué qu’aux fonctions récursives. @@ -147,6 +147,11 @@ Surcharges disponibles :\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + '{0}' ne prend pas en charge le type '{1}', car ce dernier n'a pas le membre requis (réel ou intégré) '{2}' + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. L'utilisation d'une construction générique est possible uniquement si un paramètre de type générique est connu en tant que type struct ou type référence. Ajoutez une annotation de type. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Émet des avertissements si l’attribut « TailCall » est utilisé sur des fonctions non récursives. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + préférer la méthode d’extension à la propriété simple @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Partager les champs sous-jacents dans une union discriminée [<Struct>] tant qu’ils ont le même nom et le même type @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Propriétés du test de cas d’union @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + Les propriétés indexées getter et setter doivent avoir le même type @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Champ d’enregistrement attendu @@ -987,9 +992,14 @@ 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 + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Déclaration incomplète d’une construction statique. Utilisez « static let », « static do », « static member » ou « static val » pour la déclaration. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + La syntaxe lambda raccourcie est prise en charge uniquement pour les expressions atomiques, telles que la méthode, la propriété, le champ ou l’indexeur sur l’argument ’_’ implicite. Par exemple : « let f = _. Longueur ». @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Il s’agit d’une définition de fonction qui masque un cas d’union. Si c’est ce que vous voulez, ignorez ou supprimez cet avertissement. Si vous voulez qu’il s’agit d’une déconstruction de cas d’union, ajoutez des parenthèses. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Désolé, nous n’avons pas pu trouver un membre abstrait statique qui corresponde à cette substitution No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Désolé, nous n’avons pas pu trouver une propriété abstraite statique qui corresponde à cette substitution @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Si un type union multicase est un struct, tous les champs portant le même nom doivent être du même type. Cette règle s’applique également au nom « Item » généré en cas de champs sans nom. @@ -1497,6 +1507,11 @@ La déclaration de \"interfaces with static abstract methods\" est une fonctionnalité avancée. Consultez https://aka.ms/fsharp-iwsams pour obtenir de l’aide. Vous pouvez désactiver cet avertissement à l’aide de '#nowarn \"3535\"' or '--nowarn:3535'. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + Le type '{0}' a trop de méthodes. Trouvé : '{1}', maximum : '{2}' + + Interface member '{0}' does not have a most specific implementation. Le membre d'interface '{0}' n'a pas l'implémentation la plus spécifique. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Vous pouvez supprimer les parenthèses. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - Pour F#7 et versions antérieures, les définitions de valeurs statiques ne peuvent être utilisées que dans les types avec un constructeur principal (« type X(args) = ... »). Pour les activer dans tous les autres types, utilisez la version linguistique « aperçu ». + Pour les définitions F#7 et inférieures, les définitions statiques « let », « do » et « member val » ne peuvent être utilisées que dans les types avec un constructeur principal (« type X(args) = ... »). Pour les activer dans tous les autres types, utilisez la version linguistique « 8 » ou ultérieure. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - Impossible d’appeler la méthode d’extension byref « {0} ». Le premier paramètre nécessite que la valeur soit mutable ou un type byref autre qu'en lecture seule. + Impossible d’appeler la méthode d’extension byref '{0}. Le paramètre 'this' nécessite que la valeur soit mutable ou un type byref non readonly. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - La clé du gestionnaire de packages « {0} » n'a pas été enregistrée dans {1}. Actuellement inscrit : {2}. Pour en savoir plus sur les extensions, visitez : https://aka.ms/dotnetdepmanager + La clé du gestionnaire de package «{0}» n’a pas été inscrite dans {1}. Actuellement inscrit : {2}. Vous pouvez fournir des chemins d’accès supplémentaires en passant « --compilertool :<extensionsfolder> » à la ligne de commande. Pour en savoir plus sur les extensions, consultez : https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.it.xlf b/src/Compiler/xlf/FSComp.txt.it.xlf index cdc2dd7ac91..af598a60a92 100644 --- a/src/Compiler/xlf/FSComp.txt.it.xlf +++ b/src/Compiler/xlf/FSComp.txt.it.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + Il getter e il setter di una proprietà indicizzata devono essere dello stesso tipo. Il getter della proprietà '{0}' è di tipo '{1}', mentre il setter è di tipo '{2}'. @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Le espressioni di oggetto non possono implementare interfacce con membri astratti statici o dichiarare membri statici. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + L'attributo TailCall deve essere applicato solo a funzioni ricorsive. @@ -147,6 +147,11 @@ Overload disponibili:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + '{0}' non supporta il tipo '{1}', perché in quest'ultimo manca il membro '{2}' richiesto (reale o predefinito) + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. Un costrutto generico richiede che un parametro di tipo generico sia noto come tipo riferimento o struct. Provare ad aggiungere un'annotazione di tipo. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Genera avvisi se l'attributo 'TailCall' viene utilizzato in funzioni non ricorsive. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + preferisci il metodo di estensione alla proprietà normale @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Condividi i campi sottostanti in un'unione discriminata di [<Struct>] purché abbiano lo stesso nome e tipo @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Proprietà test case di unione @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + Il getter e il setter delle proprietà indicizzate devono avere lo stesso tipo @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Previsto campo record @@ -987,9 +992,14 @@ L'accesso ai membri è ambiguo. Utilizzare le parentesi intorno alla creazione oggetto, ad esempio “(New SomeType (args)). MemberName” + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Dichiarazione incompleta di un costrutto statico. Usare 'static let','static do','static member' o 'static val' per la dichiarazione. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + La sintassi lambda a sintassi abbreviata è supportata solo per le espressioni atomiche, ad esempio metodo, proprietà, campo o indicizzatore nell'argomento '_' implicito. Ad esempio: 'let f = _. Lunghezza'. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Definizione di funzione che nasconde un case di unione. Se si desidera eseguire questa operazione, ignorare o eliminare questo avviso. Se si desidera che sia una decostruzione di case di unione, aggiungere le parentesi. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Nessun membro astratto statico trovato corrispondente all'override No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Nessuna proprietà astratta statica trovata corrispondente all'override @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Se un tipo di unione multicase è uno struct, tutti i campi con lo stesso nome devono essere dello stesso tipo. Questa regola si applica anche al nome 'Elemento' generato in caso di campi senza nome. @@ -1497,6 +1507,11 @@ La dichiarazione di \"interfaces with static abstract methods\" è una funzionalità avanzata. Per indicazioni, vedere https://aka.ms/fsharp-iwsams. È possibile disabilitare questo avviso usando '#nowarn \"3535\"' o '--nowarn:3535'. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + Il tipo '{0}' contiene troppi metodi. Trovato: '{1}', massimo: '{2}' + + Interface member '{0}' does not have a most specific implementation. Il membro di interfaccia '{0}' non contiene un'implementazione più specifica. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + È possibile rimuovere le parentesi. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - Per F#7 e versioni precedenti, le definizioni di valori statici possono essere usate solo in tipi con un costruttore primario ('type X(args) = ...'). Per abilitarli in tutti gli altri tipi, usare la versione di "anteprima" del linguaggio. + Per F#7 e versioni precedenti, le definizioni di valori statici 'let','do' e 'member val' possono essere usate solo in tipi con un costruttore primario ('type X(args) = ...'). Per abilitarli in tutti gli altri tipi, usare la versione del linguaggio '8' o successiva. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - Non è possibile chiamare il metodo di estensione byref '{0}. Il valore del primo parametro deve essere modificabile oppure un tipo byref non di sola lettura. + Non è possibile chiamare il metodo di estensione byref '{0}. ‘questo parametro deve essere modificabile oppure un tipo byref non di sola lettura. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - La chiave "'{0}" del gestione pacchetti non è stata registrata in {1}. Attualmente registrata: {2}. Per altre informazioni sulle estensioni, vedere: https://aka.ms/dotnetdepmanager + La chiave "'{0}" del gestione pacchetti non è stata registrata in {1}. Attualmente registrata: {2}. Per fornire percorsi aggiuntivi, passare '--compilertool:<extensionsfolder>' alla riga di comando. Per altre informazioni sulle estensioni, vedere: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.ja.xlf b/src/Compiler/xlf/FSComp.txt.ja.xlf index bbc8b647621..da6e725af01 100644 --- a/src/Compiler/xlf/FSComp.txt.ja.xlf +++ b/src/Compiler/xlf/FSComp.txt.ja.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + インデックスの付いたプロパティのゲッターとセッターは同じ型でなければなりません。プロパティ '{0}' は、ゲッターの型が '{1}' ですが、セッターの型は '{2}' です。 @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + オブジェクト式は、静的抽象メンバーを持つインターフェイスを実装したり、静的メンバーを宣言したりすることはできません。 The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + TailCall 属性は再帰関数にのみ適用する必要があります。 @@ -147,6 +147,11 @@ 使用可能なオーバーロード:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + 型 '{1}' には必要な (実数または組み込み) メンバー '{2}' がないため、'{0}' ではサポートされません + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. ジェネリック コンストラクトでは、ジェネリック型パラメーターが構造体または参照型として認識されている必要があります。型の注釈の追加を検討してください。 @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + 'TailCall' 属性が再帰関数以外で使用されている場合、警告が発せられます。 @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + plain プロパティよりも拡張メソッドを優先する @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + 名前と型が同じである限り、[<Struct>] 判別可能な共用体で基になるフィールドを共有する @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + ユニオン ケースのテスト プロパティ @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + インデックス付きプロパティのゲッターとセッターの型は同じである必要があります @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + レコード フィールドが必要です @@ -987,9 +992,14 @@ このメンバーへのアクセスはあいまいです。オブジェクト作成の前後にはかっこを使用してください。例: '(new SomeType(args)).MemberName' + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + 静的コンストラクトの不完全な宣言。宣言には、'static let'、'static do'、'static member'、または 'static val' を使用します。 @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + 短縮ラムダ構文は、暗黙的な '_' 引数のメソッド、プロパティ、フィールド、インデクサーなどのアトミック式でのみサポートされています。例: 'let f = _.Length'。 @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + これは、共用体のケースをシャドウする関数定義です。これが必要な場合は、この警告を無視するか、非表示にしてください。共用体のケース分解にする場合は、かっこを追加します。 @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + このオーバーライドに対応する静的抽象メンバーが見つかりませんでした No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + このオーバーライドに対応する抽象プロパティが見つかりませんでした @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + マルチケース共用体型が構造体の場合、同じ名前を持つすべてのフィールドが同じ型である必要があります。このルールは、名前のないフィールドの場合に生成された 'Item' 名にも適用されます。 @@ -1497,6 +1507,11 @@ \"interfaces with static abstract method\" の宣言は高度な機能です。ガイダンスについては https://aka.ms/fsharp-iwsams を参照してください。この警告は、'#nowarn \"3535\"' または '--nowarn:3535' を使用して無効にできます。 + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + 型 '{0}' に含まれるメソッドが多すぎます。検出した内容: '{1}'、最大値: '{2}' + + Interface member '{0}' does not have a most specific implementation. インターフェイス メンバー '{0}' には最も固有な実装がありません。 @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + かっこは削除できます。 @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - F#7 以前の場合、静的な値の定義は、プライマリ コンストラクター ('type X(args) = ...') を持つ型でのみ使用できます。他のすべての種類で有効にするには、言語バージョン 'preview' を使用します。 + F#7 以前の場合、静的な 'let'、'do'、'member val' の定義は、プライマリ コンストラクター ('type X(args) = ...') を持つ型でのみ使用できます。他のすべての型で有効にするには、言語バージョン '8' 以降を使用します。 @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - byref 拡張メソッド '{0} を呼び出すことはできません。最初のパラメーターでは、値を変更可能な byref 型または読み取り専用以外の byref 型にする必要があります。 + byref 拡張メソッド '{0}を呼び出すことはできません。'this' パラメーターには、値を変更可能にするか、読み取り専用以外の byref 型を指定する必要があります。 @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - パッケージ マネージャー キー '{0}' は {1} に登録されませんでした。現在登録済み: {2}。拡張機能の詳細については、次を参照してください: https://aka.ms/dotnetdepmanager + パッケージ マネージャー キー '{0}' は {1} に登録されませんでした。現在登録されているもの: {2}。'--compilertool:<extensionsfolder>' をコマンド ラインに渡すことで、追加のパスを指定できます。拡張機能の詳細については、次を参照してください: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.ko.xlf b/src/Compiler/xlf/FSComp.txt.ko.xlf index ca0ca6e940f..be43787c542 100644 --- a/src/Compiler/xlf/FSComp.txt.ko.xlf +++ b/src/Compiler/xlf/FSComp.txt.ko.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + 인덱싱된 속성의 getter와 setter의 형식이 같아야 합니다. '{0}' 속성에 '{1}' 형식의 getter가 있지만 '{2}’ 형식의 setter가 있습니다. @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + 개체 식은 정적 추상 멤버가 있는 인터페이스를 구현하거나 정적 멤버를 선언할 수 없습니다. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + TailCall 특성은 재귀 함수에만 적용해야 합니다. @@ -147,6 +147,11 @@ 사용 가능한 오버로드:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + '{1}' 형식에는 필수(실제 또는 기본 제공) 멤버 '{2}'이(가) 없기 때문에 '{0}'이(가) 이 형식을 지원하지 않습니다. + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. 제네릭 구문을 사용하려면 구조체 또는 참조 형식의 제네릭 형식 매개 변수가 필요합니다. 형식 주석을 추가하세요. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + 'TailCall' 특성이 비 재귀 함수에 사용되는 경우 경고를 발생합니다. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + 일반 속성보다 확장 메서드 선호 @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + 이름과 형식이 같으면 [<Struct>] 구분된 공용 구조체에서 기본 필드 공유 @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + 공용 구조체 사례 테스트 속성 @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + 인덱싱된 속성 getter와 setter의 형식이 같아야 합니다. @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + 레코드 필드 필요 @@ -987,9 +992,14 @@ 이 구성원 액세스가 모호합니다. 개체 생성 주위에 괄호를 사용하세요. 예: '(새로운 SomeType(인수)).MemberName' + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + 정적 구문의 선언이 불완전합니다. 선언에 'static let','static do','static member' 또는 'static val'을 사용합니다. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + 줄임 람다 구문은 암시적 '_' 인수의 메서드, 속성, 필드 또는 인덱서와 같은 원자성 식에 대해서만 지원됩니다. 예: 'let f = _.Length'. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + 공용 구조체 케이스를 음영 처리하는 함수입니다. 원하는 경우 이 경고를 무시하거나 표시하지 않습니다. 공용 구조체 케이스 분해가 되도록 하려면 괄호를 추가합니다. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + 이 재정의에 해당하는 정적 추상 멤버를 찾을 수 없습니다. No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + 이 재정의에 해당하는 정적 추상 속성을 찾을 수 없습니다. @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + 멀티캐시 공용 구조체 형식이 구조체이면 이름이 같은 모든 필드의 형식이 같아야 합니다. 이 규칙은 명명되지 않은 필드의 경우 생성된 '항목' 이름에도 적용됩니다. @@ -1497,6 +1507,11 @@ \"interfaces with static abstract methods\"를 선언하는 것은 고급 기능입니다. 지침은 https://aka.ms/fsharp-iwsams를 참조하세요. '#nowarn \"3535\"' 또는 '--nowarn:3535'를 사용하여 이 경고를 비활성화할 수 있습니다. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + '{0}' 형식에 메서드가 너무 많습니다. 찾은 항목: '{1}', 최대: '{2}' + + Interface member '{0}' does not have a most specific implementation. 인터페이스 멤버 '{0}'에 가장 한정적인 구현이 없습니다. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + 괄호를 제거할 수 있습니다. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - F#7 이하의 경우 정적 값 정의는 기본 생성자('type X(args) = ...')가 있는 형식에서만 사용할 수 있습니다. 다른 모든 형식에서 사용하도록 설정하려면 언어 버전 '미리 보기'를 사용합니다. + F#7 이하의 경우, 정적 'let', 'do' 및 'member val' 정의는 기본 생성자가 있는 타입('type X(args) = ...')에서만 사용할 수 있습니다. 다른 모든 형식에서 사용하도록 설정하려면 언어 버전 ‘8’ 또는 그 이상을 사용합니다. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - byref 확장 메서드 '{0}'을(를) 호출할 수 없습니다. 첫 번째 매개 변수는 변경할 수 있거나 읽기 전용이 아닌 byref 형식인 값이 필요합니다. + byref 확장 메서드 '{0}'을(를) 호출할 수 없습니다. ‘이’ 매개 변수는 변경할 수 있거나 읽기 전용이 아닌 byref 형식인 값이 필요합니다. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - 패키지 관리자 키 '{0}'이(가) {1}에서 등록되지 않았습니다. 현재 등록: {2}. 확장에 대한 자세한 내용은 다음을 참조하세요. https://aka.ms/dotnetdepmanager + 패키지 관리자 키 '{0}'이(가) {1}에 등록되지 않았습니다. 현재 등록됨: {2}. 명령줄에 '--compilertool:<extensionsfolder>'를 전달하여 추가 경로를 제공할 수 있습니다. 확장에 대한 자세한 내용은 다음을 참조하세요. https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.pl.xlf b/src/Compiler/xlf/FSComp.txt.pl.xlf index c3e44915a0c..100ba5dfc89 100644 --- a/src/Compiler/xlf/FSComp.txt.pl.xlf +++ b/src/Compiler/xlf/FSComp.txt.pl.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + Metoda pobierająca i metoda ustawiająca właściwości indeksowanej muszą mieć taki sam typ. Właściwość „{0}” ma metodę pobierającą typu „{1}”, ale metodę ustawiającą typu „{2}”. @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Wyrażenia obiektów nie mogą implementować interfejsów ze statycznymi abstrakcyjnymi elementami członkowskimi ani deklarować statycznych elementów członkowskich. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + Atrybut TailCall powinien być stosowany tylko do funkcji rekursywnych. @@ -147,6 +147,11 @@ Dostępne przeciążenia:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + Element „{0}” nie obsługuje typu „{1}”, ponieważ ten drugi nie ma wymaganej (rzeczywistej lub wbudowanej) składowej „{2}” + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. Konstrukcja ogólna wymaga, aby parametr typu ogólnego był znany jako struktura lub typ referencyjny. Rozważ dodanie adnotacji typu. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Zgłasza ostrzeżenia, jeśli atrybut „TailCall” jest używany w funkcjach niekursywnych. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + preferuj metodę rozszerzenia nad zwykłą właściwością @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Udostępnij pola źródłowe w unii rozłącznej [<Struct>], o ile mają taką samą nazwę i ten sam typ @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Właściwości testowe przypadku unii @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + Metoda pobierająca i metoda ustawiająca właściwości indeksowanych muszą mieć taki sam typ. @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Oczekiwanie pola rekordu @@ -987,9 +992,14 @@ Dostęp tego elementu członkowskiego jest niejednoznaczny. W celu utworzenia obiektu użyj nawiasów, na przykład „(nowy SomeType(args)).MemberName” + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Niekompletna deklaracja konstrukcji statycznej. Użyj elementu „static let”, „static do”, „static member” lub „static val” na potrzeby deklaracji. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + Składnia lambda skrótu jest obsługiwana tylko w przypadku wyrażeń niepodzielnych, takich jak metoda, właściwość, pole lub indeksator w dorozumianym argumencie „_”. Na przykład: „let f = _. Length”. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + To jest definicja funkcji, która zasłania przypadek unii. Jeśli to jest to, czego chcesz, zignoruj lub pomiń to ostrzeżenie. Jeśli chcesz, aby była to dekonstrukcja przypadku unii, dodaj nawiasy. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Nie odnaleziono żadnego statycznego abstrakcyjnego elementu członkowskiego odpowiadającego temu przesłonięciu No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Nie odnaleziono żadnej statycznej właściwości abstrakcyjnej odpowiadającej temu przesłonięciu @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Jeśli typ unii wieloskładnikowej jest strukturą, wszystkie pola o tej samej nazwie muszą być tego samego typu. Ta reguła ma zastosowanie również do wygenerowanej nazwy „item” w przypadku pól bez nazwy. @@ -1497,6 +1507,11 @@ Deklarowanie \"interfejsów ze statycznymi metodami abstrakcyjnymi\" jest funkcją zaawansowaną. Aby uzyskać wskazówki, zobacz https://aka.ms/fsharp-iwsams. To ostrzeżenie można wyłączyć przy użyciu polecenia „#nowarn \"3535\"" lub "--nowarn:3535”. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + Typ „{0}” ma zbyt wiele metod. Znaleziono: „{1}”, maksimum: „{2}” + + Interface member '{0}' does not have a most specific implementation. Składowa interfejsu „{0}” nie ma najbardziej specyficznej implementacji. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Nawiasy można usunąć. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - W przypadku języka F#7 i niższych, definicje wartości statycznych mogą być używane tylko w typach z konstruktorem podstawowym („type X(args) = ...”). Aby włączyć je we wszystkich innych typach, użyj wersji językowej „wersja zapoznawcza”. + W przypadku języka F#7 i niższych wersji, definicje statyczne „let”,„do” i „member val” mogą być używane tylko w typach z konstruktorem podstawowym („type X(args) = ...”). Aby włączyć je we wszystkich innych typach, użyj wersji „8” języka lub wyższej. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - Nie można wywołać metody rozszerzenia byref „{0}”. Pierwszy parametr wymaga, aby wartość była typem byref zmiennym lub innym niż tylko do odczytu. + Nie można wywołać metody rozszerzenia byref „{0}”. parametr „this” wymaga, aby wartość była typem byref podlegającym zmianie lub innym niż tylko do odczytu. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - Klucz menedżera pakietów „{0}” nie został zarejestrowany w {1}. Aktualnie zarejestrowane: {2}. Aby dowiedzieć się więcej o rozszerzeniach, odwiedź stronę: https://aka.ms/dotnetdepmanager + Klucz menedżera pakietów „{0}” nie został zarejestrowany w {1}. Aktualnie zarejestrowane: {2}. Możesz podać dodatkowe ścieżki, przekazując polecenie „--compilertool:<extensionsfolder>” do wiersza polecenia. Aby dowiedzieć się więcej o rozszerzeniach, odwiedź stronę: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.pt-BR.xlf b/src/Compiler/xlf/FSComp.txt.pt-BR.xlf index fd797b5beec..9e3e0f68919 100644 --- a/src/Compiler/xlf/FSComp.txt.pt-BR.xlf +++ b/src/Compiler/xlf/FSComp.txt.pt-BR.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + O getter e o setter de uma propriedade devem ter o mesmo tipo. A propriedade "{0}" possui getter do tipo "{1}", mas setter do tipo "{2}". @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Expressões de objeto não podem implementar interfaces com membros abstratos estáticos ou declarar membros estáticos. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + O atributo TailCall só deve ser aplicado a funções recursivas. @@ -147,6 +147,11 @@ Sobrecargas disponíveis:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + "{0}" não dá suporte ao tipo "{1}", pois o último não tem o membro necessário (real ou interno) "{2}: + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. Um constructo genérico exige que um parâmetro de tipo genérico seja conhecido como um tipo de referência ou struct. Considere adicionar uma anotação de tipo. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Gera avisos se o atributo "TailCall" for usado em funções não recursivas. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + preferir o método de extensão em vez da propriedade simples @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Compartilhar campos subjacentes em uma união discriminada [<Struct>], desde que tenham o mesmo nome e tipo @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Propriedades de teste de caso de união @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + As propriedades indexadas getter e setter devem ter o mesmo tipo @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Esperando campo de registro @@ -987,9 +992,14 @@ Este acesso de membro é ambíguo. Use parênteses em torno da criação do objeto, por exemplo, '(new SomeType(args)).MemberName''. + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Declaração incompleta de um constructo estático. Use "static let","static do","static member" ou "static val" para declaração. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + A sintaxe lambda abreviada só tem suporte para expressões atômicas, como método, propriedade, campo ou indexador no argumento '_' implícito. Por exemplo: 'let f = _. Comprimento'. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Essa é uma definição de função que sombra um caso de união. Se isso for o que você deseja, ignore ou suprime este aviso. Se você quiser que ele seja uma desconstrução de caso de união, adicione parênteses. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Nenhum membro abstrato estático encontrado que corresponda a esta substituição No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Nenhuma propriedade abstrata que corresponde a esta substituição foi encontrada @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Se um tipo de união multicase for um struct, todos os campos com o mesmo nome deverão ser do mesmo tipo. Essa regra também se aplica ao nome 'Item' gerado no caso de campos sem nome. @@ -1497,6 +1507,11 @@ Declarando \"interfaces com métodos abstratos estáticos\" é um recurso avançado. Consulte https://aka.ms/fsharp-iwsams para obter diretrizes. Você pode desabilitar esse aviso usando '#nowarn \"3535\"' ou '--nowarn:3535'. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + O tipo "{0}" tem muitos métodos. Encontrado: "{1}", máximo: "{2}" + + Interface member '{0}' does not have a most specific implementation. O membro de interface '{0}' não tem uma implementação mais específica. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Os parênteses podem ser removidos. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - Para F#7 e inferior, as definições de valores estáticos só podem ser usadas em tipos com um construtor primário ('type X(args) = ...'). Para habilitá-los em todos os outros tipos, use a versão do idioma “versão prévia”. + Para F#7 e inferior, as definições de valores estáticos só podem ser usadas em tipos com um construtor primário ('type X(args) = ...'). Para habilitá-los em todos os outros tipos, use a versão do idioma “versão prévia”. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - Não é possível chamar o método de extensão de byref '{0}. O primeiro parâmetro requer que o valor seja mutável ou não seja byref somente leitura. + Não é possível chamar o método de extensão de byref '{0}. O primeiro parâmetro requer que o valor seja mutável ou não seja byref somente leitura. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - A chave do gerenciador de pacotes “{0}” não foi registrada em {1}. Atualmente cadastrado: {2}. Para saber mais sobre extensões, visite: https://aka.ms/dotnetdepmanager + A chave do gerenciador de pacotes “{0}” não foi registrada em {1}. Atualmente cadastrado: {2}. Você pode fornecer caminhos extras passando "--compilertool:<extensionsfolder>" para a linha de comando. Para saber mais sobre extensões, visite: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.ru.xlf b/src/Compiler/xlf/FSComp.txt.ru.xlf index 8b1cad66105..bb1641fcdee 100644 --- a/src/Compiler/xlf/FSComp.txt.ru.xlf +++ b/src/Compiler/xlf/FSComp.txt.ru.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + Методы получения и установки индексированного свойства должны иметь один и тот же тип. Свойство "{0}" имеет метод получения типа "{1}" и метод задания типа "{2}". @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Выражения объектов не могут реализовывать интерфейсы со статическими абстрактными членами или объявлять статические члены. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + Атрибут TailCall следует применять только к рекурсивным функциям. @@ -147,6 +147,11 @@ Доступные перегрузки:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + '{0}' не поддерживает тип '{1}', поскольку у последнего отсутствует необходимый (реальный или встроенный) член '{2}' + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. В универсальной конструкции требуется использовать параметр универсального типа, известный как структура или ссылочный тип. Рекомендуется добавить заметку с типом. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + Выдает предупреждения, если атрибут TailCall используется в нерекурсивных функциях. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + предпочитать метод расширения вместо простого свойства @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Совместное использование базовых полей в дискриминируемом объединении [<Struct>], если они имеют одинаковое имя и тип. @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Свойства теста союзного случая @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + Методы получения и установки индексированных свойств должны иметь один и тот же тип. @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Ожидается поле записи @@ -987,9 +992,14 @@ Неоднозначный доступ к этому элементу. Заключите операцию создания объекта в круглые скобки, например (new Объект(аргументы)).Элемент + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Неполное объявление статической конструкции. Для объявления используйте «static let», «static do», «staticmember» или «static val». @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + Сокращенный синтаксис лямбда-выражений поддерживается только для атомарных выражений, таких как метод, свойство, поле или индексатор подразумеваемого аргумента «_». Например: 'let f = _.Length'. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Это определение функции, которое отражает случай объединения. Если это то, что вы хотите, игнорируйте или подавляйте это предупреждение. Если вы хотите, чтобы это была деконструкция регистра объединения, добавьте круглые скобки. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Не найден статический абстрактный элемент, соответствующий этому переопределению. No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Не найдено статическое абстрактное свойство, соответствующее этому переопределению. @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Если тип объединения нескольких регистров является структурой, то все поля с одинаковым именем должны быть одного типа. Это правило также применяется к сгенерированному имени «Элемент» в случае безымянных полей. @@ -1497,6 +1507,11 @@ Объявление \"интерфейсов со статическими абстрактными методами\" является расширенной функцией. См. руководство на https://aka.ms/fsharp-iwsams. Это предупреждение можно отключить с помощью используя "#nowarn \"3535\"" or "--nowarn:3535". + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + Тип '{0}' имеет слишком много методов. Найдено: '{1}', максимально: '{2}' + + Interface member '{0}' does not have a most specific implementation. Элемент интерфейса "{0}" не имеет наиболее конкретной реализации. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Круглые скобки можно убрать. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - Определения статических значений для F#7 и ниже можно использовать только в типах с первичным конструктором ("type X(args) = ..."). Чтобы включить их во всех других типах, используйте версию языка "preview". + Определения статических значений "let","do" и "member val" для F#7 и ниже можно использовать только в типах с первичным конструктором ("type X(args) = ..."). Чтобы включить их во всех других типах, используйте версию языка "8" или выше. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - Не удается вызвать метод расширения byref "{0}". В качестве первого параметра необходимо указать изменяемое значение или значение типа byref, доступное не только для чтения. + Не удается вызвать метод расширения byref "{0}". В качестве параметра "this" необходимо указать изменяемое значение или значение типа byref, доступное не только для чтения. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - Ключ диспетчера пакетов "{0}" не зарегистрирован в {1}. Сейчас зарегистрировано: {2}. Дополнительные сведения о расширениях см. на странице https://aka.ms/dotnetdepmanager + Ключ диспетчера пакетов "{0}" не зарегистрирован в {1}. Сейчас зарегистрировано: {2}. Чтобы указать дополнительные пути, передайте в командную строку "--compilertool:<extensionsfolder>". Дополнительные сведения о расширениях см. на странице https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.tr.xlf b/src/Compiler/xlf/FSComp.txt.tr.xlf index 84434185a19..9c753835425 100644 --- a/src/Compiler/xlf/FSComp.txt.tr.xlf +++ b/src/Compiler/xlf/FSComp.txt.tr.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + Dizini oluşturulmuş bir özelliğin alıcısı ve ayarlayıcısı aynı türde olmalıdır. '{0}' özelliği '{1}' türünde alıcıya ancak '{2}' türünde ayarlayıcıya sahip. @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + Nesne ifadeleri, statik soyut üyeler içeren arabirimleri uygulayamaz veya statik üyeleri bildiremez. The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + TailCall özniteliği yalnızca özyinelemeli işlevlere uygulanmalıdır. @@ -147,6 +147,11 @@ Kullanılabilir aşırı yüklemeler:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + '{0}', gerekli (gerçek veya yerleşik) '{2}' üyesine sahip olmadığından '{1}' türünü desteklemiyor + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. Genel yapı, genel bir tür parametresinin yapı veya başvuru türü olarak bilinmesini gerektirir. Tür ek açıklaması eklemeyi düşünün. @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + 'TailCall' özniteliği özyinelemeli olmayan işlevlerde kullanılıyorsa uyarılar oluşturur. @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + Basit özellik yerine genişletme yöntemini tercih edin @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + Aynı ada ve türe sahip oldukları sürece temel alınan alanları [<Struct>] ayırt edici birleşim biçiminde paylaşın @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + Birleşim durumu test özellikleri @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + Dizini oluşturulmuş özelliklerin alıcısı ve ayarlayıcısı aynı türde olmalıdır @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + Kayıt alanı bekleniyor @@ -987,9 +992,14 @@ Bu üye erişimi belirsiz. Lütfen nesne oluşturma etrafında parantez kullanın, örneğin '(yeni SomeType (args)).MemberName’ + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + Statik yapının bildirimi eksik. Bildirim için 'static let','static do','static member' veya 'static val' kullanın. @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + Toplu lambda söz dizimi yalnızca örtülü '_' bağımsız değişkeninde yöntem, özellik, alan veya dizin oluşturucu gibi atomik ifadeler için destekleniyor. Örnek: 'let f = _.Length'. @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + Bu, bir birleşim durumunu gizleyen bir işlev tanımıdır. Bunu istiyorsanız, bu uyarıyı yoksayın veya durdurun. Bunun bir birleşim durumu ayrıştırması olmasını istiyorsanız, parantezler ekleyin. @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + Bu geçersiz kılmaya karşılık gelen hiçbir statik soyut üye bulunamadı No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + Bu geçersiz kılmaya karşılık gelen hiçbir statik soyut özellik bulunamadı @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + Çok durumlu bir birleşim türü bir yapıysa, aynı ada sahip tüm alanların aynı türde olması gerekir. Bu kural adlandırılmamış alanlar olması durumunda oluşturulan ‘Öğe’ adı için de geçerlidir. @@ -1497,6 +1507,11 @@ \"interfaces with static abstract methods\" bildirimi gelişmiş bir özelliktir. Rehber için bkz. https://aka.ms/fsharp-iwsams. '#nowarn \"3535\"' veya '--nowarn:3535'. kullanarak bu uyarıyı devre dışı bırakabilirsiniz. + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + '{0}' türü çok fazla yöntem içeriyor. Bulunan: '{1}', üst sınır: '{2}' + + Interface member '{0}' does not have a most specific implementation. '{0}' arabirim üyesinin en belirgin uygulaması yok. @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + Parantezler kaldırılamaz. @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - F#7 ve altı için, statik değer tanımları yalnızca birincil oluşturucu ('type X(args) = ...') içeren türlerde kullanılabilir. Bunları diğer tüm türlerde etkinleştirmek için 'önizleme' dil sürümünü kullanın. + F#7 ve altı için, 'let', 'do' ve 'member val' statik değer tanımları yalnızca birincil oluşturucu ('type X(args) = ...') içeren türlerde kullanılabilir. Bunları diğer tüm türlerde etkinleştirmek için dil sürümü '8' ve üstünü kullanın. @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - '{0}' byref genişletme metodu çağrılamıyor. İlk parametre, değerin değişebilir olmasını veya salt okunur olmayan bir byref türünde olmasını gerektiriyor. + '{0}' byref genişletme metodu çağrılamıyor. ‘this’ parametresi, değerin değişebilir olmasını veya salt okunur olmayan bir byref türünde olmasını gerektiriyor. @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - Paket yöneticisi '{0}' anahtar anahtarı bu makinede {1}. Şu anda kayıtlı: {2}. Uzantılar hakkında daha fazla bilgi edinmek için şu adresi ziyaret edin: https://aka.ms/dotnetdepmanager + Paket yöneticisi anahtarı '{0}' {1} altında kayıtlı değil. Şu anda kayıtlı: {2}. Komut satırına '--compilertool:<extensionsfolder>' geçirerek ek yollar sağlayabilirsiniz. Uzantılar hakkında daha fazla bilgi edinmek için şu adresi ziyaret edin: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf b/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf index 979456fe365..ee6832b2fa4 100644 --- a/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf +++ b/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + 索引属性的 Getter 和 Setter 的类型必须相同。属性“{0}”的 Getter 的类型为“{1}”,而 Setter 的类型为“{2}”。 @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + 对象表达式无法实现具有静态抽象成员或声明静态成员的接口。 The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + TailCall 属性应仅应用于递归函数。 @@ -147,6 +147,11 @@ 可用重载:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + “{0}”不支持类型“{1}”,因为后者缺少所需的(实际或内置)成员“{2}” + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. 泛型构造要求泛型类型参数被视为结构或引用类型。请考虑添加类型注释。 @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + 如果在非递归函数上使用“TailCall”属性,则引发警告。 @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + 首选扩展方法而不是纯属性 @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + 只要它们具有相同的名称和类型,即可在 [<Struct>] 中共享基础字段 @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + 联合用例测试属性 @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + 索引属性 getter 和 setter 必须具有相同的类型 @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + 应为记录字段 @@ -987,9 +992,14 @@ 此成员访问权限不明确。请在对象创建周围使用括号,例如 “(new SomeType(args)).MemberName” + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + 静态构造的声明不完整。使用“static let”、“static do”、“static member”或“static val”进行声明。 @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + 仅原子表达式支持速记 lambda 语法,例如隐含的“_”参数上的方法、属性、字段或索引器。例如:“let f = _.Length”。 @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + 这是一个隐藏联合事例的函数定义。如果这是你想要的,请忽略或取消此警告。如果希望它是联合大小写析构,请添加括号。 @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + 找不到与此替代对应的静态抽象成员 No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + 未找到与此重写对应的静态抽象属性 @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + 如果多重联合类型是结构,则具有相同名称的所有字段必须具有相同的类型。对于未命名字段,此规则也适用于生成的“Item”名称。 @@ -1497,6 +1507,11 @@ 声明“使用静态抽象方法的接口”是一项高级功能。有关指南,请参阅 https://aka.ms/fsharp-iwsams。可以使用 "#nowarn \"3535\"' 或 '--nowarn:3535' 禁用此警告。 + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + 类型“{0}”的方法太多。1️⃣找到:“{1}”,最大值:“{2}” + + Interface member '{0}' does not have a most specific implementation. 接口成员“{0}”没有最具体的实现。 @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + 可以移除括号。 @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - 对于 F#7 及更低版本,静态值定义只能用于具有主构造函数的类型 ("type X(args) = ...")。若要在所有其他类型中启用它们,请使用“预览版”语言版本。 + 对于 F#7 及更低版本,静态“let”、“do”和“member val”定义只能用于具有主构造函数的类型 ("type X(args) = ...")。若要在所有其他类型中启用它们,请使用语言版本“8”或更高版本。 @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - 无法调用 byref 扩展方法 "{0}"。第一个参数要求该值是可变的或非只读的 byref 类型。 + 无法调用 byref 扩展方法 "{0}"。“'this”参数要求该值是可变的或非只读的 byref 类型。 @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - {0} 中未注册包管理器密钥“{1}”。当前已注册: {2}。若要详细了解扩展,请访问: https://aka.ms/dotnetdepmanager + 未在 {1} 中注册包管理器密钥“{0}”。当前已注册: {2}。可以通过将“--compilertool:<extensionsfolder>”传递到命令行来提供额外的路径。若要了解有关扩展的详细信息,请访问: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf b/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf index 8d4fef2991f..125697b5871 100644 --- a/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf +++ b/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf @@ -84,7 +84,7 @@ An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - An indexed property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. + 索引屬性的 getter 和 setter 必須具有相同類型。屬性 '{0}' 的 getter 類型為 '{1}',但 setter 類型為 '{2}'。 @@ -124,12 +124,12 @@ Object expressions cannot implement interfaces with static abstract members or declare static members. - Object expressions cannot implement interfaces with static abstract members or declare static members. + 物件運算式無法實作具有靜態抽象成員的介面或宣告靜態成員。 The TailCall attribute should only be applied to recursive functions. - The TailCall attribute should only be applied to recursive functions. + TailCall 屬性只應套用至遞迴函數。 @@ -147,6 +147,11 @@ 可用的多載:\n{0} + + '{0}' does not support the type '{1}', because the latter lacks the required (real or built-in) member '{2}' + '{0}' 不支援類型 '{1}',因為後者缺少必要的 (實際或內建) 成員 '{2}' + + A generic construct requires that a generic type parameter be known as a struct or reference type. Consider adding a type annotation. 泛型建構要求泛型型別參數必須指定為結構或參考型別。請考慮新增型別註解。 @@ -274,7 +279,7 @@ Raises warnings if the 'TailCall' attribute is used on non-recursive functions. - Raises warnings if the 'TailCall' attribute is used on non-recursive functions. + 如果 'TailCall' 屬性用於非遞迴函數,則引發警告。 @@ -444,7 +449,7 @@ prefer extension method over plain property - prefer extension method over plain property + 偏好延伸模組方法勝於純文字屬性 @@ -489,7 +494,7 @@ Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type - Share underlying fields in a [<Struct>] discriminated union as long as they have same name and type + 只要 [<Struct>] 具有相同名稱和類型,就以強制聯集共用基礎欄位 @@ -529,7 +534,7 @@ Union case test properties - Union case test properties + 聯集案例測試屬性 @@ -544,7 +549,7 @@ Indexed properties getter and setter must have the same type - Indexed properties getter and setter must have the same type + 索引屬性 getter 和 setter 必須具有相同的類型 @@ -944,7 +949,7 @@ Expecting record field - Expecting record field + 必須是記錄欄位 @@ -987,9 +992,14 @@ 此成員存取不明確。請在物件建立前後加上括弧,例如「(new SomeType(args)).MemberName」 + + Only simple patterns are allowed in primary constructors + Only simple patterns are allowed in primary constructors + + Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. - Incomplete declaration of a static construct. Use 'static let','static do','static member' or 'static val' for declaration. + 不完整的靜態建構宣告。使用 'static let'、'static do'、'static member' 或 'static val' 進行宣告。 @@ -1189,7 +1199,7 @@ Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. - Shorthand lambda syntax is only supported for atomic expressions, such as method, property, field or indexer on the implied '_' argument. For example: 'let f = _.Length'. + 只有不可部分完成運算式才支援速記 Lambda 語法,例如隱含 '_' 引數上的方法、屬性、欄位或索引子。例如: 'let f = _.Length'。 @@ -1229,7 +1239,7 @@ This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. - This is a function definition that shadows a union case. If this is what you want, ignore or suppress this warning. If you want it to be a union case deconstruction, add parentheses. + 這是陰影等位案例的函式定義。如果這是您要的,請忽略或隱藏此警告。如果您希望它是等位案例解構,請新增括弧。 @@ -1329,12 +1339,12 @@ No static abstract member was found that corresponds to this override - No static abstract member was found that corresponds to this override + 找不到對應到這個覆寫的靜態抽象成員 No static abstract property was found that corresponds to this override - No static abstract property was found that corresponds to this override + 找不到對應到這個覆寫的靜態抽象屬性 @@ -1434,7 +1444,7 @@ If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. - If a multicase union type is a struct, then all fields with the same name must be of the same type. This rule applies also to the generated 'Item' name in case of unnamed fields. + 如果多寫聯集類型是結構,則所有具有相同名稱的欄位都必須是相同的類型。此規則也適用於未命名欄位時產生的 'Item' 名稱。 @@ -1497,6 +1507,11 @@ 使用「靜態抽象方法宣告介面」是進階的功能。請參閱 https://aka.ms/fsharp-iwsams 以尋求指引。您可以使用 '#nowarn \"3535\"' 或 '--nowarn:3535' 來停用此警告。 + + The type '{0}' has too many methods. Found: '{1}', maximum: '{2}' + 類型 '{0}' 有太多方法。找到: '{1}',最大值: '{2}' + + Interface member '{0}' does not have a most specific implementation. 介面成員 '{0}' 沒有最具體的實作。 @@ -1659,7 +1674,7 @@ Parentheses can be removed. - Parentheses can be removed. + 可以移除括號。 @@ -5139,7 +5154,7 @@ For F#7 and lower, static 'let','do' and 'member val' definitions may only be used in types with a primary constructor ('type X(args) = ...'). To enable them in all other types, use language version '8' or higher. - 對於 F#7 和更低版本,靜態值定義只能用於具有主要建構函式的類型 ('type X(args) = ...')。若要在所有其他類型中啟用,請使用語言版本 'preview'。 + 對於 F#7 和更低版本,靜態 'let'、'do' 和 'member val' 定義只能用於具有主要建構函式的類型 ('type X(args) = ...')。若要在所有其他類型中啟用,請使用語言版本 '8' 或更新版本。 @@ -8544,7 +8559,7 @@ Cannot call the byref extension method '{0}. 'this' parameter requires the value to be mutable or a non-readonly byref type. - 無法呼叫 byref 擴充方法 '{0}。第一個參數需要值可變動,或為非唯讀 byref 類型。 + 無法呼叫 byref 擴充方法 '{0}。'this' 參數需要值可變動,或為非唯讀 byref 類型。 @@ -8634,7 +8649,7 @@ Package manager key '{0}' was not registered in {1}. Currently registered: {2}. You can provide extra path(s) by passing '--compilertool:<extensionsfolder>' to the command line. To learn more about extensions, visit: https://aka.ms/dotnetdepmanager - 未在 {1} 中註冊套件管理員金鑰 '{0}'。目前已註冊: {2}。若要深入了解延伸模組,請瀏覽: https://aka.ms/dotnetdepmanager + 未在 {1} 中登錄封裝管理員金鑰 '{0}'。目前註冊: {2}。您可以將 '--compilertool:<extensionsfolder>' 傳遞至命令列,以提供額外路徑。如需深入了解延伸模組,請瀏覽: https://aka.ms/dotnetdepmanager diff --git a/src/Compiler/xlf/FSStrings.cs.xlf b/src/Compiler/xlf/FSStrings.cs.xlf index b2a4e04e6c4..16a05e5a27a 100644 --- a/src/Compiler/xlf/FSStrings.cs.xlf +++ b/src/Compiler/xlf/FSStrings.cs.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + Očekává se nestatický člen. Static member is expected. - Static member is expected. + Očekává se statický člen. @@ -227,6 +227,16 @@ Pole {0} a {1} jsou odlišného typu. + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Omezení hodnoty: Hodnota {0} má odvozený obecný typ\n {1}\nNicméně hodnoty nemohou mít proměnné obecného typu jako '_a v "let x: '_a". Můžete provést jednu z následujících akcí:\n- Definujte jej jako jednoduchý datový termín, například celočíselný literál, řetězcový literál nebo případ sjednocení, například let x = 1\n- Přidejte explicitní typovou anotaci, například let x : int\n- Použijte hodnotu jako negenerický typ v pozdějším kódu pro typovou inferenci, jako například do x\nebo pokud přesto chcete typové výsledky, můžete místo toho {2} definovat jako funkci, a to buď:\n- Přidejte jednotkový parametr, jako například let x()\n- Napište explicitní typové parametry, jako například let x<'a>.\nTato chyba je způsobena tím, že vazba let bez parametrů definuje hodnotu, nikoli funkci. Hodnoty nemůžou být generické, protože se předpokládá, že výsledkem čtení hodnoty bude všude totéž, ale generické typové parametry mohou tento předpoklad zrušit tím, že umožní získat výsledky závislé na typu. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Omezení hodnoty: Hodnota {0} má odvozený obecný typ funkce.\n {1}\n Hodnoty ale nemůžou mít proměnné obecného typu, například _a v let f: _a. Místo toho byste měli {2} definovat jako funkci některým z následujících postupů:\n- Přidejte explicitní parametr, který se použije místo částečné aplikace let f param\n- Přidejte jednotkový parametr jako let f()\n- Napište explicitní typové parametry jako let f<'a>\nebo pokud nemáte v úmyslu, aby byl generický:\n- Přidejte explicitní typovou anotaci jako let f : obj -> obj\n- Použijte argumenty negenerických typů na hodnotu funkce v pozdějším kódu pro typovou inferenci jako do f().\nTato chyba je způsobena tím, že vazba let bez parametrů definuje hodnotu, nikoli funkci. Hodnoty nemůžou být generické, protože se předpokládá, že výsledkem čtení hodnoty bude všude totéž, ale generické typové parametry mohou tento předpoklad zrušit tím, že umožní získat výsledky závislé na typu. + + '{0}' is bound twice in this pattern {0} má v tomto vzoru dvě vazby. @@ -1557,31 +1567,6 @@ Následující pole vyžadují hodnoty: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Omezení hodnoty. Hodnota {0} je obecného typu\n {1}. \nBuď změňte argumenty pro {2} na explicitní, nebo (pokud hodnota nemá být obecná) přidejte poznámku typu. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Omezení hodnoty. Hodnota {0} je obecného typu\n {1}. \nZměňte {2} na funkci s explicitními argumenty nebo (pokud hodnota nemá být obecná) přidejte poznámku typu. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Omezení hodnoty. Tento člen se odvodil jako člen obecného typu\n {0}. \nKonstruktory a metody getter nebo setter vlastnosti nemůžou být obecnější než nadřazený typ. Přidejte poznámku typu, abyste přesně určili, které typy se mají zahrnout. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Omezení hodnoty. Hodnota {0} se odvodila jako hodnota obecného typu\n {1}. \nBuď změňte argumenty pro {2} na explicitní, nebo (pokud hodnota nemá být obecná) přidejte poznámku typu. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Omezení hodnoty. Hodnota {0} se odvodila jako hodnota obecného typu\n {1}. \nDefinujte {2} jako jednoduchý datový výraz, změňte ji na funkci s explicitními argumenty nebo (pokud hodnota nemá být obecná) přidejte poznámku typu. - - syntax error chyba syntaxe diff --git a/src/Compiler/xlf/FSStrings.de.xlf b/src/Compiler/xlf/FSStrings.de.xlf index 3178a6def03..af3480d9391 100644 --- a/src/Compiler/xlf/FSStrings.de.xlf +++ b/src/Compiler/xlf/FSStrings.de.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + Ein nicht statischer Member wird erwartet. Static member is expected. - Static member is expected. + Ein statischer Member wird erwartet. @@ -227,6 +227,16 @@ Die Felder "{0}" und "{1}" stammen aus unterschiedlichen Typen. + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Werteinschränkung: Der Wert "{0}" weist einen abgeleiteten generischen Typ auf.\n {1}\nWerte dürfen jedoch keine generischen Typvariablen wie "_a" in "let x: "_a" aufweisen. Sie können eine der folgenden Aktionen ausführen:\n– Definieren Sie ihn als einfachen Datenausdruck wie ein ganzzahliges Literal, ein Zeichenfolgenliteral oder einen Union-Fall wie "let x = 1"\n– Fügen Sie eine explizite Typanmerkung wie "let x : int" hinzu.\n– Verwenden Sie den Wert als nicht generischen Typ im späteren Code für Typrückschlüsse wie "do x"\noder wenn Sie weiterhin typabhängige Ergebnisse wünschen, können Sie "{2}" stattdessen als Funktion definieren, indem Sie einen der folgenden Schritte ausführen:\n– Fügen Sie einen Einheitenparameter wie "let x()" hinzu.\n– Schreiben Sie explizite Typparameter wie "let x<'a>".\nDieser Fehler liegt daran, dass eine let-Bindung ohne Parameter einen Wert definiert, keine Funktion. Werte können nicht generisch sein, da davon ausgegangen wird, dass das Lesen eines Werts überall zum selben Ergebnis führt, generische Typparameter diese Annahme jedoch möglicherweise ungültig machen, indem typabhängige Ergebnisse aktiviert werden. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Werteinschränkung: Der Wert "{0}" weist einen abgeleiteten generischen Funktionstyp auf.\n {1}\nWerte dürfen jedoch keine generischen Typvariablen wie "_a" in "let f: "_a" aufweisen. Sie sollten stattdessen "{2}" als Funktion definieren, indem Sie einen der folgenden Schritte ausführen:\n– Fügen Sie einen expliziten Parameter hinzu, der angewendet wird, anstatt eine partielle Anwendung "let f param" zu verwenden.\n– Fügen Sie einen Einheitenparameter wie "let f()" hinzu.\n– Schreiben Sie explizite Typparameter wie "let f<'a>",\n oder wenn Sie nicht beabsichtigen, dass er generisch ist, entweder:\n– Fügen Sie eine explizite Typanmerkung wie "let f : obj -> obj" hinzu.\n– Wenden Sie Argumente nicht generischer Typen auf den Funktionswert im späteren Code für Typrückschlüsse wie "do f()" an.\nDieser Fehler liegt daran, dass eine Let-Bindung ohne Parameter einen Wert definiert, keine Funktion. Werte können nicht generisch sein, da davon ausgegangen wird, dass das Lesen eines Werts überall zum selben Ergebnis führt, generische Typparameter diese Annahme jedoch möglicherweise ungültig machen, indem typabhängige Ergebnisse aktiviert werden. + + '{0}' is bound twice in this pattern {0} ist in diesem Muster doppelt gebunden. @@ -1557,31 +1567,6 @@ Für die folgenden Felder sind Werte erforderlich: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Werteinschränkung. Der Wert "{0}" hat den generischen Typ\n {1} \nLegen Sie die Argumente für "{2}" entweder als explizit fest, oder fügen Sie eine Typanmerkung hinzu, wenn der Typ nicht generisch sein soll. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Werteinschränkung. Der Wert "{0}" hat den generischen Typ\n {1} \nDefinieren Sie "{2}" entweder als Funktion mit expliziten Argumenten, oder fügen Sie eine Typanmerkung hinzu, wenn der Typ nicht generisch sein soll. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Werteinschränkung. Dieser Member wurde per Rückschluss abgeleitet als generischer Typ\n {0} \nKonstruktoren und Eigenschaftengetter/-setter dürfen nicht generischer sein als der einschließende Typ. Fügen Sie eine Typanmerkung hinzu, um die genauen Typen anzugeben. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Werteinschränkung. Der Wert "{0}" wurde per Rückschluss abgeleitet als generischer Typ\n {1} \nLegen Sie die Argumente für "{2}" entweder als explizit fest, oder fügen Sie eine Typanmerkung hinzu, wenn der Typ nicht generisch sein soll. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Werteinschränkung. Der Wert "{0}" wurde per Rückschluss abgeleitet als generischer Typ\n {1} \nDefinieren Sie "{2}" entweder als einfachen Ausdruck oder als Funktion mit expliziten Argumenten, oder fügen Sie eine Typanmerkung hinzu, wenn der Typ nicht generisch sein soll. - - syntax error Syntaxfehler diff --git a/src/Compiler/xlf/FSStrings.es.xlf b/src/Compiler/xlf/FSStrings.es.xlf index 7b2e668ea61..15af13cdb29 100644 --- a/src/Compiler/xlf/FSStrings.es.xlf +++ b/src/Compiler/xlf/FSStrings.es.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + Se espera un miembro no estático. Static member is expected. - Static member is expected. + Se espera un miembro estático. @@ -227,6 +227,16 @@ Los campos '{0}' y '{1}' son de tipos diferentes. + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restricción de valor: el valor '{0}' tiene un tipo genérico inferido\n {1}\nSin embargo, los valores no pueden tener variables de tipo genérico como '_a en "let x: '_a". Puede realizar una de las siguientes acciones:\n- Definirlo como un término de datos simple como un literal entero, un literal de cadena o un caso de unión como "let x = 1"\n- Agregar una anotación de tipo explícito como "let x : int"\n- Usar el valor como un tipo no genérico en código posterior para la inferencia de tipos como "do x"\no si aún desea resultados dependientes de tipos, puede definir '{2}' como una función en su lugar haciendo lo siguiente:\n- Agregar un parámetro de unidad como "let x()"\n- Escribir parámetros de tipo explícito como "let x<'a>".\nEste error se debe a que un enlace let sin parámetros define un valor, no una función. Los valores no pueden ser genéricos porque se supone que la lectura de un valor da como resultado lo mismo en todas partes, pero los parámetros de tipo genérico pueden invalidar esta suposición habilitando resultados dependientes de tipos. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restricción de valor: el valor '{0}' tiene un tipo de función genérica inferida\n {1}\nSin embargo, los valores no pueden tener variables de tipo genérico como '_a en "let f: '_a". Para definir '{2}' como una función, realice una de las siguientes acciones:\n- Agregue un parámetro explícito que se aplique en lugar de usar una aplicación parcial "let f param"\n- Agregue un parámetro de unidad como "let f()"\n- Escriba parámetros de tipo explícito como "let f<'a>"\no si no pretende que sea genérico, puede:\n- Agregar una anotación de tipo explícito como "let f : obj -> obj"\n- Aplicar argumentos de tipos no genéricos al valor de función en código posterior para la inferencia de tipos como "do f()".\nEste error se debe a que un enlace let sin parámetros define un valor, no una función. Los valores no pueden ser genéricos porque se supone que la lectura de un valor da como resultado lo mismo en todas partes, pero los parámetros de tipo genérico pueden invalidar esta suposición habilitando resultados dependientes de tipos. + + '{0}' is bound twice in this pattern '{0}' está enlazado dos veces en este patrón @@ -1557,31 +1567,6 @@ Los campos siguientes requieren valores: {0}. - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Restricción de valor. El valor '{0}' tiene el tipo genérico\n {1} \nConvierta los argumentos de '{2}' en explícitos o, si su intención no es que sea genérico, agregue una anotación de tipo. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Restricción de valor. El valor '{0}' tiene el tipo genérico\n {1} \nConvierta '{2}' en una función con argumentos explícitos o, si su intención no es que sea genérico, agregue una anotación de tipo. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Restricción de valor. Se ha inferido que este miembro tiene el tipo genérico\n {0} \nLos constructores y los captadores y establecedores de propiedades no pueden ser más genéricos que el tipo envolvente. Agregue una anotación de tipo para indicar los tipos exactos implicados. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Restricción de valor. Se ha inferido que el valor '{0}' tiene el tipo genérico\n {1} \nConvierta los argumentos de '{2}' en explícitos o, si su intención no es que sea genérico, agregue una anotación de tipo. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Restricción de valor. Se ha inferido que el valor '{0}' tiene el tipo genérico\n {1} \nDefina '{2}' como un término de datos simple, conviértalo en una función con argumentos explícitos o, si su intención no es que sea genérico, agregue una anotación de tipo. - - syntax error error de sintaxis diff --git a/src/Compiler/xlf/FSStrings.fr.xlf b/src/Compiler/xlf/FSStrings.fr.xlf index 35581a00f2d..4aaed1d6687 100644 --- a/src/Compiler/xlf/FSStrings.fr.xlf +++ b/src/Compiler/xlf/FSStrings.fr.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + Un membre non statique est attendu. Static member is expected. - Static member is expected. + Un membre statique est attendu. @@ -227,6 +227,16 @@ Les champs '{0}' et '{1}' sont de types différents + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restriction de valeur : La valeur '{0}' a un type générique déduit\n {1}\nCependant, les valeurs ne peuvent pas avoir de variables de type générique comme '_a dans "let x: '_a". Vous pouvez effectuer l'une des opérations suivantes :\n- Le définir comme un terme de données simple comme un littéral entier, un littéral de chaîne ou un cas d'union comme "let x = 1"\n- Ajouter une annotation de type explicite comme "let x : int"\n- Utilisez la valeur comme type non générique dans le code ultérieur pour l'inférence de type comme "do x"\ni si vous souhaitez toujours des résultats dépendants du type, vous pouvez définir '{2}' comme fonction à la place en faisant soit :\n- Ajoutez un paramètre d'unité comme "let x()"\n- Écrivez des paramètres de type explicites comme "let x<'a>".\nCette erreur est due au fait qu'une liaison let sans paramètres définit une valeur, pas une fonction. Les valeurs ne peuvent pas être génériques car la lecture d'une valeur est supposée donner le même résultat partout, mais les paramètres de type génériques peuvent invalider cette hypothèse en permettant des résultats dépendants du type. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restriction de valeur : La valeur '{0}' a un type de fonction générique déduit\n {1}\nCependant, les valeurs ne peuvent pas avoir de variables de type générique comme '_a dans "let f: '_a". Vous devez plutôt définir '{2}' comme fonction en effectuant l'une des opérations suivantes :\n- Ajouter un paramètre explicite qui est appliqué au lieu d'utiliser une application partielle "let f param"\n- Ajouter un paramètre d'unité comme "let f() "\n- Écrivez des paramètres de type explicites comme "let f<'a>"\ni si vous ne souhaitez pas qu'ils soient génériques, soit :\n- Ajoutez une annotation de type explicite comme "let f : obj -> obj" \n- Appliquer des arguments de types non génériques à la valeur de la fonction dans le code ultérieur pour l'inférence de type comme "do f()".\nCette erreur est due au fait qu'une liaison let sans paramètres définit une valeur, pas une fonction. Les valeurs ne peuvent pas être génériques car la lecture d'une valeur est supposée donner le même résultat partout, mais les paramètres de type génériques peuvent invalider cette hypothèse en permettant des résultats dépendants du type. + + '{0}' is bound twice in this pattern '{0}' est lié à deux reprises dans ce modèle @@ -1557,31 +1567,6 @@ Les champs suivants requièrent des valeurs : {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Restriction de valeur. La valeur '{0}' a le type générique\n {1} \nRendez les arguments de '{2}' explicites ou, si votre but n'est pas d'utiliser un type générique, ajoutez une annotation de type. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Restriction de valeur. La valeur '{0}' a le type générique\n {1} \nChangez '{2}' en fonction avec des arguments explicites ou, si votre but n'est pas d'utiliser un type générique, ajoutez une annotation de type. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Restriction de valeur. Il a été déduit que ce membre avait un type générique\n {0} \nLes constructeurs, ainsi que les méthodes getter/setter d'une propriété ne peuvent pas être plus génériques que le type englobant. Ajoutez une annotation de type pour indiquer les types exacts impliqués. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Restriction de valeur. Il a été déduit que la valeur '{0}' avait le type générique\n {1} \nRendez les arguments de '{2}' explicites ou, si votre but n'est pas d'utiliser un type générique, ajoutez une annotation de type. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Restriction de valeur. Il a été déduit que la valeur '{0}' avait le type générique\n {1} \nDéfinissez '{2}' en tant que terme de données simple, faites-en une fonction avec des arguments explicites ou, si votre but n'est pas d'utiliser un type générique, ajoutez une annotation de type. - - syntax error erreur de syntaxe diff --git a/src/Compiler/xlf/FSStrings.it.xlf b/src/Compiler/xlf/FSStrings.it.xlf index 5fc7bbeeec9..946b68dfe57 100644 --- a/src/Compiler/xlf/FSStrings.it.xlf +++ b/src/Compiler/xlf/FSStrings.it.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + È previsto un membro non statico. Static member is expected. - Static member is expected. + È previsto un membro statico. @@ -227,6 +227,16 @@ I campi '{0}' e '{1}' sono di tipi diversi + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restrizione del valore: il valore '{0}' ha un tipo generico dedotta\n {1}\nTuttavia, i valori non possono avere variabili di tipo generico come '_a in "let x: '_a". È possibile eseguire una delle operazioni seguenti:\n- Definirlo come termine di dati semplice come un valore letterale integer, un valore letterale stringa o un case di unione come "let x = 1"\n- Aggiungere un'annotazione di tipo esplicito come "let x : int"\n- Usare il valore come tipo non generico nel codice successivo per l'inferenza del tipo come "do x"\noppure se si vogliono ancora risultati dipendenti dal tipo, è possibile definire '{2}' come funzione eseguendo una delle operazioni seguenti:\n- Aggiungere un parametro di unità come "let x()"\n- Scrivere parametri di tipo esplicito come "let x<'a>".\nQuesto errore è dovuto al fatto che un'associazione let senza parametri definisce un valore, non una funzione. I valori non possono essere generici, perché si presuppone che la lettura di un valore restituisca lo stesso risultato ovunque, ma i parametri di tipo generico possono invalidare questa ipotesi, consentendo risultati dipendenti dal tipo. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restrizione del valore: il valore '{0}' ha un tipo di funzione generica dedotta\n {1}\nTuttavia, i valori non possono avere variabili di tipo generico come '_a in "let f: '_a". È consigliabile definire '{2}' come funzione eseguendo una delle operazioni seguenti:\n- aggiungere un parametro esplicito applicato invece di usare un'applicazione parziale "let f param"\n- Aggiungere un parametro di unità come "let f()"\n- Scrivere parametri di tipo esplicito come "let f<'a>"\no se non si vuole che sia generico, o:\n- Aggiungere un'annotazione di tipo esplicito come "let f : obj -> obj"\n- Applicare argomenti di tipi non generici al valore della funzione nel codice successivo per l'inferenza del tipo come "do f()".\nQuesto errore è dovuto al fatto che un'associazione let senza parametri definisce un valore, non una funzione. I valori non possono essere generici, perché si presuppone che la lettura di un valore restituisca lo stesso risultato ovunque, ma i parametri di tipo generico possono invalidare questa ipotesi, consentendo risultati dipendenti dal tipo. + + '{0}' is bound twice in this pattern '{0}' è associato due volte in questo criterio @@ -1557,31 +1567,6 @@ Immissione valori obbligatoria per i campi seguenti: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Limitazione valore. Il valore '{0}' ha il tipo generico\n {1} \nRendere gli argomenti di '{2}' espliciti oppure, se non si intende renderlo generico, aggiungere un'annotazione di tipo. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Limitazione valore. Il valore '{0}' ha il tipo generico\n {1} \nRendere '{2}' una funzione con argomenti espliciti oppure, se non si intende renderlo generico, aggiungere un'annotazione di tipo. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Restrizione relativa ai valori. È stato dedotto che il membro ha il tipo generico\n {0} \nI getter/setter di proprietà e i costruttori non possono essere più generici del tipo di inclusione. Aggiungere un'annotazione di tipo per indicare i tipi esatti previsti. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Limitazione valore. È stato dedotto che il valore '{0}' ha il tipo generico\n {1} \nRendere gli argomenti di '{2}' espliciti, oppure se non si intende renderlo generico, aggiungere un'annotazione di tipo. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Limitazione valore. È stato dedotto che il valore '{0}' ha il tipo generico\n {1} \nDefinire '{2}' come termine di dati semplice, renderlo una funzione con argomenti espliciti oppure, se non si intende renderlo generico, aggiungere un'annotazione di tipo. - - syntax error errore di sintassi diff --git a/src/Compiler/xlf/FSStrings.ja.xlf b/src/Compiler/xlf/FSStrings.ja.xlf index 103a4edeca0..f5f2df9a156 100644 --- a/src/Compiler/xlf/FSStrings.ja.xlf +++ b/src/Compiler/xlf/FSStrings.ja.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + 静的でないメンバーが必要です。 Static member is expected. - Static member is expected. + 静的メンバーが必要です。 @@ -227,6 +227,16 @@ フィールド '{0}' と '{1}' は異なる型です + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 値の制限: 値 '{0}' は推論されたジェネリック関数 \n {1}\n を持ちますが、 "let x: '_a" で '_a のようなジェネリック型変数を持つことはできません。次のいずれかを実行できます。①整数リテラル、文字列リテラル、または "let x = 1"\n- のような共用体ケースを簡易データ項目として定義する。②"let x : int"\n- のような明示的な型の注釈を追加する。③型依存型の結果が必要な場合は、"do x"\nor などの型の推定のためにジェネリック型以外として後のコードで使用して、:\n- のいずれかを実行する代わりに関数として '{2}' を定義できます。④"let x()"\n- のような単位パラメーターを追加する。⑤"let x<'a>".\n のような明示的な型パラメーターを記述する。このエラーは、\nパラメーターのない let バインディングが関数ではなく値を定義するため発生します。値を読み取るとどこでも同じ結果になると想定されるため、値をジェネリックにすることはできませんが、ジェネリック型パラメーターは型依存の結果を有効にすることで、この想定が無効になる可能性があります。 + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 値の制限: 値 '{0}' は推論されたジェネリック関数型 \n {1}\n を持ちますが、"let f: '_a" で '_a のようなジェネリック型変数を持つことはできません。次のいずれかを実行する代わりに、'{2}' を関数として定義する必要があります。①"let f param"\n- のような部分的な適用ではなく、\n適用される明示的なパラメーターを追加する。②"let f()"\n- のような単位パラメーターを追加する。③ジェネリック型であることを意図しない場合は、"let f<'a>"\nor のような明示的な型パラメーターを記述する。④"let f : obj -> obj"\n- のような明示的な型の注釈を追加する。⑤"do f()".\n のような型の推定のために、ジェネリック型でない引数を後のコードで関数値に適用する。このエラーは、\nパラメーターのない let バインディングが関数ではなく値を定義するため発生します。値を読み取るとどこでも同じ結果になると想定されるため、値をジェネリックにすることはできませんが、ジェネリック型パラメーターは型依存の結果を有効にすることで、この想定が無効になる可能性があります。 + + '{0}' is bound twice in this pattern このパターンで '{0}' が 2 回バインドされています @@ -1557,31 +1567,6 @@ 次のフィールドには値が必要です: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 値の制限。値 '{0}' は次のジェネリック型です。\n {1} \n明示的に引数を '{2}' にするか、ジェネリックにする意図がない場合は型の注釈を追加してください。 - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 値の制限。値 '{0}' は次のジェネリック型です。\n {1} \n明示的な引数を使用して '{2}' を関数にするか、ジェネリックにする意図がない場合は型の注釈を追加してください。 - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - 値の制限。このメンバーは次のジェネリック型を持つと推論されました。\n {0} \nコンストラクターとプロパティのゲッター/セッターは、それを囲む型よりも総称性を高くすることができません。関係する正確な型を示すために、型の注釈を追加してください。 - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 値の制限。値 '{0}' は次のジェネリック型を持つと推論されました。\n {1} \n明示的に引数を '{2}' にするか、ジェネリックにする意図がない場合は型の注釈を追加してください。 - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 値の制限。値 '{0}' は次のジェネリック型を持つと推論されました。\n {1} \n単純なデータ用語として '{2}' を定義するか、明示的な引数を使用して関数にするか、ジェネリックにする意図がない場合は型の注釈を追加してください。 - - syntax error 構文エラーです diff --git a/src/Compiler/xlf/FSStrings.ko.xlf b/src/Compiler/xlf/FSStrings.ko.xlf index 812dcd965b2..0960b7b3e26 100644 --- a/src/Compiler/xlf/FSStrings.ko.xlf +++ b/src/Compiler/xlf/FSStrings.ko.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + 비정적 멤버가 필요합니다. Static member is expected. - Static member is expected. + 정적 멤버가 필요합니다. @@ -227,6 +227,16 @@ {0}' 필드와 '{1}' 필드의 소스 형식이 서로 다릅니다. + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 값 제한: 값 '{0}'에 유추된 제네릭 형식이 있습니다.\n {1}\n하지만 값은 "let x: '_a"의 '_a와 같은 제네릭 형식 변수를 가질 수 없습니다. 다음 중 하나를 수행할 수 있습니다.\n- 정수 리터럴, 문자열 리터럴 또는 "let x = 1"과 같은 공용 구조체 대/소문자와 같은 간단한 데이터 용어로 정의합니다.\n- "let x : int"와 같은 명시적 형식 주석을 추가합니다.\n- "do x"와 같은 형식 유추를 위해 이후 코드에서 값을 제네릭이 아닌 형식으로 사용합니다.\n또는 여전히 형식 종속 결과를 원할 경우 다음 중 하나를 수행하여 '{2}'을(를) 함수로 정의할 수 있습니다.\n- "let x()"와 같은 단위 매개 변수를 추가합니다.\n- "let x<'a>"와 같은 명시적 형식 매개 변수를 작성합니다.\n이 오류는 매개 변수가 없는 let 바인딩이 함수가 아니라 값을 정의하기 때문입니다. 값을 읽으면 모든 위치에서 동일한 결과가 발생하는 것으로 가정되지만 제네릭 형식 매개 변수가 형식 종속 결과를 사용하여 이 가정을 무효화할 수 있기 때문에 값은 제네릭일 수 없습니다. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 값 제한: 값 '{0}'에 유추된 제네릭 함수 형식이 있습니다.\n {1}\n하지만 값은 "let f: '_a"의 '_a와 같은 제네릭 형식 변수를 가질 수 없습니다. 대신 다음 중 하나를 수행하여 '{2}'을(를) 함수로 정의해야 합니다.\n- 부분 애플리케이션 "let f param"을 사용하는 대신 적용되는 명시적 매개 변수를 추가합니다.\n- "let f()"와 같은 단위 매개 변수를 추가합니다.\n- "let f<'a>"와 같은 명시적 형식 매개 변수를 작성합니다.\n또는 제네렉이 되지 않게 하려는 경우.\n- "let f : obj -> obj"와 같은 명시적 형식 주석을 추가하거나\n- "do f()"와 같은 형식 유추를 위해 이후 코드의 함수 값에 제네릭이 아닌 형식의 인수를 적용합니다.\n이 오류는 매개 변수가 없는 let 바인딩이 함수가 아니라 값을 정의하기 때문입니다. 값을 읽으면 모든 위치에서 동일한 결과가 발생하는 것으로 가정되지만 제네릭 형식 매개 변수가 형식 종속 결과를 사용하여 이 가정을 무효화할 수 있기 때문에 값은 제네릭일 수 없습니다. + + '{0}' is bound twice in this pattern '{0}'은(는) 이 패턴에서 두 번 바인딩되었습니다. @@ -1557,31 +1567,6 @@ 다음 필드에는 값이 필요합니다. {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 값 제한이 있습니다. 값 '{0}'에 제네릭 형식\n {1}이(가) 있습니다. \n'{2}'에 대한 인수를 명시적으로 만들거나, 제네릭 요소로 만들지 않으려는 경우 형식 주석을 추가하세요. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 값 제한이 있습니다. 값 '{0}'에 제네릭 형식\n {1}이(가) 있습니다. \n'{2}'을(를) 명시적 인수가 포함된 함수로 만들거나, 제네릭 요소로 만들지 않으려는 경우 형식 주석을 추가하세요. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - 값 제한이 있습니다. 이 멤버는 제네릭 형식\n {0}을(를) 가지는 것으로 유추되었습니다. \n생성자 및 속성 getter/setter는 바깥쪽 형식보다 일반적일 수 없습니다. 형식 주석을 추가하여 관련 형식을 정확히 나타내세요. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 값 제한이 있습니다. 값 '{0}'은(는) 제네릭 형식\n {1}을(를) 가지는 것으로 유추되었습니다. \n'{2}'에 대한 인수를 명시적으로 만들거나, 제네릭 요소로 만들지 않으려는 경우 형식 주석을 추가하세요. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 값 제한이 있습니다. 값 '{0}'은(는) 제네릭 형식\n {1}을(를) 가지는 것으로 유추되었습니다. \n'{2}'을(를) 단순 데이터 용어로 정의하거나, 명시적 인수가 포함된 함수로 만들거나, 제네릭 요소로 만들지 않으려는 경우 형식 주석을 추가하세요. - - syntax error 구문 오류입니다. diff --git a/src/Compiler/xlf/FSStrings.pl.xlf b/src/Compiler/xlf/FSStrings.pl.xlf index d10f929a4f1..9e12b8cdea1 100644 --- a/src/Compiler/xlf/FSStrings.pl.xlf +++ b/src/Compiler/xlf/FSStrings.pl.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + Oczekiwano elementu członkowskiego innego niż statyczny. Static member is expected. - Static member is expected. + Oczekiwano statycznego elementu członkowskiego. @@ -227,6 +227,16 @@ Pola „{0}” i „{1}” są polami różnego typu + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Ograniczenie wartości: wartość „{0}” ma wywnioskowany typ ogólny\n {1}\nWartości nie mogą mieć zmiennych typu ogólnego, takich jak „_a w „let x: „_a”. Możesz wykonać jedną z następujących czynności:\n- Zdefiniuj go jako prosty termin danych, taki jak literał liczby całkowitej, literał ciągu lub przypadek unii, taki jak „let x = 1”\n- Dodaj jawną adnotację typu, taką jak „let x : int”\n- Użyj wartości jako typu nie generycznego w późniejszym kodzie dla wnioskowania typu, takiego jak „do x”,\n jeśli nadal chcesz uzyskać wyniki zależne od typu, Można zdefiniować „{2}” jako funkcję, wykonując jedną z następujących czynności:\n- Dodaj parametr jednostkowy, taki jak „let x()”\n- Zapisz jawne parametry typu, takie jak „let x<'a>”.\nTen błąd jest spowodowany tym, że powiązanie let bez parametrów definiuje wartość, a nie funkcję. Wartości nie mogą być ogólne, ponieważ zakłada się, że odczytanie wartości skutkuje tym samym wszędzie, ale parametry typu ogólnego mogą unieważnić to założenie, umożliwiając uzyskanie wyników zależnych od typu. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Ograniczenie wartości: wartość „{0}” ma wywnioskowany typ funkcji ogólnej\n {1}\nJako wartości nie mogą mieć zmiennych typu ogólnego, takich jak „_a w „let f: '_a”. Zamiast tego należy zdefiniować „{2}” jako funkcję, wykonując jedną z następujących czynności:\n- Dodaj jawny parametr, który jest stosowany zamiast używania częściowej aplikacji „let f param”\n- Dodaj parametr jednostkowy, taki jak „let f()”\n- Zapisz jawne parametry typu, takie jak „let f<'a>”\nor, jeśli nie zamierzasz, aby był ogólny, either:\n- Dodaj jawną adnotację typu, taką jak „let f : obj -> obj”\n- Zastosuj argumenty typów nie generycznych do wartości funkcji w późniejszym kodzie dla wnioskowania typu, takiego jak „do f()”.\nTen błąd jest spowodowany tym, że powiązanie let bez parametrów definiuje wartość, a nie funkcję. Wartości nie mogą być ogólne, ponieważ zakłada się, że odczytanie wartości skutkuje tym samym wszędzie, ale parametry typu ogólnego mogą unieważnić to założenie, umożliwiając uzyskanie wyników zależnych od typu. + + '{0}' is bound twice in this pattern Zmienna „{0}” została powiązana dwa razy w tym wzorcu @@ -1557,31 +1567,6 @@ Następujące pola wymagają wartości: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Ograniczenie wartości. Wartość „{0}” jest wartością typu ogólnego\n {1} \nOkreśl argumenty elementu „{2}” jako jawne lub dodaj adnotację typu, jeśli nie chcesz, aby wartość była ogólna. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Ograniczenie wartości. Wartość „{0}” jest wartością typu ogólnego\n {1} \nUstaw element „{2}” jako funkcję z jawnymi argumentami lub dodaj adnotację typu, jeśli nie chcesz, aby wartość była ogólna. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Ograniczenie wartości. Wywnioskowano, że ten element członkowski jest elementem typu ogólnego\n {0} \nKonstruktory i metody pobierające/ustawiające właściwości nie mogą być bardziej ogólne niż typ otaczający. Dodaj adnotację typu, aby dokładnie wskazać uwzględnione typy. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Ograniczenie wartości. Wywnioskowano, że wartość „{0}” jest wartością typu ogólnego\n {1} \nOkreśl argumenty elementu „{2}” jako jawne lub dodaj adnotację typu, jeśli nie chcesz, aby wartość była ogólna. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Ograniczenie wartości. Wywnioskowano, że wartość „{0}” jest wartością typu ogólnego\n {1} \nZdefiniuj element „{2}” jako prosty termin danych, określ go jako funkcję z jawnymi argumentami lub dodaj adnotację typu, jeśli nie chcesz, aby wartość była ogólna. - - syntax error błąd składni diff --git a/src/Compiler/xlf/FSStrings.pt-BR.xlf b/src/Compiler/xlf/FSStrings.pt-BR.xlf index 3255d8c404d..10626ad590b 100644 --- a/src/Compiler/xlf/FSStrings.pt-BR.xlf +++ b/src/Compiler/xlf/FSStrings.pt-BR.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + O membro não estático é esperado. Static member is expected. - Static member is expected. + O membro estático é esperado. @@ -227,6 +227,16 @@ Os campos '{0}' e '{1}' são de tipos diferentes + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restrição de valor: o valor "{0}" tem um tipo genérico inferido\n {1}\nEntretanto, os valores não podem ter variáveis de tipo genérico como '_a em "let x: '_a". Você pode fazer o seguinte:\n- Defina-o como um termo de dados simples, como um literal inteiro, um literal de cadeia de caracteres ou um caso de união como "let x = 1"\n- Adicionar uma anotação de tipo explícita como "let x : int"\n- Use o valor como um tipo não genérico em código posterior para inferência de tipo como "do x"\ne se você ainda quiser resultados dependentes de tipo, você pode definir "{2}" como uma função fazendo:\n- Adicione um parâmetro de unidade como "let x()"\n- Escreva parâmetros de tipo explícitos como "let x<'a>".\nEsse erro ocorre porque uma ligação let sem parâmetros define um valor, não uma função. Os valores não podem ser genéricos porque se supõe que a leitura de um valor resulte no mesmo em todos os lugares, mas parâmetros de tipo genérico podem invalidar essa suposição habilitando resultados dependentes de tipo. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Restrição de valor: o valor "{0}" tem um tipo de função genérica inferido\n {1}\nEntretanto, os valores não podem ter variáveis de tipo genérico como '_a em "let f: '_a". Você deve definir "{2}" como uma função seguindo um destes procedimentos:\n- Adicione um parâmetro explícito que é aplicado em vez de usar uma aplicação parcial "let f param"\n- Adicione um parâmetro de unidade como "let f() "\n- Escreva parâmetros de tipo explícitos como "let f<'a>"\ne se você não pretende que seja genérico:\n- Adicione uma anotação de tipo explícita como "let f : obj -> obj" \n- Aplique argumentos de tipos não genéricos ao valor da função em código posterior para inferência de tipo como "do f()".\nEsse erro ocorre porque uma ligação let sem parâmetros define um valor, não uma função. Os valores não podem ser genéricos porque se supõe que a leitura de um valor resulte no mesmo em todos os lugares, mas parâmetros de tipo genérico podem invalidar essa suposição habilitando resultados dependentes de tipo. + + '{0}' is bound twice in this pattern '{0}' é associado duas vezes neste padrão @@ -1557,31 +1567,6 @@ Os campos a seguir requerem valores: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Restrição de valor. O valor '{0}' tem um tipo genérico\n {1} \nTorne os argumentos '{2}' explícitos ou, se sua intenção não for deixá-los genéricos, adicione uma anotação de tipo. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Restrição de valor. O valor '{0}' tem um tipo genérico\n {1} \nInsira '{2}' em uma função com argumentos explícitos ou, se você não desejar que ele seja genérico, adicione uma anotação de tipo. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Restrição de valor. Este membro foi inferido para ter um tipo genérico\n {0} \nConstrutores e getters/setters de propriedade não podem ser mais genéricos que o tipo de delimitador. Adicione uma anotação de tipo para indicar os tipos exatos envolvidos. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Restrição de valor. O valor '{0}' foi inferido para ter um tipo genérico\n {1} \nTorne os argumentos '{2}' explícitos ou, se sua intenção não for deixá-los genéricos, adicione uma anotação de tipo. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Restrição de valor. O valor '{0}' foi inferido para ter um tipo genérico\n {1} \nDefina '{2}' como um termo de dado simples e torne-o uma função com argumentos explícitos ou, se sua intenção for deixá-los genéricos, adicione uma anotação de tipo. - - syntax error erro de sintaxe diff --git a/src/Compiler/xlf/FSStrings.ru.xlf b/src/Compiler/xlf/FSStrings.ru.xlf index 5de47b70a92..621823ff411 100644 --- a/src/Compiler/xlf/FSStrings.ru.xlf +++ b/src/Compiler/xlf/FSStrings.ru.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + Ожидается нестатический элемент. Static member is expected. - Static member is expected. + Ожидается статический элемент. @@ -227,6 +227,16 @@ Поля "{0}" и "{1}" принадлежат различным типам + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Ограничение на значение: значение '{0}' имеет предполагаемый универсальный тип\n {1}\nОднако значения не могут иметь переменные универсального типа, такие как '_a в "let x: '_a". Вы можете сделать одно из следующих действий:\n- Определите его как простой термин данных, например целочисленный литерал, строковый литерал или случай объединения, например "let x = 1".\n- Добавьте явную аннотацию типа, например "let x: int"\n- Используйте значение как необобщенный тип в более позднем коде для вывода типа, например "do x"\nили, если вам все еще нужны результаты, зависящие от типа, вы можете вместо этого определить '{2}' как функцию, выполнив одно из следующих действий:\n- Добавьте параметр модуля, например "let x()"\n- Запишите явные параметры типа, например "let x<'a>".\nЭта ошибка связана с тем, что привязка let без параметров определяет значение, а не функцию. Значения не могут быть универсальными, поскольку предполагается, что чтение значения везде приводит к одному и тому же результату, но параметры универсального типа могут сделать это предположение недействительным, включив результаты, зависящие от типа. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Ограничение значения: значение '{0}' имеет предполагаемый тип универсальной функции\n {1}\nОднако значения не могут иметь переменные универсального типа, такие как '_a в "let f: '_a". Вместо этого вам следует определить '{2}' как функцию, выполнив одно из следующих действий:\n- Добавьте явный параметр, который применяется вместо использования частичного приложения "let f param"\n- Добавьте параметр модуля, например "let f() "\n- Запишите явные параметры типа, например "let f<'a>"\nили, если вы не планируете, чтобы они были универсальными, либо:\n- Добавьте явную аннотацию типа, например "let f : obj -> obj" \n- Применить аргументы неуниверсальных типов к значению функции в более позднем коде для вывода типа, например «do f()».\nЭта ошибка связана с тем, что привязка let без параметров определяет значение, а не функцию. Значения не могут быть универсальными, поскольку предполагается, что чтение значения везде приводит к одному и тому же результату, но параметры универсального типа могут сделать это предположение недействительным, включив результаты, зависящие от типа. + + '{0}' is bound twice in this pattern {0} в данном шаблоне привязан дважды @@ -1557,31 +1567,6 @@ Для следующих полей требуются значения: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Ограничение значения. Значение "{0}" имеет универсальный тип\n {1} \nЛибо сделайте аргументы для "{2}" явными либо (если универсальный тип не требуется) добавьте аннотацию типа. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Ограничение значения. Значение "{0}" имеет универсальный тип\n {1} \nЛибо сделайте "{2}" функцией с явными аргументами, либо (если универсальный тип не требуется) добавьте аннотацию типа. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Ограничение значения. Данный выведенный элемент должен иметь универсальный тип\n {0} \nМетоды получения или задания свойств и конструкторов не могут быть более универсальными, чем вмещающий тип. Добавьте аннотацию типа, чтобы точно обозначить затрагиваемые типы. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Ограничение значения. Выведенное значение "{0}" должно иметь универсальный тип\n {1} \nЛибо сделайте аргументы для "{2}" явными, либо (если универсальный тип не требуется) добавьте аннотацию типа. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Ограничение значения. Выведенное значение "{0}" должно иметь универсальный тип\n {1} \nЛибо определите "{2}" как простой член данных, либо сделайте его функцией с явными аргументами, либо (если универсальный тип не требуется) добавьте аннотацию типа. - - syntax error синтаксическая ошибка diff --git a/src/Compiler/xlf/FSStrings.tr.xlf b/src/Compiler/xlf/FSStrings.tr.xlf index 1fac64a8dc9..7051cbfd579 100644 --- a/src/Compiler/xlf/FSStrings.tr.xlf +++ b/src/Compiler/xlf/FSStrings.tr.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + Statik olmayan üye bekleniyor. Static member is expected. - Static member is expected. + Statik üye bekleniyor. @@ -227,6 +227,16 @@ {0}' ve '{1}' alanları farklı türlerde + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Değer kısıtlaması: '{0}' değeri, çıkarsanan bir genel türe sahip\n {1}\nAncak değerlerin "let f: '_a" içinde '_a gibi genel tür değişkenleri olamaz. Şunlardan birini yapabilirsiniz:\n- Tamsayı sabit değeri, dize sabit değeri veya birleşim durumu gibi basit bir veri terimi olarak tanımlayın, örneğin "let x = 1"\n- Açık bir tür ek açıklaması ekleyin, örneğin "let x : int" \n- Tür çıkarımı için değeri sonraki kodda genel olmayan bir tür olarak kullanın, örneğin "do x" \nveya yine de türe bağımlı sonuçlar istiyorsanız, şunlardan birini yaparak '{2}' öğesini işlev olarak tanımlayın:\n- Bir birim parametresi ekleyin, örneğin "let x()"\n- Açık tür parametreleri yazın, örneğin "let x<'a>".\nBu hatanın nedeni parametre içermeyen bir let bağlamasının bir işlevi değil bir değeri tanımlamasıdır. Bir değerin okunmasının her yerde aynı şekilde sonuçlanacağı varsayıldığından değerler genel olamaz, ancak genel tür parametreleri türe bağımlı sonuçları etkinleştirerek bu varsayımı geçersiz yapabilir. + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + Değer kısıtlaması: '{0}' değeri, çıkarsanan bir genel işlev türüne sahip\n {1}\nAncak değerlerin "let f: '_a" içinde '_a gibi genel tür değişkenleri olamaz. Aşağıdakilerden birini yaparak '{2}' öğesini işlev olarak tanımlamanız gerekir:\n- Kısmi bir uygulama kullanmak yerine uygulanan açık bir parametre ekleyin, örneğin "let f param"\n- Bir birim parametresi ekleyin, örneğin "let f()"\n- Açık tür parametreleri yazın, örneğin "let f<'a>"\nveya genel olmasını istemiyorsanız ya:\n- Bir açık tür ek açıklaması ekleyin, örneğin "let f : obj -> obj"\n- Tür çıkarımı için sonraki koddaki işlev değerine genel olmayan türlerin bağımsız değişkenlerini uygulayın, örneğin "do f()".\nBu hatanın nedeni parametre içermeyen bir let bağlamasının bir işlevi değil bir değeri tanımlamasıdır. Bir değerin okunmasının her yerde aynı şekilde sonuçlanacağı varsayıldığından değerler genel olamaz, ancak genel tür parametreleri türe bağımlı sonuçları etkinleştirerek bu varsayımı geçersiz yapabilir. + + '{0}' is bound twice in this pattern '{0}' bu desende iki kez bağlandı @@ -1557,31 +1567,6 @@ Aşağıdaki alanlar için değerler gerekiyor: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Değer kısıtlaması. '{0}' değerinin genel türü:\n {1} \nYa '{2}' bağımsız değişkenlerini açık yapın ya da genel olmasını istemiyorsanız bir tür ek açıklaması ekleyin. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Değer kısıtlaması. '{0}' değerinin genel türü:\n {1} \nYa açık bağımsız değişkenlerle '{2}' için işlev dönüşümü yapın ya da genel olmasını istemiyorsanız bir tür ek açıklaması ekleyin. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Değer kısıtlaması. Bu üyenin şu genel türü olduğu çıkarıldı\n {0} \nOluşturucular ve özellik alıcıları/ayarlayıcıları kapsayan türden daha genel olamaz. Söz konusu türleri tam olarak belirtmek için bir tür ek açıklaması ekleyin. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Değer kısıtlaması. '{0}' değerinin şu genel türü olduğu çıkarıldı:\n {1} \nYa '{2}' bağımsız değişkenlerini açık yapın ya da genel olmasını istemiyorsanız bir tür ek açıklaması ekleyin. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Değer kısıtlaması. '{0}' değerinin şu genel türü olduğu çıkarıldı:\n {1} \nYa '{2}' tanımını basit veri terimi olarak yaparak onu açık bağımsız değişkenlerle bir işlev yapın ya da genel olmasını istemiyorsanız bir tür ek açıklaması ekleyin. - - syntax error sözdizimi hatası diff --git a/src/Compiler/xlf/FSStrings.zh-Hans.xlf b/src/Compiler/xlf/FSStrings.zh-Hans.xlf index 8f4363d334a..f184c75a630 100644 --- a/src/Compiler/xlf/FSStrings.zh-Hans.xlf +++ b/src/Compiler/xlf/FSStrings.zh-Hans.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + 应为非静态成员。 Static member is expected. - Static member is expected. + 应为静态成员。 @@ -227,6 +227,16 @@ 字段“{0}”和“{1}”来自不同的类型 + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 值限制: 值“{0}”具有推断的泛型类型\n {1}\n但是,值不能具有泛型类型变量,如“let x: '_a”中的 '_a。可以执行下列操作之一:\n- 将其定义为简单数据词,如整数文本、字符串文本或联合大小写(如“let x = 1”)\n- 添加显式类型批注(如“let x : int”)\n- 在后面的代码中将该值用作非泛型类型,以进行类型推理(如“do x”)\n如果仍需要依赖类型的结果,可以改为通过执行以下任一操作来定义“{2}”:\n- 添加单元参数(如“let x()”)\n- 编写显式类型参数,如“let x<'a>”。\n此错误是因为没有参数的 let 绑定定义了一个值,而不是函数。值不能是泛型的,因为会假定读取值会导致所有位置都相同,但泛型类型参数可能通过启用依赖类型的结果来使此假设失效。 + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 值限制: 值“{0}”具有推断的泛型函数类型\n {1}\n但是,值不能具有泛型类型变量,如“let f: '_a”中的 '_a。你应该将“{2}”定义为一个函数,而不是通过以下方式之一进行定义:\n- 添加一个显式参数,以替代使用部分应用“let f param”\n- 添加一个单位参数,如“let f()”\n- 编写显式类型参数,如“let f<'a>”\n如果不打算使其成为泛型的话,则可以选择:\n- 添加显式类型注释,如“let f : obj -> obj”\n- 在后续代码中对非泛型类型的参数应用于函数值以进行类型推断,例如“do f()”。\n此错误是因为没有参数的 let 绑定定义了一个值,而不是函数。值不能是泛型的,因为会假定读取值会导致所有位置都相同,但泛型类型参数可能通过启用依赖类型的结果来使此假设失效。 + + '{0}' is bound twice in this pattern “{0}”在此模式中绑定了两次 @@ -1557,31 +1567,6 @@ 以下字段需要值: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 值限制。值“{0}”具有泛型类型\n {1} \n使“{2}”的参数成为显式参数,或添加类型批注(如果您不希望它是泛型的)。 - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 值限制。值“{0}”具有泛型类型\n {1} \n使“{2}”成为具有显式参数的函数,或添加类型批注(如果您不希望它是泛型的)。 - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - 值限制。已推理出此成员具有泛型类型\n {0} \n构造函数和属性 Getter/Setter 不能比封闭类型更通用。 添加类型批注以指示涉及到的确切类型。 - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 值限制。已推理出值“{0}”具有泛型类型\n {1} \n使“{2}”的参数成为显式参数,或添加类型批注(如果您不希望它是泛型的)。 - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 值限制。已推理出值“{0}”具有泛型类型\n {1} \n将“{2}”定义为简单的数据条目,使其成为具有显式参数的函数,或添加类型批注(如果您不希望它是泛型的)。 - - syntax error 语法错误 diff --git a/src/Compiler/xlf/FSStrings.zh-Hant.xlf b/src/Compiler/xlf/FSStrings.zh-Hant.xlf index e5aa888ced3..f7e88f22576 100644 --- a/src/Compiler/xlf/FSStrings.zh-Hant.xlf +++ b/src/Compiler/xlf/FSStrings.zh-Hant.xlf @@ -44,12 +44,12 @@ Non-static member is expected. - Non-static member is expected. + 必須是非靜態成員。 Static member is expected. - Static member is expected. + 必須是靜態成員。 @@ -227,6 +227,16 @@ 欄位 '{0}' 和 '{1}' 來自不同類型 + + Value restriction: The value '{0}' has an inferred generic type\n {1}\nHowever, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:\n- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"\n- Add an explicit type annotation like "let x : int"\n- Use the value as a non-generic type in later code for type inference like "do x"\nor if you still want type-dependent results, you can define '{2}' as a function instead by doing either:\n- Add a unit parameter like "let x()"\n- Write explicit type parameters like "let x<'a>".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 值限制: 值 '{0}' 具有推斷的函式類型\n {1}\n不過,值不能有泛型類型變數,例如 "let x: '_a" 中的 '_a。您可以執行下列其中一項操作:\n- 將其定義為簡單資料項,例如整數常值、字串常值或聯集,例如 "let x = 1"\n- 新增明確類型註釋,例如 "let x : int"\n- 在稍後的程式碼中使用該值作為非泛型類型,以用於類型推斷,例如 "do x"\n,或者如果您仍然想要類型相依結果,可以改為將 '{2}' 定義為函式,方法是執行以下兩個動作之一:\n- 新增單位參數,例如 "let x()"\n- 寫入明確類型參數,例如 "let x<'a>"。\n此錯誤是因為 let 繫結沒有定義值的參數,而不是函式。值不能是泛型值,因為讀取值會假設在相同位置產生,但泛型類型參數可能透過啟用類型相依結果,使此假設失效。 + + + + Value restriction: The value '{0}' has an inferred generic function type\n {1}\nHowever, values cannot have generic type variables like '_a in "let f: '_a". You should define '{2}' as a function instead by doing one of the following:\n- Add an explicit parameter that is applied instead of using a partial application "let f param"\n- Add a unit parameter like "let f()"\n- Write explicit type parameters like "let f<'a>"\nor if you do not intend for it to be generic, either:\n- Add an explicit type annotation like "let f : obj -> obj"\n- Apply arguments of non-generic types to the function value in later code for type inference like "do f()".\nThis error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results. + 值限制: 值 '{0}' 具有推斷的泛型函式類型\n {1}\n不過,值不能有泛型類型變數,例如 "let f: '_a" 中的 '_a。您應該改為將 '{2}' 定義為函式,方法是執行以下動作之一:\n- 新增已套用的明確參數,而不是使用部分套用的 "let f param"\n- 新增單位參數,例如 "let f()"\n- 撰寫明確類型參數,例如 "let f<'a>"\n或者如果您不想讓它成為泛型,則執行以下兩個動作之一:\n- 新增明確的類型註釋,例如 "let f : obj -> obj"\n- 在稍後程式碼中將非泛型類型的引數套用至函式值,以用於類型推斷,例如 "do f()"。\n此錯誤是因為 let 繫結沒有定義值的參數,而不是函式。值不能是泛型值,因為讀取值會假設在相同位置產生,但泛型類型參數可能透過啟用類型相依結果,使此假設失效。 + + '{0}' is bound twice in this pattern '{0}' 在這個模式中繫結兩次 @@ -1557,31 +1567,6 @@ 下列欄位需要值: {0} - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 值限制。值 '{0}' 具有泛型類型\n {1} \n請將 '{2}' 的引數設為明確的,或者如果不想將它設為泛型,請加入類型註釋。 - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 值限制。值 '{0}' 具有泛型類型\n {1} \n請將 '{2}' 設為具有明確引數的函式,或者如果不想將它設為泛型,請加入類型註釋。 - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - 值限制。這個成員已被推斷為具有泛型類型\n {0} \n建構函式和屬性 getter/setter 不能比封入類型更為泛型。請加入類型註釋,以指示涉及的確切類型。 - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - 值限制。值 '{0}' 已被推斷為具有泛型類型\n {1} \n請將 '{2}' 的引數設為明確的,或者如果不想將它設為泛型,請加入類型註釋。 - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - 值限制。值 '{0}' 已被推斷為具有泛型類型\n {1} \n請將 '{2}' 定義為簡單資料項、將它設為具有明確引數的函式,或者如果不想將它設為泛型,請加入類型註釋。 - - syntax error 語法錯誤 diff --git a/src/FSharp.Core/Linq.fs b/src/FSharp.Core/Linq.fs index 257dd27edb2..cf7033e09db 100644 --- a/src/FSharp.Core/Linq.fs +++ b/src/FSharp.Core/Linq.fs @@ -59,11 +59,11 @@ module LeafExpressionConverter = |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo - let SubstHelperRaw (q:Expr, x:Var[], y:obj[]) : Expr = + let SubstHelperRaw (q:Expr, x:Var array, y:obj array) : Expr = let d = Map.ofArray (Array.zip x y) q.Substitute(fun v -> v |> d.TryFind |> Option.map (fun x -> Expr.Value (x, v.Type))) - let SubstHelper<'T> (q:Expr, x:Var[], y:obj[]) : Expr<'T> = + let SubstHelper<'T> (q:Expr, x:Var array, y:obj array) : Expr<'T> = SubstHelperRaw(q, x, y) |> Expr.Cast let showAll = @@ -390,15 +390,15 @@ module LeafExpressionConverter = let (|NewAnonymousObjectHelperQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (NewAnonymousObjectHelper)) let (|ArrayLookupQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> LanguagePrimitives.IntrinsicFunctions.GetArray x y)) - //let (|ArrayAssignQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun -> LanguagePrimitives.IntrinsicFunctions.SetArray : int[] -> int -> int -> unit)) + //let (|ArrayAssignQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun -> LanguagePrimitives.IntrinsicFunctions.SetArray : int array -> int -> int -> unit)) //let (|ArrayTypeQ|_|) (ty:System.Type) = if ty.IsArray && ty.GetArrayRank() = 1 then Some (ty.GetElementType()) else None let substHelperMeth = - methodhandleof (fun (x:Expr, y:Var[], z:obj[]) -> SubstHelper (x, y, z)) + methodhandleof (fun (x:Expr, y:Var array, z:obj array) -> SubstHelper (x, y, z)) |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo let substHelperRawMeth = - methodhandleof (fun (x:Expr, y:Var[], z:obj[]) -> SubstHelperRaw (x, y, z)) + methodhandleof (fun (x:Expr, y:Var array, z:obj array) -> SubstHelperRaw (x, y, z)) |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo @@ -737,7 +737,7 @@ module LeafExpressionConverter = else Reflection.FSharpType.MakeTupleType(argTypes) let argsP = ConvExprsToLinq env args - let rec build ty (argsP: Expression[]) = + let rec build ty (argsP: Expression array) = match Reflection.FSharpValue.PreComputeTupleConstructorInfo ty with | ctorInfo, None -> Expression.New(ctorInfo, argsP) |> asExpr | ctorInfo, Some (nestedTy) -> @@ -879,7 +879,7 @@ module LeafExpressionConverter = | None -> null - and ConvExprsToLinq env es : Expression[] = + and ConvExprsToLinq env es : Expression array = es |> List.map (ConvExprToLinqInContext env) |> Array.ofList and ConvVarToLinq (v: Var) = diff --git a/src/FSharp.Core/Linq.fsi b/src/FSharp.Core/Linq.fsi index 13f3fa4187e..5064de12f55 100644 --- a/src/FSharp.Core/Linq.fsi +++ b/src/FSharp.Core/Linq.fsi @@ -78,14 +78,14 @@ module LeafExpressionConverter = /// /// /// - val SubstHelper: Expr * Var[] * obj[] -> Expr<'T> + val SubstHelper: Expr * Var array * obj array -> Expr<'T> /// /// A runtime helper used to evaluate nested quotation literals. /// /// /// - val SubstHelperRaw: Expr * Var[] * obj[] -> Expr + val SubstHelperRaw: Expr * Var array * obj array -> Expr val internal (|SpecificCallToMethod|_|): System.RuntimeMethodHandle -> (Expr -> (Expr option * Reflection.MethodInfo * Expr list) option) diff --git a/src/FSharp.Core/array.fs b/src/FSharp.Core/array.fs index 73945231ce6..0611a1aebf0 100644 --- a/src/FSharp.Core/array.fs +++ b/src/FSharp.Core/array.fs @@ -24,12 +24,12 @@ module Array = raise (KeyNotFoundException(SR.GetString(SR.keyNotFoundAlt))) [] - let length (array: _[]) = + let length (array: _ array) = checkNonNull "array" array array.Length [] - let inline last (array: 'T[]) = + let inline last (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -38,7 +38,7 @@ module Array = array.[array.Length - 1] [] - let tryLast (array: 'T[]) = + let tryLast (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -62,7 +62,8 @@ module Array = if count < 0 then invalidArgInputMustBeNonNegative "count" count - let array: 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count + let array: 'T array = + Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count for i = 0 to Operators.Checked.(-) array.Length 1 do // use checked arithmetic here to satisfy FxCop array.[i] <- value @@ -70,7 +71,7 @@ module Array = array [] - let tryHead (array: 'T[]) = + let tryHead (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -79,12 +80,12 @@ module Array = Some array.[0] [] - let isEmpty (array: 'T[]) = + let isEmpty (array: 'T array) = checkNonNull "array" array array.Length = 0 [] - let tail (array: 'T[]) = + let tail (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -93,13 +94,13 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 1 (array.Length - 1) array [] - let empty<'T> : 'T[] = [||] + let empty<'T> : 'T array = [||] [] - let inline blit (source: 'T[]) (sourceIndex: int) (target: 'T[]) (targetIndex: int) (count: int) = + let inline blit (source: 'T array) (sourceIndex: int) (target: 'T array) (targetIndex: int) (count: int) = Array.Copy(source, sourceIndex, target, targetIndex, count) - let concatArrays (arrs: 'T[][]) : 'T[] = + let concatArrays (arrs: 'T array array) : 'T array = let mutable acc = 0 for h in arrs do @@ -118,11 +119,11 @@ module Array = res [] - let concat (arrays: seq<'T[]>) = + let concat (arrays: seq<'T array>) = checkNonNull "arrays" arrays match arrays with - | :? ('T[][]) as ts -> ts |> concatArrays // avoid a clone, since we only read the array + | :? ('T array array) as ts -> ts |> concatArrays // avoid a clone, since we only read the array | _ -> arrays |> Seq.toArray |> concatArrays [] @@ -139,10 +140,12 @@ module Array = arr [] - let collect (mapping: 'T -> 'U[]) (array: 'T[]) : 'U[] = + let collect (mapping: 'T -> 'U array) (array: 'T array) : 'U array = checkNonNull "array" array let len = array.Length - let result = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked<'U[]> len + + let result = + Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked<'U array> len for i = 0 to result.Length - 1 do result.[i] <- mapping array.[i] @@ -150,7 +153,7 @@ module Array = concatArrays result [] - let splitAt index (array: 'T[]) = + let splitAt index (array: 'T array) = checkNonNull "array" array if index < 0 then @@ -178,7 +181,7 @@ module Array = res1, res2 [] - let take count (array: 'T[]) = + let take count (array: 'T array) = checkNonNull "array" array if count < 0 then @@ -193,7 +196,7 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 count array [] - let takeWhile predicate (array: 'T[]) = + let takeWhile predicate (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -210,7 +213,7 @@ module Array = (comparer: IEqualityComparer<'SafeKey>) ([] projection: 'T -> 'SafeKey) ([] getKey: 'SafeKey -> 'Key) - (array: 'T[]) + (array: 'T array) = let length = array.Length @@ -240,11 +243,11 @@ module Array = res // We avoid wrapping a StructBox, because under 64 JIT we get some "hard" tailcalls which affect performance - let countByValueType (projection: 'T -> 'Key) (array: 'T[]) = + let countByValueType (projection: 'T -> 'Key) (array: 'T array) = countByImpl HashIdentity.Structural<'Key> projection id array // Wrap a StructBox around all keys in case the key type is itself a type using null as a representation - let countByRefType (projection: 'T -> 'Key) (array: 'T[]) = + let countByRefType (projection: 'T -> 'Key) (array: 'T array) = countByImpl RuntimeHelpers.StructBox<'Key>.Comparer (projection >> RuntimeHelpers.StructBox) @@ -252,7 +255,7 @@ module Array = array [] - let countBy (projection: 'T -> 'Key) (array: 'T[]) = + let countBy (projection: 'T -> 'Key) (array: 'T array) = checkNonNull "array" array if typeof<'Key>.IsValueType then @@ -261,13 +264,13 @@ module Array = countByRefType projection array [] - let append (array1: 'T[]) (array2: 'T[]) = + let append (array1: 'T array) (array2: 'T array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let n1 = array1.Length let n2 = array2.Length - let res: 'T[] = + let res: 'T array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (n1 + n2) Array.Copy(array1, 0, res, 0, n1) @@ -275,7 +278,7 @@ module Array = res [] - let head (array: 'T[]) = + let head (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -284,9 +287,9 @@ module Array = array.[0] [] - let copy (array: 'T[]) = + let copy (array: 'T array) = checkNonNull "array" array - (array.Clone() :?> 'T[]) // this is marginally faster + (array.Clone() :?> 'T array) // this is marginally faster //let len = array.Length //let res = zeroCreate len //for i = 0 to len - 1 do @@ -303,7 +306,7 @@ module Array = List.toArray list [] - let indexed (array: 'T[]) = + let indexed (array: 'T array) = checkNonNull "array" array let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length @@ -313,14 +316,14 @@ module Array = res [] - let inline iter ([] action) (array: 'T[]) = + let inline iter ([] action) (array: 'T array) = checkNonNull "array" array for i = 0 to array.Length - 1 do action array.[i] [] - let distinct (array: 'T[]) = + let distinct (array: 'T array) = checkNonNull "array" array let temp = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length let mutable i = 0 @@ -335,10 +338,10 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 i temp [] - let inline map ([] mapping: 'T -> 'U) (array: 'T[]) = + let inline map ([] mapping: 'T -> 'U) (array: 'T array) = checkNonNull "array" array - let res: 'U[] = + let res: 'U array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length for i = 0 to res.Length - 1 do @@ -347,7 +350,7 @@ module Array = res [] - let iter2 action (array1: 'T[]) (array2: 'U[]) = + let iter2 action (array1: 'T array) (array2: 'U array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) @@ -359,7 +362,7 @@ module Array = f.Invoke(array1.[i], array2.[i]) [] - let distinctBy projection (array: 'T[]) = + let distinctBy projection (array: 'T array) = checkNonNull "array" array let length = array.Length @@ -379,7 +382,7 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 i temp [] - let map2 mapping (array1: 'T[]) (array2: 'U[]) = + let map2 mapping (array1: 'T array) (array2: 'U array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) @@ -395,7 +398,7 @@ module Array = res [] - let map3 mapping (array1: 'T1[]) (array2: 'T2[]) (array3: 'T3[]) = + let map3 mapping (array1: 'T1 array) (array2: 'T2 array) (array3: 'T3 array) = checkNonNull "array1" array1 checkNonNull "array2" array2 checkNonNull "array3" array3 @@ -413,7 +416,7 @@ module Array = res [] - let mapi2 mapping (array1: 'T[]) (array2: 'U[]) = + let mapi2 mapping (array1: 'T array) (array2: 'U array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(mapping) @@ -429,7 +432,7 @@ module Array = res [] - let iteri action (array: 'T[]) = + let iteri action (array: 'T array) = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) @@ -437,7 +440,7 @@ module Array = f.Invoke(i, array.[i]) [] - let iteri2 action (array1: 'T[]) (array2: 'U[]) = + let iteri2 action (array1: 'T array) (array2: 'U array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(action) @@ -449,7 +452,7 @@ module Array = f.Invoke(i, array1.[i], array2.[i]) [] - let mapi (mapping: int -> 'T -> 'U) (array: 'T[]) = + let mapi (mapping: int -> 'T -> 'U) (array: 'T array) = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length @@ -470,7 +473,7 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.mapFoldBack mapping array state [] - let inline exists ([] predicate: 'T -> bool) (array: 'T[]) = + let inline exists ([] predicate: 'T -> bool) (array: 'T array) = checkNonNull "array" array let mutable state = false let mutable i = 0 @@ -482,7 +485,7 @@ module Array = state [] - let inline contains value (array: 'T[]) = + let inline contains value (array: 'T array) = checkNonNull "array" array let mutable state = false let mutable i = 0 @@ -494,7 +497,7 @@ module Array = state [] - let exists2 predicate (array1: _[]) (array2: _[]) = + let exists2 predicate (array1: _ array) (array2: _ array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(predicate) @@ -509,7 +512,7 @@ module Array = loop 0 [] - let forall (predicate: 'T -> bool) (array: 'T[]) = + let forall (predicate: 'T -> bool) (array: 'T array) = checkNonNull "array" array let len = array.Length @@ -519,7 +522,7 @@ module Array = loop 0 [] - let forall2 predicate (array1: _[]) (array2: _[]) = + let forall2 predicate (array1: _ array) (array2: _ array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(predicate) @@ -537,7 +540,7 @@ module Array = (comparer: IEqualityComparer<'SafeKey>) ([] keyf: 'T -> 'SafeKey) ([] getKey: 'SafeKey -> 'Key) - (array: 'T[]) + (array: 'T array) = let length = array.Length @@ -570,11 +573,11 @@ module Array = result // We avoid wrapping a StructBox, because under 64 JIT we get some "hard" tailcalls which affect performance - let groupByValueType (keyf: 'T -> 'Key) (array: 'T[]) = + let groupByValueType (keyf: 'T -> 'Key) (array: 'T array) = groupByImpl HashIdentity.Structural<'Key> keyf id array // Wrap a StructBox around all keys in case the key type is itself a type using null as a representation - let groupByRefType (keyf: 'T -> 'Key) (array: 'T[]) = + let groupByRefType (keyf: 'T -> 'Key) (array: 'T array) = groupByImpl RuntimeHelpers.StructBox<'Key>.Comparer (keyf >> RuntimeHelpers.StructBox) @@ -582,7 +585,7 @@ module Array = array [] - let groupBy (projection: 'T -> 'Key) (array: 'T[]) = + let groupBy (projection: 'T -> 'Key) (array: 'T array) = checkNonNull "array" array if typeof<'Key>.IsValueType then @@ -591,7 +594,7 @@ module Array = groupByRefType projection array [] - let pick chooser (array: _[]) = + let pick chooser (array: _ array) = checkNonNull "array" array let rec loop i = @@ -605,7 +608,7 @@ module Array = loop 0 [] - let tryPick chooser (array: _[]) = + let tryPick chooser (array: _ array) = checkNonNull "array" array let rec loop i = @@ -619,7 +622,7 @@ module Array = loop 0 [] - let choose (chooser: 'T -> 'U Option) (array: 'T[]) = + let choose (chooser: 'T -> 'U Option) (array: 'T array) = checkNonNull "array" array let mutable i = 0 @@ -637,7 +640,7 @@ module Array = if i <> array.Length then - let chunk1: 'U[] = + let chunk1: 'U array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked ((array.Length >>> 2) + 1) chunk1.[0] <- first @@ -656,7 +659,7 @@ module Array = i <- i + 1 if i < array.Length then - let chunk2: 'U[] = + let chunk2: 'U array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (array.Length - i) count <- 0 @@ -672,7 +675,7 @@ module Array = i <- i + 1 - let res: 'U[] = + let res: 'U array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (chunk1.Length + count) Array.Copy(chunk1, res, chunk1.Length) @@ -1071,16 +1074,16 @@ module Array = | count -> filterViaMask maskArray leftOverMask count src [] - let filter predicate (array: _[]) = + let filter predicate (array: _ array) = checkNonNull "array" array Filter.filter predicate array [] - let where predicate (array: _[]) = + let where predicate (array: _ array) = filter predicate array [] - let except (itemsToExclude: seq<_>) (array: _[]) = + let except (itemsToExclude: seq<_>) (array: _ array) = checkNonNull "itemsToExclude" itemsToExclude checkNonNull "array" array @@ -1091,7 +1094,7 @@ module Array = array |> filter cached.Add [] - let partition predicate (array: _[]) = + let partition predicate (array: _ array) = checkNonNull "array" array let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length let mutable upCount = 0 @@ -1119,7 +1122,7 @@ module Array = res1, res2 [] - let find predicate (array: _[]) = + let find predicate (array: _ array) = checkNonNull "array" array let rec loop i = @@ -1133,7 +1136,7 @@ module Array = loop 0 [] - let tryFind predicate (array: _[]) = + let tryFind predicate (array: _ array) = checkNonNull "array" array let rec loop i = @@ -1147,7 +1150,7 @@ module Array = loop 0 [] - let skip count (array: 'T[]) = + let skip count (array: 'T array) = checkNonNull "array" array if count > array.Length then @@ -1160,7 +1163,7 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked count (array.Length - count) array [] - let skipWhile predicate (array: 'T[]) = + let skipWhile predicate (array: 'T array) = checkNonNull "array" array let mutable i = 0 @@ -1172,27 +1175,27 @@ module Array = | resLen -> Microsoft.FSharp.Primitives.Basics.Array.subUnchecked i resLen array [] - let findBack predicate (array: _[]) = + let findBack predicate (array: _ array) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.findBack predicate array [] - let tryFindBack predicate (array: _[]) = + let tryFindBack predicate (array: _ array) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.tryFindBack predicate array [] - let findIndexBack predicate (array: _[]) = + let findIndexBack predicate (array: _ array) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.findIndexBack predicate array [] - let tryFindIndexBack predicate (array: _[]) = + let tryFindIndexBack predicate (array: _ array) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.tryFindIndexBack predicate array [] - let windowed windowSize (array: 'T[]) = + let windowed windowSize (array: 'T array) = checkNonNull "array" array if windowSize <= 0 then @@ -1203,7 +1206,7 @@ module Array = if windowSize > len then empty else - let res: 'T[][] = + let res: 'T array array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (len - windowSize + 1) for i = 0 to len - windowSize do @@ -1212,7 +1215,7 @@ module Array = res [] - let chunkBySize chunkSize (array: 'T[]) = + let chunkBySize chunkSize (array: 'T array) = checkNonNull "array" array if chunkSize <= 0 then @@ -1227,7 +1230,7 @@ module Array = else let chunkCount = (len - 1) / chunkSize + 1 - let res: 'T[][] = + let res: 'T array array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked chunkCount for i = 0 to len / chunkSize - 1 do @@ -1243,7 +1246,7 @@ module Array = res [] - let splitInto count (array: _[]) = + let splitInto count (array: _ array) = checkNonNull "array" array if count <= 0 then @@ -1252,7 +1255,7 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.splitInto count array [] - let zip (array1: _[]) (array2: _[]) = + let zip (array1: _ array) (array2: _ array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let len1 = array1.Length @@ -1268,7 +1271,7 @@ module Array = res [] - let zip3 (array1: _[]) (array2: _[]) (array3: _[]) = + let zip3 (array1: _ array) (array2: _ array) (array3: _ array) = checkNonNull "array1" array1 checkNonNull "array2" array2 checkNonNull "array3" array3 @@ -1285,7 +1288,7 @@ module Array = res [] - let allPairs (array1: _[]) (array2: _[]) = + let allPairs (array1: _ array) (array2: _ array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let len1 = array1.Length @@ -1313,7 +1316,7 @@ module Array = res.ToArray() [] - let unzip (array: _[]) = + let unzip (array: _ array) = checkNonNull "array" array let len = array.Length let res1 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len @@ -1327,7 +1330,7 @@ module Array = res1, res2 [] - let unzip3 (array: _[]) = + let unzip3 (array: _ array) = checkNonNull "array" array let len = array.Length let res1 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len @@ -1343,7 +1346,7 @@ module Array = res1, res2, res3 [] - let rev (array: _[]) = + let rev (array: _ array) = checkNonNull "array" array let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length let mutable j = array.Length - 1 @@ -1355,7 +1358,7 @@ module Array = res [] - let fold<'T, 'State> (folder: 'State -> 'T -> 'State) (state: 'State) (array: 'T[]) = + let fold<'T, 'State> (folder: 'State -> 'T -> 'State) (state: 'State) (array: 'T array) = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(folder) let mutable state = state @@ -1366,7 +1369,7 @@ module Array = state [] - let foldBack<'T, 'State> (folder: 'T -> 'State -> 'State) (array: 'T[]) (state: 'State) = + let foldBack<'T, 'State> (folder: 'T -> 'State -> 'State) (array: 'T array) (state: 'State) = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(folder) let mutable res = state @@ -1377,7 +1380,7 @@ module Array = res [] - let foldBack2<'T1, 'T2, 'State> folder (array1: 'T1[]) (array2: 'T2[]) (state: 'State) = + let foldBack2<'T1, 'T2, 'State> folder (array1: 'T1 array) (array2: 'T2 array) (state: 'State) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(folder) @@ -1393,7 +1396,7 @@ module Array = res [] - let fold2<'T1, 'T2, 'State> folder (state: 'State) (array1: 'T1[]) (array2: 'T2[]) = + let fold2<'T1, 'T2, 'State> folder (state: 'State) (array1: 'T1 array) (array2: 'T2 array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(folder) @@ -1407,7 +1410,7 @@ module Array = state - let foldSubRight f (array: _[]) start fin acc = + let foldSubRight f (array: _ array) start fin acc = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) let mutable res = acc @@ -1417,7 +1420,7 @@ module Array = res - let scanSubLeft f initState (array: _[]) start fin = + let scanSubLeft f initState (array: _ array) start fin = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) let mutable state = initState @@ -1430,13 +1433,13 @@ module Array = res [] - let scan<'T, 'State> folder (state: 'State) (array: 'T[]) = + let scan<'T, 'State> folder (state: 'State) (array: 'T array) = checkNonNull "array" array let len = array.Length scanSubLeft folder state array 0 (len - 1) [] - let scanBack<'T, 'State> folder (array: 'T[]) (state: 'State) = + let scanBack<'T, 'State> folder (array: 'T array) (state: 'State) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.scanSubRight folder array 0 (array.Length - 1) state @@ -1445,7 +1448,7 @@ module Array = [| value |] [] - let pairwise (array: 'T[]) = + let pairwise (array: 'T array) = checkNonNull "array" array if array.Length < 2 then @@ -1454,7 +1457,7 @@ module Array = init (array.Length - 1) (fun i -> array.[i], array.[i + 1]) [] - let reduce reduction (array: _[]) = + let reduce reduction (array: _ array) = checkNonNull "array" array let len = array.Length @@ -1470,7 +1473,7 @@ module Array = res [] - let reduceBack reduction (array: _[]) = + let reduceBack reduction (array: _ array) = checkNonNull "array" array let len = array.Length @@ -1480,7 +1483,7 @@ module Array = foldSubRight reduction array 0 (len - 2) array.[len - 1] [] - let sortInPlaceWith comparer (array: 'T[]) = + let sortInPlaceWith comparer (array: 'T array) = checkNonNull "array" array let len = array.Length @@ -1497,17 +1500,17 @@ module Array = Array.Sort(array, ComparisonIdentity.FromFunction(comparer)) [] - let sortInPlaceBy (projection: 'T -> 'U) (array: 'T[]) = + let sortInPlaceBy (projection: 'T -> 'U) (array: 'T array) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.unstableSortInPlaceBy projection array [] - let sortInPlace (array: 'T[]) = + let sortInPlace (array: 'T array) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.unstableSortInPlace array [] - let sortWith (comparer: 'T -> 'T -> int) (array: 'T[]) = + let sortWith (comparer: 'T -> 'T -> int) (array: 'T array) = checkNonNull "array" array let result = copy array sortInPlaceWith comparer result @@ -1556,7 +1559,7 @@ module Array = Seq.toArray source [] - let findIndex predicate (array: _[]) = + let findIndex predicate (array: _ array) = checkNonNull "array" array let len = array.Length @@ -1568,7 +1571,7 @@ module Array = go 0 [] - let tryFindIndex predicate (array: _[]) = + let tryFindIndex predicate (array: _ array) = checkNonNull "array" array let len = array.Length @@ -1580,12 +1583,12 @@ module Array = go 0 [] - let permute indexMap (array: _[]) = + let permute indexMap (array: _ array) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.permute indexMap array [] - let inline sum (array: ^T[]) : ^T = + let inline sum (array: ^T array) : ^T = checkNonNull "array" array let mutable acc = LanguagePrimitives.GenericZero< ^T> @@ -1595,7 +1598,7 @@ module Array = acc [] - let inline sumBy ([] projection: 'T -> ^U) (array: 'T[]) : ^U = + let inline sumBy ([] projection: 'T -> ^U) (array: 'T array) : ^U = checkNonNull "array" array let mutable acc = LanguagePrimitives.GenericZero< ^U> @@ -1605,7 +1608,7 @@ module Array = acc [] - let inline min (array: _[]) = + let inline min (array: _ array) = checkNonNull "array" array if array.Length = 0 then @@ -1622,7 +1625,7 @@ module Array = acc [] - let inline minBy ([] projection) (array: _[]) = + let inline minBy ([] projection) (array: _ array) = checkNonNull "array" array if array.Length = 0 then @@ -1642,7 +1645,7 @@ module Array = accv [] - let inline max (array: _[]) = + let inline max (array: _ array) = checkNonNull "array" array if array.Length = 0 then @@ -1659,7 +1662,7 @@ module Array = acc [] - let inline maxBy projection (array: _[]) = + let inline maxBy projection (array: _ array) = checkNonNull "array" array if array.Length = 0 then @@ -1679,7 +1682,7 @@ module Array = accv [] - let inline average (array: 'T[]) = + let inline average (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -1693,7 +1696,7 @@ module Array = LanguagePrimitives.DivideByInt< ^T> acc array.Length [] - let inline averageBy ([] projection: 'T -> ^U) (array: 'T[]) : ^U = + let inline averageBy ([] projection: 'T -> ^U) (array: 'T array) : ^U = checkNonNull "array" array if array.Length = 0 then @@ -1707,7 +1710,7 @@ module Array = LanguagePrimitives.DivideByInt< ^U> acc array.Length [] - let inline compareWith ([] comparer: 'T -> 'T -> int) (array1: 'T[]) (array2: 'T[]) = + let inline compareWith ([] comparer: 'T -> 'T -> int) (array1: 'T array) (array2: 'T array) = checkNonNull "array1" array1 checkNonNull "array2" array2 @@ -1732,7 +1735,7 @@ module Array = else 1 [] - let sub (array: 'T[]) (startIndex: int) (count: int) = + let sub (array: 'T array) (startIndex: int) (count: int) = checkNonNull "array" array if startIndex < 0 then @@ -1747,11 +1750,11 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked startIndex count array [] - let item index (array: _[]) = + let item index (array: _ array) = array.[index] [] - let tryItem index (array: 'T[]) = + let tryItem index (array: 'T array) = checkNonNull "array" array if index < 0 || index >= array.Length then @@ -1760,15 +1763,15 @@ module Array = Some(array.[index]) [] - let get (array: _[]) index = + let get (array: _ array) index = array.[index] [] - let set (array: _[]) index value = + let set (array: _ array) index value = array.[index] <- value [] - let fill (target: 'T[]) (targetIndex: int) (count: int) (value: 'T) = + let fill (target: 'T array) (targetIndex: int) (count: int) (value: 'T) = checkNonNull "target" target if targetIndex < 0 then @@ -1781,7 +1784,7 @@ module Array = target.[i] <- value [] - let exactlyOne (array: 'T[]) = + let exactlyOne (array: 'T array) = checkNonNull "array" array if array.Length = 1 then @@ -1792,7 +1795,7 @@ module Array = invalidArg "array" (SR.GetString(SR.inputSequenceTooLong)) [] - let tryExactlyOne (array: 'T[]) = + let tryExactlyOne (array: 'T array) = checkNonNull "array" array if array.Length = 1 then @@ -1800,7 +1803,7 @@ module Array = else None - let transposeArrays (array: 'T[][]) = + let transposeArrays (array: 'T array array) = let len = array.Length if len = 0 then @@ -1816,7 +1819,7 @@ module Array = (String.Format("array.[{0}]", j)) array.[j].Length - let result: 'T[][] = + let result: 'T array array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked lenInner for i in 0 .. lenInner - 1 do @@ -1828,15 +1831,15 @@ module Array = result [] - let transpose (arrays: seq<'T[]>) = + let transpose (arrays: seq<'T array>) = checkNonNull "arrays" arrays match arrays with - | :? ('T[][]) as ts -> ts |> transposeArrays // avoid a clone, since we only read the array + | :? ('T array array) as ts -> ts |> transposeArrays // avoid a clone, since we only read the array | _ -> arrays |> Seq.toArray |> transposeArrays [] - let truncate count (array: 'T[]) = + let truncate count (array: 'T array) = checkNonNull "array" array if count <= 0 then @@ -1847,7 +1850,7 @@ module Array = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 count' array [] - let removeAt (index: int) (source: 'T[]) : 'T[] = + let removeAt (index: int) (source: 'T array) : 'T array = checkNonNull "source" source if index < 0 || index >= source.Length then @@ -1865,7 +1868,7 @@ module Array = result [] - let removeManyAt (index: int) (count: int) (source: 'T[]) : 'T[] = + let removeManyAt (index: int) (count: int) (source: 'T array) : 'T array = checkNonNull "source" source if index < 0 || index > source.Length - count then @@ -1883,7 +1886,7 @@ module Array = result [] - let updateAt (index: int) (value: 'T) (source: 'T[]) : 'T[] = + let updateAt (index: int) (value: 'T) (source: 'T array) : 'T array = checkNonNull "source" source if index < 0 || index >= source.Length then @@ -1900,7 +1903,7 @@ module Array = result [] - let insertAt (index: int) (value: 'T) (source: 'T[]) : 'T[] = + let insertAt (index: int) (value: 'T) (source: 'T array) : 'T array = checkNonNull "source" source if index < 0 || index > source.Length then @@ -1920,7 +1923,7 @@ module Array = result [] - let insertManyAt (index: int) (values: seq<'T>) (source: 'T[]) : 'T[] = + let insertManyAt (index: int) (values: seq<'T>) (source: 'T array) : 'T array = checkNonNull "source" source if index < 0 || index > source.Length then @@ -1950,7 +1953,7 @@ module Array = open System.Collections.Concurrent [] - let exists (predicate: 'T -> bool) (array: 'T[]) = + let exists (predicate: 'T -> bool) (array: 'T array) = checkNonNull "array" array Parallel @@ -1965,12 +1968,12 @@ module Array = |> not [] - let forall (predicate: 'T -> bool) (array: 'T[]) = + let forall (predicate: 'T -> bool) (array: 'T array) = // Not exists $condition <==> (opposite of $condition is true forall) exists (predicate >> not) array |> not [] - let tryFindIndex predicate (array: _[]) = + let tryFindIndex predicate (array: _ array) = checkNonNull "array" array let pResult = @@ -1985,11 +1988,11 @@ module Array = pResult.LowestBreakIteration |> Option.ofNullable |> Option.map int [] - let tryFind predicate (array: _[]) = + let tryFind predicate (array: _ array) = array |> tryFindIndex predicate |> Option.map (fun i -> array[i]) [] - let tryPick chooser (array: _[]) = + let tryPick chooser (array: _ array) = checkNonNull "array" array let allChosen = new System.Collections.Concurrent.ConcurrentDictionary<_, _>() @@ -2010,14 +2013,14 @@ module Array = |> Option.bind (fun i -> allChosen[int i]) [] - let choose chooser (array: 'T[]) = + let choose chooser (array: 'T array) = checkNonNull "array" array let inputLength = array.Length - let isChosen: bool[] = + let isChosen: bool array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength - let results: 'U[] = + let results: 'U array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength let mutable outputLength = 0 @@ -2050,7 +2053,7 @@ module Array = output [] - let collect (mapping: 'T -> 'U[]) (array: 'T[]) : 'U[] = + let collect (mapping: 'T -> 'U array) (array: 'T array) : 'U array = checkNonNull "array" array let inputLength = array.Length @@ -2063,7 +2066,7 @@ module Array = concatArrays result [] - let map (mapping: 'T -> 'U) (array: 'T[]) : 'U[] = + let map (mapping: 'T -> 'U) (array: 'T array) : 'U array = checkNonNull "array" array let inputLength = array.Length @@ -2076,7 +2079,7 @@ module Array = result [] - let mapi mapping (array: 'T[]) = + let mapi mapping (array: 'T array) = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) let inputLength = array.Length @@ -2094,7 +2097,7 @@ module Array = let private maxPartitions = Environment.ProcessorCount // The maximum number of partitions to use let private minChunkSize = 256 // The minimum size of a chunk to be sorted in parallel - let private createPartitionsUpToWithMinChunkSize maxIdxExclusive minChunkSize (array: 'T[]) = + let private createPartitionsUpToWithMinChunkSize maxIdxExclusive minChunkSize (array: 'T array) = [| let chunkSize = match maxIdxExclusive with @@ -2111,13 +2114,13 @@ module Array = yield new ArraySegment<'T>(array, offset, maxIdxExclusive - offset) |] - let private createPartitionsUpTo maxIdxExclusive (array: 'T[]) = + let private createPartitionsUpTo maxIdxExclusive (array: 'T array) = createPartitionsUpToWithMinChunkSize maxIdxExclusive minChunkSize array (* This function is there also as a support vehicle for other aggregations. It is public in order to be called from inlined functions, the benefit of inlining call into it is significant *) [] - let reduceBy (projection: 'T -> 'U) (reduction: 'U -> 'U -> 'U) (array: 'T[]) = + let reduceBy (projection: 'T -> 'U) (reduction: 'U -> 'U -> 'U) (array: 'T array) = checkNonNull "array" array if array.Length = 0 then @@ -2152,7 +2155,7 @@ module Array = finalResult [] - let inline reduce ([] reduction) (array: _[]) = + let inline reduce ([] reduction) (array: _ array) = array |> reduceBy id reduction let inline vFst struct (a, _) = @@ -2162,49 +2165,49 @@ module Array = b [] - let inline minBy ([] projection) (array: _[]) = + let inline minBy ([] projection) (array: _ array) = array |> reduceBy (fun x -> struct (projection x, x)) (fun a b -> if vFst a < vFst b then a else b) |> vSnd [] - let inline min (array: _[]) = + let inline min (array: _ array) = array |> reduce (fun a b -> if a < b then a else b) [] - let inline sumBy ([] projection: 'T -> ^U) (array: 'T[]) : ^U = + let inline sumBy ([] projection: 'T -> ^U) (array: 'T array) : ^U = if array.Length = 0 then LanguagePrimitives.GenericZero else array |> reduceBy projection Operators.Checked.(+) [] - let inline sum (array: ^T[]) : ^T = + let inline sum (array: ^T array) : ^T = array |> sumBy id [] - let inline maxBy projection (array: _[]) = + let inline maxBy projection (array: _ array) = array |> reduceBy (fun x -> struct (projection x, x)) (fun a b -> if vFst a > vFst b then a else b) |> vSnd [] - let inline max (array: _[]) = + let inline max (array: _ array) = array |> reduce (fun a b -> if a > b then a else b) [] - let inline averageBy ([] projection: 'T -> ^U) (array: 'T[]) : ^U = + let inline averageBy ([] projection: 'T -> ^U) (array: 'T array) : ^U = let sum = array |> reduceBy projection Operators.Checked.(+) LanguagePrimitives.DivideByInt sum (array.Length) [] - let inline average (array: 'T[]) = + let inline average (array: 'T array) = array |> averageBy id [] - let zip (array1: _[]) (array2: _[]) = + let zip (array1: _ array) (array2: _ array) = checkNonNull "array1" array1 checkNonNull "array2" array2 let len1 = array1.Length @@ -2232,7 +2235,7 @@ module Array = (comparer: IEqualityComparer<'SafeKey>) ([] keyf: 'T -> 'SafeKey) ([] getKey: 'SafeKey -> 'Key) - (array: 'T[]) + (array: 'T array) = let counts = new ConcurrentDictionary<_, _>( @@ -2268,7 +2271,7 @@ module Array = let mutable finalIdx = 0 let finalResultsLookup = - new Dictionary<'SafeKey, int ref * 'T[]>(capacity = counts.Count, comparer = comparer) + new Dictionary<'SafeKey, int ref * 'T array>(capacity = counts.Count, comparer = comparer) for kvp in counts do let arrayForThisGroup = @@ -2294,7 +2297,7 @@ module Array = finalResults - let groupByValueTypeParallel (keyf: 'T -> 'Key) (array: 'T[]) = + let groupByValueTypeParallel (keyf: 'T -> 'Key) (array: 'T array) = // Is it a bad idea to put floating points as keys for grouping? Yes // But would the implementation fail with KeyNotFound "nan" if we just leave it? Also yes // Here we enforce nan=nan equality to prevent throwing @@ -2310,7 +2313,7 @@ module Array = // Just like in regular Array.groupBy: Wrap a StructBox around all keys in order to avoid nulls // (dotnet doesn't allow null keys in dictionaries) - let groupByRefTypeParallel (keyf: 'T -> 'Key) (array: 'T[]) = + let groupByRefTypeParallel (keyf: 'T -> 'Key) (array: 'T array) = groupByImplParallel RuntimeHelpers.StructBox<'Key>.Comparer (keyf >> RuntimeHelpers.StructBox) @@ -2318,7 +2321,7 @@ module Array = array [] - let groupBy (projection: 'T -> 'Key) (array: 'T[]) = + let groupBy (projection: 'T -> 'Key) (array: 'T array) = checkNonNull "array" array if typeof<'Key>.IsValueType then @@ -2327,12 +2330,12 @@ module Array = groupByRefTypeParallel projection array [] - let iter action (array: 'T[]) = + let iter action (array: 'T array) = checkNonNull "array" array Parallel.For(0, array.Length, (fun i -> action array.[i])) |> ignore [] - let iteri action (array: 'T[]) = + let iteri action (array: 'T array) = checkNonNull "array" array let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) Parallel.For(0, array.Length, (fun i -> f.Invoke(i, array.[i]))) |> ignore @@ -2343,7 +2346,7 @@ module Array = Parallel.For(0, count, (fun i -> result.[i] <- initializer i)) |> ignore result - let countAndCollectTrueItems predicate (array: 'T[]) = + let countAndCollectTrueItems predicate (array: 'T array) = checkNonNull "array" array let inputLength = array.Length @@ -2369,7 +2372,7 @@ module Array = trueLength, isTrue [] - let filter predicate (array: 'T[]) = + let filter predicate (array: 'T array) = let trueLength, isTrue = countAndCollectTrueItems predicate array let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked trueLength let mutable resIdx = 0 @@ -2382,7 +2385,7 @@ module Array = res [] - let partition predicate (array: 'T[]) = + let partition predicate (array: 'T array) = let trueLength, isTrue = countAndCollectTrueItems predicate array let res1 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked trueLength @@ -2402,7 +2405,7 @@ module Array = res1, res2 - let private createPartitions (array: 'T[]) = + let private createPartitions (array: 'T array) = createPartitionsUpTo array.Length array let inline pickPivot @@ -2472,7 +2475,7 @@ module Array = let pivotItem = array[pivotIdx] partitionIntoTwo (fun idx -> cmp array[idx] pivotItem) swap orig - let partitionIntoTwoUsingKeys (keys: 'A[]) (orig: ArraySegment<'T>) : ArraySegment<'T> * ArraySegment<'T> = + let partitionIntoTwoUsingKeys (keys: 'A array) (orig: ArraySegment<'T>) : ArraySegment<'T> * ArraySegment<'T> = let array = orig.Array let inline swap i j = @@ -2490,7 +2493,7 @@ module Array = partitionIntoTwo (fun idx -> compare keys[idx] pivotKey) swap orig let inline sortInPlaceHelper - (array: 'T[]) + (array: 'T array) ([] partitioningFunc: ArraySegment<'T> -> ArraySegment<'T> * ArraySegment<'T>) ([] sortingFunc: ArraySegment<'T> -> unit) = @@ -2526,7 +2529,7 @@ module Array = let sortInPlaceWithHelper (partitioningComparer: 'T -> 'T -> int) (sortingComparer: IComparer<'T>) - (inputArray: 'T[]) + (inputArray: 'T array) = let partitioningFunc = partitionIntoTwoUsingComparer partitioningComparer @@ -2535,7 +2538,7 @@ module Array = sortInPlaceHelper inputArray partitioningFunc sortingFunc - let sortKeysAndValuesInPlace (inputKeys: 'TKey[]) (values: 'TValue[]) = + let sortKeysAndValuesInPlace (inputKeys: 'TKey array) (values: 'TValue array) = let partitioningFunc = partitionIntoTwoUsingKeys inputKeys let sortingComparer = LanguagePrimitives.FastGenericComparerCanBeNull<'TKey> @@ -2546,16 +2549,16 @@ module Array = sortInPlaceHelper values partitioningFunc sortingFunc [] - let sortInPlaceWith comparer (array: 'T[]) = + let sortInPlaceWith comparer (array: 'T array) = checkNonNull "array" array let sortingComparer = ComparisonIdentity.FromFunction(comparer) sortInPlaceWithHelper comparer sortingComparer array [] - let sortInPlaceBy (projection: 'T -> 'U) (array: 'T[]) = + let sortInPlaceBy (projection: 'T -> 'U) (array: 'T array) = checkNonNull "array" array - let inputKeys: 'U[] = + let inputKeys: 'U array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length let partitions = createPartitions array @@ -2574,7 +2577,7 @@ module Array = sortKeysAndValuesInPlace inputKeys array [] - let sortInPlace (array: 'T[]) = + let sortInPlace (array: 'T array) = checkNonNull "array" array let sortingComparer: IComparer<'T> = @@ -2584,13 +2587,13 @@ module Array = sortInPlaceWithHelper partioningFunc sortingComparer array [] - let sortWith (comparer: 'T -> 'T -> int) (array: 'T[]) = + let sortWith (comparer: 'T -> 'T -> int) (array: 'T array) = let result = copy array sortInPlaceWith comparer result result [] - let sortBy projection (array: 'T[]) = + let sortBy projection (array: 'T array) = checkNonNull "array" array let inputKeys = @@ -2622,7 +2625,7 @@ module Array = sortInPlace result result - let reverseInPlace (array: 'T[]) = + let reverseInPlace (array: 'T array) = let segments = createPartitionsUpTo (array.Length / 2) array let lastIdx = array.Length - 1 diff --git a/src/FSharp.Core/array.fsi b/src/FSharp.Core/array.fsi index 7ac42219058..8a5d51f0c9e 100644 --- a/src/FSharp.Core/array.fsi +++ b/src/FSharp.Core/array.fsi @@ -35,7 +35,7 @@ module Array = /// /// [] - val allPairs: array1: 'T1[] -> array2: 'T2[] -> ('T1 * 'T2)[] + val allPairs: array1: 'T1 array -> array2: 'T2 array -> ('T1 * 'T2) array /// Builds a new array that contains the elements of the first array followed by the elements of the second array. /// @@ -53,7 +53,7 @@ module Array = /// Evaluates to [| 1; 2; 3; 4 |]. /// [] - val append: array1: 'T[] -> array2: 'T[] -> 'T[] + val append: array1: 'T array -> array2: 'T array -> 'T array /// Returns the average of the elements in the array. /// @@ -79,7 +79,7 @@ module Array = /// [] val inline average: - array: ^T[] -> ^T + array: ^T array -> ^T when ^T: (static member (+): ^T * ^T -> ^T) and ^T: (static member DivideByInt: ^T * int -> ^T) and ^T: (static member Zero: ^T) @@ -110,7 +110,7 @@ module Array = /// /// type Foo = { Bar: float } /// - /// let input : Foo[] = [| |] + /// let input : Foo array = [| |] /// /// input |> Array.averageBy (fun foo -> foo.Bar) /// @@ -118,7 +118,7 @@ module Array = /// [] val inline averageBy: - projection: ('T -> ^U) -> array: 'T[] -> ^U + projection: ('T -> ^U) -> array: 'T array -> ^U when ^U: (static member (+): ^U * ^U -> ^U) and ^U: (static member DivideByInt: ^U * int -> ^U) and ^U: (static member Zero: ^U) @@ -154,7 +154,7 @@ module Array = /// After evaluation target contains [| 0; 1; 2; 13; 14; 5 |]. /// [] - val inline blit: source: 'T[] -> sourceIndex: int -> target: 'T[] -> targetIndex: int -> count: int -> unit + val inline blit: source: 'T array -> sourceIndex: int -> target: 'T array -> targetIndex: int -> count: int -> unit /// For each element of the array, applies the given function. Concatenates all the results and return the combined array. /// @@ -167,7 +167,7 @@ module Array = /// /// /// - /// type Foo = { Bar: int[] } + /// type Foo = { Bar: int array } /// /// let input = [| {Bar = [| 1; 2 |]}; {Bar = [| 3; 4 |]} |] /// @@ -185,7 +185,7 @@ module Array = /// Evaluates to [| 1; 2; 3; 4 |] /// [] - val collect: mapping: ('T -> 'U[]) -> array: 'T[] -> 'U[] + val collect: mapping: ('T -> 'U array) -> array: 'T array -> 'U array /// Compares two arrays using the given comparison function, element by element. /// @@ -268,7 +268,7 @@ module Array = /// Evaluates to -1 /// [] - val inline compareWith: comparer: ('T -> 'T -> int) -> array1: 'T[] -> array2: 'T[] -> int + val inline compareWith: comparer: ('T -> 'T -> int) -> array1: 'T array -> array2: 'T array -> int /// Builds a new array that contains the elements of each of the given sequence of arrays. /// @@ -287,7 +287,7 @@ module Array = /// Evaluates to [| 1; 2; 3; 4; 5 |] /// [] - val concat: arrays: seq<'T[]> -> 'T[] + val concat: arrays: seq<'T array> -> 'T array /// Tests if the array contains the specified element. /// @@ -305,7 +305,7 @@ module Array = /// /// [] - val inline contains: value: 'T -> array: 'T[] -> bool when 'T: equality + val inline contains: value: 'T -> array: 'T array -> bool when 'T: equality /// Builds a new array that contains the elements of the given array. /// @@ -324,7 +324,7 @@ module Array = /// Evaluates to a new array containing[| 12; 13; 14 |]. /// [] - val copy: array: 'T[] -> 'T[] + val copy: array: 'T array -> 'T array /// Applies a key-generating function to each element of an array and returns an array yielding unique /// keys and their number of occurrences in the original array. @@ -348,7 +348,7 @@ module Array = /// Evaluates to [| ("a", 2); ("b", 1) |] /// [] - val countBy: projection: ('T -> 'Key) -> array: 'T[] -> ('Key * int)[] when 'Key: equality + val countBy: projection: ('T -> 'Key) -> array: 'T array -> ('Key * int) array when 'Key: equality /// Creates an array whose elements are all initially the given value. /// @@ -378,7 +378,7 @@ module Array = /// Note each entry in the array is the same mutable cell object. /// [] - val create: count: int -> value: 'T -> 'T[] + val create: count: int -> value: 'T -> 'T array /// Returns the first element of the array, or /// None if the array is empty. @@ -400,14 +400,14 @@ module Array = /// /// /// - /// let inputs : int[] = [| |] + /// let inputs : int array = [| |] /// /// inputs |> Array.tryHead /// /// Evaluates to None /// [] - val tryHead: array: 'T[] -> 'T option + val tryHead: array: 'T array -> 'T option /// Applies the given function to successive elements, returning the first /// result where the function returns Some(x) for some x. If the function @@ -439,7 +439,7 @@ module Array = /// /// [] - val tryPick: chooser: ('T -> 'U option) -> array: 'T[] -> 'U option + val tryPick: chooser: ('T -> 'U option) -> array: 'T array -> 'U option /// Fills a range of elements of the array with the given value. /// @@ -460,7 +460,7 @@ module Array = /// After evaluation target contains [| 0; 1; 2; 100; 100; 5 |]. /// [] - val fill: target: 'T[] -> targetIndex: int -> count: int -> value: 'T -> unit + val fill: target: 'T array -> targetIndex: int -> count: int -> value: 'T -> unit /// Applies the given function to successive elements, returning the first /// result where the function returns Some(x) for some x. If the function @@ -494,7 +494,7 @@ module Array = /// /// [] - val pick: chooser: ('T -> 'U option) -> array: 'T[] -> 'U + val pick: chooser: ('T -> 'U option) -> array: 'T array -> 'U /// Applies the given function to each element of the array. Returns /// the array comprised of the results x for each element where @@ -525,7 +525,7 @@ module Array = /// Evaluates to [| 2 |] /// [] - val choose: chooser: ('T -> 'U option) -> array: 'T[] -> 'U[] + val choose: chooser: ('T -> 'U option) -> array: 'T array -> 'U array /// Divides the input array into chunks of size at most chunkSize. /// @@ -555,7 +555,7 @@ module Array = /// Throws ArgumentException /// [] - val chunkBySize: chunkSize: int -> array: 'T[] -> 'T[][] + val chunkBySize: chunkSize: int -> array: 'T array -> 'T array array /// Returns an array that contains no duplicate entries according to generic hash and /// equality comparisons on the entries. @@ -576,7 +576,7 @@ module Array = /// Evaluates to [| 1; 2; 3 |] /// [] - val distinct: array: 'T[] -> 'T[] when 'T: equality + val distinct: array: 'T array -> 'T array when 'T: equality /// Returns an array that contains no duplicate entries according to the /// generic hash and equality comparisons on the keys returned by the given key-generating function. @@ -598,7 +598,7 @@ module Array = /// Evaluates to [| { Bar = 1 }; { Bar = 2 }; { Bar = 3 } |] /// [] - val distinctBy: projection: ('T -> 'Key) -> array: 'T[] -> 'T[] when 'Key: equality + val distinctBy: projection: ('T -> 'Key) -> array: 'T array -> 'T array when 'Key: equality /// Splits the input array into at most count chunks. /// @@ -628,7 +628,7 @@ module Array = /// Throws ArgumentException /// [] - val splitInto: count: int -> array: 'T[] -> 'T[][] + val splitInto: count: int -> array: 'T array -> 'T array array /// Returns an empty array of the given type. /// The empty array. @@ -640,7 +640,7 @@ module Array = /// [] [] - val empty<'T> : 'T[] + val empty<'T> : 'T array /// Returns the only element of the array. /// @@ -671,14 +671,14 @@ module Array = /// /// /// - /// let inputs: int[] = [| |] + /// let inputs: int array = [| |] /// /// inputs |> Array.exactlyOne /// /// Throws ArgumentException /// [] - val exactlyOne: array: 'T[] -> 'T + val exactlyOne: array: 'T array -> 'T /// Returns the only element of the array or None if array is empty or contains more than one element. /// @@ -708,14 +708,14 @@ module Array = /// /// /// - /// let inputs: int[] = [| |] + /// let inputs: int array = [| |] /// /// inputs |> Array.tryExactlyOne /// /// Evaluates to None /// [] - val tryExactlyOne: array: 'T[] -> 'T option + val tryExactlyOne: array: 'T array -> 'T option /// Returns a new list with the distinct elements of the input array which do not appear in the itemsToExclude sequence, /// using generic hash and equality comparisons to compare values. @@ -738,7 +738,7 @@ module Array = /// Evaluates to [| 2; 4 |] /// [] - val except: itemsToExclude: seq<'T> -> array: 'T[] -> 'T[] when 'T: equality + val except: itemsToExclude: seq<'T> -> array: 'T array -> 'T array when 'T: equality /// Tests if any element of the array satisfies the given predicate. /// @@ -771,7 +771,7 @@ module Array = /// Evaluates to false /// [] - val inline exists: predicate: ('T -> bool) -> array: 'T[] -> bool + val inline exists: predicate: ('T -> bool) -> array: 'T array -> bool /// Tests if any pair of corresponding elements of the arrays satisfies the given predicate. /// @@ -810,7 +810,7 @@ module Array = /// Evaluates to true /// [] - val exists2: predicate: ('T1 -> 'T2 -> bool) -> array1: 'T1[] -> array2: 'T2[] -> bool + val exists2: predicate: ('T1 -> 'T2 -> bool) -> array1: 'T1 array -> array2: 'T2 array -> bool /// Returns a new collection containing only the elements of the collection /// for which the given predicate returns "true". @@ -831,7 +831,7 @@ module Array = /// Evaluates to [| 2; 4 |] /// [] - val filter: predicate: ('T -> bool) -> array: 'T[] -> 'T[] + val filter: predicate: ('T -> bool) -> array: 'T array -> 'T array /// Returns the first element for which the given function returns 'true'. /// Raise if no such element exists. @@ -863,7 +863,7 @@ module Array = /// Throws KeyNotFoundException /// [] - val find: predicate: ('T -> bool) -> array: 'T[] -> 'T + val find: predicate: ('T -> bool) -> array: 'T array -> 'T /// Returns the last element for which the given function returns 'true'. /// Raise if no such element exists. @@ -895,7 +895,7 @@ module Array = /// Throws KeyNotFoundException /// [] - val findBack: predicate: ('T -> bool) -> array: 'T[] -> 'T + val findBack: predicate: ('T -> bool) -> array: 'T array -> 'T /// Returns the index of the first element in the array /// that satisfies the given predicate. Raise if @@ -927,7 +927,7 @@ module Array = /// Throws KeyNotFoundException /// [] - val findIndex: predicate: ('T -> bool) -> array: 'T[] -> int + val findIndex: predicate: ('T -> bool) -> array: 'T array -> int /// Returns the index of the last element in the array /// that satisfies the given predicate. Raise if @@ -960,7 +960,7 @@ module Array = /// Throws KeyNotFoundException /// [] - val findIndexBack: predicate: ('T -> bool) -> array: 'T[] -> int + val findIndexBack: predicate: ('T -> bool) -> array: 'T array -> int /// Tests if all elements of the array satisfy the given predicate. /// @@ -985,7 +985,7 @@ module Array = /// /// [] - val forall: predicate: ('T -> bool) -> array: 'T[] -> bool + val forall: predicate: ('T -> bool) -> array: 'T array -> bool /// Tests if all corresponding elements of the array satisfy the given predicate pairwise. /// @@ -1034,7 +1034,7 @@ module Array = /// Throws ArgumentException. /// [] - val forall2: predicate: ('T1 -> 'T2 -> bool) -> array1: 'T1[] -> array2: 'T2[] -> bool + val forall2: predicate: ('T1 -> 'T2 -> bool) -> array1: 'T1 array -> array2: 'T2 array -> bool /// Applies a function to each element of the collection, threading an accumulator argument /// through the computation. If the input function is f and the elements are i0...iN then computes @@ -1064,7 +1064,7 @@ module Array = /// Evaluates to 2 /// [] - val fold<'T, 'State> : folder: ('State -> 'T -> 'State) -> state: 'State -> array: 'T[] -> 'State + val fold<'T, 'State> : folder: ('State -> 'T -> 'State) -> state: 'State -> array: 'T array -> 'State /// Applies a function to each element of the array, starting from the end, threading an accumulator argument /// through the computation. If the input function is f and the elements are i0...iN then computes @@ -1107,7 +1107,7 @@ module Array = /// /// [] - val foldBack<'T, 'State> : folder: ('T -> 'State -> 'State) -> array: 'T[] -> state: 'State -> 'State + val foldBack<'T, 'State> : folder: ('T -> 'State -> 'State) -> array: 'T array -> state: 'State -> 'State /// Applies a function to pairs of elements drawn from the two collections, /// left-to-right, threading an accumulator argument @@ -1142,7 +1142,7 @@ module Array = /// [] val fold2<'T1, 'T2, 'State> : - folder: ('State -> 'T1 -> 'T2 -> 'State) -> state: 'State -> array1: 'T1[] -> array2: 'T2[] -> 'State + folder: ('State -> 'T1 -> 'T2 -> 'State) -> state: 'State -> array1: 'T1 array -> array2: 'T2 array -> 'State /// Apply a function to pairs of elements drawn from the two collections, right-to-left, /// threading an accumulator argument through the computation. The two input @@ -1191,7 +1191,7 @@ module Array = /// [] val foldBack2<'T1, 'T2, 'State> : - folder: ('T1 -> 'T2 -> 'State -> 'State) -> array1: 'T1[] -> array2: 'T2[] -> state: 'State -> 'State + folder: ('T1 -> 'T2 -> 'State -> 'State) -> array1: 'T1 array -> array2: 'T2 array -> state: 'State -> 'State /// Gets an element from an array. /// @@ -1223,7 +1223,7 @@ module Array = /// Throws IndexOutOfRangeException /// [] - val get: array: 'T[] -> index: int -> 'T + val get: array: 'T array -> index: int -> 'T /// Returns the first element of the array. /// @@ -1250,7 +1250,7 @@ module Array = /// Throws ArgumentException /// [] - val head: array: 'T[] -> 'T + val head: array: 'T array -> 'T /// Applies a key-generating function to each element of an array and yields an array of /// unique keys. Each unique key contains an array of all elements that match @@ -1272,7 +1272,7 @@ module Array = /// Evaluates to [| (1, [| 1; 3; 5 |]); (0, [| 2; 4 |]) |] /// [] - val groupBy: projection: ('T -> 'Key) -> array: 'T[] -> ('Key * 'T[])[] when 'Key: equality + val groupBy: projection: ('T -> 'Key) -> array: 'T array -> ('Key * 'T array) array when 'Key: equality /// Builds a new array whose elements are the corresponding elements of the input array /// paired with the integer index (from 0) of each element. @@ -1292,7 +1292,7 @@ module Array = /// Evaluates to [| (0, "a"); (1, "b"); (2, "c") |] /// [] - val indexed: array: 'T[] -> (int * 'T)[] + val indexed: array: 'T array -> (int * 'T) array /// Creates an array given the dimension and a generator function to compute the elements. /// @@ -1317,7 +1317,7 @@ module Array = /// Throws ArgumentException /// [] - val inline init: count: int -> initializer: (int -> 'T) -> 'T[] + val inline init: count: int -> initializer: (int -> 'T) -> 'T array /// Creates an array where the entries are initially the default value Unchecked.defaultof<'T>. /// @@ -1329,12 +1329,12 @@ module Array = /// /// /// - /// let arr : int[] = Array.zeroCreate 4 + /// let arr : int array = Array.zeroCreate 4 /// /// Evaluates to [| 0; 0; 0; 0 |] /// [] - val zeroCreate: count: int -> 'T[] + val zeroCreate: count: int -> 'T array /// Returns true if the given array is empty, otherwise false. /// @@ -1358,7 +1358,7 @@ module Array = /// Evaluates to false /// [] - val isEmpty: array: 'T[] -> bool + val isEmpty: array: 'T array -> bool /// Applies the given function to each element of the array. /// @@ -1382,7 +1382,7 @@ module Array = /// in the console. /// [] - val inline iter: action: ('T -> unit) -> array: 'T[] -> unit + val inline iter: action: ('T -> unit) -> array: 'T array -> unit /// Applies the given function to pair of elements drawn from matching indices in two arrays. The /// two arrays must have the same lengths, otherwise an ArgumentException is @@ -1411,7 +1411,7 @@ module Array = /// in the console. /// [] - val iter2: action: ('T1 -> 'T2 -> unit) -> array1: 'T1[] -> array2: 'T2[] -> unit + val iter2: action: ('T1 -> 'T2 -> unit) -> array1: 'T1 array -> array2: 'T2 array -> unit /// Applies the given function to each element of the array. The integer passed to the /// function indicates the index of element. @@ -1436,7 +1436,7 @@ module Array = /// in the console. /// [] - val iteri: action: (int -> 'T -> unit) -> array: 'T[] -> unit + val iteri: action: (int -> 'T -> unit) -> array: 'T array -> unit /// Applies the given function to pair of elements drawn from matching indices in two arrays, /// also passing the index of the elements. The two arrays must have the same lengths, @@ -1465,7 +1465,7 @@ module Array = /// in the console. /// [] - val iteri2: action: (int -> 'T1 -> 'T2 -> unit) -> array1: 'T1[] -> array2: 'T2[] -> unit + val iteri2: action: (int -> 'T1 -> 'T2 -> unit) -> array1: 'T1 array -> array2: 'T2 array -> unit /// Returns the last element of the array. /// @@ -1490,7 +1490,7 @@ module Array = /// Throws ArgumentException /// [] - val inline last: array: 'T[] -> 'T + val inline last: array: 'T array -> 'T /// Gets an element from an array. /// @@ -1522,7 +1522,7 @@ module Array = /// Throws ArgumentException /// [] - val item: index: int -> array: 'T[] -> 'T + val item: index: int -> array: 'T array -> 'T /// Returns the length of an array. You can also use property arr.Length. /// @@ -1543,7 +1543,7 @@ module Array = /// Evaluates to 3 /// [] - val length: array: 'T[] -> int + val length: array: 'T array -> int /// Returns the last element of the array. /// Return None if no such element exists. @@ -1568,7 +1568,7 @@ module Array = /// Evaluates to None /// [] - val tryLast: array: 'T[] -> 'T option + val tryLast: array: 'T array -> 'T option /// Builds a new array whose elements are the results of applying the given function /// to each of the elements of the array. @@ -1589,7 +1589,7 @@ module Array = /// Evaluates to [| 1; 3; 2 |] /// [] - val inline map: mapping: ('T -> 'U) -> array: 'T[] -> 'U[] + val inline map: mapping: ('T -> 'U) -> array: 'T array -> 'U array /// Builds a new collection whose elements are the results of applying the given function /// to the corresponding elements of the two collections pairwise. The two input @@ -1615,7 +1615,7 @@ module Array = /// Evaluates to [| 'a'; 'd'; 'o' |] /// [] - val map2: mapping: ('T1 -> 'T2 -> 'U) -> array1: 'T1[] -> array2: 'T2[] -> 'U[] + val map2: mapping: ('T1 -> 'T2 -> 'U) -> array1: 'T1 array -> array2: 'T2 array -> 'U array /// Combines map and fold. Builds a new array whose elements are the results of applying the given function /// to each of the elements of the input array. The function is also used to accumulate a final value. @@ -1646,7 +1646,7 @@ module Array = /// [] val mapFold<'T, 'State, 'Result> : - mapping: ('State -> 'T -> 'Result * 'State) -> state: 'State -> array: 'T[] -> 'Result[] * 'State + mapping: ('State -> 'T -> 'Result * 'State) -> state: 'State -> array: 'T array -> 'Result array * 'State /// Combines map and foldBack. Builds a new array whose elements are the results of applying the given function /// to each of the elements of the input array. The function is also used to accumulate a final value. @@ -1677,7 +1677,7 @@ module Array = /// [] val mapFoldBack<'T, 'State, 'Result> : - mapping: ('T -> 'State -> 'Result * 'State) -> array: 'T[] -> state: 'State -> 'Result[] * 'State + mapping: ('T -> 'State -> 'Result * 'State) -> array: 'T array -> state: 'State -> 'Result array * 'State /// Builds a new collection whose elements are the results of applying the given function /// to the corresponding triples from the three collections. The three input @@ -1706,7 +1706,8 @@ module Array = /// /// [] - val map3: mapping: ('T1 -> 'T2 -> 'T3 -> 'U) -> array1: 'T1[] -> array2: 'T2[] -> array3: 'T3[] -> 'U[] + val map3: + mapping: ('T1 -> 'T2 -> 'T3 -> 'U) -> array1: 'T1 array -> array2: 'T2 array -> array3: 'T3 array -> 'U array /// Builds a new collection whose elements are the results of applying the given function /// to the corresponding elements of the two collections pairwise, also passing the index of @@ -1732,7 +1733,7 @@ module Array = /// Evaluates to [|(0, 'a'); (1, 'd'); (2, 'o')|] /// [] - val mapi2: mapping: (int -> 'T1 -> 'T2 -> 'U) -> array1: 'T1[] -> array2: 'T2[] -> 'U[] + val mapi2: mapping: (int -> 'T1 -> 'T2 -> 'U) -> array1: 'T1 array -> array2: 'T2 array -> 'U array /// Builds a new array whose elements are the results of applying the given function /// to each of the elements of the array. The integer index passed to the @@ -1754,7 +1755,7 @@ module Array = /// Evaluates to [| 10; 11; 12 |] /// [] - val mapi: mapping: (int -> 'T -> 'U) -> array: 'T[] -> 'U[] + val mapi: mapping: (int -> 'T -> 'U) -> array: 'T array -> 'U array /// Returns the greatest of all elements of the array, compared via Operators.max on the function result. /// @@ -1778,14 +1779,14 @@ module Array = /// /// /// - /// let inputs: int[]= [| |] + /// let inputs: int array= [| |] /// /// inputs |> Array.max /// /// Throws System.ArgumentException. /// [] - val inline max: array: 'T[] -> 'T when 'T: comparison + val inline max: array: 'T array -> 'T when 'T: comparison /// Returns the greatest of all elements of the array, compared via Operators.max on the function result. /// @@ -1810,14 +1811,14 @@ module Array = /// /// /// - /// let inputs: string[]= [| |] + /// let inputs: string array= [| |] /// /// inputs |> Array.maxBy (fun s -> s.Length) /// /// Throws System.ArgumentException. /// [] - val inline maxBy: projection: ('T -> 'U) -> array: 'T[] -> 'T when 'U: comparison + val inline maxBy: projection: ('T -> 'U) -> array: 'T array -> 'T when 'U: comparison /// Returns the lowest of all elements of the array, compared via Operators.min. /// @@ -1841,14 +1842,14 @@ module Array = /// /// /// - /// let inputs: int[]= [| |] + /// let inputs: int array= [| |] /// /// inputs |> Array.min /// /// Throws System.ArgumentException. /// [] - val inline min: array: 'T[] -> 'T when 'T: comparison + val inline min: array: 'T array -> 'T when 'T: comparison /// Returns the lowest of all elements of the array, compared via Operators.min on the function result. /// @@ -1873,14 +1874,14 @@ module Array = /// /// /// - /// let inputs: string[]= [| |] + /// let inputs: string array= [| |] /// /// inputs |> Array.minBy (fun s -> s.Length) /// /// Throws System.ArgumentException. /// [] - val inline minBy: projection: ('T -> 'U) -> array: 'T[] -> 'T when 'U: comparison + val inline minBy: projection: ('T -> 'U) -> array: 'T array -> 'T when 'U: comparison /// Builds an array from the given list. /// @@ -1897,7 +1898,7 @@ module Array = /// Evaluates to [| 1; 2; 5 |]. /// [] - val ofList: list: 'T list -> 'T[] + val ofList: list: 'T list -> 'T array /// Builds a new array from the given enumerable object. /// @@ -1916,7 +1917,7 @@ module Array = /// Evaluates to [| 1; 2; 5 |]. /// [] - val ofSeq: source: seq<'T> -> 'T[] + val ofSeq: source: seq<'T> -> 'T array /// Returns an array of each element in the input array and its predecessor, with the /// exception of the first element which is only returned as the predecessor of the second element. @@ -1936,7 +1937,7 @@ module Array = /// Evaluates to [|(1, 2); (2, 3); (3, 4)|]. /// [] - val pairwise: array: 'T[] -> ('T * 'T)[] + val pairwise: array: 'T array -> ('T * 'T) array /// Splits the collection into two collections, containing the /// elements for which the given predicate returns "true" and "false" @@ -1959,7 +1960,7 @@ module Array = /// Evaluates to ([|2; 4|], [|1; 3|]). /// [] - val partition: predicate: ('T -> bool) -> array: 'T[] -> 'T[] * 'T[] + val partition: predicate: ('T -> bool) -> array: 'T array -> 'T array * 'T array /// Returns an array with all elements permuted according to the /// specified permutation. @@ -1981,7 +1982,7 @@ module Array = /// Evaluates to [|4; 1; 2; 3|]. /// [] - val permute: indexMap: (int -> int) -> array: 'T[] -> 'T[] + val permute: indexMap: (int -> int) -> array: 'T array -> 'T array /// Applies a function to each element of the array, threading an accumulator argument /// through the computation. If the input function is f and the elements are i0...iN @@ -2005,7 +2006,7 @@ module Array = /// Evaluates to 1342, by computing ((1 * 10 + 3) * 10 + 4) * 10 + 2 /// [] - val reduce: reduction: ('T -> 'T -> 'T) -> array: 'T[] -> 'T + val reduce: reduction: ('T -> 'T -> 'T) -> array: 'T array -> 'T /// Applies a function to each element of the array, starting from the end, threading an accumulator argument /// through the computation. If the input function is f and the elements are i0...iN @@ -2029,7 +2030,7 @@ module Array = /// Evaluates to 2431, by computing 1 + (3 + (4 + 2 * 10) * 10) * 10 /// [] - val reduceBack: reduction: ('T -> 'T -> 'T) -> array: 'T[] -> 'T + val reduceBack: reduction: ('T -> 'T -> 'T) -> array: 'T array -> 'T /// Creates an array by replicating the given initial value. /// @@ -2047,7 +2048,7 @@ module Array = /// Evaluates to [| "a"; "a"; "a" |]. /// [] - val replicate: count: int -> initial: 'T -> 'T[] + val replicate: count: int -> initial: 'T -> 'T array /// Returns a new array with the elements in reverse order. /// @@ -2064,7 +2065,7 @@ module Array = /// Evaluates to [| 2; 1; 0 |]. /// [] - val rev: array: 'T[] -> 'T[] + val rev: array: 'T array -> 'T array /// Like fold, but return the intermediary and final results. /// @@ -2093,7 +2094,7 @@ module Array = /// state, 1 the next state, -1 the next state, and 2 the final state. /// [] - val scan<'T, 'State> : folder: ('State -> 'T -> 'State) -> state: 'State -> array: 'T[] -> 'State[] + val scan<'T, 'State> : folder: ('State -> 'T -> 'State) -> state: 'State -> array: 'T array -> 'State array /// Like foldBack, but return both the intermediary and final results. /// @@ -2122,7 +2123,7 @@ module Array = /// state, 3 the next state, 1 the next state, and 2 the final state. /// [] - val scanBack<'T, 'State> : folder: ('T -> 'State -> 'State) -> array: 'T[] -> state: 'State -> 'State[] + val scanBack<'T, 'State> : folder: ('T -> 'State -> 'State) -> array: 'T array -> state: 'State -> 'State array /// Returns an array that contains one item only. /// @@ -2137,7 +2138,7 @@ module Array = /// Evaluates to [| 7 |]. /// [] - val inline singleton: value: 'T -> 'T[] + val inline singleton: value: 'T -> 'T array /// Sets an element of an array. /// @@ -2166,7 +2167,7 @@ module Array = /// Throws IndexOutOfRangeException /// [] - val set: array: 'T[] -> index: int -> value: 'T -> unit + val set: array: 'T array -> index: int -> value: 'T -> unit /// Builds a new array that contains the elements of the given array, excluding the first N elements. /// @@ -2206,7 +2207,7 @@ module Array = /// Evaluates to [| "a"; "b"; "c"; "d" |]. /// [] - val skip: count: int -> array: 'T[] -> 'T[] + val skip: count: int -> array: 'T array -> 'T array /// Bypasses elements in an array while the given predicate returns True, and then returns /// the remaining elements in a new array. @@ -2228,7 +2229,7 @@ module Array = /// /// [] - val skipWhile: predicate: ('T -> bool) -> array: 'T[] -> 'T[] + val skipWhile: predicate: ('T -> bool) -> array: 'T array -> 'T array /// Builds a new array that contains the given subrange specified by /// starting index and length. @@ -2261,7 +2262,7 @@ module Array = /// Evaluates to [| 2; 3; 4 |]. /// [] - val sub: array: 'T[] -> startIndex: int -> count: int -> 'T[] + val sub: array: 'T array -> startIndex: int -> count: int -> 'T array /// Sorts the elements of an array, returning a new array. Elements are compared using . /// @@ -2283,7 +2284,7 @@ module Array = /// Evaluates to [| 1; 1; 3; 4; 6; 8 |]. /// [] - val sort: array: 'T[] -> 'T[] when 'T: comparison + val sort: array: 'T array -> 'T array when 'T: comparison /// Sorts the elements of an array, using the given projection for the keys and returning a new array. /// Elements are compared using . @@ -2307,7 +2308,7 @@ module Array = /// Evaluates to [|"a"; "dd"; "bbb"; "cccc"|]. /// [] - val sortBy: projection: ('T -> 'Key) -> array: 'T[] -> 'T[] when 'Key: comparison + val sortBy: projection: ('T -> 'Key) -> array: 'T array -> 'T array when 'Key: comparison /// Sorts the elements of an array, using the given comparison function as the order, returning a new array. /// @@ -2335,7 +2336,7 @@ module Array = /// Evaluates to [|(0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb")|]. /// [] - val sortWith: comparer: ('T -> 'T -> int) -> array: 'T[] -> 'T[] + val sortWith: comparer: ('T -> 'T -> int) -> array: 'T array -> 'T array /// Sorts the elements of an array by mutating the array in-place, using the given projection for the keys. /// Elements are compared using . @@ -2357,7 +2358,7 @@ module Array = /// After evaluation array contains [|"a"; "dd"; "bbb"; "cccc"|]. /// [] - val sortInPlaceBy: projection: ('T -> 'Key) -> array: 'T[] -> unit when 'Key: comparison + val sortInPlaceBy: projection: ('T -> 'Key) -> array: 'T array -> unit when 'Key: comparison /// Sorts the elements of an array by mutating the array in-place, using the given comparison function as the order. /// @@ -2380,7 +2381,7 @@ module Array = /// After evaluation array contains [|(0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb")|]. /// [] - val sortInPlaceWith: comparer: ('T -> 'T -> int) -> array: 'T[] -> unit + val sortInPlaceWith: comparer: ('T -> 'T -> int) -> array: 'T array -> unit /// Sorts the elements of an array by mutating the array in-place, using the given comparison function. /// Elements are compared using . @@ -2398,7 +2399,7 @@ module Array = /// After evaluation array contains [| 1; 1; 3; 4; 6; 8 |]. /// [] - val sortInPlace: array: 'T[] -> unit when 'T: comparison + val sortInPlace: array: 'T array -> unit when 'T: comparison /// Splits an array into two arrays, at the given index. /// @@ -2420,7 +2421,7 @@ module Array = /// Evaluates front to [|8; 4; 3|] and back to [|1; 6; 1|]. /// [] - val splitAt: index: int -> array: 'T[] -> ('T[] * 'T[]) + val splitAt: index: int -> array: 'T array -> ('T array * 'T array) /// Sorts the elements of an array, in descending order, returning a new array. Elements are compared using . /// @@ -2440,7 +2441,7 @@ module Array = /// Evaluates to [| 8; 6; 4; 3; 1; 1 |]. /// [] - val inline sortDescending: array: 'T[] -> 'T[] when 'T: comparison + val inline sortDescending: array: 'T array -> 'T array when 'T: comparison /// Sorts the elements of an array, in descending order, using the given projection for the keys and returning a new array. /// Elements are compared using . @@ -2462,7 +2463,7 @@ module Array = /// Evaluates to [|"cccc"; "bbb"; "dd"; "a"|]. /// [] - val inline sortByDescending: projection: ('T -> 'Key) -> array: 'T[] -> 'T[] when 'Key: comparison + val inline sortByDescending: projection: ('T -> 'Key) -> array: 'T array -> 'T array when 'Key: comparison /// Returns the sum of the elements in the array. /// @@ -2481,7 +2482,7 @@ module Array = /// Evaluates to 11. /// [] - val inline sum: array: ^T[] -> ^T when ^T: (static member (+): ^T * ^T -> ^T) and ^T: (static member Zero: ^T) + val inline sum: array: ^T array -> ^T when ^T: (static member (+): ^T * ^T -> ^T) and ^T: (static member Zero: ^T) /// Returns the sum of the results generated by applying the function to each element of the array. /// @@ -2502,7 +2503,7 @@ module Array = /// [] val inline sumBy: - projection: ('T -> ^U) -> array: 'T[] -> ^U + projection: ('T -> ^U) -> array: 'T array -> ^U when ^U: (static member (+): ^U * ^U -> ^U) and ^U: (static member Zero: ^U) /// Returns the first N elements of the array. @@ -2547,7 +2548,7 @@ module Array = /// Evaluates to [| |]. /// [] - val take: count: int -> array: 'T[] -> 'T[] + val take: count: int -> array: 'T array -> 'T array /// Returns an array that contains all elements of the original array while the /// given predicate returns True, and then returns no further elements. @@ -2569,7 +2570,7 @@ module Array = /// /// [] - val takeWhile: predicate: ('T -> bool) -> array: 'T[] -> 'T[] + val takeWhile: predicate: ('T -> bool) -> array: 'T array -> 'T array /// Returns a new array containing the elements of the original except the first element. /// @@ -2590,7 +2591,7 @@ module Array = /// /// [] - val tail: array: 'T[] -> 'T[] + val tail: array: 'T array -> 'T array /// Builds a list from the given array. /// @@ -2609,7 +2610,7 @@ module Array = /// Evaluates to [ 1; 2; 5 ]. /// [] - val toList: array: 'T[] -> 'T list + val toList: array: 'T array -> 'T list /// Views the given array as a sequence. /// @@ -2628,7 +2629,7 @@ module Array = /// Evaluates to seq { 1; 2; 5 }. /// [] - val toSeq: array: 'T[] -> seq<'T> + val toSeq: array: 'T array -> seq<'T> /// Returns the transpose of the given sequence of arrays. /// @@ -2650,7 +2651,7 @@ module Array = /// Evaluates to [|[|10; 11|]; [|20; 21|]; [|30; 31|]|]. /// [] - val transpose: arrays: seq<'T[]> -> 'T[][] + val transpose: arrays: seq<'T array> -> 'T array array /// Returns at most N elements in a new array. /// @@ -2688,7 +2689,7 @@ module Array = /// Evaluates to [| |]. /// [] - val truncate: count: int -> array: 'T[] -> 'T[] + val truncate: count: int -> array: 'T array -> 'T array /// Returns the first element for which the given function returns True. /// Return None if no such element exists. @@ -2718,7 +2719,7 @@ module Array = /// Evaluates to None /// [] - val tryFind: predicate: ('T -> bool) -> array: 'T[] -> 'T option + val tryFind: predicate: ('T -> bool) -> array: 'T array -> 'T option /// Returns the last element for which the given function returns True. /// Return None if no such element exists. @@ -2748,7 +2749,7 @@ module Array = /// Evaluates to None /// [] - val tryFindBack: predicate: ('T -> bool) -> array: 'T[] -> 'T option + val tryFindBack: predicate: ('T -> bool) -> array: 'T array -> 'T option /// Returns the index of the first element in the array /// that satisfies the given predicate. @@ -2778,7 +2779,7 @@ module Array = /// Evaluates to None /// [] - val tryFindIndex: predicate: ('T -> bool) -> array: 'T[] -> int option + val tryFindIndex: predicate: ('T -> bool) -> array: 'T array -> int option /// Tries to find the nth element in the array. /// Returns None if index is negative or the input array does not contain enough elements. @@ -2808,7 +2809,7 @@ module Array = /// Evaluates to None. /// [] - val tryItem: index: int -> array: 'T[] -> 'T option + val tryItem: index: int -> array: 'T array -> 'T option /// Returns the index of the last element in the array /// that satisfies the given predicate. @@ -2838,7 +2839,7 @@ module Array = /// Evaluates to None /// [] - val tryFindIndexBack: predicate: ('T -> bool) -> array: 'T[] -> int option + val tryFindIndexBack: predicate: ('T -> bool) -> array: 'T array -> int option /// Returns an array that contains the elements generated by the given computation. /// The generator is repeatedly called to build the list until it returns `None`. @@ -2857,7 +2858,7 @@ module Array = /// Evaluates to [| 1; 2; 4; 8; 16; 32; 64 |] /// [] - val unfold<'T, 'State> : generator: ('State -> ('T * 'State) option) -> state: 'State -> 'T[] + val unfold<'T, 'State> : generator: ('State -> ('T * 'State) option) -> state: 'State -> 'T array /// Splits an array of pairs into two arrays. /// @@ -2876,7 +2877,7 @@ module Array = /// Evaluates numbers to [|1; 2|] and names to [|"one"; "two"|]. /// [] - val unzip: array: ('T1 * 'T2)[] -> ('T1[] * 'T2[]) + val unzip: array: ('T1 * 'T2) array -> ('T1 array * 'T2 array) /// Splits an array of triples into three arrays. /// @@ -2895,7 +2896,7 @@ module Array = /// Evaluates numbers to [|1; 2|], names to [|"one"; "two"|] and roman to [|"I"; "II"|]. /// [] - val unzip3: array: ('T1 * 'T2 * 'T3)[] -> ('T1[] * 'T2[] * 'T3[]) + val unzip3: array: ('T1 * 'T2 * 'T3) array -> ('T1 array * 'T2 array * 'T3 array) /// Returns a new array containing only the elements of the array /// for which the given predicate returns "true". @@ -2918,7 +2919,7 @@ module Array = /// Evaluates to [| 2; 4 |] /// [] - val where: predicate: ('T -> bool) -> array: 'T[] -> 'T[] + val where: predicate: ('T -> bool) -> array: 'T array -> 'T array /// Returns an array of sliding windows containing elements drawn from the input /// array. Each window is returned as a fresh array. @@ -2940,7 +2941,7 @@ module Array = /// Evaluates to [|[|1; 2; 3|]; [|2; 3; 4|]; [|3; 4; 5|]|] /// [] - val windowed: windowSize: int -> array: 'T[] -> 'T[][] + val windowed: windowSize: int -> array: 'T array -> 'T array array /// Combines the two arrays into an array of pairs. The two arrays must have equal lengths, otherwise an ArgumentException is /// raised. @@ -2963,7 +2964,7 @@ module Array = /// Evaluates to [| (1, "one"); (2, "two") |]. /// [] - val zip: array1: 'T1[] -> array2: 'T2[] -> ('T1 * 'T2)[] + val zip: array1: 'T1 array -> array2: 'T2 array -> ('T1 * 'T2) array /// Combines three arrays into an array of pairs. The three arrays must have equal lengths, otherwise an ArgumentException is /// raised. @@ -2988,7 +2989,7 @@ module Array = /// Evaluates to [|(1, "one", "I"); (2, "two", "II")|]. /// [] - val zip3: array1: 'T1[] -> array2: 'T2[] -> array3: 'T3[] -> ('T1 * 'T2 * 'T3)[] + val zip3: array1: 'T1 array -> array2: 'T2 array -> array3: 'T3 array -> ('T1 * 'T2 * 'T3) array /// Return a new array with the item at a given index removed. /// @@ -3008,7 +3009,7 @@ module Array = /// Evaluates to [| 0; 2 |]. /// [] - val removeAt: index: int -> source: 'T[] -> 'T[] + val removeAt: index: int -> source: 'T array -> 'T array /// Return a new array with the number of items starting at a given index removed. /// @@ -3029,7 +3030,7 @@ module Array = /// Evaluates to [| 0; 3 |]. /// [] - val removeManyAt: index: int -> count: int -> source: 'T[] -> 'T[] + val removeManyAt: index: int -> count: int -> source: 'T array -> 'T array /// Return a new array with the item at a given index set to the new value. /// @@ -3050,7 +3051,7 @@ module Array = /// Evaluates to [| 0; 9; 2 |]. /// [] - val updateAt: index: int -> value: 'T -> source: 'T[] -> 'T[] + val updateAt: index: int -> value: 'T -> source: 'T array -> 'T array /// Return a new array with a new item inserted before the given index. /// @@ -3071,7 +3072,7 @@ module Array = /// Evaluates to [| 0; 9; 1; 2 |]. /// [] - val insertAt: index: int -> value: 'T -> source: 'T[] -> 'T[] + val insertAt: index: int -> value: 'T -> source: 'T array -> 'T array /// Return a new array with new items inserted before the given index. /// @@ -3092,7 +3093,7 @@ module Array = /// Evaluates to [| 0; 8; 9; 1; 2 |]. /// [] - val insertManyAt: index: int -> values: seq<'T> -> source: 'T[] -> 'T[] + val insertManyAt: index: int -> values: seq<'T> -> source: 'T array -> 'T array /// Provides parallel operations on arrays module Parallel = @@ -3121,7 +3122,7 @@ module Array = /// [] [] - val forall: predicate: ('T -> bool) -> array: 'T[] -> bool + val forall: predicate: ('T -> bool) -> array: 'T array -> bool /// Tests if any element of the array satisfies the given predicate. /// @@ -3155,7 +3156,7 @@ module Array = /// [] [] - val exists: predicate: ('T -> bool) -> array: 'T[] -> bool + val exists: predicate: ('T -> bool) -> array: 'T array -> bool /// Returns the first element for which the given function returns True. /// Returns None if no such element exists. @@ -3186,7 +3187,7 @@ module Array = /// [] [] - val tryFind: predicate: ('T -> bool) -> array: 'T[] -> 'T option + val tryFind: predicate: ('T -> bool) -> array: 'T array -> 'T option /// Returns the index of the first element in the array /// that satisfies the given predicate. @@ -3217,7 +3218,7 @@ module Array = /// [] [] - val tryFindIndex: predicate: ('T -> bool) -> array: 'T[] -> int option + val tryFindIndex: predicate: ('T -> bool) -> array: 'T array -> int option /// Applies the given function to successive elements, returning the first /// result where the function returns Some(x) for some x. If the function @@ -3250,7 +3251,7 @@ module Array = /// [] [] - val tryPick: chooser: ('T -> 'U option) -> array: 'T[] -> 'U option + val tryPick: chooser: ('T -> 'U option) -> array: 'T array -> 'U option /// Applies a function to each element of the array in parallel, threading an accumulator argument /// through the computation for each thread involved in the computation. After processing entire input, results from all threads are reduced together. @@ -3278,7 +3279,7 @@ module Array = [] [] - val inline reduce: reduction: ('T -> 'T -> 'T) -> array: 'T[] -> 'T + val inline reduce: reduction: ('T -> 'T -> 'T) -> array: 'T array -> 'T /// Applies a projection function to each element of the array in parallel, reducing elements in each thread with a dedicated 'reduction' function. /// After processing entire input, results from all threads are reduced together. @@ -3306,7 +3307,7 @@ module Array = [] [] - val reduceBy: projection: ('T -> 'U) -> reduction: ('U -> 'U -> 'U) -> array: 'T[] -> 'U + val reduceBy: projection: ('T -> 'U) -> reduction: ('U -> 'U -> 'U) -> array: 'T array -> 'U /// Returns the greatest of all elements of the array, compared via Operators.max. /// @@ -3330,7 +3331,7 @@ module Array = /// /// /// - /// let inputs: int[]= [| |] + /// let inputs: int array= [| |] /// /// inputs |> Array.Parallel.max /// @@ -3338,7 +3339,7 @@ module Array = /// [] [] - val inline max: array: 'T[] -> 'T when 'T: comparison + val inline max: array: 'T array -> 'T when 'T: comparison /// Returns the greatest of all elements of the array, compared via Operators.max on the function result. /// @@ -3363,7 +3364,7 @@ module Array = /// /// /// - /// let inputs: string[]= [| |] + /// let inputs: string array= [| |] /// /// inputs |> Array.Parallel.maxBy (fun s -> s.Length) /// @@ -3371,7 +3372,7 @@ module Array = /// [] [] - val inline maxBy: projection: ('T -> 'U) -> array: 'T[] -> 'T when 'U: comparison + val inline maxBy: projection: ('T -> 'U) -> array: 'T array -> 'T when 'U: comparison /// Returns the smallest of all elements of the array, compared via Operators.min. /// @@ -3395,7 +3396,7 @@ module Array = /// /// /// - /// let inputs: int[]= [| |] + /// let inputs: int array= [| |] /// /// inputs |> Array.Parallel.min /// @@ -3403,7 +3404,7 @@ module Array = /// [] [] - val inline min: array: 'T[] -> 'T when 'T: comparison + val inline min: array: 'T array -> 'T when 'T: comparison /// Returns the lowest of all elements of the array, compared via Operators.min on the function result. /// @@ -3428,7 +3429,7 @@ module Array = /// /// /// - /// let inputs: string[]= [| |] + /// let inputs: string array= [| |] /// /// inputs |> Array.Parallel.minBy (fun s -> s.Length) /// @@ -3436,7 +3437,7 @@ module Array = /// [] [] - val inline minBy: projection: ('T -> 'U) -> array: 'T[] -> 'T when 'U: comparison + val inline minBy: projection: ('T -> 'U) -> array: 'T array -> 'T when 'U: comparison /// Returns the sum of the elements in the array. /// @@ -3456,7 +3457,8 @@ module Array = /// [] [] - val inline sum: array: ^T[] -> ^T when ^T: (static member (+): ^T * ^T -> ^T) and ^T: (static member Zero: ^T) + val inline sum: + array: ^T array -> ^T when ^T: (static member (+): ^T * ^T -> ^T) and ^T: (static member Zero: ^T) /// Returns the sum of the results generated by applying the function to each element of the array. /// @@ -3478,7 +3480,7 @@ module Array = [] [] val inline sumBy: - projection: ('T -> ^U) -> array: 'T[] -> ^U + projection: ('T -> ^U) -> array: 'T array -> ^U when ^U: (static member (+): ^U * ^U -> ^U) and ^U: (static member Zero: ^U) /// Returns the average of the elements in the array. @@ -3506,7 +3508,7 @@ module Array = [] [] val inline average: - array: ^T[] -> ^T + array: ^T array -> ^T when ^T: (static member (+): ^T * ^T -> ^T) and ^T: (static member DivideByInt: ^T * int -> ^T) /// Returns the average of the elements generated by applying the function to each element of the array. @@ -3535,7 +3537,7 @@ module Array = /// /// type Foo = { Bar: float } /// - /// let input : Foo[] = [| |] + /// let input : Foo array = [| |] /// /// input |> Array.Parallel.averageBy (fun foo -> foo.Bar) /// @@ -3544,7 +3546,7 @@ module Array = [] [] val inline averageBy: - projection: ('T -> ^U) -> array: 'T[] -> ^U + projection: ('T -> ^U) -> array: 'T array -> ^U when ^U: (static member (+): ^U * ^U -> ^U) and ^U: (static member DivideByInt: ^U * int -> ^U) /// Apply the given function to each element of the array. Return @@ -3579,7 +3581,7 @@ module Array = /// Evaluates to [| 2 |] /// [] - val choose: chooser: ('T -> 'U option) -> array: 'T[] -> 'U[] + val choose: chooser: ('T -> 'U option) -> array: 'T array -> 'U array /// For each element of the array, apply the given function. Concatenate all the results and return the combined array. /// @@ -3589,13 +3591,13 @@ module Array = /// /// The input array. /// - /// 'U[] + /// 'U array /// /// Thrown when the input array is null. /// /// /// - /// type Foo = { Bar: int[] } + /// type Foo = { Bar: int array } /// /// let input = [| {Bar = [| 1; 2 |]}; {Bar = [| 3; 4 |]} |] /// @@ -3613,7 +3615,7 @@ module Array = /// Evaluates to [| 1; 2; 3; 4 |] /// [] - val collect: mapping: ('T -> 'U[]) -> array: 'T[] -> 'U[] + val collect: mapping: ('T -> 'U array) -> array: 'T array -> 'U array /// Build a new array whose elements are the results of applying the given function /// to each of the elements of the array. @@ -3637,7 +3639,7 @@ module Array = /// Evaluates to [| 1; 3; 2 |] /// [] - val map: mapping: ('T -> 'U) -> array: 'T[] -> 'U[] + val map: mapping: ('T -> 'U) -> array: 'T array -> 'U array /// Build a new array whose elements are the results of applying the given function /// to each of the elements of the array. The integer index passed to the @@ -3662,7 +3664,7 @@ module Array = /// Evaluates to [| 10; 11; 12 |] /// [] - val mapi: mapping: (int -> 'T -> 'U) -> array: 'T[] -> 'U[] + val mapi: mapping: (int -> 'T -> 'U) -> array: 'T array -> 'U array /// Applies a key-generating function to each element of an array in parallel and yields an array of /// unique keys. Each unique key contains an array of all elements that match @@ -3689,7 +3691,7 @@ module Array = [] [] - val groupBy: projection: ('T -> 'Key) -> array: 'T[] -> ('Key * 'T[])[] when 'Key: equality + val groupBy: projection: ('T -> 'Key) -> array: 'T array -> ('Key * 'T array) array when 'Key: equality /// Apply the given function to each element of the array. /// @@ -3715,7 +3717,7 @@ module Array = /// /// [] - val iter: action: ('T -> unit) -> array: 'T[] -> unit + val iter: action: ('T -> unit) -> array: 'T array -> unit /// Apply the given function to each element of the array. The integer passed to the /// function indicates the index of element. @@ -3742,7 +3744,7 @@ module Array = /// /// [] - val iteri: action: (int -> 'T -> unit) -> array: 'T[] -> unit + val iteri: action: (int -> 'T -> unit) -> array: 'T array -> unit /// Create an array given the dimension and a generator function to compute the elements. /// @@ -3761,7 +3763,7 @@ module Array = /// Evaluates to [| 5; 6; 7; 8 |] /// [] - val init: count: int -> initializer: (int -> 'T) -> 'T[] + val init: count: int -> initializer: (int -> 'T) -> 'T array /// Split the collection into two collections, containing the /// elements for which the given predicate returns "true" and "false" @@ -3786,7 +3788,7 @@ module Array = /// Evaluates to ([|2; 4|], [|1; 3|]). /// [] - val partition: predicate: ('T -> bool) -> array: 'T[] -> 'T[] * 'T[] + val partition: predicate: ('T -> bool) -> array: 'T array -> 'T array * 'T array /// Sorts the elements of an array in parallel, returning a new array. Elements are compared using . /// @@ -3809,7 +3811,7 @@ module Array = /// [] [] - val sort: array: 'T[] -> 'T[] when 'T: comparison + val sort: array: 'T array -> 'T array when 'T: comparison /// Sorts the elements of an array in parallel, using the given projection for the keys and returning a new array. /// Elements are compared using . @@ -3835,7 +3837,7 @@ module Array = [] [] - val sortBy: projection: ('T -> 'Key) -> array: 'T[] -> 'T[] when 'Key: comparison + val sortBy: projection: ('T -> 'Key) -> array: 'T array -> 'T array when 'Key: comparison /// Sorts the elements of an array in parallel, using the given comparison function as the order, returning a new array. /// @@ -3864,7 +3866,7 @@ module Array = /// [] [] - val sortWith: comparer: ('T -> 'T -> int) -> array: 'T[] -> 'T[] + val sortWith: comparer: ('T -> 'T -> int) -> array: 'T array -> 'T array /// Sorts the elements of an array by mutating the array in-place in parallel, using the given projection for the keys. /// Elements are compared using . @@ -3887,7 +3889,7 @@ module Array = /// [] [] - val sortInPlaceBy: projection: ('T -> 'Key) -> array: 'T[] -> unit when 'Key: comparison + val sortInPlaceBy: projection: ('T -> 'Key) -> array: 'T array -> unit when 'Key: comparison /// Sorts the elements of an array by mutating the array in-place in parallel, using the given comparison function as the order. /// @@ -3911,7 +3913,7 @@ module Array = /// [] [] - val sortInPlaceWith: comparer: ('T -> 'T -> int) -> array: 'T[] -> unit + val sortInPlaceWith: comparer: ('T -> 'T -> int) -> array: 'T array -> unit /// Sorts the elements of an array by mutating the array in-place in parallel, using the given comparison function. /// Elements are compared using . @@ -3930,7 +3932,7 @@ module Array = /// [] [] - val sortInPlace: array: 'T[] -> unit when 'T: comparison + val sortInPlace: array: 'T array -> unit when 'T: comparison /// Sorts the elements of an array in parallel, in descending order, returning a new array. Elements are compared using . /// @@ -3951,7 +3953,7 @@ module Array = /// [] [] - val sortDescending: array: 'T[] -> 'T[] when 'T: comparison + val sortDescending: array: 'T array -> 'T array when 'T: comparison /// Sorts the elements of an array in parallel, in descending order, using the given projection for the keys and returning a new array. /// Elements are compared using . @@ -3974,7 +3976,7 @@ module Array = /// [] [] - val sortByDescending: projection: ('T -> 'Key) -> array: 'T[] -> 'T[] when 'Key: comparison + val sortByDescending: projection: ('T -> 'Key) -> array: 'T array -> 'T array when 'Key: comparison /// Combines the two arrays into an array of pairs. The two arrays must have equal lengths, otherwise an ArgumentException is /// raised. @@ -3998,7 +4000,7 @@ module Array = /// [] [] - val zip: array1: 'T1[] -> array2: 'T2[] -> ('T1 * 'T2)[] + val zip: array1: 'T1 array -> array2: 'T2 array -> ('T1 * 'T2) array /// Returns a new collection containing only the elements of the collection /// for which the given predicate returns true. @@ -4020,4 +4022,4 @@ module Array = /// [] [] - val filter: predicate: ('T -> bool) -> array: 'T[] -> 'T[] + val filter: predicate: ('T -> bool) -> array: 'T array -> 'T array diff --git a/src/FSharp.Core/async.fs b/src/FSharp.Core/async.fs index 7eedb9e167c..b530fa72485 100644 --- a/src/FSharp.Core/async.fs +++ b/src/FSharp.Core/async.fs @@ -2253,7 +2253,7 @@ module CommonExtensions = type System.IO.Stream with [] // give the extension member a 'nice', unmangled compiled name, unique within this module - member stream.AsyncRead(buffer: byte[], ?offset, ?count) = + member stream.AsyncRead(buffer: byte array, ?offset, ?count) = let offset = defaultArg offset 0 let count = defaultArg count buffer.Length Async.FromBeginEnd(buffer, offset, count, stream.BeginRead, stream.EndRead) @@ -2275,7 +2275,7 @@ module CommonExtensions = } [] // give the extension member a 'nice', unmangled compiled name, unique within this module - member stream.AsyncWrite(buffer: byte[], ?offset: int, ?count: int) = + member stream.AsyncWrite(buffer: byte array, ?offset: int, ?count: int) = let offset = defaultArg offset 0 let count = defaultArg count buffer.Length Async.FromBeginEnd(buffer, offset, count, stream.BeginWrite, stream.EndWrite) @@ -2365,7 +2365,7 @@ module WebExtensions = ) [] // give the extension member a 'nice', unmangled compiled name, unique within this module - member this.AsyncDownloadData(address: Uri) : Async = + member this.AsyncDownloadData(address: Uri) : Async = this.Download( event = this.DownloadDataCompleted, handler = (fun action -> Net.DownloadDataCompletedEventHandler action), diff --git a/src/FSharp.Core/async.fsi b/src/FSharp.Core/async.fsi index 35b3e227a5d..6b621176c9d 100644 --- a/src/FSharp.Core/async.fsi +++ b/src/FSharp.Core/async.fsi @@ -428,7 +428,7 @@ namespace Microsoft.FSharp.Control /// /// This will print "3", "5", "7", "11" (in any order) in 1-2 seconds and then [| false; true; true; true; false; true |]. /// - static member Parallel : computations:seq> -> Async<'T[]> + static member Parallel : computations:seq> -> Async<'T array> /// Creates an asynchronous computation that executes all the given asynchronous computations, /// initially queueing each as work items and using a fork/join pattern. @@ -475,7 +475,7 @@ namespace Microsoft.FSharp.Control /// This will print "3", "5" (in any order) in 1-2 seconds, and then "7", "11" (in any order) in 1-2 more seconds and then /// [| false; true; true; true; false; true |]. /// - static member Parallel : computations:seq> * ?maxDegreeOfParallelism : int -> Async<'T[]> + static member Parallel : computations:seq> * ?maxDegreeOfParallelism : int -> Async<'T array> /// Creates an asynchronous computation that executes all the given asynchronous computations sequentially. /// @@ -520,7 +520,7 @@ namespace Microsoft.FSharp.Control /// This will print "3", "5", "7", "11" with ~1-2 seconds between them except for pauses where even numbers would be and then /// prints [| false; true; true; true; false; true |]. /// - static member Sequential : computations:seq> -> Async<'T[]> + static member Sequential : computations:seq> -> Async<'T array> /// /// Creates an asynchronous computation that executes all given asynchronous computations in parallel, @@ -1409,17 +1409,17 @@ namespace Microsoft.FSharp.Control /// /// [] // give the extension member a nice, unmangled compiled name, unique within this module - member AsyncRead : buffer:byte[] * ?offset:int * ?count:int -> Async + member AsyncRead : buffer:byte array * ?offset:int * ?count:int -> Async /// Returns an asynchronous computation that will read the given number of bytes from the stream. /// /// The number of bytes to read. /// - /// An asynchronous computation that returns the read byte[] when run. + /// An asynchronous computation that returns the read byte array when run. /// /// [] // give the extension member a nice, unmangled compiled name, unique within this module - member AsyncRead : count:int -> Async + member AsyncRead : count:int -> Async /// Returns an asynchronous computation that will write the given bytes to the stream. /// @@ -1435,7 +1435,7 @@ namespace Microsoft.FSharp.Control /// /// [] // give the extension member a nice, unmangled compiled name, unique within this module - member AsyncWrite : buffer:byte[] * ?offset:int * ?count:int -> Async + member AsyncWrite : buffer:byte array * ?offset:int * ?count:int -> Async ///The family of first class event values for delegate types that satisfy the F# delegate constraint. @@ -1522,7 +1522,7 @@ namespace Microsoft.FSharp.Control /// /// Downloads the data in bytes and decodes it to a string. [] // give the extension member a nice, unmangled compiled name, unique within this module - member AsyncDownloadData : address:System.Uri -> Async + member AsyncDownloadData : address:System.Uri -> Async /// Returns an asynchronous computation that, when run, will wait for the download of the given URI to specified file. /// diff --git a/src/FSharp.Core/collections.fsi b/src/FSharp.Core/collections.fsi index 1e8494aa9e3..9baf6097394 100644 --- a/src/FSharp.Core/collections.fsi +++ b/src/FSharp.Core/collections.fsi @@ -70,7 +70,7 @@ module HashIdentity = /// /// open System.Collections.Generic /// - /// let dict = new Dictionary<int[],int>(HashIdentity.Structural) + /// let dict = new Dictionary<int array,int>(HashIdentity.Structural) /// /// let arr1 = [| 1;2;3 |] /// let arr2 = [| 1;2;3 |] @@ -134,7 +134,7 @@ module HashIdentity = /// /// open System.Collections.Generic /// - /// let dict = new Dictionary<int[],int>(HashIdentity.Structural) + /// let dict = new Dictionary<int array,int>(HashIdentity.Structural) /// /// let arr1 = [| 1;2;3 |] /// let arr2 = [| 1;2;3 |] diff --git a/src/FSharp.Core/event.fs b/src/FSharp.Core/event.fs index da356eefb05..338d7275fc3 100644 --- a/src/FSharp.Core/event.fs +++ b/src/FSharp.Core/event.fs @@ -31,7 +31,7 @@ module private Atomic = type DelegateEvent<'Delegate when 'Delegate :> System.Delegate>() = let mutable multicast: System.Delegate = null - member x.Trigger(args: obj[]) = + member x.Trigger(args: obj array) = match multicast with | null -> () | d -> d.DynamicInvoke(args) |> ignore diff --git a/src/FSharp.Core/event.fsi b/src/FSharp.Core/event.fsi index 12557f0dc22..09225b9b0fa 100644 --- a/src/FSharp.Core/event.fsi +++ b/src/FSharp.Core/event.fsi @@ -23,7 +23,7 @@ type DelegateEvent<'Delegate when 'Delegate :> System.Delegate> = /// The parameters for the event. /// /// - member Trigger: args: obj[] -> unit + member Trigger: args: obj array -> unit /// Publishes the event as a first class event value. /// diff --git a/src/FSharp.Core/fslib-extra-pervasives.fs b/src/FSharp.Core/fslib-extra-pervasives.fs index d12a20211b8..def5d42c2e5 100644 --- a/src/FSharp.Core/fslib-extra-pervasives.fs +++ b/src/FSharp.Core/fslib-extra-pervasives.fs @@ -215,7 +215,7 @@ module ExtraTopLevelOperators = let getArray (vals: seq<'T>) = match vals with - | :? ('T[]) as arr -> arr + | :? ('T array) as arr -> arr | _ -> Seq.toArray vals [] @@ -415,7 +415,7 @@ type TypeProviderConfig (systemRuntimeContainsType: string -> bool, getReferencedAssembliesOption: (unit -> string array) option) = let mutable resolutionFolder: string = null let mutable runtimeAssembly: string = null - let mutable referencedAssemblies: string[] = null + let mutable referencedAssemblies: string array = null let mutable temporaryFolder: string = null let mutable isInvalidationSupported: bool = false let mutable useResolutionFolderAtRuntime: bool = false @@ -468,31 +468,31 @@ type IProvidedNamespace = abstract NamespaceName: string - abstract GetNestedNamespaces: unit -> IProvidedNamespace[] + abstract GetNestedNamespaces: unit -> IProvidedNamespace array - abstract GetTypes: unit -> Type[] + abstract GetTypes: unit -> Type array abstract ResolveTypeName: typeName: string -> Type type ITypeProvider = inherit System.IDisposable - abstract GetNamespaces: unit -> IProvidedNamespace[] + abstract GetNamespaces: unit -> IProvidedNamespace array - abstract GetStaticParameters: typeWithoutArguments: Type -> ParameterInfo[] + abstract GetStaticParameters: typeWithoutArguments: Type -> ParameterInfo array abstract ApplyStaticArguments: - typeWithoutArguments: Type * typePathWithArguments: string[] * staticArguments: obj[] -> Type + typeWithoutArguments: Type * typePathWithArguments: string array * staticArguments: obj array -> Type - abstract GetInvokerExpression: syntheticMethodBase: MethodBase * parameters: Expr[] -> Expr + abstract GetInvokerExpression: syntheticMethodBase: MethodBase * parameters: Expr array -> Expr [] abstract Invalidate: IEvent - abstract GetGeneratedAssemblyContents: assembly: System.Reflection.Assembly -> byte[] + abstract GetGeneratedAssemblyContents: assembly: System.Reflection.Assembly -> byte array type ITypeProvider2 = - abstract GetStaticParametersForMethod: methodWithoutArguments: MethodBase -> ParameterInfo[] + abstract GetStaticParametersForMethod: methodWithoutArguments: MethodBase -> ParameterInfo array abstract ApplyStaticArgumentsForMethod: - methodWithoutArguments: MethodBase * methodNameWithArguments: string * staticArguments: obj[] -> MethodBase + methodWithoutArguments: MethodBase * methodNameWithArguments: string * staticArguments: obj array -> MethodBase diff --git a/src/FSharp.Core/fslib-extra-pervasives.fsi b/src/FSharp.Core/fslib-extra-pervasives.fsi index 619f5ff05d4..bd4bf0ee8b5 100644 --- a/src/FSharp.Core/fslib-extra-pervasives.fsi +++ b/src/FSharp.Core/fslib-extra-pervasives.fsi @@ -459,7 +459,7 @@ namespace Microsoft.FSharp.Core.CompilerServices new : systemRuntimeContainsType : (string -> bool) -> TypeProviderConfig /// Create a configuration which calls the given functions for the corresponding operation. - new : systemRuntimeContainsType : (string -> bool) * getReferencedAssemblies : (unit -> string[]) -> TypeProviderConfig + new : systemRuntimeContainsType : (string -> bool) * getReferencedAssemblies : (unit -> string array) -> TypeProviderConfig /// Get the full path to use to resolve relative paths in any file name arguments given to the type provider instance. member ResolutionFolder : string with get,set @@ -468,7 +468,7 @@ namespace Microsoft.FSharp.Core.CompilerServices member RuntimeAssembly : string with get,set /// Get the referenced assemblies for the type provider instance. - member ReferencedAssemblies : string[] with get,set + member ReferencedAssemblies : string array with get,set /// Get the full path to use for temporary files for the type provider instance. member TemporaryFolder : string with get,set @@ -493,13 +493,13 @@ namespace Microsoft.FSharp.Core.CompilerServices abstract NamespaceName : string /// The sub-namespaces in this namespace. An optional member to prevent generation of namespaces until an outer namespace is explored. - abstract GetNestedNamespaces : unit -> IProvidedNamespace[] + abstract GetNestedNamespaces : unit -> IProvidedNamespace array /// /// The top-level types /// /// - abstract GetTypes : unit -> Type[] + abstract GetTypes : unit -> Type array /// /// Compilers call this method to query a type provider for a type name. @@ -518,7 +518,7 @@ namespace Microsoft.FSharp.Core.CompilerServices /// /// Gets the namespaces provided by the type provider. /// - abstract GetNamespaces : unit -> IProvidedNamespace[] + abstract GetNamespaces : unit -> IProvidedNamespace array /// /// Get the static parameters for a provided type. @@ -527,7 +527,7 @@ namespace Microsoft.FSharp.Core.CompilerServices /// A type returned by GetTypes or ResolveTypeName /// /// - abstract GetStaticParameters : typeWithoutArguments:Type -> ParameterInfo[] + abstract GetStaticParameters : typeWithoutArguments:Type -> ParameterInfo array /// /// Apply static arguments to a provided type that accepts static arguments. @@ -540,7 +540,7 @@ namespace Microsoft.FSharp.Core.CompilerServices /// the static parameters, indexed by name /// /// - abstract ApplyStaticArguments : typeWithoutArguments:Type * typePathWithArguments:string[] * staticArguments:obj[] -> Type + abstract ApplyStaticArguments : typeWithoutArguments:Type * typePathWithArguments:string array * staticArguments:obj array -> Type /// /// Called by the compiler to ask for an Expression tree to replace the given MethodBase with. @@ -550,7 +550,7 @@ namespace Microsoft.FSharp.Core.CompilerServices /// Expressions that represent the parameters to this call. /// /// An expression that the compiler will use in place of the given method base. - abstract GetInvokerExpression : syntheticMethodBase:MethodBase * parameters:Expr[] -> Expr + abstract GetInvokerExpression : syntheticMethodBase:MethodBase * parameters:Expr array -> Expr /// /// Triggered when an assumption changes that invalidates the resolutions so far reported by the provider @@ -561,7 +561,7 @@ namespace Microsoft.FSharp.Core.CompilerServices /// /// Get the physical contents of the given logical provided assembly. /// - abstract GetGeneratedAssemblyContents : assembly:Assembly -> byte[] + abstract GetGeneratedAssemblyContents : assembly:Assembly -> byte array /// Represents additional, optional information for a type provider component type ITypeProvider2 = @@ -573,7 +573,7 @@ namespace Microsoft.FSharp.Core.CompilerServices /// A method returned by GetMethod on a provided type /// /// The static parameters of the provided method, if any - abstract GetStaticParametersForMethod : methodWithoutArguments:MethodBase -> ParameterInfo[] + abstract GetStaticParametersForMethod : methodWithoutArguments:MethodBase -> ParameterInfo array /// /// Apply static arguments to a provided method that accepts static arguments. @@ -584,4 +584,4 @@ namespace Microsoft.FSharp.Core.CompilerServices /// the values of the static parameters, indexed by name /// /// The provided method definition corresponding to the given static parameter values - abstract ApplyStaticArgumentsForMethod : methodWithoutArguments:MethodBase * methodNameWithArguments:string * staticArguments:obj[] -> MethodBase + abstract ApplyStaticArgumentsForMethod : methodWithoutArguments:MethodBase * methodNameWithArguments:string * staticArguments:obj array -> MethodBase diff --git a/src/FSharp.Core/list.fs b/src/FSharp.Core/list.fs index e3559a13958..dc81209a8c7 100644 --- a/src/FSharp.Core/list.fs +++ b/src/FSharp.Core/list.fs @@ -327,7 +327,7 @@ module List = loop state list1 list2 - let foldArraySubRight (f: OptimizedClosures.FSharpFunc<'T, _, _>) (arr: 'T[]) start fin acc = + let foldArraySubRight (f: OptimizedClosures.FSharpFunc<'T, _, _>) (arr: 'T array) start fin acc = let mutable state = acc for i = fin downto start do @@ -365,7 +365,7 @@ module List = let scanArraySubRight<'T, 'State> (f: OptimizedClosures.FSharpFunc<'T, 'State, 'State>) - (arr: _[]) + (arr: _ array) start fin initState diff --git a/src/FSharp.Core/list.fsi b/src/FSharp.Core/list.fsi index d746198f7fb..05ff605b247 100644 --- a/src/FSharp.Core/list.fsi +++ b/src/FSharp.Core/list.fsi @@ -1594,7 +1594,7 @@ module List = /// Evaluates to [ 1; 2; 5 ]. /// [] - val ofArray : array:'T[] -> 'T list + val ofArray : array:'T array -> 'T list /// Builds a new list from the given enumerable object. /// @@ -2176,7 +2176,7 @@ module List = /// Evaluates to [| 1; 2; 5 |]. /// [] - val toArray: list:'T list -> 'T[] + val toArray: list:'T list -> 'T array /// Views the given list as a sequence. /// diff --git a/src/FSharp.Core/local.fs b/src/FSharp.Core/local.fs index 70b1647cb4b..61f00c02aa3 100644 --- a/src/FSharp.Core/local.fs +++ b/src/FSharp.Core/local.fs @@ -193,7 +193,7 @@ module internal List = cons let groupBy (comparer:IEqualityComparer<'SafeKey>) (keyf:'T->'SafeKey) (getKey:'SafeKey->'Key) (list: 'T list) = - let dict = Dictionary<_, _ list []> comparer + let dict = Dictionary<_, _ list array> comparer // Build the groupings let rec loop list = diff --git a/src/FSharp.Core/local.fsi b/src/FSharp.Core/local.fsi index 9c2ebc0bbfd..1b210474062 100644 --- a/src/FSharp.Core/local.fsi +++ b/src/FSharp.Core/local.fsi @@ -72,10 +72,10 @@ module internal List = val splitInto: int -> 'T list -> 'T list list val zip: 'T1 list -> 'T2 list -> ('T1 * 'T2) list val zip3: 'T1 list -> 'T2 list -> 'T3 list -> ('T1 * 'T2 * 'T3) list - val ofArray: 'T[] -> 'T list + val ofArray: 'T array -> 'T list val take: int -> 'T list -> 'T list val takeWhile: ('T -> bool) -> 'T list -> 'T list - val toArray: 'T list -> 'T[] + val toArray: 'T list -> 'T array val inline ofSeq: seq<'T> -> 'T List val splitAt: int -> 'T list -> ('T list * 'T list) val transpose: 'T list list -> 'T list list @@ -84,40 +84,40 @@ module internal List = module internal Array = // The input parameter should be checked by callers if necessary - val inline zeroCreateUnchecked: int -> 'T[] + val inline zeroCreateUnchecked: int -> 'T array - val inline init: int -> (int -> 'T) -> 'T[] + val inline init: int -> (int -> 'T) -> 'T array - val splitInto: int -> 'T[] -> 'T[][] + val splitInto: int -> 'T array -> 'T array array - val findBack: predicate: ('T -> bool) -> array: 'T[] -> 'T + val findBack: predicate: ('T -> bool) -> array: 'T array -> 'T - val tryFindBack: predicate: ('T -> bool) -> array: 'T[] -> 'T option + val tryFindBack: predicate: ('T -> bool) -> array: 'T array -> 'T option - val findIndexBack: predicate: ('T -> bool) -> array: 'T[] -> int + val findIndexBack: predicate: ('T -> bool) -> array: 'T array -> int - val tryFindIndexBack: predicate: ('T -> bool) -> array: 'T[] -> int option + val tryFindIndexBack: predicate: ('T -> bool) -> array: 'T array -> int option - val mapFold: ('State -> 'T -> 'U * 'State) -> 'State -> 'T[] -> 'U[] * 'State + val mapFold: ('State -> 'T -> 'U * 'State) -> 'State -> 'T array -> 'U array * 'State - val mapFoldBack: ('T -> 'State -> 'U * 'State) -> 'T[] -> 'State -> 'U[] * 'State + val mapFoldBack: ('T -> 'State -> 'U * 'State) -> 'T array -> 'State -> 'U array * 'State - val permute: indexMap: (int -> int) -> 'T[] -> 'T[] + val permute: indexMap: (int -> int) -> 'T array -> 'T array val scanSubRight: - f: ('T -> 'State -> 'State) -> array: 'T[] -> start: int -> fin: int -> initState: 'State -> 'State[] + f: ('T -> 'State -> 'State) -> array: 'T array -> start: int -> fin: int -> initState: 'State -> 'State array - val inline subUnchecked: int -> int -> 'T[] -> 'T[] + val inline subUnchecked: int -> int -> 'T array -> 'T array - val unstableSortInPlaceBy: projection: ('T -> 'Key) -> array: 'T[] -> unit when 'Key: comparison + val unstableSortInPlaceBy: projection: ('T -> 'Key) -> array: 'T array -> unit when 'Key: comparison - val unstableSortInPlace: array: 'T[] -> unit when 'T: comparison + val unstableSortInPlace: array: 'T array -> unit when 'T: comparison - val stableSortInPlaceBy: projection: ('T -> 'Key) -> array: 'T[] -> unit when 'Key: comparison + val stableSortInPlaceBy: projection: ('T -> 'Key) -> array: 'T array -> unit when 'Key: comparison - val stableSortInPlaceWith: comparer: ('T -> 'T -> int) -> array: 'T[] -> unit + val stableSortInPlaceWith: comparer: ('T -> 'T -> int) -> array: 'T array -> unit - val stableSortInPlace: array: 'T[] -> unit when 'T: comparison + val stableSortInPlace: array: 'T array -> unit when 'T: comparison module internal Seq = val tryLastV: 'T seq -> 'T ValueOption diff --git a/src/FSharp.Core/map.fs b/src/FSharp.Core/map.fs index 35145ad8ec7..43459ecdf33 100644 --- a/src/FSharp.Core/map.fs +++ b/src/FSharp.Core/map.fs @@ -546,13 +546,13 @@ module MapTree = let ofSeq comparer (c: seq<'Key * 'T>) = match c with - | :? (('Key * 'T)[]) as xs -> ofArray comparer xs + | :? (('Key * 'T) array) as xs -> ofArray comparer xs | :? (('Key * 'T) list) as xs -> ofList comparer xs | _ -> use ie = c.GetEnumerator() mkFromEnumerator comparer empty ie - let copyToArray m (arr: _[]) i = + let copyToArray m (arr: _ array) i = let mutable j = i m diff --git a/src/FSharp.Core/map.fsi b/src/FSharp.Core/map.fsi index 49913cadbda..e6b0b1afb30 100644 --- a/src/FSharp.Core/map.fsi +++ b/src/FSharp.Core/map.fsi @@ -294,7 +294,7 @@ module Map = /// /// [] - val ofArray: elements: ('Key * 'T)[] -> Map<'Key, 'T> + val ofArray: elements: ('Key * 'T) array -> Map<'Key, 'T> /// Returns a new map made from the given bindings. /// @@ -361,7 +361,7 @@ module Map = /// /// [] - val toArray: table: Map<'Key, 'T> -> ('Key * 'T)[] + val toArray: table: Map<'Key, 'T> -> ('Key * 'T) array /// Is the map empty? /// diff --git a/src/FSharp.Core/option.fsi b/src/FSharp.Core/option.fsi index a3283345317..2aa2e315d51 100644 --- a/src/FSharp.Core/option.fsi +++ b/src/FSharp.Core/option.fsi @@ -380,7 +380,7 @@ module Option = /// /// [] - val inline toArray: option: 'T option -> 'T[] + val inline toArray: option: 'T option -> 'T array /// Convert the option to a list of length 0 or 1. /// @@ -838,7 +838,7 @@ module ValueOption = /// /// [] - val inline toArray: voption: 'T voption -> 'T[] + val inline toArray: voption: 'T voption -> 'T array /// Convert the value option to a list of length 0 or 1. /// diff --git a/src/FSharp.Core/prim-types-prelude.fsi b/src/FSharp.Core/prim-types-prelude.fsi index f9f8715c1ff..b9bbc5c125f 100644 --- a/src/FSharp.Core/prim-types-prelude.fsi +++ b/src/FSharp.Core/prim-types-prelude.fsi @@ -133,7 +133,7 @@ namespace Microsoft.FSharp.Core /// Basic Types type uint = uint32 - /// Single dimensional, zero-based arrays, written int[], string[] etc. + /// Single dimensional, zero-based arrays, written int array, string array etc. /// /// Use the values in the Array module to manipulate values /// of this type, or the notation arr.[x] to get/set array @@ -396,7 +396,7 @@ namespace Microsoft.FSharp.Core type 'T ``[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]`` = (# "!0[0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...,0 ...]" #) - /// Single dimensional, zero-based arrays, written int[], string[] etc. + /// Single dimensional, zero-based arrays, written int array, string array etc. /// /// Use the values in the module to manipulate values /// of this type, or the notation arr.[x] to get/set array diff --git a/src/FSharp.Core/prim-types.fs b/src/FSharp.Core/prim-types.fs index d44fa86610b..e1f64380f4a 100644 --- a/src/FSharp.Core/prim-types.fs +++ b/src/FSharp.Core/prim-types.fs @@ -225,7 +225,7 @@ namespace Microsoft.FSharp.Core variantNumber:int, sequenceNumber:int, resourceName:string, - typeDefinitions:System.Type[]) = + typeDefinitions:System.Type array) = inherit Attribute() member _.SourceConstructFlags = sourceConstructFlags member _.SequenceNumber = sequenceNumber @@ -272,7 +272,7 @@ namespace Microsoft.FSharp.Core [] [] - type CompilationArgumentCountsAttribute(counts:int[]) = + type CompilationArgumentCountsAttribute(counts:int array) = inherit Attribute() member _.Counts = let unboxPrim(x:obj) = (# "unbox.any !0" type ('T) x : 'T #) @@ -289,6 +289,7 @@ namespace Microsoft.FSharp.Core let mutable maintainsVarSpace = false let mutable maintainsVarSpaceWithBind = false let mutable joinOnWord = "" + new() = CustomOperationAttribute("") member _.Name = name member _.AllowIntoPattern with get() = allowInto and set v = allowInto <- v member _.IsLikeZip with get() = isBinary and set v = isBinary <- v @@ -525,10 +526,10 @@ namespace Microsoft.FSharp.Core let inline ignore _ = () let inline intOfByte (b:byte) = (# "" b : int #) let inline raise (e: System.Exception) = (# "throw" e : 'U #) - let inline length (x: 'T[]) = (# "ldlen conv.i4" x : int #) - let inline zeroCreate (n:int) = (# "newarr !0" type ('T) n : 'T[] #) - let inline get (arr: 'T[]) (n:int) = (# "ldelem.any !0" type ('T) arr n : 'T #) - let set (arr: 'T[]) (n:int) (x:'T) = (# "stelem.any !0" type ('T) arr n x #) + let inline length (x: 'T array) = (# "ldlen conv.i4" x : int #) + let inline zeroCreate (n:int) = (# "newarr !0" type ('T) n : 'T array #) + let inline get (arr: 'T array) (n:int) = (# "ldelem.any !0" type ('T) arr n : 'T #) + let set (arr: 'T array) (n:int) (x:'T) = (# "stelem.any !0" type ('T) arr n x #) let inline objEq (xobj:obj) (yobj:obj) = (# "ceq" xobj yobj : bool #) @@ -574,7 +575,7 @@ namespace Microsoft.FSharp.Core let inline opxor (x:int) (y:int) : int = (# "xor" x y : int32 #) let inline combineTupleHashes (h1 : int) (h2 : int) = (opxor ((opshl h1 5) + h1) h2) - let combineTupleHashCodes (codes : int []) = + let combineTupleHashCodes (codes : int array) = let mutable (num : int32) = codes.Length - 1 while (num > 1) do @@ -759,7 +760,7 @@ namespace Microsoft.FSharp.Core SetArray dst i (GetArray arr (start + i)) dst - let inline SetArraySub arr (start:int) (len:int) (src:_[]) = + let inline SetArraySub arr (start:int) (len:int) (src:_ array) = for i = 0 to len - 1 do SetArray arr (start+i) (GetArray src i) @@ -887,6 +888,123 @@ namespace Microsoft.FSharp.Core module HashCompare = + //------------------------------------------------------------------------- + // LanguagePrimitives.HashCompare: HASHING. + //------------------------------------------------------------------------- + + let defaultHashNodes = 18 + + /// The implementation of IEqualityComparer, using depth-limited for hashing and PER semantics for NaN equality. + type CountLimitedHasherPER(sz:int) = + [] + val mutable nodeCount : int + + member x.Fresh() = + if (System.Threading.Interlocked.CompareExchange(&(x.nodeCount), sz, 0) = 0) then + x + else + new CountLimitedHasherPER(sz) + + interface IEqualityComparer + + /// The implementation of IEqualityComparer, using unlimited depth for hashing and ER semantics for NaN equality. + type UnlimitedHasherER() = + interface IEqualityComparer + + /// The implementation of IEqualityComparer, using unlimited depth for hashing and PER semantics for NaN equality. + type UnlimitedHasherPER() = + interface IEqualityComparer + + + /// The unique object for unlimited depth for hashing and ER semantics for equality. + let fsEqualityComparerUnlimitedHashingER = UnlimitedHasherER() + + /// The unique object for unlimited depth for hashing and PER semantics for equality. + let fsEqualityComparerUnlimitedHashingPER = UnlimitedHasherPER() + + let inline HashCombine nr x y = (x <<< 1) + y + 631 * nr + + let GenericHashObjArray (iec : IEqualityComparer) (x: obj array) : int = + let len = x.Length + let mutable i = len - 1 + if i > defaultHashNodes then i <- defaultHashNodes // limit the hash + let mutable acc = 0 + while (i >= 0) do + // NOTE: GenericHash* call decreases nr + acc <- HashCombine i acc (iec.GetHashCode(x.GetValue(i))); + i <- i - 1 + acc + + // optimized case - byte arrays + let GenericHashByteArray (x: byte array) : int = + let len = length x + let mutable i = len - 1 + if i > defaultHashNodes then i <- defaultHashNodes // limit the hash + let mutable acc = 0 + while (i >= 0) do + acc <- HashCombine i acc (intOfByte (get x i)); + i <- i - 1 + acc + + // optimized case - int arrays + let GenericHashInt32Array (x: int array) : int = + let len = length x + let mutable i = len - 1 + if i > defaultHashNodes then i <- defaultHashNodes // limit the hash + let mutable acc = 0 + while (i >= 0) do + acc <- HashCombine i acc (get x i); + i <- i - 1 + acc + + // optimized case - int arrays + let GenericHashInt64Array (x: int64 array) : int = + let len = length x + let mutable i = len - 1 + if i > defaultHashNodes then i <- defaultHashNodes // limit the hash + let mutable acc = 0 + while (i >= 0) do + acc <- HashCombine i acc (int32 (get x i)); + i <- i - 1 + acc + + // special case - arrays do not by default have a decent structural hashing function + let GenericHashArbArray (iec : IEqualityComparer) (x: System.Array) : int = + match x.Rank with + | 1 -> + let b = x.GetLowerBound(0) + let len = x.Length + let mutable i = b + len - 1 + if i > b + defaultHashNodes then i <- b + defaultHashNodes // limit the hash + let mutable acc = 0 + while (i >= b) do + // NOTE: GenericHash* call decreases nr + acc <- HashCombine i acc (iec.GetHashCode(x.GetValue(i))); + i <- i - 1 + acc + | _ -> + HashCombine 10 (x.GetLength(0)) (x.GetLength(1)) + + // Core implementation of structural hashing, corresponds to pseudo-code in the + // F# Language spec. Searches for the IStructuralHash interface, otherwise uses GetHashCode(). + // Arrays are structurally hashed through a separate technique. + // + // "iec" is either fsEqualityComparerUnlimitedHashingER, fsEqualityComparerUnlimitedHashingPER or a CountLimitedHasherPER. + let rec GenericHashParamObj (iec : IEqualityComparer) (x: obj) : int = + match x with + | null -> 0 + | (:? System.Array as a) -> + match a with + | :? (obj array) as oa -> GenericHashObjArray iec oa + | :? (byte array) as ba -> GenericHashByteArray ba + | :? (int array) as ba -> GenericHashInt32Array ba + | :? (int64 array) as ba -> GenericHashInt64Array ba + | _ -> GenericHashArbArray iec a + | :? IStructuralEquatable as a -> + a.GetHashCode(iec) + | _ -> + x.GetHashCode() + //------------------------------------------------------------------------- // LanguagePrimitives.HashCompare: Physical Equality //------------------------------------------------------------------------- @@ -950,10 +1068,10 @@ namespace Microsoft.FSharp.Core | (:? System.Array as arr1),_ -> match arr1,yobj with // Fast path - | (:? (obj[]) as arr1), (:? (obj[]) as arr2) -> + | (:? (obj array) as arr1), (:? (obj array) as arr2) -> GenericComparisonObjArrayWithComparer comp arr1 arr2 // Fast path - | (:? (byte[]) as arr1), (:? (byte[]) as arr2) -> + | (:? (byte array) as arr1), (:? (byte array) as arr2) -> GenericComparisonByteArray arr1 arr2 | _, (:? System.Array as arr2) -> GenericComparisonArbArrayWithComparer comp arr1 arr2 @@ -1051,7 +1169,7 @@ namespace Microsoft.FSharp.Core precheck (k+1) let c = precheck 0 if c <> 0 then c else - let idxs : int64[] = zeroCreate ndims + let idxs : int64 array = zeroCreate ndims let rec checkN k baseIdx i lim = if i >=. lim then 0 else set idxs k (baseIdx +. i) @@ -1068,7 +1186,7 @@ namespace Microsoft.FSharp.Core check 0 /// optimized case: Core implementation of structural comparison on object arrays. - and GenericComparisonObjArrayWithComparer (comp:GenericComparer) (x:obj[]) (y:obj[]) : int = + and GenericComparisonObjArrayWithComparer (comp:GenericComparer) (x:obj array) (y:obj array) : int = let lenx = x.Length let leny = y.Length let c = intOrder lenx leny @@ -1083,7 +1201,7 @@ namespace Microsoft.FSharp.Core res /// optimized case: Core implementation of structural comparison on arrays. - and GenericComparisonByteArray (x:byte[]) (y:byte[]) : int = + and GenericComparisonByteArray (x:byte array) (y:byte array) : int = let lenx = x.Length let leny = y.Length let c = intOrder lenx leny @@ -1334,7 +1452,7 @@ namespace Microsoft.FSharp.Core /// optimized case: Core implementation of structural equality on arrays. - let GenericEqualityByteArray (x:byte[]) (y:byte[]) : bool= + let GenericEqualityByteArray (x:byte array) (y:byte array) : bool= let lenx = x.Length let leny = y.Length let c = (lenx = leny) @@ -1349,7 +1467,7 @@ namespace Microsoft.FSharp.Core res /// optimized case: Core implementation of structural equality on arrays. - let GenericEqualityInt32Array (x:int[]) (y:int[]) : bool= + let GenericEqualityInt32Array (x:int array) (y:int array) : bool= let lenx = x.Length let leny = y.Length let c = (lenx = leny) @@ -1364,7 +1482,7 @@ namespace Microsoft.FSharp.Core res /// optimized case: Core implementation of structural equality on arrays - let GenericEqualitySingleArray er (x:float32[]) (y:float32[]) : bool= + let GenericEqualitySingleArray er (x:float32 array) (y:float32 array) : bool= let lenx = x.Length let leny = y.Length let f32eq x y = if er && not(float32Eq x x) && not(float32Eq y y) then true else (float32Eq x y) @@ -1380,7 +1498,7 @@ namespace Microsoft.FSharp.Core res /// optimized case: Core implementation of structural equality on arrays. - let GenericEqualityDoubleArray er (x:float[]) (y:float[]) : bool= + let GenericEqualityDoubleArray er (x:float array) (y:float array) : bool= let lenx = x.Length let leny = y.Length let c = (lenx = leny) @@ -1396,7 +1514,7 @@ namespace Microsoft.FSharp.Core res /// optimized case: Core implementation of structural equality on arrays. - let GenericEqualityCharArray (x:char[]) (y:char[]) : bool= + let GenericEqualityCharArray (x:char array) (y:char array) : bool= let lenx = x.Length let leny = y.Length let c = (lenx = leny) @@ -1411,7 +1529,7 @@ namespace Microsoft.FSharp.Core res /// optimized case: Core implementation of structural equality on arrays. - let GenericEqualityInt64Array (x:int64[]) (y:int64[]) : bool= + let GenericEqualityInt64Array (x:int64 array) (y:int64 array) : bool= let lenx = x.Length let leny = y.Length let c = (lenx = leny) @@ -1446,14 +1564,14 @@ namespace Microsoft.FSharp.Core | (:? System.Array as arr1),_ -> match arr1,yobj with // Fast path - | (:? (obj[]) as arr1), (:? (obj[]) as arr2) -> GenericEqualityObjArray er iec arr1 arr2 + | (:? (obj array) as arr1), (:? (obj array) as arr2) -> GenericEqualityObjArray er iec arr1 arr2 // Fast path - | (:? (byte[]) as arr1), (:? (byte[]) as arr2) -> GenericEqualityByteArray arr1 arr2 - | (:? (int32[]) as arr1), (:? (int32[]) as arr2) -> GenericEqualityInt32Array arr1 arr2 - | (:? (int64[]) as arr1), (:? (int64[]) as arr2) -> GenericEqualityInt64Array arr1 arr2 - | (:? (char[]) as arr1), (:? (char[]) as arr2) -> GenericEqualityCharArray arr1 arr2 - | (:? (float32[]) as arr1), (:? (float32[]) as arr2) -> GenericEqualitySingleArray er arr1 arr2 - | (:? (float[]) as arr1), (:? (float[]) as arr2) -> GenericEqualityDoubleArray er arr1 arr2 + | (:? (byte array) as arr1), (:? (byte array) as arr2) -> GenericEqualityByteArray arr1 arr2 + | (:? (int32 array) as arr1), (:? (int32 array) as arr2) -> GenericEqualityInt32Array arr1 arr2 + | (:? (int64 array) as arr1), (:? (int64 array) as arr2) -> GenericEqualityInt64Array arr1 arr2 + | (:? (char array) as arr1), (:? (char array) as arr2) -> GenericEqualityCharArray arr1 arr2 + | (:? (float32 array) as arr1), (:? (float32 array) as arr2) -> GenericEqualitySingleArray er arr1 arr2 + | (:? (float array) as arr1), (:? (float array) as arr2) -> GenericEqualityDoubleArray er arr1 arr2 | _, (:? System.Array as arr2) -> GenericEqualityArbArray er iec arr1 arr2 | _ -> xobj.Equals(yobj) | (:? IStructuralEquatable as x1),_ -> x1.Equals(yobj,iec) @@ -1508,7 +1626,7 @@ namespace Microsoft.FSharp.Core int32Eq (x.GetLowerBound(k)) (y.GetLowerBound(k)) && precheck (k+1)) precheck 0 && - let idxs : int64[] = zeroCreate ndims + let idxs : int64 array = zeroCreate ndims // check contents let rec checkN k baseIdx i lim = (i >=. lim) || @@ -1524,7 +1642,7 @@ namespace Microsoft.FSharp.Core check 0 /// optimized case: Core implementation of structural equality on object arrays. - and GenericEqualityObjArray er iec (x:obj[]) (y:obj[]) : bool = + and GenericEqualityObjArray er iec (x:obj array) (y:obj array) : bool = let lenx = x.Length let leny = y.Length let c = (lenx = leny ) @@ -1664,126 +1782,6 @@ namespace Microsoft.FSharp.Core when 'T : decimal = System.Decimal.op_Equality((# "" x:decimal #), (# "" y:decimal #)) when 'T : DateTime = DateTime.Equals((# "" x : DateTime #), (# "" y : DateTime #)) - //------------------------------------------------------------------------- - // LanguagePrimitives.HashCompare: HASHING. - //------------------------------------------------------------------------- - - - - let defaultHashNodes = 18 - - /// The implementation of IEqualityComparer, using depth-limited for hashing and PER semantics for NaN equality. - type CountLimitedHasherPER(sz:int) = - [] - val mutable nodeCount : int - - member x.Fresh() = - if (System.Threading.Interlocked.CompareExchange(&(x.nodeCount), sz, 0) = 0) then - x - else - new CountLimitedHasherPER(sz) - - interface IEqualityComparer - - /// The implementation of IEqualityComparer, using unlimited depth for hashing and ER semantics for NaN equality. - type UnlimitedHasherER() = - interface IEqualityComparer - - /// The implementation of IEqualityComparer, using unlimited depth for hashing and PER semantics for NaN equality. - type UnlimitedHasherPER() = - interface IEqualityComparer - - - /// The unique object for unlimited depth for hashing and ER semantics for equality. - let fsEqualityComparerUnlimitedHashingER = UnlimitedHasherER() - - /// The unique object for unlimited depth for hashing and PER semantics for equality. - let fsEqualityComparerUnlimitedHashingPER = UnlimitedHasherPER() - - let inline HashCombine nr x y = (x <<< 1) + y + 631 * nr - - let GenericHashObjArray (iec : IEqualityComparer) (x: obj[]) : int = - let len = x.Length - let mutable i = len - 1 - if i > defaultHashNodes then i <- defaultHashNodes // limit the hash - let mutable acc = 0 - while (i >= 0) do - // NOTE: GenericHash* call decreases nr - acc <- HashCombine i acc (iec.GetHashCode(x.GetValue(i))); - i <- i - 1 - acc - - // optimized case - byte arrays - let GenericHashByteArray (x: byte[]) : int = - let len = length x - let mutable i = len - 1 - if i > defaultHashNodes then i <- defaultHashNodes // limit the hash - let mutable acc = 0 - while (i >= 0) do - acc <- HashCombine i acc (intOfByte (get x i)); - i <- i - 1 - acc - - // optimized case - int arrays - let GenericHashInt32Array (x: int[]) : int = - let len = length x - let mutable i = len - 1 - if i > defaultHashNodes then i <- defaultHashNodes // limit the hash - let mutable acc = 0 - while (i >= 0) do - acc <- HashCombine i acc (get x i); - i <- i - 1 - acc - - // optimized case - int arrays - let GenericHashInt64Array (x: int64[]) : int = - let len = length x - let mutable i = len - 1 - if i > defaultHashNodes then i <- defaultHashNodes // limit the hash - let mutable acc = 0 - while (i >= 0) do - acc <- HashCombine i acc (int32 (get x i)); - i <- i - 1 - acc - - // special case - arrays do not by default have a decent structural hashing function - let GenericHashArbArray (iec : IEqualityComparer) (x: System.Array) : int = - match x.Rank with - | 1 -> - let b = x.GetLowerBound(0) - let len = x.Length - let mutable i = b + len - 1 - if i > b + defaultHashNodes then i <- b + defaultHashNodes // limit the hash - let mutable acc = 0 - while (i >= b) do - // NOTE: GenericHash* call decreases nr - acc <- HashCombine i acc (iec.GetHashCode(x.GetValue(i))); - i <- i - 1 - acc - | _ -> - HashCombine 10 (x.GetLength(0)) (x.GetLength(1)) - - // Core implementation of structural hashing, corresponds to pseudo-code in the - // F# Language spec. Searches for the IStructuralHash interface, otherwise uses GetHashCode(). - // Arrays are structurally hashed through a separate technique. - // - // "iec" is either fsEqualityComparerUnlimitedHashingER, fsEqualityComparerUnlimitedHashingPER or a CountLimitedHasherPER. - let rec GenericHashParamObj (iec : IEqualityComparer) (x: obj) : int = - match x with - | null -> 0 - | (:? System.Array as a) -> - match a with - | :? (obj[]) as oa -> GenericHashObjArray iec oa - | :? (byte[]) as ba -> GenericHashByteArray ba - | :? (int[]) as ba -> GenericHashInt32Array ba - | :? (int64[]) as ba -> GenericHashInt64Array ba - | _ -> GenericHashArbArray iec a - | :? IStructuralEquatable as a -> - a.GetHashCode(iec) - | _ -> - x.GetHashCode() - - /// Fill in the implementation of CountLimitedHasherPER type CountLimitedHasherPER with @@ -2602,7 +2600,7 @@ namespace Microsoft.FSharp.Core type Type with /// Gets a single static non-conversion operator or method by types - member inline this.GetSingleStaticMethodByTypes(name: string, parameterTypes: Type[]) = + member inline this.GetSingleStaticMethodByTypes(name: string, parameterTypes: Type array) = let staticBindingFlags = (# "" 0b111000 : BindingFlags #) // BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic this.GetMethod(name, staticBindingFlags, null, parameterTypes, null ) @@ -4002,7 +4000,7 @@ namespace Microsoft.FSharp.Collections let items length = let items = zeroCreate length - let rec copy (items: 'T[]) l i = + let rec copy (items: 'T array) l i = match l with | [] -> () | h :: t -> @@ -6039,11 +6037,11 @@ namespace Microsoft.FSharp.Core low, high - let inline GetArraySlice (source: _[]) start finish = + let inline GetArraySlice (source: _ array) start finish = let start, finish = ComputeSlice 0 start finish source.Length GetArraySub source start (finish - start + 1) - let inline SetArraySlice (target: _[]) start finish (source: _[]) = + let inline SetArraySlice (target: _ array) start finish (source: _ array) = let start = (match start with None -> 0 | Some n -> n) let finish = (match finish with None -> target.Length - 1 | Some n -> n) SetArraySub target start (finish - start + 1) source @@ -6075,7 +6073,7 @@ namespace Microsoft.FSharp.Core let inline GetArraySlice2DFixed2 (source: _[,]) start1 finish1 index2 = GetArraySlice2DFixed source start1 finish1 index2 0 - let inline SetArraySlice2DFixed (target: _[,]) (source: _[]) index start finish nonFixedDim = + let inline SetArraySlice2DFixed (target: _[,]) (source: _ array) index start finish nonFixedDim = let bound = target.GetLowerBound(nonFixedDim) let start, finish = ComputeSlice bound start finish (GetArray2DLength target nonFixedDim) let len = (finish - start + 1) @@ -6087,9 +6085,9 @@ namespace Microsoft.FSharp.Core for j = 0 to len - 1 do setArrayElem j - let inline SetArraySlice2DFixed1 (target: _[,]) index1 start2 finish2 (source: _[]) = SetArraySlice2DFixed target source index1 start2 finish2 1 + let inline SetArraySlice2DFixed1 (target: _[,]) index1 start2 finish2 (source: _ array) = SetArraySlice2DFixed target source index1 start2 finish2 1 - let inline SetArraySlice2DFixed2 (target: _[,]) start1 finish1 index2 (source:_[]) = SetArraySlice2DFixed target source index2 start1 finish1 0 + let inline SetArraySlice2DFixed2 (target: _[,]) start1 finish1 index2 (source:_ array) = SetArraySlice2DFixed target source index2 start1 finish1 0 let inline SetArraySlice2D (target: _[,]) start1 finish1 start2 finish2 (source: _[,]) = let bound1 = target.GetLowerBound(0) @@ -6203,7 +6201,7 @@ namespace Microsoft.FSharp.Core let inline SetArraySlice3DFixedSingle3 (target: _[,,]) start1 finish1 start2 finish2 index (source: _[,]) = SetArraySlice3DFixedSingle target source index start1 finish1 start2 finish2 0 1 - let inline SetArraySlice3DFixedDouble (target: _[,,]) (source: _[]) index1 index2 start finish nonFixedDim = + let inline SetArraySlice3DFixedDouble (target: _[,,]) (source: _ array) index1 index2 start finish nonFixedDim = let bound = target.GetLowerBound(nonFixedDim) let start, finish = ComputeSlice bound start finish (GetArray3DLength target nonFixedDim) let len = (finish - start + 1) @@ -6216,13 +6214,13 @@ namespace Microsoft.FSharp.Core for j = 0 to len - 1 do setArrayElem j - let inline SetArraySlice3DFixedDouble1 (target: _[,,]) index1 index2 start3 finish3 (source: _[]) = + let inline SetArraySlice3DFixedDouble1 (target: _[,,]) index1 index2 start3 finish3 (source: _ array) = SetArraySlice3DFixedDouble target source index1 index2 start3 finish3 2 - let inline SetArraySlice3DFixedDouble2 (target: _[,,]) index1 start2 finish2 index3 (source: _[]) = + let inline SetArraySlice3DFixedDouble2 (target: _[,,]) index1 start2 finish2 index3 (source: _ array) = SetArraySlice3DFixedDouble target source index1 index3 start2 finish2 1 - let inline SetArraySlice3DFixedDouble3 (target: _[,,]) start1 finish1 index2 index3 (source: _[]) = + let inline SetArraySlice3DFixedDouble3 (target: _[,,]) start1 finish1 index2 index3 (source: _ array) = SetArraySlice3DFixedDouble target source index2 index3 start1 finish1 0 let inline GetArraySlice4D (source: _[,,,]) start1 finish1 start2 finish2 start3 finish3 start4 finish4 = @@ -6440,7 +6438,7 @@ namespace Microsoft.FSharp.Core let inline SetArraySlice4DFixedDouble6 (target: _[,,,]) start1 finish1 start2 finish2 index3 index4 (source: _[,]) = SetArraySlice4DFixedDouble target source index3 index4 start1 finish1 start2 finish2 0 1 - let inline SetArraySlice4DFixedTriple (target: _[,,,]) (source: _[]) index1 index2 index3 start1 finish1 nonFixedDim1 = + let inline SetArraySlice4DFixedTriple (target: _[,,,]) (source: _ array) index1 index2 index3 start1 finish1 nonFixedDim1 = let bound1 = target.GetLowerBound(nonFixedDim1) let start1, finish1 = ComputeSlice bound1 start1 finish1 (GetArray4DLength target nonFixedDim1) let len1 = (finish1 - start1 + 1) @@ -6454,16 +6452,16 @@ namespace Microsoft.FSharp.Core for i = 0 to len1 - 1 do setArrayElem i - let inline SetArraySlice4DFixedTriple1 (target: _[,,,]) start1 finish1 index2 index3 index4 (source: _[]) = + let inline SetArraySlice4DFixedTriple1 (target: _[,,,]) start1 finish1 index2 index3 index4 (source: _ array) = SetArraySlice4DFixedTriple target source index2 index3 index4 start1 finish1 0 - let inline SetArraySlice4DFixedTriple2 (target: _[,,,]) index1 start2 finish2 index3 index4 (source: _[]) = + let inline SetArraySlice4DFixedTriple2 (target: _[,,,]) index1 start2 finish2 index3 index4 (source: _ array) = SetArraySlice4DFixedTriple target source index1 index3 index4 start2 finish2 1 - let inline SetArraySlice4DFixedTriple3 (target: _[,,,]) index1 index2 start3 finish3 index4 (source: _[]) = + let inline SetArraySlice4DFixedTriple3 (target: _[,,,]) index1 index2 start3 finish3 index4 (source: _ array) = SetArraySlice4DFixedTriple target source index1 index2 index4 start3 finish3 2 - let inline SetArraySlice4DFixedTriple4 (target: _[,,,]) index1 index2 index3 start4 finish4 (source: _[]) = + let inline SetArraySlice4DFixedTriple4 (target: _[,,,]) index1 index2 index3 start4 finish4 (source: _ array) = SetArraySlice4DFixedTriple target source index1 index2 index3 start4 finish4 3 let inline GetStringSlice (source: string) start finish = diff --git a/src/FSharp.Core/prim-types.fsi b/src/FSharp.Core/prim-types.fsi index 13fb9e46ff9..e3c2bb245b6 100644 --- a/src/FSharp.Core/prim-types.fsi +++ b/src/FSharp.Core/prim-types.fsi @@ -420,6 +420,10 @@ namespace Microsoft.FSharp.Core /// CustomOperationAttribute new: name:string -> CustomOperationAttribute + /// Create an instance of attribute with empty name + /// CustomOperationAttribute + new: unit -> CustomOperationAttribute + /// Get the name of the custom operation when used in a query or other computation expression member Name: string @@ -687,7 +691,7 @@ namespace Microsoft.FSharp.Core /// The name of the resource needed to resolve the source construct. /// /// CompilationMappingAttribute - new: resourceName:string * typeDefinitions:System.Type[] -> CompilationMappingAttribute + new: resourceName:string * typeDefinitions:System.Type array -> CompilationMappingAttribute /// Indicates the relationship between the compiled entity and F# source code member SourceConstructFlags: SourceConstructFlags @@ -702,7 +706,7 @@ namespace Microsoft.FSharp.Core member ResourceName: string /// Indicates the type definitions needed to resolve the source construct - member TypeDefinitions: System.Type[] + member TypeDefinitions: System.Type array /// This attribute is inserted automatically by the F# compiler to tag /// methods which are given the 'CompiledName' attribute. @@ -805,7 +809,7 @@ namespace Microsoft.FSharp.Core /// Indicates the number of arguments in each argument group. /// /// CompilationArgumentCountsAttribute - new: counts:int[] -> CompilationArgumentCountsAttribute + new: counts:int array -> CompilationArgumentCountsAttribute /// Indicates the number of arguments in each argument group member Counts: System.Collections.Generic.IEnumerable @@ -1785,7 +1789,7 @@ namespace Microsoft.FSharp.Core /// The standard overloaded associative (indexed) lookup operator //[] - val inline GetArray: source: 'T[] -> index: int -> 'T + val inline GetArray: source: 'T array -> index: int -> 'T /// The standard overloaded associative (2-indexed) lookup operator //[] @@ -1801,7 +1805,7 @@ namespace Microsoft.FSharp.Core /// The standard overloaded associative (indexed) mutation operator //[] - val inline SetArray: target: 'T[] -> index: int -> value: 'T -> unit + val inline SetArray: target: 'T array -> index: int -> value: 'T -> unit /// The standard overloaded associative (2-indexed) mutation operator //[] @@ -4859,7 +4863,7 @@ namespace Microsoft.FSharp.Core /// The end index. /// /// The sub array from the input indices. - val inline GetArraySlice: source:'T[] -> start:int option -> finish:int option -> 'T[] + val inline GetArraySlice: source:'T array -> start:int option -> finish:int option -> 'T array /// Sets a slice of an array /// @@ -4867,7 +4871,7 @@ namespace Microsoft.FSharp.Core /// The start index. /// The end index. /// The source array. - val inline SetArraySlice: target:'T[] -> start:int option -> finish:int option -> source:'T[] -> unit + val inline SetArraySlice: target:'T array -> start:int option -> finish:int option -> source:'T array -> unit /// Gets a region slice of an array /// @@ -4888,7 +4892,7 @@ namespace Microsoft.FSharp.Core /// The end index of the second dimension. /// /// The sub array from the input indices. - val inline GetArraySlice2DFixed1: source:'T[,] -> index1:int -> start2:int option -> finish2:int option -> 'T[] + val inline GetArraySlice2DFixed1: source:'T[,] -> index1:int -> start2:int option -> finish2:int option -> 'T array /// Gets a vector slice of a 2D array. The index of the second dimension is fixed. /// @@ -4898,7 +4902,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the second dimension. /// /// The sub array from the input indices. - val inline GetArraySlice2DFixed2: source:'T[,] -> start1:int option -> finish1:int option -> index2: int -> 'T[] + val inline GetArraySlice2DFixed2: source:'T[,] -> start1:int option -> finish1:int option -> index2: int -> 'T array /// Sets a region slice of an array /// @@ -4917,7 +4921,7 @@ namespace Microsoft.FSharp.Core /// The start index of the second dimension. /// The end index of the second dimension. /// The source array. - val inline SetArraySlice2DFixed1: target:'T[,] -> index1:int -> start2:int option -> finish2:int option -> source:'T[] -> unit + val inline SetArraySlice2DFixed1: target:'T[,] -> index1:int -> start2:int option -> finish2:int option -> source:'T array -> unit /// Sets a vector slice of a 2D array. The index of the second dimension is fixed. /// @@ -4926,7 +4930,7 @@ namespace Microsoft.FSharp.Core /// The end index of the first dimension. /// The index of the second dimension. /// The source array. - val inline SetArraySlice2DFixed2: target:'T[,] -> start1:int option -> finish1:int option -> index2:int -> source:'T[] -> unit + val inline SetArraySlice2DFixed2: target:'T[,] -> start1:int option -> finish1:int option -> index2:int -> source:'T array -> unit /// Gets a slice of an array /// @@ -4986,7 +4990,7 @@ namespace Microsoft.FSharp.Core /// The end index of the third dimension. /// /// The one dimensional sub array from the given indices. - val inline GetArraySlice3DFixedDouble1: source:'T[,,] -> index1:int -> index2:int -> start3:int option -> finish3:int option -> 'T[] + val inline GetArraySlice3DFixedDouble1: source:'T[,,] -> index1:int -> index2:int -> start3:int option -> finish3:int option -> 'T array /// Gets a 1D slice of a 3D array. /// @@ -4997,7 +5001,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the third dimension. /// /// The one dimensional sub array from the given indices. - val inline GetArraySlice3DFixedDouble2: source:'T[,,] -> index1:int -> start2:int option -> finish2:int option -> index3:int -> 'T[] + val inline GetArraySlice3DFixedDouble2: source:'T[,,] -> index1:int -> start2:int option -> finish2:int option -> index3:int -> 'T array /// Gets a 1D slice of a 3D array. /// @@ -5008,7 +5012,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the third dimension. /// /// The one dimensional sub array from the given indices. - val inline GetArraySlice3DFixedDouble3: source:'T[,,] -> start1:int option -> finish1:int option -> index2:int -> index3:int -> 'T[] + val inline GetArraySlice3DFixedDouble3: source:'T[,,] -> start1:int option -> finish1:int option -> index2:int -> index3:int -> 'T array /// Sets a slice of an array /// @@ -5071,7 +5075,7 @@ namespace Microsoft.FSharp.Core /// The source array. /// /// The one dimensional sub array from the given indices. - val inline SetArraySlice3DFixedDouble1: target: 'T[,,] -> index1: int -> index2: int -> start3: int option -> finish3: int option -> source: 'T[] -> unit + val inline SetArraySlice3DFixedDouble1: target: 'T[,,] -> index1: int -> index2: int -> start3: int option -> finish3: int option -> source: 'T array -> unit /// Sets a 1D slice of a 3D array. /// @@ -5083,7 +5087,7 @@ namespace Microsoft.FSharp.Core /// The source array. /// /// The one dimensional sub array from the given indices. - val inline SetArraySlice3DFixedDouble2: target: 'T[,,] -> index1: int -> start2: int option -> finish2: int option -> index3: int -> source: 'T[] -> unit + val inline SetArraySlice3DFixedDouble2: target: 'T[,,] -> index1: int -> start2: int option -> finish2: int option -> index3: int -> source: 'T array -> unit /// Sets a 1D slice of a 3D array. /// @@ -5095,7 +5099,7 @@ namespace Microsoft.FSharp.Core /// The source array. /// /// The one dimensional sub array from the given indices. - val inline SetArraySlice3DFixedDouble3: target: 'T[,,] -> start1: int option -> finish1: int option -> index2: int -> index3: int -> source: 'T[] -> unit + val inline SetArraySlice3DFixedDouble3: target: 'T[,,] -> start1: int option -> finish1: int option -> index2: int -> index3: int -> source: 'T array -> unit /// Gets a slice of an array /// @@ -5256,7 +5260,7 @@ namespace Microsoft.FSharp.Core /// The end index of the fourth dimension. /// /// The one dimensional sub array from the given indices. - val inline GetArraySlice4DFixedTriple4: source: 'T[,,,] -> index1: int -> index2: int -> index3: int -> start4: int option -> finish4: int option -> 'T[] + val inline GetArraySlice4DFixedTriple4: source: 'T[,,,] -> index1: int -> index2: int -> index3: int -> start4: int option -> finish4: int option -> 'T array /// Gets a 1D slice of a 4D array /// @@ -5268,7 +5272,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the fourth dimension. /// /// The one dimensional sub array from the given indices. - val inline GetArraySlice4DFixedTriple3: source: 'T[,,,] -> index1: int -> index2: int -> start3: int option -> finish3: int option -> index4: int -> 'T[] + val inline GetArraySlice4DFixedTriple3: source: 'T[,,,] -> index1: int -> index2: int -> start3: int option -> finish3: int option -> index4: int -> 'T array /// Gets a 1D slice of a 4D array /// @@ -5280,7 +5284,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the fourth dimension. /// /// The one dimensional sub array from the given indices. - val inline GetArraySlice4DFixedTriple2: source:'T[,,,] -> index1: int -> start2: int option -> finish2: int option -> index3: int -> index4: int -> 'T[] + val inline GetArraySlice4DFixedTriple2: source:'T[,,,] -> index1: int -> start2: int option -> finish2: int option -> index3: int -> index4: int -> 'T array /// Gets a 1D slice of a 4D array /// @@ -5292,7 +5296,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the fourth dimension. /// /// The one dimensional sub array from the given indices. - val inline GetArraySlice4DFixedTriple1: source: 'T[,,,] -> start1: int option -> finish1: int option -> index2: int -> index3: int -> index4: int -> 'T[] + val inline GetArraySlice4DFixedTriple1: source: 'T[,,,] -> start1: int option -> finish1: int option -> index2: int -> index3: int -> index4: int -> 'T array /// Sets a 3D slice of a 4D array /// @@ -5427,7 +5431,7 @@ namespace Microsoft.FSharp.Core /// The start index of the fourth dimension. /// The end index of the fourth dimension. /// The source array. - val inline SetArraySlice4DFixedTriple4: target:'T[,,,] -> index1:int -> index2:int -> index3:int -> start4:int option -> finish4:int option -> source: 'T[] -> unit + val inline SetArraySlice4DFixedTriple4: target:'T[,,,] -> index1:int -> index2:int -> index3:int -> start4:int option -> finish4:int option -> source: 'T array -> unit /// Sets a 1D slice of a 4D array /// @@ -5438,7 +5442,7 @@ namespace Microsoft.FSharp.Core /// The end index of the third dimension. /// The fixed index of the fourth dimension. /// The source array. - val inline SetArraySlice4DFixedTriple3: target:'T[,,,] -> index1:int -> index2:int -> start3:int option -> finish3:int option -> index4:int -> source: 'T[] -> unit + val inline SetArraySlice4DFixedTriple3: target:'T[,,,] -> index1:int -> index2:int -> start3:int option -> finish3:int option -> index4:int -> source: 'T array -> unit /// Sets a 1D slice of a 4D array /// @@ -5449,7 +5453,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the third dimension. /// The fixed index of the fourth dimension. /// The source array. - val inline SetArraySlice4DFixedTriple2: target:'T[,,,] -> index1:int -> start2: int option -> finish2:int option -> index3:int -> index4:int -> source: 'T[] -> unit + val inline SetArraySlice4DFixedTriple2: target:'T[,,,] -> index1:int -> start2: int option -> finish2:int option -> index3:int -> index4:int -> source: 'T array -> unit /// Sets a 1D slice of a 4D array /// @@ -5460,7 +5464,7 @@ namespace Microsoft.FSharp.Core /// The fixed index of the third dimension. /// The fixed index of the fourth dimension. /// The source array. - val inline SetArraySlice4DFixedTriple1: target:'T[,,,] -> start1:int option -> finish1:int option -> index2:int -> index3:int -> index4:int -> source: 'T[] -> unit + val inline SetArraySlice4DFixedTriple1: target:'T[,,,] -> start1:int option -> finish1:int option -> index2:int -> index3:int -> index4:int -> source: 'T array -> unit /// Sets a slice of an array /// diff --git a/src/FSharp.Core/printf.fs b/src/FSharp.Core/printf.fs index 9a7d461d698..7afcce1e66b 100644 --- a/src/FSharp.Core/printf.fs +++ b/src/FSharp.Core/printf.fs @@ -19,7 +19,7 @@ open LanguagePrimitives.IntrinsicOperators type PrintfFormat<'Printer, 'State, 'Residue, 'Result> [] - (value:string, captures: obj[], captureTys: Type[]) = + (value:string, captures: obj array, captureTys: Type array) = [] new (value) = new PrintfFormat<'Printer, 'State, 'Residue, 'Result>(value, null, null) @@ -34,7 +34,7 @@ type PrintfFormat<'Printer, 'State, 'Residue, 'Result> type PrintfFormat<'Printer, 'State, 'Residue, 'Result, 'Tuple> [] - (value:string, captures, captureTys: Type[]) = + (value:string, captures, captureTys: Type array) = inherit PrintfFormat<'Printer, 'State, 'Residue, 'Result>(value, captures, captureTys) @@ -274,7 +274,7 @@ module internal PrintfImpl = | StepPercentStar2 of prefix: string // Count the number of string fragments in a sequence of steps - static member BlockCount(steps: Step[]) = + static member BlockCount(steps: Step array) = let mutable count = 0 for step in steps do match step with @@ -323,7 +323,7 @@ module internal PrintfImpl = if not (String.IsNullOrEmpty s) then env.Write s - member env.RunSteps (args: obj[], argTys: Type[], steps: Step[]) = + member env.RunSteps (args: obj array, argTys: Type array, steps: Step array) = let mutable argIndex = 0 let mutable tyIndex = 0 @@ -1029,7 +1029,7 @@ module internal PrintfImpl = type LargeStringPrintfEnv<'Result>(continuation, blockSize) = inherit PrintfEnv(()) - let buf: string[] = Array.zeroCreate blockSize + let buf: string array = Array.zeroCreate blockSize let mutable ptr = 0 override _.Finish() : 'Result = continuation (String.Concat buf) @@ -1089,8 +1089,8 @@ module internal PrintfImpl = [] type FormatParser<'Printer, 'State, 'Residue, 'Result>(fmt: string) = - let buildCaptureFunc (spec: FormatSpecifier, allSteps, argTys: Type[], retTy, nextInfo) = - let (next:obj, nextCanCombine: bool, nextArgTys: Type[], nextRetTy, nextNextOpt) = nextInfo + let buildCaptureFunc (spec: FormatSpecifier, allSteps, argTys: Type array, retTy, nextInfo) = + let (next:obj, nextCanCombine: bool, nextArgTys: Type array, nextRetTy, nextNextOpt) = nextInfo assert (argTys.Length > 0) // See if we can compress a capture to a multi-capture @@ -1133,7 +1133,7 @@ module internal PrintfImpl = let factoryObj = mi.Invoke(null, [| next |]) factoryObj, true, argTys, retTy, Some next - let buildStep (spec: FormatSpecifier) (argTys: Type[]) prefix = + let buildStep (spec: FormatSpecifier) (argTys: Type array) prefix = if spec.TypeChar = 'a' then StepLittleA prefix elif spec.TypeChar = 't' then diff --git a/src/FSharp.Core/printf.fsi b/src/FSharp.Core/printf.fsi index a188e570183..2e4d009c537 100644 --- a/src/FSharp.Core/printf.fsi +++ b/src/FSharp.Core/printf.fsi @@ -30,16 +30,18 @@ type PrintfFormat<'Printer, 'State, 'Residue, 'Result> = /// The captured expressions in an interpolated string. /// The types of expressions for %A expression gaps in interpolated string. /// The PrintfFormat containing the formatted result. - new: value: string * captures: obj[] * captureTys: Type[] -> PrintfFormat<'Printer, 'State, 'Residue, 'Result> + new: + value: string * captures: obj array * captureTys: Type array -> + 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[] + member Captures: obj array /// The capture types associated with an interpolated string. - member CaptureTypes: System.Type[] + member CaptureTypes: System.Type array /// Type of a formatting expression. /// @@ -69,7 +71,7 @@ type PrintfFormat<'Printer, 'State, 'Residue, 'Result, 'Tuple> = /// /// The created format string. new: - value: string * captures: obj[] * captureTys: Type[] -> + value: string * captures: obj array * captureTys: Type array -> PrintfFormat<'Printer, 'State, 'Residue, 'Result, 'Tuple> /// Type of a formatting expression. diff --git a/src/FSharp.Core/quotations.fs b/src/FSharp.Core/quotations.fs index 18a3f4cae12..4c71bf0d928 100644 --- a/src/FSharp.Core/quotations.fs +++ b/src/FSharp.Core/quotations.fs @@ -92,7 +92,7 @@ module Helpers = | null -> nullArg argName | _ -> () - let getTypesFromParamInfos (infos: ParameterInfo[]) = + let getTypesFromParamInfos (infos: ParameterInfo array) = infos |> Array.map (fun pi -> pi.ParameterType) open Helpers @@ -456,7 +456,7 @@ module Patterns = /// as a computation. type Instantiable<'T> = (int -> Type) -> 'T - type ByteStream(bytes: byte[], initial: int, len: int) = + type ByteStream(bytes: byte array, initial: int, len: int) = let mutable pos = initial let lim = initial + len @@ -970,7 +970,7 @@ module Patterns = if (not (assignableFrom expectedType receivedType)) then invalidArg "receivedType" (String.Format(threeHoleSR, name, expectedType, receivedType)) - let checkArgs (paramInfos: ParameterInfo[]) (args: Expr list) = + let checkArgs (paramInfos: ParameterInfo array) (args: Expr list) = if (paramInfos.Length <> args.Length) then invalidArg "args" (SR.GetString(SR.QincorrectNumArgs)) @@ -1381,7 +1381,7 @@ module Patterns = let typesEqual (tys1: Type list) (tys2: Type list) = (tys1.Length = tys2.Length) && List.forall2 typeEquals tys1 tys2 - let instFormal (typarEnv: Type[]) (ty: Instantiable<'T>) = + let instFormal (typarEnv: Type array) (ty: Instantiable<'T>) = ty (fun i -> typarEnv.[i]) let getGenericArguments (genericType: Type) = @@ -1672,9 +1672,9 @@ module Patterns = type InputState = { is: ByteStream - istrings: string[] + istrings: string array localAssembly: System.Reflection.Assembly - referencedTypeDefs: Type[] + referencedTypeDefs: Type array } let u_byte_as_int st = @@ -1935,7 +1935,7 @@ module Patterns = varn = env.varn + 1 } - let mkTyparSubst (tyargs: Type[]) = + let mkTyparSubst (tyargs: Type array) = let n = tyargs.Length fun idx -> @@ -1944,7 +1944,7 @@ module Patterns = else invalidOp (SR.GetString(SR.QtypeArgumentOutOfRange)) - let envClosed (spliceTypes: Type[]) = + let envClosed (spliceTypes: Type array) = { vars = Map.empty varn = 0 @@ -2256,7 +2256,7 @@ module Patterns = //-------------------------------------------------------------------------- /// Fill the holes in an Expr - let rec fillHolesInRawExpr (l: Expr[]) (E t as e) = + let rec fillHolesInRawExpr (l: Expr array) (E t as e) = match t with | VarTerm _ -> e | LambdaTerm(v, b) -> EA(LambdaTerm(v, fillHolesInRawExpr l b), e.CustomAttributes) @@ -2363,7 +2363,7 @@ module Patterns = resourceName.StartsWith(ReflectedDefinitionsResourceNameBase, StringComparison.Ordinal) /// Get the reflected definition at the given (always generic) instantiation - let tryGetReflectedDefinition (methodBase: MethodBase, tyargs: Type[]) = + let tryGetReflectedDefinition (methodBase: MethodBase, tyargs: Type array) = checkNonNull "methodBase" methodBase let data = @@ -2692,12 +2692,12 @@ type Expr with static member Cast(source: Expr) = cast source - static member Deserialize(qualifyingType: Type, spliceTypes, spliceExprs, bytes: byte[]) = + static member Deserialize(qualifyingType: Type, spliceTypes, spliceExprs, bytes: byte array) = checkNonNull "qualifyingType" qualifyingType checkNonNull "bytes" bytes deserialize (qualifyingType, [||], Array.ofList spliceTypes, Array.ofList spliceExprs, bytes) - static member Deserialize40(qualifyingType: Type, referencedTypes, spliceTypes, spliceExprs, bytes: byte[]) = + static member Deserialize40(qualifyingType: Type, referencedTypes, spliceTypes, spliceExprs, bytes: byte array) = checkNonNull "spliceExprs" spliceExprs checkNonNull "spliceTypes" spliceTypes checkNonNull "referencedTypeDefs" referencedTypes diff --git a/src/FSharp.Core/quotations.fsi b/src/FSharp.Core/quotations.fsi index f3aec29009a..ad69f801996 100644 --- a/src/FSharp.Core/quotations.fsi +++ b/src/FSharp.Core/quotations.fsi @@ -1269,7 +1269,7 @@ type Expr = /// /// The resulting expression. static member Deserialize: - qualifyingType: Type * spliceTypes: Type list * spliceExprs: Expr list * bytes: byte[] -> Expr + qualifyingType: Type * spliceTypes: Type list * spliceExprs: Expr list * bytes: byte array -> Expr /// This function is called automatically when quotation syntax (<@ @>) and other sources of /// quotations are used. @@ -1282,7 +1282,11 @@ type Expr = /// /// The resulting expression. static member Deserialize40: - qualifyingType: Type * referencedTypes: Type[] * spliceTypes: Type[] * spliceExprs: Expr[] * bytes: byte[] -> + qualifyingType: Type * + referencedTypes: Type array * + spliceTypes: Type array * + spliceExprs: Expr array * + bytes: byte array -> Expr /// Permits interactive environments such as F# Interactive @@ -1293,7 +1297,8 @@ type Expr = /// The unique name for the resources being added. /// The serialized resource to register with the environment. /// - static member RegisterReflectedDefinitions: assembly: Assembly * resource: string * serializedValue: byte[] -> unit + static member RegisterReflectedDefinitions: + assembly: Assembly * resource: string * serializedValue: byte array -> unit /// Permits interactive environments such as F# Interactive /// to explicitly register new pickled resources that represent persisted @@ -1305,7 +1310,7 @@ type Expr = /// The serialized resource to register with the environment. /// static member RegisterReflectedDefinitions: - assembly: Assembly * resource: string * serializedValue: byte[] * referencedTypes: Type[] -> unit + assembly: Assembly * resource: string * serializedValue: byte array * referencedTypes: Type array -> unit /// Fetches or creates a new variable with the given name and type from a global pool of shared variables /// indexed by name and type. The type is given by the explicit or inferred type parameter diff --git a/src/FSharp.Core/reflect.fs b/src/FSharp.Core/reflect.fs index df487893df9..500d0b2effc 100644 --- a/src/FSharp.Core/reflect.fs +++ b/src/FSharp.Core/reflect.fs @@ -91,12 +91,12 @@ module internal Impl = expr.Compile() - let compileRecordOrUnionCaseReaderFunc (typ, props: PropertyInfo[]) = + let compileRecordOrUnionCaseReaderFunc (typ, props: PropertyInfo array) = let param = Expression.Parameter(typeof, "param") let typedParam = Expression.Variable typ let expr = - Expression.Lambda>( + Expression.Lambda>( Expression.Block( [ typedParam ], Expression.Assign(typedParam, Expression.Convert(param, typ)), @@ -115,10 +115,10 @@ module internal Impl = let compileRecordConstructorFunc (ctorInfo: ConstructorInfo) = let ctorParams = ctorInfo.GetParameters() - let paramArray = Expression.Parameter(typeof, "paramArray") + let paramArray = Expression.Parameter(typeof, "paramArray") let expr = - Expression.Lambda>( + Expression.Lambda>( Expression.Convert( Expression.New( ctorInfo, @@ -139,10 +139,10 @@ module internal Impl = let compileUnionCaseConstructorFunc (methodInfo: MethodInfo) = let methodParams = methodInfo.GetParameters() - let paramArray = Expression.Parameter(typeof, "param") + let paramArray = Expression.Parameter(typeof, "param") let expr = - Expression.Lambda>( + Expression.Lambda>( Expression.Convert( Expression.Call( methodInfo, @@ -192,10 +192,10 @@ module internal Impl = ] ) - let elements = Expression.Parameter(typeof, "elements") + let elements = Expression.Parameter(typeof, "elements") let expr = - Expression.Lambda>( + Expression.Lambda>( Expression.Convert(constituentTuple typ elements 0, typeof), elements ) @@ -208,10 +208,10 @@ module internal Impl = let elements = match getTupleElementAccessors typ with // typ is a struct tuple and its elements are accessed via fields - | Choice1Of2(fi: FieldInfo[]) -> + | Choice1Of2(fi: FieldInfo array) -> fi |> Array.map (fun fi -> Expression.Field(tuple, fi), fi.FieldType) // typ is a class tuple and its elements are accessed via properties - | Choice2Of2(pi: PropertyInfo[]) -> + | Choice2Of2(pi: PropertyInfo array) -> pi |> Array.map (fun pi -> Expression.Property(tuple, pi), pi.PropertyType) for index, (element, elementType) in elements |> Array.indexed do @@ -235,7 +235,7 @@ module internal Impl = } let param = Expression.Parameter(typeof, "outerTuple") - let outputArray = Expression.Variable(typeof, "output") + let outputArray = Expression.Variable(typeof, "output") let rec outputLength tupleEncField (typ: Type) = let genericArgs = typ.GetGenericArguments() @@ -246,7 +246,7 @@ module internal Impl = genericArgs.Length let expr = - Expression.Lambda>( + Expression.Lambda>( Expression.Block( [ outputArray ], [ @@ -266,7 +266,7 @@ module internal Impl = //----------------------------------------------------------------- // ATTRIBUTE DECOMPILATION - let tryFindCompilationMappingAttribute (attrs: obj[]) = + let tryFindCompilationMappingAttribute (attrs: obj array) = match attrs with | null | [||] -> None @@ -275,7 +275,7 @@ module internal Impl = Some(a.SourceConstructFlags, a.SequenceNumber, a.VariantNumber) | _ -> invalidOp (SR.GetString(SR.multipleCompilationMappings)) - let findCompilationMappingAttribute (attrs: obj[]) = + let findCompilationMappingAttribute (attrs: obj array) = match tryFindCompilationMappingAttribute attrs with | None -> failwith "no compilation mapping attribute" | Some a -> a @@ -688,10 +688,10 @@ module internal Impl = |] let private dictionaryLock = obj () - let private refTupleTypes = Dictionary() - let private valueTupleTypes = Dictionary() + let private refTupleTypes = Dictionary() + let private valueTupleTypes = Dictionary() - let rec mkTupleType isStruct (asm: Assembly) (tys: Type[]) = + let rec mkTupleType isStruct (asm: Assembly) (tys: Type array) = let table = let makeIt n = let tupleFullName n = @@ -777,7 +777,7 @@ module internal Impl = [] let lastRegularTupIndex = 6 //nestedTupIndex - 1 (wait for arithmetic in constants) - let rec mkTupleTypeNetStandard (tupTyTbl: Type[]) (tys: Type[]) = + let rec mkTupleTypeNetStandard (tupTyTbl: Type array) (tys: Type array) = let tblIdx = tys.Length - 1 assert (tblIdx >= 0) assert (nestedTupIndex = tupTyTbl.Length - 1) @@ -804,12 +804,12 @@ module internal Impl = else tyargs - let orderTupleProperties (props: PropertyInfo[]) = - // The PropertyInfo[] may not come back in order, so ensure ordering here. + let orderTupleProperties (props: PropertyInfo array) = + // The PropertyInfo array may not come back in order, so ensure ordering here. props |> Array.sortBy (fun p -> p.Name) // alphabetic works because there is max. 8 of them - let orderTupleFields (fields: FieldInfo[]) = - // The FieldInfo[] may not come back in order, so ensure ordering here. + let orderTupleFields (fields: FieldInfo array) = + // The FieldInfo array may not come back in order, so ensure ordering here. fields |> Array.sortBy (fun fi -> fi.Name) // alphabetic works because there is max. 8 of them let getTupleConstructorMethod (typ: Type) = @@ -845,7 +845,7 @@ module internal Impl = let getTupleCtor (typ: Type) = let ctor = getTupleConstructorMethod typ - (fun (args: obj[]) -> + (fun (args: obj array) -> ctor.Invoke(BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| BindingFlags.Public, null, args, null)) let getTupleElementAccessors (typ: Type) = @@ -886,7 +886,7 @@ module internal Impl = let tyBenc = etys.[tupleEncField] let maker2 = getTupleConstructor tyBenc - (fun (args: obj[]) -> + (fun (args: obj array) -> let encVal = maker2 args.[tupleEncField..] maker1 (Array.append args.[0 .. tupleEncField - 1] [| encVal |])) @@ -1005,7 +1005,7 @@ module internal Impl = let getRecordConstructor (typ: Type, bindingFlags) = let ctor = getRecordConstructorMethod (typ, bindingFlags) - (fun (args: obj[]) -> + (fun (args: obj array) -> ctor.Invoke(BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| bindingFlags, null, args, null)) let getRecordConstructorCompiled (typ: Type, bindingFlags) = @@ -1155,7 +1155,7 @@ type FSharpType = checkNonNull "range" range func.MakeGenericType [| domain; range |] - static member MakeTupleType(types: Type[]) = + static member MakeTupleType(types: Type array) = checkNonNull "types" types if types.Length = 0 then @@ -1166,7 +1166,7 @@ type FSharpType = mkTupleTypeNetStandard refTupleTypesNetStandard types - static member MakeTupleType(asm: Assembly, types: Type[]) = + static member MakeTupleType(asm: Assembly, types: Type array) = checkNonNull "types" types if @@ -1179,7 +1179,7 @@ type FSharpType = TupleFromSpecifiedAssembly.mkTupleType false asm types - static member MakeStructTupleType(asm: Assembly, types: Type[]) = + static member MakeStructTupleType(asm: Assembly, types: Type array) = checkNonNull "types" types if @@ -1192,7 +1192,7 @@ type FSharpType = TupleFromSpecifiedAssembly.mkTupleType true asm types - static member MakeStructTupleType(types: Type[]) = + static member MakeStructTupleType(types: Type array) = checkNonNull "types" types if types.Length = 0 then @@ -1278,7 +1278,7 @@ type FSharpValue = checkNonNull "info" info compilePropGetterFunc(info).Invoke - static member PreComputeRecordReader(recordType: Type, ?bindingFlags) : (obj -> obj[]) = + static member PreComputeRecordReader(recordType: Type, ?bindingFlags) : (obj -> obj array) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public checkRecordType ("recordType", recordType, bindingFlags) getRecordReaderCompiled (recordType, bindingFlags) @@ -1308,7 +1308,7 @@ type FSharpValue = let (f: (obj -> obj) -> obj) = downcast o f implementation - static member MakeTuple(tupleElements: obj[], tupleType: Type) = + static member MakeTuple(tupleElements: obj array, tupleType: Type) = checkNonNull "tupleElements" tupleElements checkTupleType ("tupleType", tupleType) getTupleConstructor tupleType tupleElements @@ -1341,7 +1341,7 @@ type FSharpValue = fields.[index] - static member PreComputeTupleReader(tupleType: Type) : (obj -> obj[]) = + static member PreComputeTupleReader(tupleType: Type) : (obj -> obj array) = checkTupleType ("tupleType", tupleType) (compileTupleReader tupleEncField getTupleElementAccessors tupleType).Invoke @@ -1359,7 +1359,7 @@ type FSharpValue = checkTupleType ("tupleType", tupleType) getTupleConstructorInfo tupleType - static member MakeUnion(unionCase: UnionCaseInfo, args: obj[], ?bindingFlags) = + static member MakeUnion(unionCase: UnionCaseInfo, args: obj array, ?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public checkNonNull "unionCase" unionCase getUnionCaseConstructor (unionCase.DeclaringType, unionCase.Tag, bindingFlags) args @@ -1409,7 +1409,7 @@ type FSharpValue = checkUnionType (unionType, bindingFlags) getUnionTagMemberInfo (unionType, bindingFlags) - static member PreComputeUnionReader(unionCase: UnionCaseInfo, ?bindingFlags) : (obj -> obj[]) = + static member PreComputeUnionReader(unionCase: UnionCaseInfo, ?bindingFlags) : (obj -> obj array) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public checkNonNull "unionCase" unionCase let typ = unionCase.DeclaringType @@ -1460,7 +1460,11 @@ module FSharpReflectionExtensions = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.GetRecordFields(record, bindingFlags) - static member PreComputeRecordReader(recordType: Type, ?allowAccessToPrivateRepresentation) : (obj -> obj[]) = + static member PreComputeRecordReader + ( + recordType: Type, + ?allowAccessToPrivateRepresentation + ) : (obj -> obj array) = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.PreComputeRecordReader(recordType, bindingFlags) @@ -1472,7 +1476,7 @@ module FSharpReflectionExtensions = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.PreComputeRecordConstructorInfo(recordType, bindingFlags) - static member MakeUnion(unionCase: UnionCaseInfo, args: obj[], ?allowAccessToPrivateRepresentation) = + static member MakeUnion(unionCase: UnionCaseInfo, args: obj array, ?allowAccessToPrivateRepresentation) = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.MakeUnion(unionCase, args, bindingFlags) @@ -1500,7 +1504,7 @@ module FSharpReflectionExtensions = ( unionCase: UnionCaseInfo, ?allowAccessToPrivateRepresentation - ) : (obj -> obj[]) = + ) : (obj -> obj array) = let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation FSharpValue.PreComputeUnionReader(unionCase, bindingFlags) diff --git a/src/FSharp.Core/reflect.fsi b/src/FSharp.Core/reflect.fsi index 5d69af7f9a3..9aa76f62a69 100644 --- a/src/FSharp.Core/reflect.fsi +++ b/src/FSharp.Core/reflect.fsi @@ -82,7 +82,7 @@ type UnionCaseInfo = /// VariantNumber = 0;}|]|] /// /// - member GetCustomAttributes: unit -> obj[] + member GetCustomAttributes: unit -> obj array /// Returns the custom attributes associated with the case matching the given attribute type. /// The type of attributes to return. @@ -111,7 +111,7 @@ type UnionCaseInfo = /// TypeId = FSI_0147+Signal;}|]|] /// /// - member GetCustomAttributes: attributeType: Type -> obj[] + member GetCustomAttributes: attributeType: Type -> obj array /// Returns the custom attributes data associated with the case. /// An list of custom attribute data items. @@ -176,7 +176,7 @@ type UnionCaseInfo = /// [|("width", "Double"); ("Item2", "Double"); ("height", "Double")|]|] /// /// - member GetFields: unit -> PropertyInfo[] + member GetFields: unit -> PropertyInfo array /// The integer tag for the case. /// @@ -243,7 +243,7 @@ type FSharpValue = /// static member MakeRecord: [] recordType: Type * - values: obj[] * + values: obj array * ?bindingFlags: BindingFlags -> obj @@ -258,7 +258,7 @@ type FSharpValue = /// The array of fields from the record. /// /// - static member GetRecordFields: record: obj * ?bindingFlags: BindingFlags -> obj[] + static member GetRecordFields: record: obj * ?bindingFlags: BindingFlags -> obj array /// Precompute a function for reading all the fields from a record. The fields are returned in the /// same order as the fields reported by a call to Microsoft.FSharp.Reflection.Type.GetInfo for @@ -282,7 +282,7 @@ type FSharpValue = static member PreComputeRecordReader: [] recordType: Type * ?bindingFlags: BindingFlags -> - (obj -> obj[]) + (obj -> obj array) /// Precompute a function for constructing a record value. /// @@ -300,7 +300,7 @@ type FSharpValue = static member PreComputeRecordConstructor: [] recordType: Type * ?bindingFlags: BindingFlags -> - (obj[] -> obj) + (obj array -> obj) /// Get a ConstructorInfo for a record type /// @@ -324,7 +324,7 @@ type FSharpValue = /// The constructed union case. /// /// - static member MakeUnion: unionCase: UnionCaseInfo * args: obj[] * ?bindingFlags: BindingFlags -> obj + static member MakeUnion: unionCase: UnionCaseInfo * args: obj array * ?bindingFlags: BindingFlags -> obj /// Identify the union case and its fields for an object /// @@ -346,7 +346,7 @@ type FSharpValue = value: obj * [] unionType: Type * ?bindingFlags: BindingFlags -> - UnionCaseInfo * obj[] + UnionCaseInfo * obj array /// Assumes the given type is a union type. /// If not, is raised during pre-computation. @@ -387,7 +387,7 @@ type FSharpValue = /// A function to for reading the fields of the given union case. /// /// - static member PreComputeUnionReader: unionCase: UnionCaseInfo * ?bindingFlags: BindingFlags -> (obj -> obj[]) + static member PreComputeUnionReader: unionCase: UnionCaseInfo * ?bindingFlags: BindingFlags -> (obj -> obj array) /// Precompute a function for constructing a discriminated union value for a particular union case. /// @@ -397,7 +397,8 @@ type FSharpValue = /// A function for constructing values of the given union case. /// /// - static member PreComputeUnionConstructor: unionCase: UnionCaseInfo * ?bindingFlags: BindingFlags -> (obj[] -> obj) + static member PreComputeUnionConstructor: + unionCase: UnionCaseInfo * ?bindingFlags: BindingFlags -> (obj array -> obj) /// A method that constructs objects of the given case /// @@ -421,7 +422,7 @@ type FSharpValue = /// The fields from the given exception. /// /// - static member GetExceptionFields: exn: obj * ?bindingFlags: BindingFlags -> obj[] + static member GetExceptionFields: exn: obj * ?bindingFlags: BindingFlags -> obj array /// Creates an instance of a tuple type /// @@ -435,7 +436,7 @@ type FSharpValue = /// An instance of the tuple type with the given elements. /// /// - static member MakeTuple: tupleElements: obj[] * tupleType: Type -> obj + static member MakeTuple: tupleElements: obj array * tupleType: Type -> obj /// Reads a field from a tuple value. /// @@ -460,7 +461,7 @@ type FSharpValue = /// An array of the fields from the given tuple. /// /// - static member GetTupleFields: tuple: obj -> obj[] + static member GetTupleFields: tuple: obj -> obj array /// Precompute a function for reading the values of a particular tuple type /// @@ -475,7 +476,7 @@ type FSharpValue = /// /// static member PreComputeTupleReader: - [] tupleType: Type -> (obj -> obj[]) + [] tupleType: Type -> (obj -> obj array) /// Gets information that indicates how to read a field of a tuple /// @@ -502,7 +503,7 @@ type FSharpValue = /// /// static member PreComputeTupleConstructor: - [] tupleType: Type -> (obj[] -> obj) + [] tupleType: Type -> (obj array -> obj) /// Gets a method that constructs objects of the given tuple type. /// For small tuples, no additional type will be returned. @@ -554,7 +555,7 @@ type FSharpType = static member GetRecordFields: [] recordType: Type * ?bindingFlags: BindingFlags -> - PropertyInfo[] + PropertyInfo array /// Gets the cases of a union type. /// @@ -570,7 +571,7 @@ type FSharpType = /// static member GetUnionCases: [] unionType: Type * ?bindingFlags: BindingFlags -> - UnionCaseInfo[] + UnionCaseInfo array /// Return true if the typ is a representation of an F# record type /// @@ -611,7 +612,7 @@ type FSharpType = static member GetExceptionFields: [] exceptionType: Type * ?bindingFlags: BindingFlags -> - PropertyInfo[] + PropertyInfo array /// Returns true if the typ is a representation of an F# exception declaration /// @@ -646,7 +647,7 @@ type FSharpType = /// The type representing the tuple containing the input elements. /// /// - static member MakeTupleType: types: Type[] -> Type + static member MakeTupleType: types: Type array -> Type /// Returns a representing an F# tuple type with the given element types /// @@ -656,7 +657,7 @@ type FSharpType = /// The type representing the tuple containing the input elements. /// /// - static member MakeTupleType: asm: Assembly * types: Type[] -> Type + static member MakeTupleType: asm: Assembly * types: Type array -> Type /// Returns a representing an F# struct tuple type with the given element types /// @@ -666,7 +667,7 @@ type FSharpType = /// The type representing the struct tuple containing the input elements. /// /// - static member MakeStructTupleType: asm: Assembly * types: Type[] -> Type + static member MakeStructTupleType: asm: Assembly * types: Type array -> Type /// Returns a representing an F# struct tuple type with the given element types /// @@ -675,7 +676,7 @@ type FSharpType = /// The type representing the struct tuple containing the input elements. /// /// - static member MakeStructTupleType: types: Type[] -> Type + static member MakeStructTupleType: types: Type array -> Type /// Return true if the typ is a representation of an F# tuple type /// @@ -712,7 +713,7 @@ type FSharpType = /// /// static member GetTupleElements: - [] tupleType: Type -> Type[] + [] tupleType: Type -> Type array /// Gets the domain and range types from an F# function type or from the runtime type of a closure implementing an F# type /// @@ -744,7 +745,7 @@ module FSharpReflectionExtensions = /// static member MakeRecord: [] recordType: Type * - values: obj[] * + values: obj array * ?allowAccessToPrivateRepresentation: bool -> obj @@ -763,7 +764,7 @@ module FSharpReflectionExtensions = static member GetRecordFields: [] record: obj * ?allowAccessToPrivateRepresentation: bool -> - obj[] + obj array /// Precompute a function for reading all the fields from a record. The fields are returned in the /// same order as the fields reported by a call to Microsoft.FSharp.Reflection.Type.GetInfo for @@ -787,7 +788,7 @@ module FSharpReflectionExtensions = static member PreComputeRecordReader: [] recordType: Type * ?allowAccessToPrivateRepresentation: bool -> - (obj -> obj[]) + (obj -> obj array) /// Precompute a function for constructing a record value. /// @@ -805,7 +806,7 @@ module FSharpReflectionExtensions = static member PreComputeRecordConstructor: [] recordType: Type * ?allowAccessToPrivateRepresentation: bool -> - (obj[] -> obj) + (obj array -> obj) /// Get a ConstructorInfo for a record type /// @@ -830,7 +831,7 @@ module FSharpReflectionExtensions = /// /// static member MakeUnion: - unionCase: UnionCaseInfo * args: obj[] * ?allowAccessToPrivateRepresentation: bool -> obj + unionCase: UnionCaseInfo * args: obj array * ?allowAccessToPrivateRepresentation: bool -> obj /// Identify the union case and its fields for an object /// @@ -853,7 +854,7 @@ module FSharpReflectionExtensions = value: obj * [] unionType: Type * ?allowAccessToPrivateRepresentation: bool -> - UnionCaseInfo * obj[] + UnionCaseInfo * obj array /// Assumes the given type is a union type. /// If not, is raised during pre-computation. @@ -897,7 +898,7 @@ module FSharpReflectionExtensions = /// /// static member PreComputeUnionReader: - unionCase: UnionCaseInfo * ?allowAccessToPrivateRepresentation: bool -> (obj -> obj[]) + unionCase: UnionCaseInfo * ?allowAccessToPrivateRepresentation: bool -> (obj -> obj array) /// Precompute a function for constructing a discriminated union value for a particular union case. /// @@ -908,7 +909,7 @@ module FSharpReflectionExtensions = /// /// static member PreComputeUnionConstructor: - unionCase: UnionCaseInfo * ?allowAccessToPrivateRepresentation: bool -> (obj[] -> obj) + unionCase: UnionCaseInfo * ?allowAccessToPrivateRepresentation: bool -> (obj array -> obj) /// A method that constructs objects of the given case /// @@ -933,7 +934,7 @@ module FSharpReflectionExtensions = /// The fields from the given exception. /// /// - static member GetExceptionFields: exn: obj * ?allowAccessToPrivateRepresentation: bool -> obj[] + static member GetExceptionFields: exn: obj * ?allowAccessToPrivateRepresentation: bool -> obj array type FSharpType with @@ -950,7 +951,7 @@ module FSharpReflectionExtensions = static member GetRecordFields: [] recordType: Type * ?allowAccessToPrivateRepresentation: bool -> - PropertyInfo[] + PropertyInfo array /// Gets the cases of a union type. /// @@ -967,7 +968,7 @@ module FSharpReflectionExtensions = static member GetUnionCases: [] unionType: Type * ?allowAccessToPrivateRepresentation: bool -> - UnionCaseInfo[] + UnionCaseInfo array /// Return true if the typ is a representation of an F# record type /// @@ -1010,7 +1011,7 @@ module FSharpReflectionExtensions = static member GetExceptionFields: [] exceptionType: Type * ?allowAccessToPrivateRepresentation: bool -> - PropertyInfo[] + PropertyInfo array /// Returns true if the exceptionType is a representation of an F# exception declaration /// diff --git a/src/FSharp.Core/result.fsi b/src/FSharp.Core/result.fsi index a5b7a5cb37a..db9a2aa2a42 100644 --- a/src/FSharp.Core/result.fsi +++ b/src/FSharp.Core/result.fsi @@ -166,7 +166,7 @@ module Result = val inline 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. + /// foldBack 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. @@ -266,7 +266,7 @@ module Result = /// /// [] - val inline toArray: result: Result<'T, 'Error> -> 'T[] + val inline toArray: result: Result<'T, 'Error> -> 'T array /// Convert the result to a list of length 0 or 1. /// diff --git a/src/FSharp.Core/resumable.fs b/src/FSharp.Core/resumable.fs index e63e79f92dd..24131ea155f 100644 --- a/src/FSharp.Core/resumable.fs +++ b/src/FSharp.Core/resumable.fs @@ -115,6 +115,7 @@ module StateMachineHelpers = "__stateMachine should always be guarded by __useResumableCode and only used in valid state machine implementations" module ResumableCode = + open System.Runtime.ExceptionServices let inline GetResumptionFunc (sm: byref>) = sm.ResumptionDynamicInfo.ResumptionFunc @@ -294,7 +295,10 @@ module ResumableCode = // reraise at the end of the finally block match savedExn with | None -> true - | Some exn -> raise exn + | Some exn -> + // This should preserve initial location for the failure (file + line, given they're available). + ExceptionDispatchInfo.Capture(exn).Throw() + true else let rf = GetResumptionFunc &sm @@ -384,7 +388,7 @@ module ResumableCode = if __stack_fin then match savedExn with | None -> () - | Some exn -> raise exn + | Some exn -> ExceptionDispatchInfo.Capture(exn).Throw() __stack_fin //-- RESUMABLE CODE END diff --git a/src/FSharp.Core/seq.fs b/src/FSharp.Core/seq.fs index 13770d726ca..bfe050f9f7c 100644 --- a/src/FSharp.Core/seq.fs +++ b/src/FSharp.Core/seq.fs @@ -873,7 +873,7 @@ module Seq = checkNonNull "source" source match source with - | :? ('T[]) as a -> a.Length = 0 + | :? ('T array) as a -> a.Length = 0 | :? ('T list) as a -> a.IsEmpty | :? ICollection<'T> as a -> a.Count = 0 | _ -> @@ -890,7 +890,7 @@ module Seq = checkNonNull "source" source match source with - | :? ('T[]) as a -> a.Length + | :? ('T array) as a -> a.Length | :? ('T list) as a -> a.Length | :? ICollection<'T> as a -> a.Count | _ -> @@ -1014,7 +1014,7 @@ module Seq = checkNonNull "source" source match source with - | :? ('T[]) as res -> (res.Clone() :?> 'T[]) + | :? ('T array) as res -> (res.Clone() :?> 'T array) | :? ('T list) as res -> List.toArray res | :? ICollection<'T> as res -> // Directly create an array and copy ourselves. @@ -1037,7 +1037,7 @@ module Seq = else [||] - let foldArraySubRight (f: OptimizedClosures.FSharpFunc<'T, _, _>) (arr: 'T[]) start fin acc = + let foldArraySubRight (f: OptimizedClosures.FSharpFunc<'T, _, _>) (arr: 'T array) start fin acc = let mutable state = acc for i = fin downto start do @@ -1181,7 +1181,7 @@ module Seq = checkNonNull "source" source source |> toArray |> Array.findIndexBack predicate - // windowed : int -> seq<'T> -> seq<'T[]> + // windowed : int -> seq<'T> -> seq<'T array> [] let windowed windowSize (source: seq<_>) = checkNonNull "source" source diff --git a/src/FSharp.Core/seq.fsi b/src/FSharp.Core/seq.fsi index 9ce69ed5ce4..4bdf2a54d6d 100644 --- a/src/FSharp.Core/seq.fsi +++ b/src/FSharp.Core/seq.fsi @@ -249,7 +249,7 @@ module Seq = /// Throws ArgumentException /// [] - val chunkBySize: chunkSize: int -> source: seq<'T> -> seq<'T[]> + val chunkBySize: chunkSize: int -> source: seq<'T> -> seq<'T array> /// Applies the given function to each element of the sequence and concatenates all the /// results. @@ -530,7 +530,7 @@ module Seq = /// Throws ArgumentException /// [] - val splitInto: count: int -> source: seq<'T> -> seq<'T[]> + val splitInto: count: int -> source: seq<'T> -> seq<'T array> /// Creates an empty sequence. /// @@ -1833,7 +1833,7 @@ module Seq = /// Evaluates to a sequence yielding the same results as seq { 1; 2; 5 }. /// [] - val ofArray: source: 'T[] -> seq<'T> + val ofArray: source: 'T array -> seq<'T> /// Views the given list as a sequence. /// @@ -1955,7 +1955,7 @@ module Seq = /// /// let readonlyView = input |> Seq.readonly /// - /// (readonlyView :?> int[]).[1] <- 4 + /// (readonlyView :?> int array).[1] <- 4 /// /// Throws an InvalidCastException. /// @@ -2474,7 +2474,7 @@ module Seq = /// Evaluates to [| 1; 2; 5 |]. /// [] - val toArray: source: seq<'T> -> 'T[] + val toArray: source: seq<'T> -> 'T array /// Builds a list from the given collection. /// @@ -2792,7 +2792,7 @@ module Seq = /// Evaluates to a sequence of arrays yielding the results seq { [| 1; 2; 3 |]; [| 2; 3; 4 |]; [| 3; 4; 5 |] } /// [] - val windowed: windowSize: int -> source: seq<'T> -> seq<'T[]> + val windowed: windowSize: int -> source: seq<'T> -> seq<'T array> /// Combines the two sequences into a sequence of pairs. The two sequences need not have equal lengths: /// when one sequence is exhausted any remaining elements in the other diff --git a/src/FSharp.Core/seqcore.fs b/src/FSharp.Core/seqcore.fs index 2ec6f60815a..187ed402362 100644 --- a/src/FSharp.Core/seqcore.fs +++ b/src/FSharp.Core/seqcore.fs @@ -553,7 +553,7 @@ type ListCollector<'T> = member this.AddMany (values: seq<'T>) = // cook a faster iterator for lists and arrays match values with - | :? ('T[]) as valuesAsArray -> + | :? ('T array) as valuesAsArray -> for v in valuesAsArray do this.Add v | :? ('T list) as valuesAsList -> @@ -631,7 +631,7 @@ type ArrayCollector<'T> = else // cook a faster iterator for lists and arrays match values with - | :? ('T[]) as valuesAsArray -> + | :? ('T array) as valuesAsArray -> for v in valuesAsArray do this.Add v | :? ('T list) as valuesAsList -> diff --git a/src/FSharp.Core/seqcore.fsi b/src/FSharp.Core/seqcore.fsi index 1522522000b..e58e1f6ce68 100644 --- a/src/FSharp.Core/seqcore.fsi +++ b/src/FSharp.Core/seqcore.fsi @@ -205,7 +205,7 @@ type ArrayCollector<'T> = member AddMany: values: seq<'T> -> unit /// Add multiple elements to the collector and return the resulting array - member AddManyAndClose: values: seq<'T> -> 'T[] + member AddManyAndClose: values: seq<'T> -> 'T array /// Return the resulting list - member Close: unit -> 'T[] + member Close: unit -> 'T array diff --git a/src/FSharp.Core/set.fs b/src/FSharp.Core/set.fs index aaed3e37a41..b47bef257c1 100644 --- a/src/FSharp.Core/set.fs +++ b/src/FSharp.Core/set.fs @@ -669,7 +669,7 @@ module internal SetTree = loop t [] - let copyToArray s (arr: _[]) i = + let copyToArray s (arr: _ array) i = let mutable j = i iter diff --git a/src/FSharp.Core/set.fsi b/src/FSharp.Core/set.fsi index f1c2fd291c2..58615cedaa9 100644 --- a/src/FSharp.Core/set.fsi +++ b/src/FSharp.Core/set.fsi @@ -752,7 +752,7 @@ module Set = /// The sample evaluates to the following output: The set is set [(1, 2, 3)] and type is "FSharpSet`1" /// [] - val ofArray: array: 'T[] -> Set<'T> + val ofArray: array: 'T array -> Set<'T> /// Builds an array that contains the elements of the set in order. /// @@ -766,10 +766,10 @@ module Set = /// let array = Set.toArray set /// printfn$ "The set is {set} and type is {array.GetType().Name}" /// - /// The sample evaluates to the following output: The set is [|1; 2; 3|] and type is System.Int32[] + /// The sample evaluates to the following output: The set is [|1; 2; 3|] and type is System.Int32 array /// [] - val toArray: set: Set<'T> -> 'T[] + val toArray: set: Set<'T> -> 'T array /// Returns an ordered view of the collection as an enumerable object. /// diff --git a/src/FSharp.Core/string.fs b/src/FSharp.Core/string.fs index 42f86f75079..d716b793db1 100644 --- a/src/FSharp.Core/string.fs +++ b/src/FSharp.Core/string.fs @@ -26,7 +26,7 @@ module String = [] let concat sep (strings: seq) = - let concatArray sep (strings: string[]) = + let concatArray sep (strings: string array) = match length sep with | 0 -> String.Concat strings // following line should be used when this overload becomes part of .NET Standard (it's only in .NET Core) @@ -34,7 +34,7 @@ module String = | _ -> String.Join(sep, strings, 0, strings.Length) match strings with - | :? (string[]) as arr -> concatArray sep arr + | :? (string array) as arr -> concatArray sep arr | :? (string list) as lst -> lst |> List.toArray |> concatArray sep diff --git a/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.fsproj b/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.fsproj index f7560b70738..a427f7006dd 100644 --- a/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.fsproj +++ b/src/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.fsproj @@ -9,13 +9,6 @@ .NET Core compatible version of the F# compiler fsc.exe. /blob/main/release-notes.md#FSharp-Tools-$(FSProductVersionReleaseNotesVersion) true - - $(NoWarn);NU1505 diff --git a/src/fsc/fsc.targets b/src/fsc/fsc.targets index 47d7ea87264..2973feb613e 100644 --- a/src/fsc/fsc.targets +++ b/src/fsc/fsc.targets @@ -4,14 +4,6 @@ Exe - - $(NoWarn);NU1505 - $(NoWarn);44 $(NoWarn);75 true diff --git a/src/fsi/fsi.targets b/src/fsi/fsi.targets index 4e8c6a6cbc3..2f38a20ecc3 100644 --- a/src/fsi/fsi.targets +++ b/src/fsi/fsi.targets @@ -4,13 +4,6 @@ Exe - - $(NoWarn);NU1505 $(NoWarn);44 true $(OtherFlags) --warnon:1182 diff --git a/tests/AheadOfTime/Trimming/SelfContained_Trimming_Test/SelfContained_Trimming_Test.fsproj b/tests/AheadOfTime/Trimming/SelfContained_Trimming_Test/SelfContained_Trimming_Test.fsproj index cb02b7e0fd6..90842baa584 100644 --- a/tests/AheadOfTime/Trimming/SelfContained_Trimming_Test/SelfContained_Trimming_Test.fsproj +++ b/tests/AheadOfTime/Trimming/SelfContained_Trimming_Test/SelfContained_Trimming_Test.fsproj @@ -5,7 +5,6 @@ net8.0 preview true - true diff --git a/tests/AheadOfTime/Trimming/StaticLinkedFSharpCore_Trimming_Test/StaticLinkedFSharpCore_Trimming_Test.fsproj b/tests/AheadOfTime/Trimming/StaticLinkedFSharpCore_Trimming_Test/StaticLinkedFSharpCore_Trimming_Test.fsproj index d36faf2c0df..7fd0dc7091c 100644 --- a/tests/AheadOfTime/Trimming/StaticLinkedFSharpCore_Trimming_Test/StaticLinkedFSharpCore_Trimming_Test.fsproj +++ b/tests/AheadOfTime/Trimming/StaticLinkedFSharpCore_Trimming_Test/StaticLinkedFSharpCore_Trimming_Test.fsproj @@ -5,7 +5,6 @@ net8.0 preview true - true false --standalone diff --git a/tests/AheadOfTime/Trimming/check.ps1 b/tests/AheadOfTime/Trimming/check.ps1 index 8d2d17adef2..373cd534ce2 100644 --- a/tests/AheadOfTime/Trimming/check.ps1 +++ b/tests/AheadOfTime/Trimming/check.ps1 @@ -40,7 +40,7 @@ function CheckTrim($root, $tfm, $outputfile, $expected_len) { # error NETSDK1124: Trimming assemblies requires .NET Core 3.0 or higher. # Check net7.0 trimmed assemblies -CheckTrim -root "SelfContained_Trimming_Test" -tfm "net8.0" -outputfile "FSharp.Core.dll" -expected_len 288768 +CheckTrim -root "SelfContained_Trimming_Test" -tfm "net8.0" -outputfile "FSharp.Core.dll" -expected_len 288256 # Check net7.0 trimmed assemblies CheckTrim -root "StaticLinkedFSharpCore_Trimming_Test" -tfm "net8.0" -outputfile "StaticLinkedFSharpCore_Trimming_Test.dll" -expected_len 8822272 diff --git a/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncLock.fs b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncLock.fs new file mode 100644 index 00000000000..ef4b69a3910 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncLock.fs @@ -0,0 +1,26 @@ +module CompilerService.AsyncLock + +open Internal.Utilities.Collections + +open Xunit +open System.Threading.Tasks + + +[] +let ``Async lock works`` () = + task { + use lock = new AsyncLock() + + let mutable x = 0 + + let job () = task { + let y = x + do! Task.Delay(10) + x <- y + 1 + } + + let jobs = [ for _ in 1..100 -> lock.Do job ] + let! _ = Task.WhenAll(jobs) + + Assert.Equal(100, x) + } \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs new file mode 100644 index 00000000000..71dbb5c957f --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs @@ -0,0 +1,542 @@ +module CompilerService.AsyncMemoize + +open System +open System.Threading +open Xunit +open Internal.Utilities.Collections +open System.Threading.Tasks +open System.Diagnostics +open System.Collections.Concurrent +open FSharp.Compiler.DiagnosticsLogger +open FSharp.Compiler.Diagnostics +open FSharp.Compiler.BuildGraph + + +let timeout = TimeSpan.FromSeconds 10 + +let waitFor (mre: ManualResetEvent) = + if not <| mre.WaitOne timeout then + failwith "waitFor timed out" + + +let rec internal spinFor (duration: TimeSpan) = + node { + let sw = Stopwatch.StartNew() + do! Async.Sleep 10 |> NodeCode.AwaitAsync + let remaining = duration - sw.Elapsed + if remaining > TimeSpan.Zero then + return! spinFor remaining + } + + +[] +let ``Basics``() = + + let computation key = node { + do! Async.Sleep 1 |> NodeCode.AwaitAsync + return key * 2 + } + + let eventLog = ConcurrentBag() + + let memoize = AsyncMemoize() + memoize.OnEvent(fun (e, (_label, k, _version)) -> eventLog.Add (e, k)) + + let result = + seq { + memoize.Get'(5, computation 5) + memoize.Get'(5, computation 5) + memoize.Get'(2, computation 2) + memoize.Get'(5, computation 5) + memoize.Get'(3, computation 3) + memoize.Get'(2, computation 2) + } + |> NodeCode.Parallel + |> NodeCode.RunImmediateWithoutCancellation + + let expected = [| 10; 10; 4; 10; 6; 4|] + + Assert.Equal(expected, result) + + let groups = eventLog |> Seq.groupBy snd |> Seq.toList + Assert.Equal(3, groups.Length) + for key, events in groups do + Assert.Equal>(Set [ Started, key; Finished, key ], Set events) + +[] +let ``We can cancel a job`` () = + task { + + let jobStarted = new ManualResetEvent(false) + + let jobCanceled = new ManualResetEvent(false) + + let computation action = node { + action() |> ignore + do! spinFor timeout + failwith "Should be canceled before it gets here" + } + + let eventLog = ConcurrentQueue() + let memoize = AsyncMemoize() + memoize.OnEvent(fun (e, (_label, k, _version)) -> + eventLog.Enqueue (e, k) + if e = Canceled then + jobCanceled.Set() |> ignore + ) + + use cts1 = new CancellationTokenSource() + use cts2 = new CancellationTokenSource() + use cts3 = new CancellationTokenSource() + + let key = 1 + + let _task1 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation jobStarted.Set), ct = cts1.Token) + + waitFor jobStarted + jobStarted.Reset() |> ignore + + let _task2 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation ignore), ct = cts2.Token) + let _task3 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation ignore), ct = cts3.Token) + + cts1.Cancel() + cts2.Cancel() + + waitFor jobStarted + + cts3.Cancel() + + waitFor jobCanceled + + Assert.Equal<(JobEvent * int) array>([| Started, key; Started, key; Canceled, key |], eventLog |> Seq.toArray ) + } + +[] +let ``Job is restarted if first requestor cancels`` () = + task { + let jobStarted = new ManualResetEvent(false) + + let jobCanComplete = new ManualResetEvent(false) + + let computation key = node { + jobStarted.Set() |> ignore + waitFor jobCanComplete + return key * 2 + } + + let eventLog = ConcurrentStack() + let memoize = AsyncMemoize() + memoize.OnEvent(fun (e, (_, k, _version)) -> eventLog.Push (e, k)) + + use cts1 = new CancellationTokenSource() + use cts2 = new CancellationTokenSource() + use cts3 = new CancellationTokenSource() + + let key = 1 + + let _task1 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation key), ct = cts1.Token) + + waitFor jobStarted + jobStarted.Reset() |> ignore + + let _task2 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation key), ct = cts2.Token) + let _task3 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation key), ct = cts3.Token) + + cts1.Cancel() + + waitFor jobStarted + + cts3.Cancel() + + jobCanComplete.Set() |> ignore + + let! result = _task2 + Assert.Equal(2, result) + + let orderedLog = eventLog |> Seq.rev |> Seq.toList + let expected = [ Started, key; Started, key; Finished, key ] + + Assert.Equal<_ list>(expected, orderedLog) + } + +[] +let ``Job is restarted if first requestor cancels but keeps running if second requestor cancels`` () = + task { + let jobStarted = new ManualResetEvent(false) + + let jobCanComplete = new ManualResetEvent(false) + + let computation key = node { + jobStarted.Set() |> ignore + waitFor jobCanComplete + return key * 2 + } + + let eventLog = ConcurrentStack() + let memoize = AsyncMemoize() + memoize.OnEvent(fun (e, (_label, k, _version)) -> eventLog.Push (e, k)) + + use cts1 = new CancellationTokenSource() + use cts2 = new CancellationTokenSource() + use cts3 = new CancellationTokenSource() + + let key = 1 + + let _task1 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation key), ct = cts1.Token) + + jobStarted.WaitOne() |> ignore + jobStarted.Reset() |> ignore + + let _task2 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation key), ct = cts2.Token) + let _task3 = NodeCode.StartAsTask_ForTesting( memoize.Get'(key, computation key), ct = cts3.Token) + + cts1.Cancel() + + jobStarted.WaitOne() |> ignore + + cts2.Cancel() + + jobCanComplete.Set() |> ignore + + let! result = _task3 + Assert.Equal(2, result) + + let orderedLog = eventLog |> Seq.rev |> Seq.toList + let expected = [ Started, key; Started, key; Finished, key ] + + Assert.Equal<_ list>(expected, orderedLog) + } + + +type ExpectedException() = + inherit Exception() + +[] +let ``Stress test`` () = + + let seed = System.Random().Next() + + let rng = System.Random seed + let threads = 30 + let iterations = 30 + let maxDuration = 100 + let minTimeout = 0 + let maxTimeout = 500 + let exceptionProbability = 0.01 + let gcProbability = 0.1 + let stepMs = 10 + let keyCount = rng.Next(5, 200) + let keys = [| 1 .. keyCount |] + + let testTimeoutMs = threads * iterations * maxDuration + + let intenseComputation durationMs result = + async { + if rng.NextDouble() < exceptionProbability then + raise (ExpectedException()) + let s = Stopwatch.StartNew() + let mutable number = 0 + while (int s.ElapsedMilliseconds) < durationMs do + number <- number + 1 % 12345 + return [result] + } |> NodeCode.AwaitAsync + + let rec sleepyComputation durationMs result = + node { + if rng.NextDouble() < (exceptionProbability / (float durationMs / float stepMs)) then + raise (ExpectedException()) + if durationMs > 0 then + do! Async.Sleep (min stepMs durationMs) |> NodeCode.AwaitAsync + return! sleepyComputation (durationMs - stepMs) result + else + return [result] + } + + let rec mixedComputation durationMs result = + node { + if durationMs > 0 then + if rng.NextDouble() < 0.5 then + let! _ = intenseComputation (min stepMs durationMs) () + () + else + let! _ = sleepyComputation (min stepMs durationMs) () + () + return! mixedComputation (durationMs - stepMs) result + else + return [result] + } + + let computations = [| + intenseComputation + sleepyComputation + mixedComputation + |] + + let cache = AsyncMemoize(keepStrongly=5, keepWeakly=10) + + let mutable started = 0 + let mutable canceled = 0 + let mutable timeout = 0 + let mutable failed = 0 + let mutable completed = 0 + + let test = + seq { + for _ in 1..threads do + let rec loop iteration = + task { + if gcProbability > rng.NextDouble() then + GC.Collect(2, GCCollectionMode.Forced, false) + + let computation = computations[rng.Next computations.Length] + let durationMs = rng.Next maxDuration + let timeoutMs = rng.Next(minTimeout, maxTimeout) + let key = keys[rng.Next keys.Length] + let result = key * 2 + let job = cache.Get'(key, computation durationMs result) + let cts = new CancellationTokenSource() + let runningJob = NodeCode.StartAsTask_ForTesting(job, ct = cts.Token) + cts.CancelAfter timeoutMs + Interlocked.Increment &started |> ignore + try + let! actual = runningJob + Assert.Equal(result, actual.Head) + Interlocked.Increment &completed |> ignore + with + | :? TaskCanceledException as _e -> + Interlocked.Increment &canceled |> ignore + | :? OperationCanceledException as _e -> + Interlocked.Increment &canceled |> ignore + | :? TimeoutException -> Interlocked.Increment &timeout |> ignore + | :? ExpectedException -> Interlocked.Increment &failed |> ignore + | :? AggregateException as ex when + ex.Flatten().InnerExceptions |> Seq.exists (fun e -> e :? ExpectedException) -> + Interlocked.Increment &failed |> ignore + | e -> + failwith $"Seed {seed} failed on iteration {iteration}: %A{e}" + if iteration < iterations then + return! loop (iteration + 1) + return () + } + loop 1 + } + |> Task.WhenAll + + if not (test.Wait testTimeoutMs) then failwith "Test timed out - most likely deadlocked" + + Assert.Equal (threads * iterations, started) + // Assert.Equal((0,0,0,0,0),(started, completed, canceled, failed, timeout)) + Assert.Equal (started, completed + canceled + failed + timeout) + + Assert.True ((float completed) > ((float started) * 0.1), "Less than 10 % completed jobs") + + +[] +[] +[] +let ``Cancel running jobs with the same key`` cancelDuplicate expectFinished = + task { + let cache = AsyncMemoize(cancelDuplicateRunningJobs=cancelDuplicate) + + let mutable started = 0 + let mutable finished = 0 + + let job1started = new ManualResetEvent(false) + let job1finished = new ManualResetEvent(false) + + let jobCanContinue = new ManualResetEvent(false) + + let job2started = new ManualResetEvent(false) + let job2finished = new ManualResetEvent(false) + + let work onStart onFinish = node { + Interlocked.Increment &started |> ignore + onStart() |> ignore + waitFor jobCanContinue + do! spinFor (TimeSpan.FromMilliseconds 100) + Interlocked.Increment &finished |> ignore + onFinish() |> ignore + } + + let key1 = + { new ICacheKey<_, _> with + member _.GetKey() = 1 + member _.GetVersion() = 1 + member _.GetLabel() = "key1" } + + cache.Get(key1, work job1started.Set job1finished.Set) |> Async.AwaitNodeCode |> Async.Start + + waitFor job1started + + let key2 = + { new ICacheKey<_, _> with + member _.GetKey() = key1.GetKey() + member _.GetVersion() = key1.GetVersion() + 1 + member _.GetLabel() = "key2" } + + cache.Get(key2, work job2started.Set job2finished.Set ) |> Async.AwaitNodeCode |> Async.Start + + waitFor job2started + + jobCanContinue.Set() |> ignore + + waitFor job2finished + + if not cancelDuplicate then + waitFor job1finished + + Assert.Equal((2, expectFinished), (started, finished)) + } + + +type DummyException(msg) = + inherit Exception(msg) + +[] +let ``Preserve thread static diagnostics`` () = + + let seed = System.Random().Next() + + let rng = System.Random seed + + let job1Cache = AsyncMemoize() + let job2Cache = AsyncMemoize() + + let job1 (input: string) = node { + let! _ = Async.Sleep (rng.Next(1, 30)) |> NodeCode.AwaitAsync + let ex = DummyException("job1 error") + DiagnosticsThreadStatics.DiagnosticsLogger.ErrorR(ex) + return Ok input + } + + let job2 (input: int) = node { + + DiagnosticsThreadStatics.DiagnosticsLogger.Warning(DummyException("job2 error 1")) + + let! _ = Async.Sleep (rng.Next(1, 30)) |> NodeCode.AwaitAsync + + let key = { new ICacheKey<_, _> with + member _.GetKey() = "job1" + member _.GetVersion() = input + member _.GetLabel() = "job1" } + + let! result = job1Cache.Get(key, job1 "${input}" ) + + DiagnosticsThreadStatics.DiagnosticsLogger.Warning(DummyException("job2 error 2")) + + return input, result + + } + + let tasks = seq { + for i in 1 .. 100 do + + task { + let diagnosticsLogger = + CompilationDiagnosticLogger($"Testing task {i}", FSharpDiagnosticOptions.Default) + + use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Optimize) + + DiagnosticsThreadStatics.DiagnosticsLogger.Warning(DummyException("task error")) + + + let key = { new ICacheKey<_, _> with + member _.GetKey() = "job2" + member _.GetVersion() = rng.Next(1, 10) + member _.GetLabel() = "job2" } + + let! result = job2Cache.Get(key, job2 (i % 10)) |> Async.AwaitNodeCode + + let diagnostics = diagnosticsLogger.GetDiagnostics() + + //Assert.Equal(3, diagnostics.Length) + + return result, diagnostics + } + } + + let results = (Task.WhenAll tasks).Result + + let _diagnosticCounts = results |> Seq.map snd |> Seq.map Array.length |> Seq.groupBy id |> Seq.map (fun (k, v) -> k, v |> Seq.length) |> Seq.sortBy fst |> Seq.toList + + //Assert.Equal<(int * int) list>([4, 100], diagnosticCounts) + + let diagnosticMessages = results |> Seq.map snd |> Seq.map (Array.map (fun (d, _) -> d.Exception.Message) >> Array.toList) |> Set + + Assert.Equal>(Set [["task error"; "job2 error 1"; "job1 error"; "job2 error 2"; ]], diagnosticMessages) + + +[] +let ``Preserve thread static diagnostics already completed job`` () = + + let cache = AsyncMemoize() + + let key = { new ICacheKey<_, _> with + member _.GetKey() = "job1" + member _.GetVersion() = 1 + member _.GetLabel() = "job1" } + + let job (input: string) = node { + let ex = DummyException($"job {input} error") + DiagnosticsThreadStatics.DiagnosticsLogger.ErrorR(ex) + return Ok input + } + + async { + + let diagnosticsLogger = CompilationDiagnosticLogger($"Testing", FSharpDiagnosticOptions.Default) + + use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Optimize) + + let! _ = cache.Get(key, job "1" ) |> Async.AwaitNodeCode + let! _ = cache.Get(key, job "2" ) |> Async.AwaitNodeCode + + let diagnosticMessages = diagnosticsLogger.GetDiagnostics() |> Array.map (fun (d, _) -> d.Exception.Message) |> Array.toList + + Assert.Equal>(["job 1 error"; "job 1 error"], diagnosticMessages) + + } + |> Async.StartAsTask + + +[] +let ``We get diagnostics from the job that failed`` () = + + let cache = AsyncMemoize() + + let key = { new ICacheKey<_, _> with + member _.GetKey() = "job1" + member _.GetVersion() = 1 + member _.GetLabel() = "job1" } + + let job (input: int) = node { + let ex = DummyException($"job {input} error") + do! Async.Sleep 100 |> NodeCode.AwaitAsync + DiagnosticsThreadStatics.DiagnosticsLogger.Error(ex) + return 5 + } + + let result = + [1; 2] + |> Seq.map (fun i -> + async { + let diagnosticsLogger = CompilationDiagnosticLogger($"Testing", FSharpDiagnosticOptions.Default) + + use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Optimize) + try + let! _ = cache.Get(key, job i ) |> Async.AwaitNodeCode + () + with _ -> + () + let diagnosticMessages = diagnosticsLogger.GetDiagnostics() |> Array.map (fun (d, _) -> d.Exception.Message) |> Array.toList + + return diagnosticMessages + }) + |> Async.Parallel + |> Async.StartAsTask + |> (fun t -> t.Result) + |> Array.toList + + Assert.True( + result = [["job 1 error"]; ["job 1 error"]] || + result = [["job 2 error"]; ["job 2 error"]] ) diff --git a/tests/FSharp.Compiler.ComponentTests/CompilerService/LruCache.fs b/tests/FSharp.Compiler.ComponentTests/CompilerService/LruCache.fs new file mode 100644 index 00000000000..a477f7e6f7c --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/CompilerService/LruCache.fs @@ -0,0 +1,197 @@ +module CompilerService.LruCache +open Internal.Utilities.Collections + +open Xunit +open System + +[] +let ``Adding an item to the cache should make it retrievable``() = + let cache = new LruCache(keepStrongly = 2) + cache.Set(1, "one") + let result = cache.TryGet(1) + Assert.Equal("one", result.Value) + +[] +let ``Adding an item to the cache should evict the least recently used item if the cache is full``() = + let cache = new LruCache(keepStrongly = 2, keepWeakly = 0) + cache.Set(1, "one") + cache.Set(2, "two") + cache.Set(3, "three") + let result = cache.TryGet(1) + Assert.Null(result) + +[] +let ``Adding an item to the cache should not evict a required item``() = + let cache = new LruCache(keepStrongly = 2, requiredToKeep = (fun v -> v = "one")) + cache.Set(1, "one") + cache.Set(2, "two") + cache.Set(3, "three") + let result = cache.TryGet(1) + Assert.Equal("one", result.Value) + +[] +let ``Adding an item to the cache should not evict a strongly kept item``() = + let cache = new LruCache(keepStrongly = 2, keepWeakly = 0) + cache.Set(1, "one") + cache.Set(2, "two") + cache.Set(1, "one") + cache.Set(3, "three") + let result = cache.TryGet(1) + Assert.Equal("one", result.Value) + +[] +let ``Adding an item to the cache should not evict a strongly kept item, even if it is the least recently used``() = + let cache = new LruCache(keepStrongly = 2, keepWeakly = 0, requiredToKeep = (fun v -> v = "one")) + cache.Set(1, "one") + cache.Set(2, "two") + cache.Set(3, "three") + let result = cache.TryGet(1) + Assert.Equal("one", result.Value) + +[] +let ``Adding an item to the cache should not evict a weakly kept item if its reference is still valid``() = + let cache = new LruCache(keepStrongly = 2, keepWeakly = 1) + let value = "one" + cache.Set(1, value) + cache.Set(2, "two") + GC.Collect(2, GCCollectionMode.Forced, true) + let result = cache.TryGet(1) + Assert.Equal(value, result.Value) + + +// Doing this directly in the test prevents GC for some reason +let private addObjToCache (cache: LruCache<_, int,_>) key = + let o = obj () + cache.Set(key, o) + +[] +let ``Adding an item to the cache should evict a weakly kept item if its reference is no longer valid``() = + let cache = new LruCache<_, int, _>(keepStrongly = 2, keepWeakly = 1) + addObjToCache cache 1 + addObjToCache cache 2 + addObjToCache cache 3 + GC.Collect(2, GCCollectionMode.Forced, true) + + let result = cache.TryGet(1) + Assert.True(result.IsNone) + + +[] +let ``When a new version is added other versions get weakened`` () = + let eventLog = ResizeArray() + + let cache = new LruCache<_, int, _>(keepStrongly = 2, keepWeakly = 2, event = (fun e v -> eventLog.Add(e, v))) + + cache.Set(1, 1, "one1") + cache.Set(1, 2, "one2") + cache.Set(1, 3, "one3") + cache.Set(1, 4, "one4") + + let expected = [ + CacheEvent.Weakened, ("[no label]", 1, 1) + CacheEvent.Weakened, ("[no label]", 1, 2) + CacheEvent.Weakened, ("[no label]", 1, 3) + CacheEvent.Evicted, ("[no label]", 1, 1) + ] + + Assert.Equal>(expected, eventLog |> Seq.toList) + +[] +let ``When a new version is added other versions don't get weakened when they're required to keep`` () = + let eventLog = ResizeArray() + + let cache = new LruCache<_, int, _>(keepStrongly = 2, keepWeakly = 2, requiredToKeep = ((=) "one1"), event = (fun e v -> eventLog.Add(e, v))) + + cache.Set(1, 1, "one1") + cache.Set(1, 2, "one2") + cache.Set(1, 3, "one3") + cache.Set(1, 4, "one4") + + let expected = [ + CacheEvent.Weakened, ("[no label]", 1, 2) + CacheEvent.Weakened, ("[no label]", 1, 3) + ] + + Assert.Equal>(expected, eventLog |> Seq.toList) + +[] +let ``Looking up a weakened item will strengthen it`` () = + let eventLog = ResizeArray() + + let cache = new LruCache<_, int, _>(keepStrongly = 2, keepWeakly = 2, event = (fun e v -> eventLog.Add(e, v))) + + cache.Set(1, 1, "one1") + cache.Set(1, 2, "one2") + cache.Set(1, 3, "one3") + cache.Set(1, 4, "one4") + + let result = cache.TryGet(1, 2) + Assert.Equal("one2", result.Value) + + let expected = [ + CacheEvent.Weakened, ("[no label]", 1, 1) + CacheEvent.Weakened, ("[no label]", 1, 2) + CacheEvent.Weakened, ("[no label]", 1, 3) + CacheEvent.Evicted, ("[no label]", 1, 1) + CacheEvent.Strengthened, ("[no label]", 1, 2) + ] + + Assert.Equal>(expected, eventLog |> Seq.toList) + + +[] +let ``New version doesn't push other keys out of strong list``() = + + let eventLog = ResizeArray() + + let cache = new LruCache<_, int, _>(keepStrongly = 2, keepWeakly = 2, event = (fun e v -> eventLog.Add(e, v))) + + cache.Set(1, 1, "one1") + cache.Set(1, 2, "one2") + cache.Set(1, 3, "one3") + cache.Set(1, 4, "one4") + cache.Set(2, 1, "two1") + cache.Set(2, 2, "two2") + + let expected = [ + CacheEvent.Weakened, ("[no label]", 1, 1) + CacheEvent.Weakened, ("[no label]", 1, 2) + CacheEvent.Weakened, ("[no label]", 1, 3) + CacheEvent.Evicted, ("[no label]", 1, 1) + CacheEvent.Weakened, ("[no label]", 2, 1) + CacheEvent.Evicted, ("[no label]", 1, 2) + ] + + Assert.Equal>(expected, eventLog |> Seq.toList) + +[] +let ``We can clear specific keys based on a predicate``() = + + let eventLog = ResizeArray() + + let cache = new LruCache<_, int, _>(keepStrongly = 2, keepWeakly = 2, event = (fun e v -> eventLog.Add(e, v))) + + cache.Set(1, 1, "one1") + cache.Set(1, 2, "one2") + cache.Set(1, 3, "one3") + cache.Set(1, 4, "one4") + cache.Set(2, 1, "two1") + cache.Set(2, 2, "two2") + + cache.Clear((=) 1) + + let result = cache.TryGet(1, 2) + Assert.True(result.IsNone) + + let expected = [ + CacheEvent.Weakened, ("[no label]", 1, 1) + CacheEvent.Weakened, ("[no label]", 1, 2) + CacheEvent.Weakened, ("[no label]", 1, 3) + CacheEvent.Evicted, ("[no label]", 1, 1) + CacheEvent.Weakened, ("[no label]", 2, 1) + CacheEvent.Evicted, ("[no label]", 1, 2) + CacheEvent.Cleared, ("[no label]", 1, 3) + CacheEvent.Cleared, ("[no label]", 1, 4) + ] + + Assert.Equal>(expected, eventLog |> Seq.toList) diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/ValueRestriction/E_NotMemberOrFunction01.fsx b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/ValueRestriction/E_NotMemberOrFunction01.fsx index 182fb04be48..5cb7755a083 100644 --- a/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/ValueRestriction/E_NotMemberOrFunction01.fsx +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/ValueRestriction/E_NotMemberOrFunction01.fsx @@ -1,6 +1,6 @@ // #Conformance #ObjectOrientedTypes #Classes #TypeInference #ValueRestriction -//Value restriction\. The value 'x1' has been inferred to have generic type. val x1: \('_a -> unit\) .Either make the arguments to 'x1' explicit or, if you do not intend for it to be generic, add a type annotation\.$ +//Value restriction: The value 'x1' has an inferred generic function type val x1: \('_a -> unit\)However, values cannot have generic type variables like '_a in "let f: '_a". You should define 'x1' as a function instead by doing one of the following:- Add an explicit parameter that is applied instead of using a partial application "let f param"- Add a unit parameter like "let f\(\)"- Write explicit type parameters like "let f<'a>"or if you do not intend for it to be generic, either:- Add an explicit type annotation like "let f : obj -> obj"- Apply arguments of non-generic types to the function value in later code for type inference like "do f\(\)"\.This error is because a let binding without parameters defines a value, not a function\. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results\.$ // We expect a value restriction here. The inferred signature is: // val x1: (?1 -> unit) diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/Expressions/ComputationExpressions/CustomOperations.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/Expressions/ComputationExpressions/CustomOperations.fs new file mode 100644 index 00000000000..28e9ff22c7a --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/Expressions/ComputationExpressions/CustomOperations.fs @@ -0,0 +1,43 @@ +namespace Conformance.Expressions.ComputationExpressions + +open Xunit +open FSharp.Test.Compiler + +module CustomOperations = + + [] + let ``[] without explicit name is allowed, uses method name as operation name`` () = + FSharp """ + module CustomOperationTest + type CBuilder() = + [] + member this.Foo _ = "Foo" + [] + member this.foo _ = "foo" + [] + member this.bar _ = "bar" + member this.Yield _ = () + member this.Zero _ = () + + + [] + let main _ = + let cb = CBuilder() + + let x = cb { Foo } + let y = cb { foo } + let z = cb { bar } + printfn $"{x}" + printfn $"{y}" + + if x <> "Foo" then + failwith "not Foo" + if y <> "foo" then + failwith "not foo" + if z <> "bar" then + failwith "not bar" + 0 + """ + |> asExe + |> compileAndRun + |> shouldSucceed \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/Expressions/ObjectExpressions/ObjectExpressions.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/Expressions/ObjectExpressions/ObjectExpressions.fs index 6ef849136ae..03e543491ac 100644 --- a/tests/FSharp.Compiler.ComponentTests/Conformance/Expressions/ObjectExpressions/ObjectExpressions.fs +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/Expressions/ObjectExpressions/ObjectExpressions.fs @@ -72,6 +72,7 @@ let foo = { new Foo() with member __.ToString() = base.ToString() } |> typecheck |> shouldFail |> withDiagnostics [ + (Error 759, Line 5, Col 13, Line 5, Col 22, "Instances of this type cannot be created since it has been marked abstract or not all methods have been given implementations. Consider using an object expression '{ new ... with ... }' instead."); (Error 738, Line 5, Col 11, Line 5, Col 24, "Invalid object expression. Objects without overrides or interfaces should use the expression form 'new Type(args)' without braces.") (Error 740, Line 5, Col 11, Line 5, Col 24, "Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq { ... }'") ] diff --git a/tests/FSharp.Compiler.ComponentTests/ConstraintSolver/MemberConstraints.fs b/tests/FSharp.Compiler.ComponentTests/ConstraintSolver/MemberConstraints.fs index 3bb1770b411..b3c33031acb 100644 --- a/tests/FSharp.Compiler.ComponentTests/ConstraintSolver/MemberConstraints.fs +++ b/tests/FSharp.Compiler.ComponentTests/ConstraintSolver/MemberConstraints.fs @@ -74,3 +74,43 @@ type DataItem< ^input> with """ |> compile |> shouldSucceed + + [] + let ``Indirect constraint by operator`` () = + FSharp """ +List.average [42] |> ignore +""" + |> typecheck + |> shouldFail + |> withSingleDiagnostic + (Error 1, Line 2, Col 15, Line 2, Col 17, "'List.average' does not support the type 'int', because the latter lacks the required (real or built-in) member 'DivideByInt'") + + [] + let ``Direct constraint by named (pseudo) operator`` () = + FSharp """ +abs -1u |> ignore +""" + |> typecheck + |> shouldFail + |> withSingleDiagnostic + (Error 1, Line 2, Col 6, Line 2, Col 8, "The type 'uint32' does not support the operator 'abs'") + + [] + let ``Direct constraint by simple operator`` () = + FSharp """ +"" >>> 1 |> ignore +""" + |> typecheck + |> shouldFail + |> withSingleDiagnostic + (Error 1, Line 2, Col 1, Line 2, Col 3, "The type 'string' does not support the operator '>>>'") + + [] + let ``Direct constraint by pseudo operator`` () = + FSharp """ +ignore ["1" .. "42"] +""" + |> typecheck + |> shouldFail + |> withSingleDiagnostic + (Error 1, Line 2, Col 9, Line 2, Col 12, "The type 'string' does not support the operator 'op_Range'") diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.net472.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.net472.bsl index 66fa1c78b4d..e092d8fd8ea 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.net472.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.net472.bsl @@ -432,14 +432,14 @@ } .method public static class TestModule/MyNullableOption`1 - mapPossiblyNullable(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 f, - class TestModule/MyNullableOption`1 myOpt) cil managed + mapPossiblyNullable(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 f, + class TestModule/MyNullableOption`1 myOpt) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationArgumentCountsAttribute::.ctor(int32[]) = ( 01 00 02 00 00 00 01 00 00 00 01 00 00 00 00 00 ) .param type a .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .param type b - .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) + .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .maxstack 4 .locals init (class TestModule/MyNullableOption`1 V_0, diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.netcore.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.netcore.bsl index 31eb914a6f2..d48f01435d7 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.netcore.bsl +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Nullness/NullAsTrueValue.fs.il.netcore.bsl @@ -432,14 +432,14 @@ } .method public static class TestModule/MyNullableOption`1 - mapPossiblyNullable(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 f, - class TestModule/MyNullableOption`1 myOpt) cil managed + mapPossiblyNullable(class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2 f, + class TestModule/MyNullableOption`1 myOpt) cil managed { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationArgumentCountsAttribute::.ctor(int32[]) = ( 01 00 02 00 00 00 01 00 00 00 01 00 00 00 00 00 ) .param type a .custom instance void [runtime]System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .param type b - .custom instance void [runtime]System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .maxstack 4 .locals init (class TestModule/MyNullableOption`1 V_0, diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/VeryLargeClasses.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/VeryLargeClasses.fs new file mode 100644 index 00000000000..8819cf27cdc --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/VeryLargeClasses.fs @@ -0,0 +1,50 @@ +namespace EmittedIL + +open Microsoft.FSharp.Core +open Xunit +open FSharp.Test.Compiler + +module VeryLargeClasses = + + let classWithManyMethods n = + let methods = + let mutable source = "" + for i = 0 to n - 1 do + source <- source + $""" + static member Method%05x{i}() = () """ + source + + FSharp + $""" + namespace VeryLargeClassesTestcases + + type Type1 ={methods} + """ + + [] + let ``More than 64K Methods -- should fail`` () = + classWithManyMethods (1024 * 64 + 1) + |> compile + |> shouldFail + |> withDiagnostics [ + (Error 3864, Line 1, Col 1, Line 1, Col 1, "The type 'VeryLargeClassesTestcases.Type1' has too many methods. Found: '65537', maximum: '65520'") + ] + + [] + let ``Exactly (0xfff0) Methods -- should succeed`` () = + FSharp + """ +module MyMain +open System +open System.Reflection +do printfn $"location: {typeof.Assembly.Location}" +let asm = Assembly.LoadFrom(typeof.Assembly.Location) +printfn $"asm: {asm}" +let types = asm.GetTypes() +printfn "length: {types.Length}" +""" + |> withReferences [ classWithManyMethods 0xfff0 |> asLibrary ] + |> asExe + |> compileAndRun + |> shouldSucceed + diff --git a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/ExtendedDiagnosticDataTests.fs b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/ExtendedDiagnosticDataTests.fs index fea4dfddbb7..eec3ce03dcd 100644 --- a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/ExtendedDiagnosticDataTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/ExtendedDiagnosticDataTests.fs @@ -143,8 +143,10 @@ if true then 1 else "a" Assert.Equal("int", typeMismatch.ExpectedType.Format(displayContext)) Assert.Equal("string", typeMismatch.ActualType.Format(displayContext))) -[] -let ``ArgumentsInSigAndImplMismatchExtendedData 01`` () = +[] +[] +[] +let ``ArgumentsInSigAndImplMismatchExtendedData 01`` useTransparentCompiler = let encodeFsi = Fsi """ module Test @@ -157,7 +159,7 @@ let f (y: int) = () """ encodeFsi |> withAdditionalSourceFile encodeFs - |> typecheckProject true + |> typecheckProject true useTransparentCompiler |> checkDiagnostic (3218, "The argument names in the signature 'x' and implementation 'y' do not match. The argument name from the signature file will be used. This may cause problems when debugging or profiling.") (fun (argsMismatch: ArgumentsInSigAndImplMismatchExtendedData) -> @@ -166,8 +168,10 @@ let f (y: int) = () Assert.True(argsMismatch.SignatureRange.FileName.EndsWith("fsi")) Assert.True(argsMismatch.ImplementationRange.FileName.EndsWith("fs"))) -[] -let ``FieldNotContainedDiagnosticExtendedData 01`` () = +[] +[] +[] +let ``FieldNotContainedDiagnosticExtendedData 01`` useTransparentCompiler = let encodeFsi = Fsi """ namespace rec Foo @@ -182,7 +186,7 @@ type A = """ encodeFsi |> withAdditionalSourceFile encodeFs - |> typecheckProject true + |> typecheckProject true useTransparentCompiler |> checkDiagnostic (193, "The module contains the field\n myStatic: int \nbut its signature specifies\n myStatic: int \nthe accessibility specified in the signature is more than that specified in the implementation") (fun (fieldsData: FieldNotContainedDiagnosticExtendedData) -> diff --git a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs index 3366ed91c3f..9bad5b4d0af 100644 --- a/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs +++ b/tests/FSharp.Compiler.ComponentTests/ErrorMessages/TailCallAttribute.fs @@ -1486,3 +1486,29 @@ namespace N Message = "The TailCall attribute should only be applied to recursive functions." } ] + + [] + let ``Warn about self-defined attribute`` () = // is the analysis available for users of older FSharp.Core versions + """ +module Microsoft.FSharp.Core + + open System + + [] + type TailCallAttribute() = inherit Attribute() + + [] + let rec f x = 1 + f x + """ + |> FSharp + |> compile + |> shouldFail + |> withResults [ + { Error = Warning 3569 + Range = { StartLine = 10 + StartColumn = 23 + EndLine = 10 + EndColumn = 26 } + Message = + "The member or function 'f' has the 'TailCallAttribute' attribute, but is not being used in a tail recursive way." } + ] diff --git a/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj b/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj index 56e23439441..857cbdb7d2c 100644 --- a/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj +++ b/tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj @@ -19,6 +19,7 @@ $(DefineConstants);DEBUG true + true @@ -71,13 +72,14 @@ - + + @@ -124,6 +126,7 @@ + @@ -268,6 +271,9 @@ + + + @@ -296,16 +302,17 @@ + + - - - - %(RelativeDir)TestSource\%(Filename)%(Extension) + %(RelativeDir)TestSource\%(Filename)%(Extension) + + %(RelativeDir)\BaseLine\%(Filename)%(Extension) diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/CommonWorkflows.fs b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/CommonWorkflows.fs index ce9846a0ee5..f4c5c41770d 100644 --- a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/CommonWorkflows.fs +++ b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/CommonWorkflows.fs @@ -100,13 +100,14 @@ let ``Changes in a referenced project`` () = checkFile "Last" expectSignatureChanged } -[] -let ``Language service works if the same file is listed twice`` () = +[] +// TODO: This will probably require some special care in TransparentCompiler... +let ``Language service works if the same file is listed twice`` () = let file = sourceFile "First" [] - let project = SyntheticProject.Create(file) + let project = SyntheticProject.Create(file, file) project.Workflow { - checkFile "First" expectOk - addFileAbove "First" file + // checkFile "First" expectOk + // addFileAbove "First" file checkFile "First" (expectSingleWarningAndNoErrors "Please verify that it is included only once in the project file.") } diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/FindReferences.fs b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/FindReferences.fs index c8cff9112c2..b12edf8cb6d 100644 --- a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/FindReferences.fs +++ b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/FindReferences.fs @@ -5,6 +5,8 @@ open FSharp.Compiler.CodeAnalysis open FSharp.Test.ProjectGeneration open FSharp.Test.ProjectGeneration.Helpers +#nowarn "57" + type Occurence = Definition | InType | Use let deriveOccurence (su:FSharpSymbolUse) = @@ -344,7 +346,7 @@ and mytype = MyType let symbolUse = getSymbolUse fileName source "MyType" options checker |> Async.RunSynchronously - checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol, fastCheck = true) + checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol) |> Async.RunSynchronously |> expectToFind [ fileName, 2, 5, 11 @@ -430,7 +432,7 @@ match 2 with let symbolUse = getSymbolUse fileName source "Even" options checker |> Async.RunSynchronously - checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol, fastCheck = true) + checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol) |> Async.RunSynchronously |> expectToFind [ fileName, 2, 6, 10 @@ -463,7 +465,7 @@ module Two = let symbolUse = getSymbolUse fileName source "Even" options checker |> Async.RunSynchronously - checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol, fastCheck = true) + checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol) |> Async.RunSynchronously |> expectToFind [ fileName, 4, 10, 14 @@ -619,7 +621,7 @@ let y = MyType.Two let symbolUse = getSymbolUse fileName source "MyType" options checker |> Async.RunSynchronously - checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol, fastCheck = true) + checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol) |> Async.RunSynchronously |> expectToFind [ fileName, 4, 5, 11 @@ -648,7 +650,7 @@ let y = MyType.Three let symbolUse = getSymbolUse fileName source "MyType" options checker |> Async.RunSynchronously - checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol, fastCheck = true) + checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol) |> Async.RunSynchronously |> expectToFind [ fileName, 4, 7, 13 diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/ProjectSnapshot.fs b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/ProjectSnapshot.fs new file mode 100644 index 00000000000..90e28cc63ac --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/ProjectSnapshot.fs @@ -0,0 +1,104 @@ +module FSharpChecker.ProjectSnapshot + +open Xunit +open System +open FSharp.Compiler.CodeAnalysis.ProjectSnapshot + + +// TODO: restore tests + +//[] +//let WithoutImplFilesThatHaveSignatures () = + +// let snapshot = FSharpProjectSnapshot.Create( +// projectFileName = "Dummy.fsproj", +// projectId = None, +// sourceFiles = [ +// { FileName = "A.fsi"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "A.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "B.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "C.fsi"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "C.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// ], +// referencesOnDisk = [], +// otherOptions = [], +// referencedProjects = [], +// isIncompleteTypeCheckEnvironment = true, +// useScriptResolutionRules = false, +// loadTime = DateTime(1234, 5, 6), +// unresolvedReferences = None, +// originalLoadReferences = [], +// stamp = None +// ) + +// let result = snapshot.WithoutImplFilesThatHaveSignatures + +// let expected = [| "A.fsi"; "B.fs"; "C.fsi" |] + +// Assert.Equal(expected, result.SourceFileNames |> List.toArray) + +// Assert.Equal(result.FullVersion, snapshot.SignatureVersion) + +//[] +//let WithoutImplFilesThatHaveSignaturesExceptLastOne () = + +// let snapshot = FSharpProjectSnapshot.Create( +// projectFileName = "Dummy.fsproj", +// projectId = None, +// sourceFiles = [ +// { FileName = "A.fsi"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "A.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "B.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "C.fsi"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "C.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// ], +// referencesOnDisk = [], +// otherOptions = [], +// referencedProjects = [], +// isIncompleteTypeCheckEnvironment = true, +// useScriptResolutionRules = false, +// loadTime = DateTime(1234, 5, 6), +// unresolvedReferences = None, +// originalLoadReferences = [], +// stamp = None +// ) + +// let result = snapshot.WithoutImplFilesThatHaveSignaturesExceptLastOne + +// let expected = [| "A.fsi"; "B.fs"; "C.fsi"; "C.fs" |] + +// Assert.Equal(expected, result.SourceFileNames |> List.toArray) + +// Assert.Equal(result.FullVersion, snapshot.LastFileVersion) + + +//[] +//let WithoutImplFilesThatHaveSignaturesExceptLastOne_2 () = + +// let snapshot = FSharpProjectSnapshot.Create( +// projectFileName = "Dummy.fsproj", +// projectId = None, +// sourceFiles = [ +// { FileName = "A.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "B.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// { FileName = "C.fs"; Version = "1"; GetSource = Unchecked.defaultof<_> } +// ], +// referencesOnDisk = [], +// otherOptions = [], +// referencedProjects = [], +// isIncompleteTypeCheckEnvironment = true, +// useScriptResolutionRules = false, +// loadTime = DateTime(1234, 5, 6), +// unresolvedReferences = None, +// originalLoadReferences = [], +// stamp = None +// ) + +// let result = snapshot.WithoutImplFilesThatHaveSignaturesExceptLastOne + +// let expected = [| "A.fs"; "B.fs"; "C.fs" |] + +// Assert.Equal(expected, result.SourceFileNames |> List.toArray) + +// Assert.Equal(result.FullVersion, snapshot.LastFileVersion) + diff --git a/tests/FSharp.Compiler.ComponentTests/FSharpChecker/TransparentCompiler.fs b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/TransparentCompiler.fs new file mode 100644 index 00000000000..57a9e266fe8 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/FSharpChecker/TransparentCompiler.fs @@ -0,0 +1,803 @@ +module FSharpChecker.TransparentCompiler + +open System.Collections.Concurrent +open System.Diagnostics +open FSharp.Compiler.CodeAnalysis +open Internal.Utilities.Collections +open FSharp.Compiler.CodeAnalysis.TransparentCompiler +open Internal.Utilities.Library.Extras +open FSharp.Compiler.GraphChecking.GraphProcessing +open FSharp.Compiler.Diagnostics + +open Xunit + +open FSharp.Test.ProjectGeneration +open FSharp.Test.ProjectGeneration.Helpers +open System.IO +open Microsoft.CodeAnalysis +open System +open System.Threading.Tasks +open System.Threading +open TypeChecks + +open OpenTelemetry +open OpenTelemetry.Resources +open OpenTelemetry.Trace + + +#nowarn "57" + +[] +let ``Use Transparent Compiler`` () = + + let size = 20 + + let project = + { SyntheticProject.Create() with + SourceFiles = [ + sourceFile $"File%03d{0}" [] + for i in 1..size do + sourceFile $"File%03d{i}" [$"File%03d{i-1}"] + ] + } + + let first = "File001" + let middle = $"File%03d{size / 2}" + let last = $"File%03d{size}" + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + updateFile first updatePublicSurface + checkFile first expectSignatureChanged + checkFile last expectSignatureChanged + updateFile middle updatePublicSurface + checkFile last expectSignatureChanged + addFileAbove middle (sourceFile "addedFile" [first]) + updateFile middle (addDependency "addedFile") + checkFile middle expectSignatureChanged + checkFile last expectSignatureChanged + } + +[] +let ``Parallel processing`` () = + + let project = SyntheticProject.Create( + sourceFile "A" [], + sourceFile "B" ["A"], + sourceFile "C" ["A"], + sourceFile "D" ["A"], + sourceFile "E" ["B"; "C"; "D"]) + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + checkFile "E" expectOk + updateFile "A" updatePublicSurface + saveFile "A" + + checkFile "E" expectSignatureChanged + } + +[] +let ``Parallel processing with signatures`` () = + + let project = SyntheticProject.Create( + sourceFile "A" [] |> addSignatureFile, + sourceFile "B" ["A"] |> addSignatureFile, + sourceFile "C" ["A"] |> addSignatureFile, + sourceFile "D" ["A"] |> addSignatureFile, + sourceFile "E" ["B"; "C"; "D"] |> addSignatureFile) + + //let cacheEvents = ConcurrentBag<_>() + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + //withChecker (fun checker -> checker.CacheEvent.Add cacheEvents.Add) + checkFile "E" expectOk + updateFile "A" updatePublicSurface + checkFile "E" expectNoChanges + regenerateSignature "A" + regenerateSignature "B" + regenerateSignature "C" + regenerateSignature "D" + regenerateSignature "E" + checkFile "E" expectSignatureChanged + } + +let makeTestProject () = + SyntheticProject.Create( + sourceFile "First" [], + sourceFile "Second" ["First"], + sourceFile "Third" ["First"], + { sourceFile "Last" ["Second"; "Third"] with EntryPoint = true }) + +let testWorkflow () = + ProjectWorkflowBuilder(makeTestProject(), useTransparentCompiler = true) + +[] +let ``Edit file, check it, then check dependent file`` () = + testWorkflow() { + updateFile "First" breakDependentFiles + checkFile "First" expectSignatureChanged + checkFile "Second" expectErrors + } + +[] +let ``Edit file, don't check it, check dependent file`` () = + testWorkflow() { + updateFile "First" breakDependentFiles + checkFile "Second" expectErrors + } + +[] +let ``Check transitive dependency`` () = + testWorkflow() { + updateFile "First" breakDependentFiles + checkFile "Last" expectSignatureChanged + } + +[] +let ``Change multiple files at once`` () = + testWorkflow() { + updateFile "First" (setPublicVersion 2) + updateFile "Second" (setPublicVersion 2) + updateFile "Third" (setPublicVersion 2) + checkFile "Last" (expectSignatureContains "val f: x: 'a -> (ModuleFirst.TFirstV_2<'a> * ModuleSecond.TSecondV_2<'a>) * (ModuleFirst.TFirstV_2<'a> * ModuleThird.TThirdV_2<'a>) * TLastV_1<'a>") + } + +[] +let ``Files depend on signature file if present`` () = + let project = makeTestProject() |> updateFile "First" addSignatureFile + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + updateFile "First" breakDependentFiles + saveFile "First" + checkFile "Second" expectNoChanges + } + +[] +let ``Project with signatures`` () = + + let project = SyntheticProject.Create( + { sourceFile "First" [] with + Source = "let f (x: int) = x" + SignatureFile = AutoGenerated }, + { sourceFile "Second" ["First"] with + Source = "let a x = ModuleFirst.f x" + SignatureFile = AutoGenerated }) + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + checkFile "Second" expectOk + } + +[] +let ``Signature update`` () = + + let project = SyntheticProject.Create( + { sourceFile "First" [] with + Source = "let f (x: int) = x" + SignatureFile = Custom "val f: x: int -> int" }, + { sourceFile "Second" ["First"] with + Source = "let a x = ModuleFirst.f x" }) + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + checkFile "Second" expectOk + updateFile "First" (fun f -> { f with SignatureFile = Custom "val f: x: string -> string" }) + checkFile "Second" expectSignatureChanged + } + +[] +let ``Adding a file`` () = + testWorkflow() { + addFileAbove "Second" (sourceFile "New" []) + updateFile "Second" (addDependency "New") + checkFile "Last" (expectSignatureContains "val f: x: 'a -> (ModuleFirst.TFirstV_1<'a> * ModuleNew.TNewV_1<'a> * ModuleSecond.TSecondV_1<'a>) * (ModuleFirst.TFirstV_1<'a> * ModuleThird.TThirdV_1<'a>) * TLastV_1<'a>") + } + +[] +let ``Removing a file`` () = + testWorkflow() { + removeFile "Second" + checkFile "Last" expectErrors + } + +[] +let ``Changes in a referenced project`` () = + let library = SyntheticProject.Create("library", sourceFile "Library" []) + + let project = + { makeTestProject() with DependsOn = [library] } + |> updateFile "First" (addDependency "Library") + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + + updateFile "First" updatePublicSurface + checkFile "Last" expectOk + + updateFile "Library" updatePublicSurface + saveFile "Library" + checkFile "Last" expectSignatureChanged + + } + +[] +let ``File is not checked twice`` () = + + let cacheEvents = ConcurrentQueue() + + testWorkflow() { + withChecker (fun checker -> + async { + do! Async.Sleep 50 // wait for events from initial project check + checker.Caches.TcIntermediate.OnEvent cacheEvents.Enqueue + }) + updateFile "First" updatePublicSurface + checkFile "Third" expectOk + } |> ignore + + let intermediateTypeChecks = + cacheEvents + |> Seq.groupBy (fun (_e, (_l, (f, _p), _)) -> f |> Path.GetFileName) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Map + + Assert.Equal([Weakened; Started; Finished], intermediateTypeChecks["FileFirst.fs"]) + Assert.Equal([Weakened; Started; Finished], intermediateTypeChecks["FileThird.fs"]) + +[] +let ``If a file is checked as a dependency it's not re-checked later`` () = + let cacheEvents = ConcurrentQueue() + + testWorkflow() { + withChecker (fun checker -> + async { + do! Async.Sleep 50 // wait for events from initial project check + checker.Caches.TcIntermediate.OnEvent cacheEvents.Enqueue + }) + updateFile "First" updatePublicSurface + checkFile "Last" expectOk + checkFile "Third" expectOk + } |> ignore + + let intermediateTypeChecks = + cacheEvents + |> Seq.groupBy (fun (_e, (_l, (f, _p), _)) -> f |> Path.GetFileName) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Map + + Assert.Equal([Weakened; Started; Finished], intermediateTypeChecks["FileThird.fs"]) + + +// [] TODO: differentiate complete and minimal checking requests +let ``We don't check files that are not depended on`` () = + let project = SyntheticProject.Create( + sourceFile "First" [], + sourceFile "Second" ["First"], + sourceFile "Third" ["First"], + sourceFile "Last" ["Third"]) + + let cacheEvents = ConcurrentQueue() + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + withChecker (fun checker -> + async { + do! Async.Sleep 50 // wait for events from initial project check + checker.Caches.TcIntermediate.OnEvent cacheEvents.Enqueue + }) + updateFile "First" updatePublicSurface + checkFile "Last" expectOk + } |> ignore + + let intermediateTypeChecks = + cacheEvents + |> Seq.groupBy (fun (_e, (_l, (f, _p), _)) -> Path.GetFileName f) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Map + + Assert.Equal([Started; Finished], intermediateTypeChecks["FileFirst.fs"]) + Assert.Equal([Started; Finished], intermediateTypeChecks["FileThird.fs"]) + Assert.False (intermediateTypeChecks.ContainsKey "FileSecond.fs") + +// [] TODO: differentiate complete and minimal checking requests +let ``Files that are not depended on don't invalidate cache`` () = + let project = SyntheticProject.Create( + sourceFile "First" [], + sourceFile "Second" ["First"], + sourceFile "Third" ["First"], + sourceFile "Last" ["Third"]) + + let cacheTcIntermediateEvents = ConcurrentQueue() + let cacheGraphConstructionEvents = ConcurrentQueue() + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + updateFile "First" updatePublicSurface + checkFile "Last" expectOk + withChecker (fun checker -> + async { + do! Async.Sleep 50 // wait for events from initial project check + checker.Caches.TcIntermediate.OnEvent cacheTcIntermediateEvents.Enqueue + checker.Caches.DependencyGraph.OnEvent cacheGraphConstructionEvents.Enqueue + + }) + updateFile "Second" updatePublicSurface + checkFile "Last" expectOk + } |> ignore + + let intermediateTypeChecks = + cacheTcIntermediateEvents + |> Seq.groupBy (fun (_e, (l, _k, _)) -> l) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Map + + let graphConstructions = + cacheGraphConstructionEvents + |> Seq.groupBy (fun (_e, (l, _k, _)) -> l) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Map + + Assert.Equal([Started; Finished], graphConstructions["FileLast.fs"]) + + Assert.Equal([], intermediateTypeChecks |> Map.toList) + +// [] TODO: differentiate complete and minimal checking requests +let ``Files that are not depended on don't invalidate cache part 2`` () = + let project = SyntheticProject.Create( + sourceFile "A" [], + sourceFile "B" ["A"], + sourceFile "C" ["A"], + sourceFile "D" ["B"; "C"], + sourceFile "E" ["C"]) + + let cacheTcIntermediateEvents = ConcurrentQueue() + let cacheGraphConstructionEvents = ConcurrentQueue() + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + updateFile "A" updatePublicSurface + checkFile "D" expectOk + withChecker (fun checker -> + async { + do! Async.Sleep 50 // wait for events from initial project check + checker.Caches.TcIntermediate.OnEvent cacheTcIntermediateEvents.Enqueue + checker.Caches.DependencyGraph.OnEvent cacheGraphConstructionEvents.Enqueue + }) + updateFile "B" updatePublicSurface + checkFile "E" expectOk + } |> ignore + + let intermediateTypeChecks = + cacheTcIntermediateEvents + |> Seq.groupBy (fun (_e, (l, _k, _)) -> l) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Seq.toList + + let graphConstructions = + cacheGraphConstructionEvents + |> Seq.groupBy (fun (_e, (l, _k, _)) -> l) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Seq.toList + + Assert.Equal(["FileE.fs", [Started; Finished]], graphConstructions) + Assert.Equal(["FileE.fs", [Started; Finished]], intermediateTypeChecks) + +[] +let ``Changing impl files doesn't invalidate cache when they have signatures`` () = + let project = SyntheticProject.Create( + { sourceFile "A" [] with SignatureFile = AutoGenerated }, + { sourceFile "B" ["A"] with SignatureFile = AutoGenerated }, + { sourceFile "C" ["B"] with SignatureFile = AutoGenerated }) + + let cacheEvents = ConcurrentQueue() + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + updateFile "A" updatePublicSurface + checkFile "C" expectOk + withChecker (fun checker -> + async { + do! Async.Sleep 50 // wait for events from initial project check + checker.Caches.TcIntermediate.OnEvent cacheEvents.Enqueue + }) + updateFile "A" updateInternal + checkFile "C" expectOk + } |> ignore + + let intermediateTypeChecks = + cacheEvents + |> Seq.groupBy (fun (_e, (l, _k, _)) -> l) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Seq.toList + + Assert.Equal([], intermediateTypeChecks) + +[] +let ``Changing impl file doesn't invalidate an in-memory referenced project`` () = + let library = SyntheticProject.Create("library", { sourceFile "A" [] with SignatureFile = AutoGenerated }) + + let project = { + SyntheticProject.Create("project", sourceFile "B" ["A"] ) + with DependsOn = [library] } + + let cacheEvents = ConcurrentQueue() + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + checkFile "B" expectOk + withChecker (fun checker -> + async { + do! Async.Sleep 50 // wait for events from initial project check + checker.Caches.TcIntermediate.OnEvent cacheEvents.Enqueue + }) + updateFile "A" updateInternal + checkFile "B" expectOk + } |> ignore + + let intermediateTypeChecks = + cacheEvents + |> Seq.groupBy (fun (_e, (l, _k, _)) -> l) + |> Seq.map (fun (k, g) -> k, g |> Seq.map fst |> Seq.toList) + |> Seq.toList + + Assert.Equal([], intermediateTypeChecks) + + +[] +[] +[] +let ``Multi-project`` signatureFiles = + + let sigFile = if signatureFiles then AutoGenerated else No + + let library = SyntheticProject.Create("library", + { sourceFile "LibA" [] + with + Source = "let f (x: int) = x" + SignatureFile = sigFile }, + { sourceFile "LibB" ["LibA"] with SignatureFile = sigFile }, + { sourceFile "LibC" ["LibA"] with SignatureFile = sigFile }, + { sourceFile "LibD" ["LibB"; "LibC"] with SignatureFile = sigFile } + ) + + let project = + { SyntheticProject.Create("app", + sourceFile "A" ["LibB"], + sourceFile "B" ["A"; "LibB"], + sourceFile "C" ["A"; "LibC"], + sourceFile "D" ["A"; "LibD"] + ) + with DependsOn = [library] } + + ProjectWorkflowBuilder(project, useTransparentCompiler = true) { + updateFile "LibA" updatePublicSurface + checkFile "D" expectOk + } + + + +type ProjectAction = Get | Modify of (SyntheticProject -> SyntheticProject) +type ProjectModificaiton = Update of int | Add | Remove +type ProjectRequest = ProjectAction * AsyncReplyChannel + +type FuzzingEvent = StartedChecking | FinishedChecking of bool | AbortedChecking of string | ModifiedImplFile | ModifiedSigFile + +[] +type SignatureFiles = Yes = 1 | No = 2 | Some = 3 + +let fuzzingTest seed (project: SyntheticProject) = task { + let rng = System.Random seed + + let checkingThreads = 3 + let maxModificationDelayMs = 10 + let maxCheckingDelayMs = 20 + //let runTimeMs = 30000 + let signatureFileModificationProbability = 0.25 + let modificationLoopIterations = 10 + let checkingLoopIterations = 5 + + let minCheckingTimeoutMs = 0 + let maxCheckingTimeoutMs = 300 + + let builder = ProjectWorkflowBuilder(project, useTransparentCompiler = true, autoStart = false) + let checker = builder.Checker + + // Force creation and caching of options + do! SaveAndCheckProject project checker |> Async.Ignore + + let projectAgent = MailboxProcessor.Start(fun (inbox: MailboxProcessor) -> + let rec loop project = + async { + let! action, reply = inbox.Receive() + let! project = + match action with + | Modify f -> async { + let p = f project + do! saveProject p false checker + return p } + | Get -> async.Return project + reply.Reply project + return! loop project + } + loop project) + + let getProject () = + projectAgent.PostAndAsyncReply(pair Get) + + let modifyProject f = + projectAgent.PostAndAsyncReply(pair(Modify f)) |> Async.Ignore + + let modificationProbabilities = [ + Update 1, 80 + Update 2, 5 + Update 10, 5 + //Add, 2 + //Remove, 1 + ] + + let modificationPicker = [| + for op, prob in modificationProbabilities do + for _ in 1 .. prob do + op + |] + + let addComment s = $"{s}\n\n// {rng.NextDouble()}" + let modifyImplFile f = { f with ExtraSource = f.ExtraSource |> addComment } + let modifySigFile f = { f with SignatureFile = Custom (f.SignatureFile.CustomText |> addComment) } + + let getRandomItem (xs: 'x array) = xs[rng.Next(0, xs.Length)] + + let getRandomModification () = modificationPicker |> getRandomItem + + let getRandomFile (project: SyntheticProject) = project.GetAllFiles() |> List.toArray |> getRandomItem + + let log = new ThreadLocal<_>((fun () -> ResizeArray<_>()), true) + + let exceptions = ConcurrentBag() + + let modificationLoop _ = task { + for _ in 1 .. modificationLoopIterations do + do! Task.Delay (rng.Next maxModificationDelayMs) + let modify project = + match getRandomModification() with + | Update n -> + + use _ = Activity.start "Update" [||] + let files = Set [ for _ in 1..n -> getRandomFile project |> snd ] + (project, files) + ||> Seq.fold (fun p file -> + let fileId = file.Id + let project, file = project.FindInAllProjects fileId + let opName, f = + if file.HasSignatureFile && rng.NextDouble() < signatureFileModificationProbability + then ModifiedSigFile, modifySigFile + else ModifiedImplFile, modifyImplFile + log.Value.Add (DateTime.Now.Ticks, opName, $"{project.Name} / {fileId}") + p |> updateFileInAnyProject fileId f) + | Add + | Remove -> + // TODO: + project + do! modifyProject modify + } + + let checkingLoop n _ = task { + for _ in 1 .. checkingLoopIterations do + let! project = getProject() + let p, file = project |> getRandomFile + + let timeout = rng.Next(minCheckingTimeoutMs, maxCheckingTimeoutMs) + + log.Value.Add (DateTime.Now.Ticks, StartedChecking, $"Loop #{n} {file.Id} ({timeout} ms timeout)") + let ct = new CancellationTokenSource() + ct.CancelAfter(timeout) + let job = Async.StartAsTask(checker |> checkFile file.Id p, cancellationToken = ct.Token) + try + use _ = Activity.start "Check" [||] + + let! parseResult, checkResult = job + log.Value.Add (DateTime.Now.Ticks, FinishedChecking (match checkResult with FSharpCheckFileAnswer.Succeeded _ -> true | _ -> false), $"Loop #{n} {file.Id}") + expectOk (parseResult, checkResult) () + with ex -> + let message = + match ex with + | :? AggregateException as e -> + match e.InnerException with + | :? GraphProcessingException as e -> $"GPE: {e.InnerException.Message}" + | _ -> e.Message + | _ -> ex.Message + log.Value.Add (DateTime.Now.Ticks, AbortedChecking (message), $"Loop #{n} {file.Id} %A{ex}") + if ex.Message <> "A task was canceled." then exceptions.Add ex + + do! Task.Delay (rng.Next maxCheckingDelayMs) + } + + use _tracerProvider = + Sdk.CreateTracerProviderBuilder() + .AddSource("fsc") + .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName="F# Fuzzing", serviceVersion = "1")) + .AddJaegerExporter() + .Build() + + use _ = Activity.start $"Fuzzing {project.Name}" [ Activity.Tags.project, project.Name; "seed", seed.ToString() ] + + do! task { + let threads = + seq { + modificationLoop CancellationToken.None + // ignore modificationLoop + for n in 1..checkingThreads do + checkingLoop n CancellationToken.None + } + + try + let! _x = threads |> Seq.skip 1 |> Task.WhenAll + () + with + | e -> + let _log = log.Values |> Seq.collect id |> Seq.sortBy p13 |> Seq.toArray + failwith $"Seed: {seed}\nException: %A{e}" + } + let log = log.Values |> Seq.collect id |> Seq.sortBy p13 |> Seq.toArray + + let _stats = log |> Array.groupBy (p23) |> Array.map (fun (op, xs) -> op, xs.Length) |> Map + + let _errors = _stats |> Map.toSeq |> Seq.filter (fst >> function AbortedChecking ex when ex <> "A task was canceled." -> true | _ -> false) |> Seq.toArray + + let _exceptions = exceptions + + Assert.Equal>([||], _errors) + + //Assert.Equal>(Map.empty, _stats) + + builder.DeleteProjectDir() +} + + +[] +[] +[] +[] +let Fuzzing signatureFiles = + + let seed = 1106087513 + let rng = System.Random(int seed) + + let fileCount = 30 + let maxDepsPerFile = 3 + + let fileName i = sprintf $"F%03d{i}" + + //let extraCode = __SOURCE_DIRECTORY__ ++ ".." ++ ".." ++ ".." ++ "src" ++ "Compiler" ++ "Utilities" ++ "EditDistance.fs" |> File.ReadAllLines |> Seq.skip 5 |> String.concat "\n" + let extraCode = "" + + let files = + [| for i in 1 .. fileCount do + let name = fileName i + let deps = [ + for _ in 1 .. maxDepsPerFile do + if i > 1 then + fileName <| rng.Next(1, i) ] + let signature = + match signatureFiles with + | SignatureFiles.Yes -> AutoGenerated + | SignatureFiles.Some when rng.NextDouble() < 0.5 -> AutoGenerated + | _ -> No + + { sourceFile name deps + with + SignatureFile = signature + ExtraSource = extraCode } + |] + + let initialProject = SyntheticProject.Create(files) + + let builder = ProjectWorkflowBuilder(initialProject, useTransparentCompiler = true, autoStart = false) + let checker = builder.Checker + + let initialProject = initialProject |> absorbAutoGeneratedSignatures checker |> Async.RunSynchronously + + fuzzingTest seed initialProject + + +let reposDir = __SOURCE_DIRECTORY__ ++ ".." ++ ".." ++ ".." ++ ".." +let giraffeDir = reposDir ++ "Giraffe" ++ "src" ++ "Giraffe" |> Path.GetFullPath +let giraffeTestsDir = reposDir ++ "Giraffe" ++ "tests" ++ "Giraffe.Tests" |> Path.GetFullPath +let giraffeSignaturesDir = reposDir ++ "giraffe-signatures" ++ "src" ++ "Giraffe" |> Path.GetFullPath +let giraffeSignaturesTestsDir = reposDir ++ "giraffe-signatures" ++ "tests" ++ "Giraffe.Tests" |> Path.GetFullPath + + +type GiraffeTheoryAttribute() = + inherit Xunit.TheoryAttribute() + do + if not (Directory.Exists giraffeDir) then + do base.Skip <- $"Giraffe not found ({giraffeDir}). You can get it here: https://github.com/giraffe-fsharp/Giraffe" + if not (Directory.Exists giraffeSignaturesDir) then + do base.Skip <- $"Giraffe (with signatures) not found ({giraffeSignaturesDir}). You can get it here: https://github.com/nojaf/Giraffe/tree/signatures" + +[] +[] +[] +let GiraffeFuzzing signatureFiles = + let seed = System.Random().Next() + //let seed = 1044159179 + + let giraffeDir = if signatureFiles then giraffeSignaturesDir else giraffeDir + let giraffeTestsDir = if signatureFiles then giraffeSignaturesTestsDir else giraffeTestsDir + + let giraffeProject = SyntheticProject.CreateFromRealProject giraffeDir + let giraffeProject = { giraffeProject with OtherOptions = "--nowarn:FS3520"::giraffeProject.OtherOptions } + + let testsProject = SyntheticProject.CreateFromRealProject giraffeTestsDir + let testsProject = + { testsProject + with + OtherOptions = "--nowarn:FS3520"::testsProject.OtherOptions + DependsOn = [ giraffeProject ] + NugetReferences = giraffeProject.NugetReferences @ testsProject.NugetReferences + } + + fuzzingTest seed testsProject + + + +[] +[] +[] +let ``File moving test`` signatureFiles = + let giraffeDir = if signatureFiles then giraffeSignaturesDir else giraffeDir + let giraffeProject = SyntheticProject.CreateFromRealProject giraffeDir + let giraffeProject = { giraffeProject with OtherOptions = "--nowarn:FS3520"::giraffeProject.OtherOptions } + + giraffeProject.Workflow { + // clearCache -- for better tracing + checkFile "Json" expectOk + moveFile "Json" 1 Down + checkFile "Json" expectOk + } + + +[] +[] +let ``What happens if bootrstapInfoStatic needs to be recomputed`` _ = + + let giraffeProject = SyntheticProject.CreateFromRealProject giraffeSignaturesDir + let giraffeProject = { giraffeProject with OtherOptions = "--nowarn:FS3520"::giraffeProject.OtherOptions } + + giraffeProject.Workflow { + updateFile "Helpers" (fun f -> { f with SignatureFile = Custom (f.SignatureFile.CustomText + "\n") }) + checkFile "EndpointRouting" expectOk + withChecker (fun checker -> + async { + checker.Caches.BootstrapInfoStatic.Clear() + checker.Caches.BootstrapInfo.Clear() + checker.Caches.FrameworkImports.Clear() + ignore checker + return () + }) + updateFile "Core" (fun f -> { f with SignatureFile = Custom (f.SignatureFile.CustomText + "\n") }) + checkFile "EndpointRouting" expectOk + } + + +module ParsedInputHashing = + + let source = """ + +type T = { A: int; B: string } + +module Stuff = + + // Some comment + let f x = x + 75 +""" + + let getParseResult source = + let fileName, snapshot, checker = singleFileChecker source + checker.ParseFile(fileName, snapshot) |> Async.RunSynchronously + + //[] + let ``Hash stays the same when whitespace changes`` () = + + //let parseResult = getParseResult source + + //let hash = parseResult.ParseTree |> parsedInputHash |> BitConverter.ToString + + //let parseResult2 = getParseResult (source + "\n \n") + + //let hash2 = parseResult2.ParseTree |> parsedInputHash |> BitConverter.ToString + + //Assert.Equal(hash, hash2) + + () \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Language/DiscriminatedUnionTests.fs b/tests/FSharp.Compiler.ComponentTests/Language/DiscriminatedUnionTests.fs index 194284177cc..a8b1e0cb404 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/DiscriminatedUnionTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/DiscriminatedUnionTests.fs @@ -17,6 +17,20 @@ if foo.IsBar then failwith "Should not be Bar" |> compileExeAndRun |> shouldSucceed + [] + let ``Simple Is* discriminated union properties are not visible for a single case union`` () = + Fsx """ +type Foo = Bar of string +let foo = Foo.Bar "hi" +if not foo.IsBar then failwith "Should be Bar" + + """ + |> withLangVersionPreview + |> typecheck + |> shouldFail + |> withDiagnostics [Error 39, Line 4, Col 12, Line 4, Col 17, "The type 'Foo' does not define the field, constructor or member 'IsBar'. Maybe you want one of the following: + Bar"] + [] let ``Simple Is* discriminated union property satisfies SRTP constraint`` () = Fsx """ diff --git a/tests/FSharp.Compiler.ComponentTests/Language/ExtensionMethodTests.fs b/tests/FSharp.Compiler.ComponentTests/Language/ExtensionMethodTests.fs index 510ac830ae4..60f902e9ef5 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/ExtensionMethodTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/ExtensionMethodTests.fs @@ -648,3 +648,40 @@ module M = |> withReferences [ csharp ] fsharp |> compile |> shouldSucceed + + [] + let ``F# CSharpStyleExtensionMethod consumed in F#`` () = + let producer = + FSharp + """ +namespace Producer + +open System.Runtime.CompilerServices + +type WidgetBuilder<'msg, 'marker>() = class end + +type IMarkerOne = interface end + +// Commenting out [] breaks +//[] +type WidgetBuilderExtensions = + [] + static member inline one(this: WidgetBuilder<'msg, #IMarkerOne>) = this +""" + |> withLangVersion80 + |> withName "FSLibProducer" + + let fsharp2 = + FSharp + """ +namespace Consumer + +open Producer + +module FSLibConsumer = + let x = WidgetBuilder().one() +""" + |> withName "FSLibConsumer" + |> withReferences [ producer ] + + fsharp2 |> compile |> shouldSucceed diff --git a/tests/FSharp.Compiler.ComponentTests/Language/SequenceExpressionTests.fs b/tests/FSharp.Compiler.ComponentTests/Language/SequenceExpressionTests.fs index 2f90f8963c6..982ae0c820b 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/SequenceExpressionTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/SequenceExpressionTests.fs @@ -440,5 +440,6 @@ let typedSeq = |> typecheck |> shouldFail |> withErrorCode 30 - |> withDiagnosticMessageMatches "Value restriction. The value 'typedSeq' has been inferred to have generic type" + |> withDiagnosticMessageMatches "Value restriction: The value 'typedSeq' has an inferred generic type" + |> withDiagnosticMessageMatches "val typedSeq: '_a seq" \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Signatures/MissingDiagnostic.fs b/tests/FSharp.Compiler.ComponentTests/Signatures/MissingDiagnostic.fs index 55181649b03..15b2ae61df0 100644 --- a/tests/FSharp.Compiler.ComponentTests/Signatures/MissingDiagnostic.fs +++ b/tests/FSharp.Compiler.ComponentTests/Signatures/MissingDiagnostic.fs @@ -27,28 +27,34 @@ let ``Compile gives errors`` () = but here has type 'char' ") -[] -let ``Type check project with signature file doesn't get the diagnostic`` () = +[] +[] +[] +let ``Type check project with signature file doesn't get the diagnostic`` useTransparentCompiler = Fsi signature |> withAdditionalSourceFile (FsSource implementation) - |> typecheckProject false + |> typecheckProject false useTransparentCompiler |> fun projectResults -> projectResults.Diagnostics |> ignore Assert.False (projectResults.Diagnostics |> Array.isEmpty) -[] -let ``Type check project without signature file does get the diagnostic`` () = +[] +[] +[] +let ``Type check project without signature file does get the diagnostic`` useTransparentCompiler = Fs implementation - |> typecheckProject false + |> typecheckProject false useTransparentCompiler |> fun projectResults -> projectResults.Diagnostics |> ignore Assert.False (projectResults.Diagnostics |> Array.isEmpty) -[] -let ``Enabling enablePartialTypeChecking = true doesn't change the problem`` () = +[] +[] +[] +let ``Enabling enablePartialTypeChecking = true doesn't change the problem`` useTransparentCompiler = Fsi signature |> withAdditionalSourceFile (FsSource implementation) - |> typecheckProject true + |> typecheckProject true useTransparentCompiler |> fun projectResults -> projectResults.Diagnostics |> ignore Assert.False (projectResults.Diagnostics |> Array.isEmpty) \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/Scenarios.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/Scenarios.fs index c75aed594c3..80f7caecafb 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/Scenarios.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/Scenarios.fs @@ -800,4 +800,114 @@ printfn "Hello" """ Set.empty ] + scenario + "Nameof module with namespace" + [ + sourceFile + "A.fs" + """ +namespace X.Y.Z + +module Foo = + let x = 2 +""" + Set.empty + sourceFile + "B.fs" + """ +namespace X.Y.Z + +module Point = + let y = nameof Foo +""" + (set [| 0 |]) + ] + scenario + "Nameof module without namespace" + [ + sourceFile + "A.fs" + """ +module Foo + +let x = 2 +""" + Set.empty + sourceFile + "B.fs" + """ +module Point + +let y = nameof Foo +""" + (set [| 0 |]) + ] + scenario + "Single module name should always be checked, regardless of own namespace" + [ + sourceFile "X.fs" "namespace X.Y" Set.empty + sourceFile + "A.fs" + """ +module Foo + +let x = 2 +""" + Set.empty + sourceFile + "B.fs" + """ +namespace X.Y + +type T() = + let _ = nameof Foo +""" + (set [| 1 |]) + ] + scenario + "nameof pattern" + [ + sourceFile "A.fs" "module Foo" Set.empty + sourceFile + "B.fs" + """ +module Bar + +do + match "" with + | nameof Foo -> () + | _ -> () +""" + (set [| 0 |]) + ] + scenario + "parentheses around module name in nameof pattern" + [ + sourceFile "A.fs" "module Foo" Set.empty + sourceFile + "B.fs" + """ +module Bar + +do + match "" with + | nameof ((Foo)) -> () + | _ -> () +""" + (set [| 0 |]) + ] + + scenario + "parentheses around module name in nameof expression" + [ + sourceFile "A.fs" "module Foo" Set.empty + sourceFile + "B.fs" + """ +module Bar + +let _ = nameof ((Foo)) +""" + (set [| 0 |]) + ] ] \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs index 9e25c623532..c4680870efc 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/TypedTreeGraph.fs @@ -140,7 +140,7 @@ let ``Create Graph from typed tree`` (projectArgumentsFilePath: string) = graphFromTypedTree |> Graph.map (fun n -> n,files.[n].File) - |> Graph.serialiseToMermaid $"{fileName}.typed-tree.deps.md" + |> Graph.writeMermaidToFile $"{fileName}.typed-tree.deps.md" let collectAllDeps (graph: Graph) = (Map.empty, [ 0 .. (sourceFiles.Length - 1) ]) @@ -161,7 +161,7 @@ let ``Create Graph from typed tree`` (projectArgumentsFilePath: string) = graphFromHeuristic |> Graph.map (fun n -> n, files.[n].File) - |> Graph.serialiseToMermaid $"{fileName}.heuristic-tree.deps.md" + |> Graph.writeMermaidToFile $"{fileName}.heuristic-tree.deps.md" let heuristicMap = collectAllDeps graphFromHeuristic diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/TyparNameTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/TyparNameTests.fs index 118ea134ff3..339fa1e2629 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/TyparNameTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/TyparNameTests.fs @@ -14,7 +14,7 @@ module TyparNameTests = (additionalFile: SourceCodeFileKind) : string array = let typeCheckResult = - cUnit |> withAdditionalSourceFile additionalFile |> typecheckProject false + cUnit |> withAdditionalSourceFile additionalFile |> typecheckProject false false assert (Array.isEmpty typeCheckResult.Diagnostics) diff --git a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.debug.bsl b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.debug.bsl index 15b58c9aea1..954fca3437d 100644 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.debug.bsl +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.debug.bsl @@ -318,8 +318,6 @@ FSharp.Compiler.AbstractIL.IL+ILAttributesStored: System.String ToString() FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean Equals(ILCallingConv) FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean Equals(System.Object) FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean IsCallconv -FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean get_IsCallconv() FSharp.Compiler.AbstractIL.IL+ILCallingConv: ILArgConvention Item2 FSharp.Compiler.AbstractIL.IL+ILCallingConv: ILArgConvention get_Item2() FSharp.Compiler.AbstractIL.IL+ILCallingConv: ILCallingConv Instance @@ -2078,7 +2076,7 @@ FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: FSharp.Compiler.Symbols. FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: System.String ToString() FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: System.String[] DependencyFiles FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: System.String[] get_DependencyFiles() -FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker Create(Microsoft.FSharp.Core.FSharpOption`1[System.Int32], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.LegacyReferenceResolver], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`2[System.String,System.DateTime],Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`3[System.Object,System.IntPtr,System.Int32]]]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker Create(Microsoft.FSharp.Core.FSharpOption`1[System.Int32], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.LegacyReferenceResolver], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`2[System.String,System.DateTime],Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`3[System.Object,System.IntPtr,System.Int32]]]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker Instance FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker get_Instance() FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpProjectOptions GetProjectOptionsFromCommandLineArgs(System.String, System.String[], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) @@ -2089,14 +2087,19 @@ FSharp.Compiler.CodeAnalysis.FSharpChecker: Int32 get_ActualCheckFileCount() FSharp.Compiler.CodeAnalysis.FSharpChecker: Int32 get_ActualParseFileCount() FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer] CheckFileInProject(FSharp.Compiler.CodeAnalysis.FSharpParseFileResults, System.String, Int32, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults] ParseAndCheckProject(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults] ParseAndCheckProject(FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] GetBackgroundParseResultsForFileInProject(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] ParseFile(System.String, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpParsingOptions, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] ParseFile(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] ParseFileInProject(System.String, System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] CheckFileInProjectAllowingStaleCachedResults(FSharp.Compiler.CodeAnalysis.FSharpParseFileResults, System.String, Int32, System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.EditorServices.SemanticClassificationView]] GetBackgroundSemanticClassificationForFile(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.EditorServices.SemanticClassificationView]] GetBackgroundSemanticClassificationForFile(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit] NotifyFileChanged(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit] NotifyProjectCleaned(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Collections.Generic.IEnumerable`1[FSharp.Compiler.Text.Range]] FindBackgroundReferencesInFile(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, FSharp.Compiler.Symbols.FSharpSymbol, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Collections.Generic.IEnumerable`1[FSharp.Compiler.Text.Range]] FindBackgroundReferencesInFile(System.String, FSharpProjectSnapshot, FSharp.Compiler.Symbols.FSharpSymbol, Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, Int32, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults]] GetBackgroundCheckResultsForFileInProject(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectOptionsFromScript(System.String, FSharp.Compiler.Text.ISourceText, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) @@ -2117,6 +2120,7 @@ FSharp.Compiler.CodeAnalysis.FSharpChecker: System.Tuple`2[FSharp.Compiler.CodeA FSharp.Compiler.CodeAnalysis.FSharpChecker: System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParsingOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]] GetParsingOptionsFromProjectOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions) FSharp.Compiler.CodeAnalysis.FSharpChecker: System.Tuple`2[FSharp.Compiler.Tokenization.FSharpTokenInfo[],FSharp.Compiler.Tokenization.FSharpTokenizerLexState] TokenizeLine(System.String, FSharp.Compiler.Tokenization.FSharpTokenizerLexState) FSharp.Compiler.CodeAnalysis.FSharpChecker: Void ClearCache(System.Collections.Generic.IEnumerable`1[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Void ClearCache(System.Collections.Generic.IEnumerable`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Void ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() FSharp.Compiler.CodeAnalysis.FSharpChecker: Void InvalidateAll() FSharp.Compiler.CodeAnalysis.FSharpChecker: Void InvalidateConfiguration(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) @@ -2334,6 +2338,76 @@ FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: System.String get_baggage() FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: System.String get_itemSpec() FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: System.String itemSpec FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: Void .ctor(System.String, Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`2[System.String,System.String],System.String], System.String) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Boolean IsSignatureFile +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Boolean get_IsSignatureFile() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: FSharpFileSnapshot Create(System.String, System.String, Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,System.Threading.Tasks.Task`1[FSharp.Compiler.Text.ISourceTextNew]]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: FSharpFileSnapshot CreateFromFileSystem(System.String) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String FileName +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String GetFileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String Version +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String get_FileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String get_Version() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.Threading.Tasks.Task`1[FSharp.Compiler.Text.ISourceTextNew] GetSource() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Void .ctor(System.String, System.String, Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,System.Threading.Tasks.Task`1[FSharp.Compiler.Text.ISourceTextNew]]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Boolean Equals(FSharpProjectIdentifier) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Boolean Equals(System.Object, System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: FSharpProjectIdentifier NewFSharpProjectIdentifier(System.String, System.String) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 CompareTo(FSharpProjectIdentifier) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 CompareTo(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 CompareTo(System.Object, System.Collections.IComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 GetHashCode(System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 Tag +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 get_Tag() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String ToString() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String get_outputFileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String get_projectFileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String outputFileName +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String projectFileName +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectIdentifier Identifier +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectIdentifier get_Identifier() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectSnapshot Create(System.String, Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk], Microsoft.FSharp.Collections.FSharpList`1[System.String], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot], Boolean, Boolean, System.DateTime, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpUnresolvedReferencesSet], Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Text.Range,System.String,System.String]], Microsoft.FSharp.Core.FSharpOption`1[System.Int64]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectSnapshot Replace(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot] FromOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot] FromOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Core.FSharpFunc`2[System.String,Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot]]], Microsoft.FSharp.Core.FSharpOption`1[System.Collections.Generic.Dictionary`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot]]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot] FromOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, System.String, Int32, FSharp.Compiler.Text.ISourceText) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: System.String Label +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: System.String get_Label() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpProjectSnapshot get_options() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpProjectSnapshot options +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpReferencedProjectSnapshot CreateFSharp(System.String, FSharpProjectSnapshot) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpReferencedProjectSnapshot NewFSharpReference(System.String, FSharpProjectSnapshot) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Int32 Tag +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Int32 get_Tag() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String OutputFile +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String ToString() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String get_OutputFile() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String get_projectOutputFile() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String projectOutputFile +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Boolean Equals(ReferenceOnDisk) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Boolean Equals(System.Object, System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 CompareTo(ReferenceOnDisk) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 CompareTo(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 CompareTo(System.Object, System.Collections.IComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 GetHashCode(System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.DateTime LastModified +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.DateTime get_LastModified() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.String Path +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.String ToString() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.String get_Path() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Void .ctor(System.String, System.DateTime) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk FSharp.Compiler.CompilerEnvironment: Boolean IsCheckerSupportedSubcategory(System.String) FSharp.Compiler.CompilerEnvironment: Boolean IsCompilable(System.String) FSharp.Compiler.CompilerEnvironment: Boolean IsScriptFile(System.String) @@ -4271,8 +4345,6 @@ FSharp.Compiler.EditorServices.ToolTipElementData: Void .ctor(Microsoft.FSharp.C FSharp.Compiler.EditorServices.ToolTipText: Boolean Equals(FSharp.Compiler.EditorServices.ToolTipText) FSharp.Compiler.EditorServices.ToolTipText: Boolean Equals(System.Object) FSharp.Compiler.EditorServices.ToolTipText: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.EditorServices.ToolTipText: Boolean IsToolTipText -FSharp.Compiler.EditorServices.ToolTipText: Boolean get_IsToolTipText() FSharp.Compiler.EditorServices.ToolTipText: FSharp.Compiler.EditorServices.ToolTipText NewToolTipText(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.EditorServices.ToolTipElement]) FSharp.Compiler.EditorServices.ToolTipText: Int32 GetHashCode() FSharp.Compiler.EditorServices.ToolTipText: Int32 GetHashCode(System.Collections.IEqualityComparer) @@ -4292,7 +4364,6 @@ FSharp.Compiler.EditorServices.TupledArgumentLocation: Int32 GetHashCode() FSharp.Compiler.EditorServices.TupledArgumentLocation: Int32 GetHashCode(System.Collections.IEqualityComparer) FSharp.Compiler.EditorServices.TupledArgumentLocation: System.String ToString() FSharp.Compiler.EditorServices.TupledArgumentLocation: Void .ctor(Boolean, FSharp.Compiler.Text.Range) -FSharp.Compiler.EditorServices.UnnecessaryParentheses: Microsoft.FSharp.Control.FSharpAsync`1[System.Collections.Generic.IEnumerable`1[FSharp.Compiler.Text.Range]] getUnnecessaryParentheses(Microsoft.FSharp.Core.FSharpFunc`2[System.Int32,System.String], FSharp.Compiler.Syntax.ParsedInput) FSharp.Compiler.EditorServices.UnresolvedSymbol: Boolean Equals(FSharp.Compiler.EditorServices.UnresolvedSymbol) FSharp.Compiler.EditorServices.UnresolvedSymbol: Boolean Equals(System.Object) FSharp.Compiler.EditorServices.UnresolvedSymbol: Boolean Equals(System.Object, System.Collections.IEqualityComparer) @@ -4316,8 +4387,6 @@ FSharp.Compiler.EditorServices.XmlDocParser: Microsoft.FSharp.Collections.FSharp FSharp.Compiler.EditorServices.XmlDocable: Boolean Equals(FSharp.Compiler.EditorServices.XmlDocable) FSharp.Compiler.EditorServices.XmlDocable: Boolean Equals(System.Object) FSharp.Compiler.EditorServices.XmlDocable: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.EditorServices.XmlDocable: Boolean IsXmlDocable -FSharp.Compiler.EditorServices.XmlDocable: Boolean get_IsXmlDocable() FSharp.Compiler.EditorServices.XmlDocable: FSharp.Compiler.EditorServices.XmlDocable NewXmlDocable(Int32, Int32, Microsoft.FSharp.Collections.FSharpList`1[System.String]) FSharp.Compiler.EditorServices.XmlDocable: Int32 CompareTo(FSharp.Compiler.EditorServices.XmlDocable) FSharp.Compiler.EditorServices.XmlDocable: Int32 CompareTo(System.Object) @@ -5556,8 +5625,6 @@ FSharp.Compiler.Syntax.DebugPointAtInOrTo: System.String ToString() FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean Equals(FSharp.Compiler.Syntax.DebugPointAtLeafExpr) FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean Equals(System.Object) FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean IsYes -FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean get_IsYes() FSharp.Compiler.Syntax.DebugPointAtLeafExpr: FSharp.Compiler.Syntax.DebugPointAtLeafExpr NewYes(FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.DebugPointAtLeafExpr: FSharp.Compiler.Text.Range Item FSharp.Compiler.Syntax.DebugPointAtLeafExpr: FSharp.Compiler.Text.Range get_Item() @@ -5692,8 +5759,6 @@ FSharp.Compiler.Syntax.Ident: System.String ToString() FSharp.Compiler.Syntax.Ident: System.String get_idText() FSharp.Compiler.Syntax.Ident: System.String idText FSharp.Compiler.Syntax.Ident: Void .ctor(System.String, FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.ParsedHashDirective: Boolean IsParsedHashDirective -FSharp.Compiler.Syntax.ParsedHashDirective: Boolean get_IsParsedHashDirective() FSharp.Compiler.Syntax.ParsedHashDirective: FSharp.Compiler.Syntax.ParsedHashDirective NewParsedHashDirective(System.String, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirectiveArgument], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.ParsedHashDirective: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.ParsedHashDirective: FSharp.Compiler.Text.Range range @@ -5732,8 +5797,6 @@ FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: FSharp.Compiler.Text.Range g FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: Int32 Tag FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: System.String ToString() -FSharp.Compiler.Syntax.ParsedImplFile: Boolean IsParsedImplFile -FSharp.Compiler.Syntax.ParsedImplFile: Boolean get_IsParsedImplFile() FSharp.Compiler.Syntax.ParsedImplFile: FSharp.Compiler.Syntax.ParsedImplFile NewParsedImplFile(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirective], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedImplFileFragment]) FSharp.Compiler.Syntax.ParsedImplFile: Int32 Tag FSharp.Compiler.Syntax.ParsedImplFile: Int32 get_Tag() @@ -5785,11 +5848,9 @@ FSharp.Compiler.Syntax.ParsedImplFileFragment: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedImplFileFragment: System.String ToString() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsExe FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsLastCompiland -FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsParsedImplFileInput FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsScript FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsExe() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsLastCompiland() -FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsParsedImplFileInput() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsScript() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_isScript() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean isScript @@ -5853,8 +5914,12 @@ FSharp.Compiler.Syntax.ParsedInput: Microsoft.FSharp.Collections.FSharpSet`1[Sys FSharp.Compiler.Syntax.ParsedInput: System.String FileName FSharp.Compiler.Syntax.ParsedInput: System.String ToString() FSharp.Compiler.Syntax.ParsedInput: System.String get_FileName() -FSharp.Compiler.Syntax.ParsedScriptInteraction: Boolean IsDefinitions -FSharp.Compiler.Syntax.ParsedScriptInteraction: Boolean get_IsDefinitions() +FSharp.Compiler.Syntax.ParsedInputModule: Boolean exists(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,System.Boolean]], FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode]]] tryNode(FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: Microsoft.FSharp.Core.FSharpOption`1[T] tryPickLast[T](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Core.FSharpOption`1[T]]], FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: Microsoft.FSharp.Core.FSharpOption`1[T] tryPick[T](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Core.FSharpOption`1[T]]], FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: State foldWhile[State](Microsoft.FSharp.Core.FSharpFunc`2[State,Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Core.FSharpOption`1[State]]]], State, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: State fold[State](Microsoft.FSharp.Core.FSharpFunc`2[State,Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,State]]], State, FSharp.Compiler.Syntax.ParsedInput) FSharp.Compiler.Syntax.ParsedScriptInteraction: FSharp.Compiler.Syntax.ParsedScriptInteraction NewDefinitions(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.ParsedScriptInteraction: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.ParsedScriptInteraction: FSharp.Compiler.Text.Range range @@ -5863,8 +5928,6 @@ FSharp.Compiler.Syntax.ParsedScriptInteraction: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedScriptInteraction: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl] defns FSharp.Compiler.Syntax.ParsedScriptInteraction: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl] get_defns() FSharp.Compiler.Syntax.ParsedScriptInteraction: System.String ToString() -FSharp.Compiler.Syntax.ParsedSigFile: Boolean IsParsedSigFile -FSharp.Compiler.Syntax.ParsedSigFile: Boolean get_IsParsedSigFile() FSharp.Compiler.Syntax.ParsedSigFile: FSharp.Compiler.Syntax.ParsedSigFile NewParsedSigFile(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirective], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedSigFileFragment]) FSharp.Compiler.Syntax.ParsedSigFile: Int32 Tag FSharp.Compiler.Syntax.ParsedSigFile: Int32 get_Tag() @@ -5914,8 +5977,6 @@ FSharp.Compiler.Syntax.ParsedSigFileFragment: FSharp.Compiler.Syntax.ParsedSigFi FSharp.Compiler.Syntax.ParsedSigFileFragment: Int32 Tag FSharp.Compiler.Syntax.ParsedSigFileFragment: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedSigFileFragment: System.String ToString() -FSharp.Compiler.Syntax.ParsedSigFileInput: Boolean IsParsedSigFileInput -FSharp.Compiler.Syntax.ParsedSigFileInput: Boolean get_IsParsedSigFileInput() FSharp.Compiler.Syntax.ParsedSigFileInput: FSharp.Compiler.Syntax.ParsedSigFileInput NewParsedSigFileInput(System.String, FSharp.Compiler.Syntax.QualifiedNameOfFile, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ScopedPragma], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirective], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleOrNamespaceSig], FSharp.Compiler.SyntaxTrivia.ParsedSigFileInputTrivia, Microsoft.FSharp.Collections.FSharpSet`1[System.String]) FSharp.Compiler.Syntax.ParsedSigFileInput: FSharp.Compiler.Syntax.QualifiedNameOfFile QualifiedName FSharp.Compiler.Syntax.ParsedSigFileInput: FSharp.Compiler.Syntax.QualifiedNameOfFile get_QualifiedName() @@ -5988,8 +6049,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.QualifiedNameOfFile: Boolean IsQualifiedNameOfFile -FSharp.Compiler.Syntax.QualifiedNameOfFile: Boolean get_IsQualifiedNameOfFile() FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident Id FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident Item FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident get_Id() @@ -6005,8 +6064,6 @@ FSharp.Compiler.Syntax.QualifiedNameOfFile: System.String get_Text() FSharp.Compiler.Syntax.ScopedPragma: Boolean Equals(FSharp.Compiler.Syntax.ScopedPragma) FSharp.Compiler.Syntax.ScopedPragma: Boolean Equals(System.Object) FSharp.Compiler.Syntax.ScopedPragma: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.Syntax.ScopedPragma: Boolean IsWarningOff -FSharp.Compiler.Syntax.ScopedPragma: Boolean get_IsWarningOff() FSharp.Compiler.Syntax.ScopedPragma: FSharp.Compiler.Syntax.ScopedPragma NewWarningOff(FSharp.Compiler.Text.Range, Int32) FSharp.Compiler.Syntax.ScopedPragma: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.ScopedPragma: FSharp.Compiler.Text.Range range @@ -6020,9 +6077,7 @@ FSharp.Compiler.Syntax.ScopedPragma: System.String ToString() FSharp.Compiler.Syntax.SeqExprOnly: Boolean Equals(FSharp.Compiler.Syntax.SeqExprOnly) FSharp.Compiler.Syntax.SeqExprOnly: Boolean Equals(System.Object) FSharp.Compiler.Syntax.SeqExprOnly: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.Syntax.SeqExprOnly: Boolean IsSeqExprOnly FSharp.Compiler.Syntax.SeqExprOnly: Boolean Item -FSharp.Compiler.Syntax.SeqExprOnly: Boolean get_IsSeqExprOnly() FSharp.Compiler.Syntax.SeqExprOnly: Boolean get_Item() FSharp.Compiler.Syntax.SeqExprOnly: FSharp.Compiler.Syntax.SeqExprOnly NewSeqExprOnly(Boolean) FSharp.Compiler.Syntax.SeqExprOnly: Int32 CompareTo(FSharp.Compiler.Syntax.SeqExprOnly) @@ -6065,8 +6120,6 @@ FSharp.Compiler.Syntax.SynAccess: Int32 GetHashCode(System.Collections.IEquality FSharp.Compiler.Syntax.SynAccess: Int32 Tag FSharp.Compiler.Syntax.SynAccess: Int32 get_Tag() FSharp.Compiler.Syntax.SynAccess: System.String ToString() -FSharp.Compiler.Syntax.SynArgInfo: Boolean IsSynArgInfo -FSharp.Compiler.Syntax.SynArgInfo: Boolean get_IsSynArgInfo() FSharp.Compiler.Syntax.SynArgInfo: Boolean get_optional() FSharp.Compiler.Syntax.SynArgInfo: Boolean optional FSharp.Compiler.Syntax.SynArgInfo: FSharp.Compiler.Syntax.SynArgInfo NewSynArgInfo(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]) @@ -6123,8 +6176,6 @@ FSharp.Compiler.Syntax.SynAttributeList: Microsoft.FSharp.Collections.FSharpList FSharp.Compiler.Syntax.SynAttributeList: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttribute] get_Attributes() FSharp.Compiler.Syntax.SynAttributeList: System.String ToString() FSharp.Compiler.Syntax.SynAttributeList: Void .ctor(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttribute], FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.SynBinding: Boolean IsSynBinding -FSharp.Compiler.Syntax.SynBinding: Boolean get_IsSynBinding() FSharp.Compiler.Syntax.SynBinding: Boolean get_isInline() FSharp.Compiler.Syntax.SynBinding: Boolean get_isMutable() FSharp.Compiler.Syntax.SynBinding: Boolean isInline @@ -6188,8 +6239,6 @@ FSharp.Compiler.Syntax.SynBindingKind: Int32 GetHashCode(System.Collections.IEqu FSharp.Compiler.Syntax.SynBindingKind: Int32 Tag FSharp.Compiler.Syntax.SynBindingKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynBindingKind: System.String ToString() -FSharp.Compiler.Syntax.SynBindingReturnInfo: Boolean IsSynBindingReturnInfo -FSharp.Compiler.Syntax.SynBindingReturnInfo: Boolean get_IsSynBindingReturnInfo() FSharp.Compiler.Syntax.SynBindingReturnInfo: FSharp.Compiler.Syntax.SynBindingReturnInfo NewSynBindingReturnInfo(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.SyntaxTrivia.SynBindingReturnInfoTrivia) FSharp.Compiler.Syntax.SynBindingReturnInfo: FSharp.Compiler.Syntax.SynType get_typeName() FSharp.Compiler.Syntax.SynBindingReturnInfo: FSharp.Compiler.Syntax.SynType typeName @@ -6224,8 +6273,6 @@ FSharp.Compiler.Syntax.SynByteStringKind: Int32 GetHashCode(System.Collections.I FSharp.Compiler.Syntax.SynByteStringKind: Int32 Tag FSharp.Compiler.Syntax.SynByteStringKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynByteStringKind: System.String ToString() -FSharp.Compiler.Syntax.SynComponentInfo: Boolean IsSynComponentInfo -FSharp.Compiler.Syntax.SynComponentInfo: Boolean get_IsSynComponentInfo() FSharp.Compiler.Syntax.SynComponentInfo: Boolean get_preferPostfix() FSharp.Compiler.Syntax.SynComponentInfo: Boolean preferPostfix FSharp.Compiler.Syntax.SynComponentInfo: FSharp.Compiler.Syntax.SynComponentInfo NewSynComponentInfo(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynTyparDecls], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynTypeConstraint], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], FSharp.Compiler.Xml.PreXmlDoc, Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) @@ -6425,8 +6472,6 @@ FSharp.Compiler.Syntax.SynConst: FSharp.Compiler.Text.Range Range(FSharp.Compile FSharp.Compiler.Syntax.SynConst: Int32 Tag FSharp.Compiler.Syntax.SynConst: Int32 get_Tag() FSharp.Compiler.Syntax.SynConst: System.String ToString() -FSharp.Compiler.Syntax.SynEnumCase: Boolean IsSynEnumCase -FSharp.Compiler.Syntax.SynEnumCase: Boolean get_IsSynEnumCase() FSharp.Compiler.Syntax.SynEnumCase: FSharp.Compiler.Syntax.SynEnumCase NewSynEnumCase(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynIdent, FSharp.Compiler.Syntax.SynExpr, FSharp.Compiler.Xml.PreXmlDoc, FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynEnumCaseTrivia) FSharp.Compiler.Syntax.SynEnumCase: FSharp.Compiler.Syntax.SynExpr get_valueExpr() FSharp.Compiler.Syntax.SynEnumCase: FSharp.Compiler.Syntax.SynExpr valueExpr @@ -6445,8 +6490,6 @@ FSharp.Compiler.Syntax.SynEnumCase: Int32 get_Tag() FSharp.Compiler.Syntax.SynEnumCase: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList] attributes FSharp.Compiler.Syntax.SynEnumCase: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList] get_attributes() FSharp.Compiler.Syntax.SynEnumCase: System.String ToString() -FSharp.Compiler.Syntax.SynExceptionDefn: Boolean IsSynExceptionDefn -FSharp.Compiler.Syntax.SynExceptionDefn: Boolean get_IsSynExceptionDefn() FSharp.Compiler.Syntax.SynExceptionDefn: FSharp.Compiler.Syntax.SynExceptionDefn NewSynExceptionDefn(FSharp.Compiler.Syntax.SynExceptionDefnRepr, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynExceptionDefn: FSharp.Compiler.Syntax.SynExceptionDefnRepr exnRepr FSharp.Compiler.Syntax.SynExceptionDefn: FSharp.Compiler.Syntax.SynExceptionDefnRepr get_exnRepr() @@ -6461,8 +6504,6 @@ FSharp.Compiler.Syntax.SynExceptionDefn: Microsoft.FSharp.Collections.FSharpList FSharp.Compiler.Syntax.SynExceptionDefn: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_withKeyword() FSharp.Compiler.Syntax.SynExceptionDefn: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] withKeyword FSharp.Compiler.Syntax.SynExceptionDefn: System.String ToString() -FSharp.Compiler.Syntax.SynExceptionDefnRepr: Boolean IsSynExceptionDefnRepr -FSharp.Compiler.Syntax.SynExceptionDefnRepr: Boolean get_IsSynExceptionDefnRepr() FSharp.Compiler.Syntax.SynExceptionDefnRepr: FSharp.Compiler.Syntax.SynExceptionDefnRepr NewSynExceptionDefnRepr(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynUnionCase, Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident]], FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynExceptionDefnRepr: FSharp.Compiler.Syntax.SynUnionCase caseName FSharp.Compiler.Syntax.SynExceptionDefnRepr: FSharp.Compiler.Syntax.SynUnionCase get_caseName() @@ -6481,8 +6522,6 @@ FSharp.Compiler.Syntax.SynExceptionDefnRepr: Microsoft.FSharp.Core.FSharpOption` FSharp.Compiler.Syntax.SynExceptionDefnRepr: Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident]] get_longId() FSharp.Compiler.Syntax.SynExceptionDefnRepr: Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident]] longId FSharp.Compiler.Syntax.SynExceptionDefnRepr: System.String ToString() -FSharp.Compiler.Syntax.SynExceptionSig: Boolean IsSynExceptionSig -FSharp.Compiler.Syntax.SynExceptionSig: Boolean get_IsSynExceptionSig() FSharp.Compiler.Syntax.SynExceptionSig: FSharp.Compiler.Syntax.SynExceptionDefnRepr exnRepr FSharp.Compiler.Syntax.SynExceptionSig: FSharp.Compiler.Syntax.SynExceptionDefnRepr get_exnRepr() FSharp.Compiler.Syntax.SynExceptionSig: FSharp.Compiler.Syntax.SynExceptionSig NewSynExceptionSig(FSharp.Compiler.Syntax.SynExceptionDefnRepr, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberSig], FSharp.Compiler.Text.Range) @@ -7417,8 +7456,6 @@ FSharp.Compiler.Syntax.SynExpr: FSharp.Compiler.Text.Range get_RangeWithoutAnyEx FSharp.Compiler.Syntax.SynExpr: Int32 Tag FSharp.Compiler.Syntax.SynExpr: Int32 get_Tag() FSharp.Compiler.Syntax.SynExpr: System.String ToString() -FSharp.Compiler.Syntax.SynExprAndBang: Boolean IsSynExprAndBang -FSharp.Compiler.Syntax.SynExprAndBang: Boolean get_IsSynExprAndBang() FSharp.Compiler.Syntax.SynExprAndBang: Boolean get_isFromSource() FSharp.Compiler.Syntax.SynExprAndBang: Boolean get_isUse() FSharp.Compiler.Syntax.SynExprAndBang: Boolean isFromSource @@ -7437,8 +7474,7 @@ FSharp.Compiler.Syntax.SynExprAndBang: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynExprAndBang: Int32 Tag FSharp.Compiler.Syntax.SynExprAndBang: Int32 get_Tag() FSharp.Compiler.Syntax.SynExprAndBang: System.String ToString() -FSharp.Compiler.Syntax.SynExprRecordField: Boolean IsSynExprRecordField -FSharp.Compiler.Syntax.SynExprRecordField: Boolean get_IsSynExprRecordField() +FSharp.Compiler.Syntax.SynExprModule: Boolean shouldBeParenthesizedInContext(Microsoft.FSharp.Core.FSharpFunc`2[System.Int32,System.String], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynExpr) FSharp.Compiler.Syntax.SynExprRecordField: FSharp.Compiler.Syntax.SynExprRecordField NewSynExprRecordField(System.Tuple`2[FSharp.Compiler.Syntax.SynLongIdent,System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr], Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`2[FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Position]]]) FSharp.Compiler.Syntax.SynExprRecordField: Int32 Tag FSharp.Compiler.Syntax.SynExprRecordField: Int32 get_Tag() @@ -7451,8 +7487,6 @@ FSharp.Compiler.Syntax.SynExprRecordField: Microsoft.FSharp.Core.FSharpOption`1[ FSharp.Compiler.Syntax.SynExprRecordField: System.String ToString() FSharp.Compiler.Syntax.SynExprRecordField: System.Tuple`2[FSharp.Compiler.Syntax.SynLongIdent,System.Boolean] fieldName FSharp.Compiler.Syntax.SynExprRecordField: System.Tuple`2[FSharp.Compiler.Syntax.SynLongIdent,System.Boolean] get_fieldName() -FSharp.Compiler.Syntax.SynField: Boolean IsSynField -FSharp.Compiler.Syntax.SynField: Boolean get_IsSynField() FSharp.Compiler.Syntax.SynField: Boolean get_isMutable() FSharp.Compiler.Syntax.SynField: Boolean get_isStatic() FSharp.Compiler.Syntax.SynField: Boolean isMutable @@ -7477,8 +7511,6 @@ FSharp.Compiler.Syntax.SynField: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Com FSharp.Compiler.Syntax.SynField: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess] accessibility FSharp.Compiler.Syntax.SynField: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess] get_accessibility() FSharp.Compiler.Syntax.SynField: System.String ToString() -FSharp.Compiler.Syntax.SynIdent: Boolean IsSynIdent -FSharp.Compiler.Syntax.SynIdent: Boolean get_IsSynIdent() FSharp.Compiler.Syntax.SynIdent: FSharp.Compiler.Syntax.Ident get_ident() FSharp.Compiler.Syntax.SynIdent: FSharp.Compiler.Syntax.Ident ident FSharp.Compiler.Syntax.SynIdent: FSharp.Compiler.Syntax.SynIdent NewSynIdent(FSharp.Compiler.Syntax.Ident, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia]) @@ -7487,8 +7519,6 @@ FSharp.Compiler.Syntax.SynIdent: Int32 get_Tag() FSharp.Compiler.Syntax.SynIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia] get_trivia() FSharp.Compiler.Syntax.SynIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia] trivia FSharp.Compiler.Syntax.SynIdent: System.String ToString() -FSharp.Compiler.Syntax.SynInterfaceImpl: Boolean IsSynInterfaceImpl -FSharp.Compiler.Syntax.SynInterfaceImpl: Boolean get_IsSynInterfaceImpl() FSharp.Compiler.Syntax.SynInterfaceImpl: FSharp.Compiler.Syntax.SynInterfaceImpl NewSynInterfaceImpl(FSharp.Compiler.Syntax.SynType, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynBinding], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynInterfaceImpl: FSharp.Compiler.Syntax.SynType get_interfaceTy() FSharp.Compiler.Syntax.SynInterfaceImpl: FSharp.Compiler.Syntax.SynType interfaceTy @@ -7525,9 +7555,7 @@ FSharp.Compiler.Syntax.SynInterpolatedStringPart: FSharp.Compiler.Syntax.SynInte FSharp.Compiler.Syntax.SynInterpolatedStringPart: Int32 Tag FSharp.Compiler.Syntax.SynInterpolatedStringPart: Int32 get_Tag() FSharp.Compiler.Syntax.SynInterpolatedStringPart: System.String ToString() -FSharp.Compiler.Syntax.SynLongIdent: Boolean IsSynLongIdent FSharp.Compiler.Syntax.SynLongIdent: Boolean ThereIsAnExtraDotAtTheEnd -FSharp.Compiler.Syntax.SynLongIdent: Boolean get_IsSynLongIdent() FSharp.Compiler.Syntax.SynLongIdent: Boolean get_ThereIsAnExtraDotAtTheEnd() FSharp.Compiler.Syntax.SynLongIdent: FSharp.Compiler.Syntax.SynLongIdent NewSynLongIdent(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia]]) FSharp.Compiler.Syntax.SynLongIdent: FSharp.Compiler.Text.Range Range @@ -7553,8 +7581,6 @@ FSharp.Compiler.Syntax.SynLongIdent: Microsoft.FSharp.Collections.FSharpList`1[M FSharp.Compiler.Syntax.SynLongIdent: System.String ToString() FSharp.Compiler.Syntax.SynLongIdentHelpers: FSharp.Compiler.Syntax.SynLongIdent LongIdentWithDots(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range]) FSharp.Compiler.Syntax.SynLongIdentHelpers: System.Tuple`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident],Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range]] |LongIdentWithDots|(FSharp.Compiler.Syntax.SynLongIdent) -FSharp.Compiler.Syntax.SynMatchClause: Boolean IsSynMatchClause -FSharp.Compiler.Syntax.SynMatchClause: Boolean get_IsSynMatchClause() FSharp.Compiler.Syntax.SynMatchClause: FSharp.Compiler.Syntax.DebugPointAtTarget debugPoint FSharp.Compiler.Syntax.SynMatchClause: FSharp.Compiler.Syntax.DebugPointAtTarget get_debugPoint() FSharp.Compiler.Syntax.SynMatchClause: FSharp.Compiler.Syntax.SynExpr get_resultExpr() @@ -7708,8 +7734,8 @@ FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: Microsoft.FSharp.Core.FSharpO 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.Syntax.SynPat ctorArgs +FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.Syntax.SynPat get_ctorArgs() FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia get_trivia() FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia trivia FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.Text.Range get_range() @@ -7809,7 +7835,7 @@ 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.SyntaxTrivia.SynMemberDefnAbstractSlotTrivia) 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, FSharp.Compiler.Syntax.SynMemberFlags, FSharp.Compiler.Syntax.SynMemberFlags, FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Syntax.SynExpr, FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynMemberDefnAutoPropertyTrivia) 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.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia) +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.SynPat, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], FSharp.Compiler.Xml.PreXmlDoc, FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia) 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) FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewInterface(FSharp.Compiler.Syntax.SynType, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn]], FSharp.Compiler.Text.Range) @@ -8052,8 +8078,6 @@ FSharp.Compiler.Syntax.SynModuleDecl: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynModuleDecl: Int32 Tag FSharp.Compiler.Syntax.SynModuleDecl: Int32 get_Tag() FSharp.Compiler.Syntax.SynModuleDecl: System.String ToString() -FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean IsSynModuleOrNamespace -FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean get_IsSynModuleOrNamespace() FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean get_isRecursive() FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean isRecursive FSharp.Compiler.Syntax.SynModuleOrNamespace: FSharp.Compiler.Syntax.SynModuleOrNamespace NewSynModuleOrNamespace(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], Boolean, FSharp.Compiler.Syntax.SynModuleOrNamespaceKind, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl], FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynModuleOrNamespaceTrivia) @@ -8112,8 +8136,6 @@ FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: Int32 GetHashCode(System.Collec FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: Int32 Tag FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: System.String ToString() -FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean IsSynModuleOrNamespaceSig -FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean get_IsSynModuleOrNamespaceSig() FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean get_isRecursive() FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean isRecursive FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: FSharp.Compiler.Syntax.SynModuleOrNamespaceKind get_kind() @@ -8466,6 +8488,7 @@ FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynPat: Int32 Tag FSharp.Compiler.Syntax.SynPat: Int32 get_Tag() FSharp.Compiler.Syntax.SynPat: System.String ToString() +FSharp.Compiler.Syntax.SynPatModule: Boolean shouldBeParenthesizedInContext(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynPat) FSharp.Compiler.Syntax.SynRationalConst+Integer: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.SynRationalConst+Integer: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynRationalConst+Integer: Int32 get_value() @@ -8514,8 +8537,6 @@ FSharp.Compiler.Syntax.SynRationalConst: FSharp.Compiler.Syntax.SynRationalConst FSharp.Compiler.Syntax.SynRationalConst: Int32 Tag FSharp.Compiler.Syntax.SynRationalConst: Int32 get_Tag() FSharp.Compiler.Syntax.SynRationalConst: System.String ToString() -FSharp.Compiler.Syntax.SynReturnInfo: Boolean IsSynReturnInfo -FSharp.Compiler.Syntax.SynReturnInfo: Boolean get_IsSynReturnInfo() FSharp.Compiler.Syntax.SynReturnInfo: FSharp.Compiler.Syntax.SynReturnInfo NewSynReturnInfo(System.Tuple`2[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Syntax.SynArgInfo], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynReturnInfo: FSharp.Compiler.Text.Range Range FSharp.Compiler.Syntax.SynReturnInfo: FSharp.Compiler.Text.Range get_Range() @@ -8589,8 +8610,6 @@ FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: FSharp.Compiler.Syntax.Syn FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: Int32 Tag FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: Int32 get_Tag() FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: System.String ToString() -FSharp.Compiler.Syntax.SynSimplePats: Boolean IsSimplePats -FSharp.Compiler.Syntax.SynSimplePats: Boolean get_IsSimplePats() FSharp.Compiler.Syntax.SynSimplePats: FSharp.Compiler.Syntax.SynSimplePats NewSimplePats(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynSimplePat], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynSimplePats: FSharp.Compiler.Text.Range Range FSharp.Compiler.Syntax.SynSimplePats: FSharp.Compiler.Text.Range get_Range() @@ -8681,8 +8700,6 @@ FSharp.Compiler.Syntax.SynTupleTypeSegment: FSharp.Compiler.Text.Range get_Range FSharp.Compiler.Syntax.SynTupleTypeSegment: Int32 Tag FSharp.Compiler.Syntax.SynTupleTypeSegment: Int32 get_Tag() FSharp.Compiler.Syntax.SynTupleTypeSegment: System.String ToString() -FSharp.Compiler.Syntax.SynTypar: Boolean IsSynTypar -FSharp.Compiler.Syntax.SynTypar: Boolean get_IsSynTypar() FSharp.Compiler.Syntax.SynTypar: Boolean get_isCompGen() FSharp.Compiler.Syntax.SynTypar: Boolean isCompGen FSharp.Compiler.Syntax.SynTypar: FSharp.Compiler.Syntax.Ident get_ident() @@ -8695,8 +8712,6 @@ FSharp.Compiler.Syntax.SynTypar: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynTypar: Int32 Tag FSharp.Compiler.Syntax.SynTypar: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypar: System.String ToString() -FSharp.Compiler.Syntax.SynTyparDecl: Boolean IsSynTyparDecl -FSharp.Compiler.Syntax.SynTyparDecl: Boolean get_IsSynTyparDecl() FSharp.Compiler.Syntax.SynTyparDecl: FSharp.Compiler.Syntax.SynTypar get_typar() FSharp.Compiler.Syntax.SynTyparDecl: FSharp.Compiler.Syntax.SynTypar typar FSharp.Compiler.Syntax.SynTyparDecl: FSharp.Compiler.Syntax.SynTyparDecl NewSynTyparDecl(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynTypar, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynType], FSharp.Compiler.SyntaxTrivia.SynTyparDeclTrivia) @@ -9129,8 +9144,6 @@ FSharp.Compiler.Syntax.SynTypeConstraint: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynTypeConstraint: Int32 Tag FSharp.Compiler.Syntax.SynTypeConstraint: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypeConstraint: System.String ToString() -FSharp.Compiler.Syntax.SynTypeDefn: Boolean IsSynTypeDefn -FSharp.Compiler.Syntax.SynTypeDefn: Boolean get_IsSynTypeDefn() FSharp.Compiler.Syntax.SynTypeDefn: FSharp.Compiler.Syntax.SynComponentInfo get_typeInfo() FSharp.Compiler.Syntax.SynTypeDefn: FSharp.Compiler.Syntax.SynComponentInfo typeInfo FSharp.Compiler.Syntax.SynTypeDefn: FSharp.Compiler.Syntax.SynTypeDefn NewSynTypeDefn(FSharp.Compiler.Syntax.SynComponentInfo, FSharp.Compiler.Syntax.SynTypeDefnRepr, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberDefn], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynTypeDefnTrivia) @@ -9247,8 +9260,6 @@ FSharp.Compiler.Syntax.SynTypeDefnRepr: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynTypeDefnRepr: Int32 Tag FSharp.Compiler.Syntax.SynTypeDefnRepr: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypeDefnRepr: System.String ToString() -FSharp.Compiler.Syntax.SynTypeDefnSig: Boolean IsSynTypeDefnSig -FSharp.Compiler.Syntax.SynTypeDefnSig: Boolean get_IsSynTypeDefnSig() FSharp.Compiler.Syntax.SynTypeDefnSig: FSharp.Compiler.Syntax.SynComponentInfo get_typeInfo() FSharp.Compiler.Syntax.SynTypeDefnSig: FSharp.Compiler.Syntax.SynComponentInfo typeInfo FSharp.Compiler.Syntax.SynTypeDefnSig: FSharp.Compiler.Syntax.SynTypeDefnSig NewSynTypeDefnSig(FSharp.Compiler.Syntax.SynComponentInfo, FSharp.Compiler.Syntax.SynTypeDefnSigRepr, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberSig], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynTypeDefnSigTrivia) @@ -9318,8 +9329,8 @@ FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collectio FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`2[FSharp.Compiler.Syntax.SynValSig,FSharp.Compiler.Syntax.SynMemberFlags]] slotsigs FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]] get_inherits() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]] inherits -FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynSimplePats] get_implicitCtorSynPats() -FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynSimplePats] implicitCtorSynPats +FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynPat] get_implicitCtorSynPats() +FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynPat] implicitCtorSynPats FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+LibraryOnlyILAssembly: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+LibraryOnlyILAssembly: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+LibraryOnlyILAssembly: System.Object get_ilType() @@ -9370,7 +9381,7 @@ FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Boolean get_IsTypeAbbrev() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Boolean get_IsUnion() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewEnum(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynEnumCase], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewException(FSharp.Compiler.Syntax.SynExceptionDefnRepr) -FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewGeneral(FSharp.Compiler.Syntax.SynTypeDefnKind, Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]], Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`2[FSharp.Compiler.Syntax.SynValSig,FSharp.Compiler.Syntax.SynMemberFlags]], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], Boolean, Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynSimplePats], FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewGeneral(FSharp.Compiler.Syntax.SynTypeDefnKind, Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]], Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`2[FSharp.Compiler.Syntax.SynValSig,FSharp.Compiler.Syntax.SynMemberFlags]], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], Boolean, Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynPat], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewLibraryOnlyILAssembly(System.Object, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewNone(FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewRecord(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], FSharp.Compiler.Text.Range) @@ -9390,8 +9401,6 @@ FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Text.Range get_Ran FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Int32 Tag FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: System.String ToString() -FSharp.Compiler.Syntax.SynUnionCase: Boolean IsSynUnionCase -FSharp.Compiler.Syntax.SynUnionCase: Boolean get_IsSynUnionCase() FSharp.Compiler.Syntax.SynUnionCase: FSharp.Compiler.Syntax.SynIdent get_ident() FSharp.Compiler.Syntax.SynUnionCase: FSharp.Compiler.Syntax.SynIdent ident FSharp.Compiler.Syntax.SynUnionCase: FSharp.Compiler.Syntax.SynUnionCase NewSynUnionCase(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynIdent, FSharp.Compiler.Syntax.SynUnionCaseKind, FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynUnionCaseTrivia) @@ -9432,8 +9441,6 @@ FSharp.Compiler.Syntax.SynUnionCaseKind: FSharp.Compiler.Syntax.SynUnionCaseKind FSharp.Compiler.Syntax.SynUnionCaseKind: Int32 Tag FSharp.Compiler.Syntax.SynUnionCaseKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynUnionCaseKind: System.String ToString() -FSharp.Compiler.Syntax.SynValData: Boolean IsSynValData -FSharp.Compiler.Syntax.SynValData: Boolean get_IsSynValData() FSharp.Compiler.Syntax.SynValData: FSharp.Compiler.Syntax.SynValData NewSynValData(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberFlags], FSharp.Compiler.Syntax.SynValInfo, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]) FSharp.Compiler.Syntax.SynValData: FSharp.Compiler.Syntax.SynValInfo SynValInfo FSharp.Compiler.Syntax.SynValData: FSharp.Compiler.Syntax.SynValInfo get_SynValInfo() @@ -9446,8 +9453,6 @@ FSharp.Compiler.Syntax.SynValData: Microsoft.FSharp.Core.FSharpOption`1[FSharp.C FSharp.Compiler.Syntax.SynValData: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberFlags] get_memberFlags() FSharp.Compiler.Syntax.SynValData: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberFlags] memberFlags FSharp.Compiler.Syntax.SynValData: System.String ToString() -FSharp.Compiler.Syntax.SynValInfo: Boolean IsSynValInfo -FSharp.Compiler.Syntax.SynValInfo: Boolean get_IsSynValInfo() FSharp.Compiler.Syntax.SynValInfo: FSharp.Compiler.Syntax.SynArgInfo get_returnInfo() FSharp.Compiler.Syntax.SynValInfo: FSharp.Compiler.Syntax.SynArgInfo returnInfo FSharp.Compiler.Syntax.SynValInfo: FSharp.Compiler.Syntax.SynValInfo NewSynValInfo(Microsoft.FSharp.Collections.FSharpList`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynArgInfo]], FSharp.Compiler.Syntax.SynArgInfo) @@ -9460,8 +9465,6 @@ FSharp.Compiler.Syntax.SynValInfo: Microsoft.FSharp.Collections.FSharpList`1[Mic FSharp.Compiler.Syntax.SynValInfo: Microsoft.FSharp.Collections.FSharpList`1[System.String] ArgNames FSharp.Compiler.Syntax.SynValInfo: Microsoft.FSharp.Collections.FSharpList`1[System.String] get_ArgNames() FSharp.Compiler.Syntax.SynValInfo: System.String ToString() -FSharp.Compiler.Syntax.SynValSig: Boolean IsSynValSig -FSharp.Compiler.Syntax.SynValSig: Boolean get_IsSynValSig() FSharp.Compiler.Syntax.SynValSig: Boolean get_isInline() FSharp.Compiler.Syntax.SynValSig: Boolean get_isMutable() FSharp.Compiler.Syntax.SynValSig: Boolean isInline @@ -9496,9 +9499,7 @@ FSharp.Compiler.Syntax.SynValSig: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Co FSharp.Compiler.Syntax.SynValSig: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr] get_synExpr() FSharp.Compiler.Syntax.SynValSig: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr] synExpr FSharp.Compiler.Syntax.SynValSig: System.String ToString() -FSharp.Compiler.Syntax.SynValTyparDecls: Boolean IsSynValTyparDecls FSharp.Compiler.Syntax.SynValTyparDecls: Boolean canInfer -FSharp.Compiler.Syntax.SynValTyparDecls: Boolean get_IsSynValTyparDecls() FSharp.Compiler.Syntax.SynValTyparDecls: Boolean get_canInfer() FSharp.Compiler.Syntax.SynValTyparDecls: FSharp.Compiler.Syntax.SynValTyparDecls NewSynValTyparDecls(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynTyparDecls], Boolean) FSharp.Compiler.Syntax.SynValTyparDecls: Int32 Tag @@ -9605,9 +9606,12 @@ FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+SynTypeDefn FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+SynTypeDefnSig FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+SynValSig FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+Tags +FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Text.Range Range +FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SyntaxNode: Int32 Tag FSharp.Compiler.Syntax.SyntaxNode: Int32 get_Tag() FSharp.Compiler.Syntax.SyntaxNode: System.String ToString() +FSharp.Compiler.Syntax.SyntaxNodeModule: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList] |Attributes|(FSharp.Compiler.Syntax.SyntaxNode) FSharp.Compiler.Syntax.SyntaxTraversal: Microsoft.FSharp.Core.FSharpOption`1[T] Traverse[T](FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput, FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitAttributeApplication(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynAttributeList) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitBinding(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SynBinding,Microsoft.FSharp.Core.FSharpOption`1[T]], FSharp.Compiler.Syntax.SynBinding) @@ -9627,7 +9631,7 @@ FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOptio FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitPat(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SynPat,Microsoft.FSharp.Core.FSharpOption`1[T]], FSharp.Compiler.Syntax.SynPat) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitRecordDefn(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitRecordField(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynLongIdent]) -FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitSimplePats(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynSimplePat]) +FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitSimplePats(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynPat) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitType(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SynType,Microsoft.FSharp.Core.FSharpOption`1[T]], FSharp.Compiler.Syntax.SynType) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitTypeAbbrev(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitUnionDefn(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynUnionCase], FSharp.Compiler.Text.Range) @@ -10344,6 +10348,7 @@ FSharp.Compiler.Text.ISourceText: System.String GetSubTextFromRange(FSharp.Compi FSharp.Compiler.Text.ISourceText: System.String GetSubTextString(Int32, Int32) FSharp.Compiler.Text.ISourceText: System.Tuple`2[System.Int32,System.Int32] GetLastCharacterPosition() FSharp.Compiler.Text.ISourceText: Void CopyTo(Int32, Char[], Int32, Int32) +FSharp.Compiler.Text.ISourceTextNew: System.Collections.Immutable.ImmutableArray`1[System.Byte] GetChecksum() FSharp.Compiler.Text.Line: Int32 fromZ(Int32) FSharp.Compiler.Text.Line: Int32 toZ(Int32) FSharp.Compiler.Text.NavigableTaggedText: FSharp.Compiler.Text.Range Range @@ -10423,6 +10428,8 @@ FSharp.Compiler.Text.RangeModule: System.Tuple`2[System.String,System.Tuple`2[Sy FSharp.Compiler.Text.RangeModule: System.Tuple`2[System.Tuple`2[System.Int32,System.Int32],System.Tuple`2[System.Int32,System.Int32]] toZ(FSharp.Compiler.Text.Range) FSharp.Compiler.Text.RangeModule: Void outputRange(System.IO.TextWriter, FSharp.Compiler.Text.Range) FSharp.Compiler.Text.SourceText: FSharp.Compiler.Text.ISourceText ofString(System.String) +FSharp.Compiler.Text.SourceTextNew: FSharp.Compiler.Text.ISourceTextNew ofISourceText(FSharp.Compiler.Text.ISourceText) +FSharp.Compiler.Text.SourceTextNew: FSharp.Compiler.Text.ISourceTextNew ofString(System.String) FSharp.Compiler.Text.TaggedText: FSharp.Compiler.Text.TextTag Tag FSharp.Compiler.Text.TaggedText: FSharp.Compiler.Text.TextTag get_Tag() FSharp.Compiler.Text.TaggedText: System.String Text diff --git a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl index 15b58c9aea1..954fca3437d 100644 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.SurfaceArea.netstandard20.release.bsl @@ -318,8 +318,6 @@ FSharp.Compiler.AbstractIL.IL+ILAttributesStored: System.String ToString() FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean Equals(ILCallingConv) FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean Equals(System.Object) FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean IsCallconv -FSharp.Compiler.AbstractIL.IL+ILCallingConv: Boolean get_IsCallconv() FSharp.Compiler.AbstractIL.IL+ILCallingConv: ILArgConvention Item2 FSharp.Compiler.AbstractIL.IL+ILCallingConv: ILArgConvention get_Item2() FSharp.Compiler.AbstractIL.IL+ILCallingConv: ILCallingConv Instance @@ -2078,7 +2076,7 @@ FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: FSharp.Compiler.Symbols. FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: System.String ToString() FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: System.String[] DependencyFiles FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults: System.String[] get_DependencyFiles() -FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker Create(Microsoft.FSharp.Core.FSharpOption`1[System.Int32], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.LegacyReferenceResolver], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`2[System.String,System.DateTime],Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`3[System.Object,System.IntPtr,System.Int32]]]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker Create(Microsoft.FSharp.Core.FSharpOption`1[System.Int32], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.LegacyReferenceResolver], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`2[System.String,System.DateTime],Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`3[System.Object,System.IntPtr,System.Int32]]]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.DocumentSource], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker Instance FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpChecker get_Instance() FSharp.Compiler.CodeAnalysis.FSharpChecker: FSharp.Compiler.CodeAnalysis.FSharpProjectOptions GetProjectOptionsFromCommandLineArgs(System.String, System.String[], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean]) @@ -2089,14 +2087,19 @@ FSharp.Compiler.CodeAnalysis.FSharpChecker: Int32 get_ActualCheckFileCount() FSharp.Compiler.CodeAnalysis.FSharpChecker: Int32 get_ActualParseFileCount() FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer] CheckFileInProject(FSharp.Compiler.CodeAnalysis.FSharpParseFileResults, System.String, Int32, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults] ParseAndCheckProject(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults] ParseAndCheckProject(FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] GetBackgroundParseResultsForFileInProject(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] ParseFile(System.String, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpParsingOptions, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] ParseFile(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults] ParseFileInProject(System.String, System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] CheckFileInProjectAllowingStaleCachedResults(FSharp.Compiler.CodeAnalysis.FSharpParseFileResults, System.String, Int32, System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.EditorServices.SemanticClassificationView]] GetBackgroundSemanticClassificationForFile(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.EditorServices.SemanticClassificationView]] GetBackgroundSemanticClassificationForFile(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit] NotifyFileChanged(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit] NotifyProjectCleaned(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Collections.Generic.IEnumerable`1[FSharp.Compiler.Text.Range]] FindBackgroundReferencesInFile(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, FSharp.Compiler.Symbols.FSharpSymbol, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Collections.Generic.IEnumerable`1[FSharp.Compiler.Text.Range]] FindBackgroundReferencesInFile(System.String, FSharpProjectSnapshot, FSharp.Compiler.Symbols.FSharpSymbol, Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, FSharpProjectSnapshot, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileAnswer]] ParseAndCheckFileInProject(System.String, Int32, FSharp.Compiler.Text.ISourceText, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParseFileResults,FSharp.Compiler.CodeAnalysis.FSharpCheckFileResults]] GetBackgroundCheckResultsForFileInProject(System.String, FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Microsoft.FSharp.Control.FSharpAsync`1[System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]]] GetProjectOptionsFromScript(System.String, FSharp.Compiler.Text.ISourceText, Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.DateTime], Microsoft.FSharp.Core.FSharpOption`1[System.String[]], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Core.FSharpOption`1[System.Int64], Microsoft.FSharp.Core.FSharpOption`1[System.String]) @@ -2117,6 +2120,7 @@ FSharp.Compiler.CodeAnalysis.FSharpChecker: System.Tuple`2[FSharp.Compiler.CodeA FSharp.Compiler.CodeAnalysis.FSharpChecker: System.Tuple`2[FSharp.Compiler.CodeAnalysis.FSharpParsingOptions,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Diagnostics.FSharpDiagnostic]] GetParsingOptionsFromProjectOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions) FSharp.Compiler.CodeAnalysis.FSharpChecker: System.Tuple`2[FSharp.Compiler.Tokenization.FSharpTokenInfo[],FSharp.Compiler.Tokenization.FSharpTokenizerLexState] TokenizeLine(System.String, FSharp.Compiler.Tokenization.FSharpTokenizerLexState) FSharp.Compiler.CodeAnalysis.FSharpChecker: Void ClearCache(System.Collections.Generic.IEnumerable`1[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions], Microsoft.FSharp.Core.FSharpOption`1[System.String]) +FSharp.Compiler.CodeAnalysis.FSharpChecker: Void ClearCache(System.Collections.Generic.IEnumerable`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier], Microsoft.FSharp.Core.FSharpOption`1[System.String]) FSharp.Compiler.CodeAnalysis.FSharpChecker: Void ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() FSharp.Compiler.CodeAnalysis.FSharpChecker: Void InvalidateAll() FSharp.Compiler.CodeAnalysis.FSharpChecker: Void InvalidateConfiguration(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpOption`1[System.String]) @@ -2334,6 +2338,76 @@ FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: System.String get_baggage() FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: System.String get_itemSpec() FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: System.String itemSpec FSharp.Compiler.CodeAnalysis.LegacyResolvedFile: Void .ctor(System.String, Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`2[System.String,System.String],System.String], System.String) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Boolean IsSignatureFile +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Boolean get_IsSignatureFile() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: FSharpFileSnapshot Create(System.String, System.String, Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,System.Threading.Tasks.Task`1[FSharp.Compiler.Text.ISourceTextNew]]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: FSharpFileSnapshot CreateFromFileSystem(System.String) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String FileName +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String GetFileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String Version +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String get_FileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.String get_Version() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: System.Threading.Tasks.Task`1[FSharp.Compiler.Text.ISourceTextNew] GetSource() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot: Void .ctor(System.String, System.String, Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,System.Threading.Tasks.Task`1[FSharp.Compiler.Text.ISourceTextNew]]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Boolean Equals(FSharpProjectIdentifier) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Boolean Equals(System.Object, System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: FSharpProjectIdentifier NewFSharpProjectIdentifier(System.String, System.String) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 CompareTo(FSharpProjectIdentifier) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 CompareTo(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 CompareTo(System.Object, System.Collections.IComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 GetHashCode(System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 Tag +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: Int32 get_Tag() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String ToString() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String get_outputFileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String get_projectFileName() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String outputFileName +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier: System.String projectFileName +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectIdentifier Identifier +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectIdentifier get_Identifier() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectSnapshot Create(System.String, Microsoft.FSharp.Core.FSharpOption`1[System.String], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk], Microsoft.FSharp.Collections.FSharpList`1[System.String], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot], Boolean, Boolean, System.DateTime, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.CodeAnalysis.FSharpUnresolvedReferencesSet], Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Text.Range,System.String,System.String]], Microsoft.FSharp.Core.FSharpOption`1[System.Int64]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: FSharpProjectSnapshot Replace(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot] FromOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot] FromOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,Microsoft.FSharp.Core.FSharpFunc`2[System.String,Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot]]], Microsoft.FSharp.Core.FSharpOption`1[System.Collections.Generic.Dictionary`2[FSharp.Compiler.CodeAnalysis.FSharpProjectOptions,FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot]]) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: Microsoft.FSharp.Control.FSharpAsync`1[FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot] FromOptions(FSharp.Compiler.CodeAnalysis.FSharpProjectOptions, System.String, Int32, FSharp.Compiler.Text.ISourceText) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: System.String Label +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot: System.String get_Label() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpProjectSnapshot get_options() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpProjectSnapshot options +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpReferencedProjectSnapshot CreateFSharp(System.String, FSharpProjectSnapshot) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: FSharpReferencedProjectSnapshot NewFSharpReference(System.String, FSharpProjectSnapshot) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Int32 Tag +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: Int32 get_Tag() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String OutputFile +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String ToString() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String get_OutputFile() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String get_projectOutputFile() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot: System.String projectOutputFile +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Boolean Equals(ReferenceOnDisk) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Boolean Equals(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Boolean Equals(System.Object, System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 CompareTo(ReferenceOnDisk) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 CompareTo(System.Object) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 CompareTo(System.Object, System.Collections.IComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 GetHashCode() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Int32 GetHashCode(System.Collections.IEqualityComparer) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.DateTime LastModified +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.DateTime get_LastModified() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.String Path +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.String ToString() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: System.String get_Path() +FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk: Void .ctor(System.String, System.DateTime) +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpFileSnapshot +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectIdentifier +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpProjectSnapshot +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+FSharpReferencedProjectSnapshot +FSharp.Compiler.CodeAnalysis.ProjectSnapshot: FSharp.Compiler.CodeAnalysis.ProjectSnapshot+ReferenceOnDisk FSharp.Compiler.CompilerEnvironment: Boolean IsCheckerSupportedSubcategory(System.String) FSharp.Compiler.CompilerEnvironment: Boolean IsCompilable(System.String) FSharp.Compiler.CompilerEnvironment: Boolean IsScriptFile(System.String) @@ -4271,8 +4345,6 @@ FSharp.Compiler.EditorServices.ToolTipElementData: Void .ctor(Microsoft.FSharp.C FSharp.Compiler.EditorServices.ToolTipText: Boolean Equals(FSharp.Compiler.EditorServices.ToolTipText) FSharp.Compiler.EditorServices.ToolTipText: Boolean Equals(System.Object) FSharp.Compiler.EditorServices.ToolTipText: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.EditorServices.ToolTipText: Boolean IsToolTipText -FSharp.Compiler.EditorServices.ToolTipText: Boolean get_IsToolTipText() FSharp.Compiler.EditorServices.ToolTipText: FSharp.Compiler.EditorServices.ToolTipText NewToolTipText(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.EditorServices.ToolTipElement]) FSharp.Compiler.EditorServices.ToolTipText: Int32 GetHashCode() FSharp.Compiler.EditorServices.ToolTipText: Int32 GetHashCode(System.Collections.IEqualityComparer) @@ -4292,7 +4364,6 @@ FSharp.Compiler.EditorServices.TupledArgumentLocation: Int32 GetHashCode() FSharp.Compiler.EditorServices.TupledArgumentLocation: Int32 GetHashCode(System.Collections.IEqualityComparer) FSharp.Compiler.EditorServices.TupledArgumentLocation: System.String ToString() FSharp.Compiler.EditorServices.TupledArgumentLocation: Void .ctor(Boolean, FSharp.Compiler.Text.Range) -FSharp.Compiler.EditorServices.UnnecessaryParentheses: Microsoft.FSharp.Control.FSharpAsync`1[System.Collections.Generic.IEnumerable`1[FSharp.Compiler.Text.Range]] getUnnecessaryParentheses(Microsoft.FSharp.Core.FSharpFunc`2[System.Int32,System.String], FSharp.Compiler.Syntax.ParsedInput) FSharp.Compiler.EditorServices.UnresolvedSymbol: Boolean Equals(FSharp.Compiler.EditorServices.UnresolvedSymbol) FSharp.Compiler.EditorServices.UnresolvedSymbol: Boolean Equals(System.Object) FSharp.Compiler.EditorServices.UnresolvedSymbol: Boolean Equals(System.Object, System.Collections.IEqualityComparer) @@ -4316,8 +4387,6 @@ FSharp.Compiler.EditorServices.XmlDocParser: Microsoft.FSharp.Collections.FSharp FSharp.Compiler.EditorServices.XmlDocable: Boolean Equals(FSharp.Compiler.EditorServices.XmlDocable) FSharp.Compiler.EditorServices.XmlDocable: Boolean Equals(System.Object) FSharp.Compiler.EditorServices.XmlDocable: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.EditorServices.XmlDocable: Boolean IsXmlDocable -FSharp.Compiler.EditorServices.XmlDocable: Boolean get_IsXmlDocable() FSharp.Compiler.EditorServices.XmlDocable: FSharp.Compiler.EditorServices.XmlDocable NewXmlDocable(Int32, Int32, Microsoft.FSharp.Collections.FSharpList`1[System.String]) FSharp.Compiler.EditorServices.XmlDocable: Int32 CompareTo(FSharp.Compiler.EditorServices.XmlDocable) FSharp.Compiler.EditorServices.XmlDocable: Int32 CompareTo(System.Object) @@ -5556,8 +5625,6 @@ FSharp.Compiler.Syntax.DebugPointAtInOrTo: System.String ToString() FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean Equals(FSharp.Compiler.Syntax.DebugPointAtLeafExpr) FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean Equals(System.Object) FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean IsYes -FSharp.Compiler.Syntax.DebugPointAtLeafExpr: Boolean get_IsYes() FSharp.Compiler.Syntax.DebugPointAtLeafExpr: FSharp.Compiler.Syntax.DebugPointAtLeafExpr NewYes(FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.DebugPointAtLeafExpr: FSharp.Compiler.Text.Range Item FSharp.Compiler.Syntax.DebugPointAtLeafExpr: FSharp.Compiler.Text.Range get_Item() @@ -5692,8 +5759,6 @@ FSharp.Compiler.Syntax.Ident: System.String ToString() FSharp.Compiler.Syntax.Ident: System.String get_idText() FSharp.Compiler.Syntax.Ident: System.String idText FSharp.Compiler.Syntax.Ident: Void .ctor(System.String, FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.ParsedHashDirective: Boolean IsParsedHashDirective -FSharp.Compiler.Syntax.ParsedHashDirective: Boolean get_IsParsedHashDirective() FSharp.Compiler.Syntax.ParsedHashDirective: FSharp.Compiler.Syntax.ParsedHashDirective NewParsedHashDirective(System.String, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirectiveArgument], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.ParsedHashDirective: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.ParsedHashDirective: FSharp.Compiler.Text.Range range @@ -5732,8 +5797,6 @@ FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: FSharp.Compiler.Text.Range g FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: Int32 Tag FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedHashDirectiveArgument: System.String ToString() -FSharp.Compiler.Syntax.ParsedImplFile: Boolean IsParsedImplFile -FSharp.Compiler.Syntax.ParsedImplFile: Boolean get_IsParsedImplFile() FSharp.Compiler.Syntax.ParsedImplFile: FSharp.Compiler.Syntax.ParsedImplFile NewParsedImplFile(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirective], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedImplFileFragment]) FSharp.Compiler.Syntax.ParsedImplFile: Int32 Tag FSharp.Compiler.Syntax.ParsedImplFile: Int32 get_Tag() @@ -5785,11 +5848,9 @@ FSharp.Compiler.Syntax.ParsedImplFileFragment: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedImplFileFragment: System.String ToString() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsExe FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsLastCompiland -FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsParsedImplFileInput FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean IsScript FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsExe() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsLastCompiland() -FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsParsedImplFileInput() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_IsScript() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean get_isScript() FSharp.Compiler.Syntax.ParsedImplFileInput: Boolean isScript @@ -5853,8 +5914,12 @@ FSharp.Compiler.Syntax.ParsedInput: Microsoft.FSharp.Collections.FSharpSet`1[Sys FSharp.Compiler.Syntax.ParsedInput: System.String FileName FSharp.Compiler.Syntax.ParsedInput: System.String ToString() FSharp.Compiler.Syntax.ParsedInput: System.String get_FileName() -FSharp.Compiler.Syntax.ParsedScriptInteraction: Boolean IsDefinitions -FSharp.Compiler.Syntax.ParsedScriptInteraction: Boolean get_IsDefinitions() +FSharp.Compiler.Syntax.ParsedInputModule: Boolean exists(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,System.Boolean]], FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode]]] tryNode(FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: Microsoft.FSharp.Core.FSharpOption`1[T] tryPickLast[T](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Core.FSharpOption`1[T]]], FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: Microsoft.FSharp.Core.FSharpOption`1[T] tryPick[T](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Core.FSharpOption`1[T]]], FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: State foldWhile[State](Microsoft.FSharp.Core.FSharpFunc`2[State,Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,Microsoft.FSharp.Core.FSharpOption`1[State]]]], State, FSharp.Compiler.Syntax.ParsedInput) +FSharp.Compiler.Syntax.ParsedInputModule: State fold[State](Microsoft.FSharp.Core.FSharpFunc`2[State,Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode],Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SyntaxNode,State]]], State, FSharp.Compiler.Syntax.ParsedInput) FSharp.Compiler.Syntax.ParsedScriptInteraction: FSharp.Compiler.Syntax.ParsedScriptInteraction NewDefinitions(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.ParsedScriptInteraction: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.ParsedScriptInteraction: FSharp.Compiler.Text.Range range @@ -5863,8 +5928,6 @@ FSharp.Compiler.Syntax.ParsedScriptInteraction: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedScriptInteraction: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl] defns FSharp.Compiler.Syntax.ParsedScriptInteraction: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl] get_defns() FSharp.Compiler.Syntax.ParsedScriptInteraction: System.String ToString() -FSharp.Compiler.Syntax.ParsedSigFile: Boolean IsParsedSigFile -FSharp.Compiler.Syntax.ParsedSigFile: Boolean get_IsParsedSigFile() FSharp.Compiler.Syntax.ParsedSigFile: FSharp.Compiler.Syntax.ParsedSigFile NewParsedSigFile(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirective], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedSigFileFragment]) FSharp.Compiler.Syntax.ParsedSigFile: Int32 Tag FSharp.Compiler.Syntax.ParsedSigFile: Int32 get_Tag() @@ -5914,8 +5977,6 @@ FSharp.Compiler.Syntax.ParsedSigFileFragment: FSharp.Compiler.Syntax.ParsedSigFi FSharp.Compiler.Syntax.ParsedSigFileFragment: Int32 Tag FSharp.Compiler.Syntax.ParsedSigFileFragment: Int32 get_Tag() FSharp.Compiler.Syntax.ParsedSigFileFragment: System.String ToString() -FSharp.Compiler.Syntax.ParsedSigFileInput: Boolean IsParsedSigFileInput -FSharp.Compiler.Syntax.ParsedSigFileInput: Boolean get_IsParsedSigFileInput() FSharp.Compiler.Syntax.ParsedSigFileInput: FSharp.Compiler.Syntax.ParsedSigFileInput NewParsedSigFileInput(System.String, FSharp.Compiler.Syntax.QualifiedNameOfFile, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ScopedPragma], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.ParsedHashDirective], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleOrNamespaceSig], FSharp.Compiler.SyntaxTrivia.ParsedSigFileInputTrivia, Microsoft.FSharp.Collections.FSharpSet`1[System.String]) FSharp.Compiler.Syntax.ParsedSigFileInput: FSharp.Compiler.Syntax.QualifiedNameOfFile QualifiedName FSharp.Compiler.Syntax.ParsedSigFileInput: FSharp.Compiler.Syntax.QualifiedNameOfFile get_QualifiedName() @@ -5988,8 +6049,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.QualifiedNameOfFile: Boolean IsQualifiedNameOfFile -FSharp.Compiler.Syntax.QualifiedNameOfFile: Boolean get_IsQualifiedNameOfFile() FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident Id FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident Item FSharp.Compiler.Syntax.QualifiedNameOfFile: FSharp.Compiler.Syntax.Ident get_Id() @@ -6005,8 +6064,6 @@ FSharp.Compiler.Syntax.QualifiedNameOfFile: System.String get_Text() FSharp.Compiler.Syntax.ScopedPragma: Boolean Equals(FSharp.Compiler.Syntax.ScopedPragma) FSharp.Compiler.Syntax.ScopedPragma: Boolean Equals(System.Object) FSharp.Compiler.Syntax.ScopedPragma: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.Syntax.ScopedPragma: Boolean IsWarningOff -FSharp.Compiler.Syntax.ScopedPragma: Boolean get_IsWarningOff() FSharp.Compiler.Syntax.ScopedPragma: FSharp.Compiler.Syntax.ScopedPragma NewWarningOff(FSharp.Compiler.Text.Range, Int32) FSharp.Compiler.Syntax.ScopedPragma: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.ScopedPragma: FSharp.Compiler.Text.Range range @@ -6020,9 +6077,7 @@ FSharp.Compiler.Syntax.ScopedPragma: System.String ToString() FSharp.Compiler.Syntax.SeqExprOnly: Boolean Equals(FSharp.Compiler.Syntax.SeqExprOnly) FSharp.Compiler.Syntax.SeqExprOnly: Boolean Equals(System.Object) FSharp.Compiler.Syntax.SeqExprOnly: Boolean Equals(System.Object, System.Collections.IEqualityComparer) -FSharp.Compiler.Syntax.SeqExprOnly: Boolean IsSeqExprOnly FSharp.Compiler.Syntax.SeqExprOnly: Boolean Item -FSharp.Compiler.Syntax.SeqExprOnly: Boolean get_IsSeqExprOnly() FSharp.Compiler.Syntax.SeqExprOnly: Boolean get_Item() FSharp.Compiler.Syntax.SeqExprOnly: FSharp.Compiler.Syntax.SeqExprOnly NewSeqExprOnly(Boolean) FSharp.Compiler.Syntax.SeqExprOnly: Int32 CompareTo(FSharp.Compiler.Syntax.SeqExprOnly) @@ -6065,8 +6120,6 @@ FSharp.Compiler.Syntax.SynAccess: Int32 GetHashCode(System.Collections.IEquality FSharp.Compiler.Syntax.SynAccess: Int32 Tag FSharp.Compiler.Syntax.SynAccess: Int32 get_Tag() FSharp.Compiler.Syntax.SynAccess: System.String ToString() -FSharp.Compiler.Syntax.SynArgInfo: Boolean IsSynArgInfo -FSharp.Compiler.Syntax.SynArgInfo: Boolean get_IsSynArgInfo() FSharp.Compiler.Syntax.SynArgInfo: Boolean get_optional() FSharp.Compiler.Syntax.SynArgInfo: Boolean optional FSharp.Compiler.Syntax.SynArgInfo: FSharp.Compiler.Syntax.SynArgInfo NewSynArgInfo(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]) @@ -6123,8 +6176,6 @@ FSharp.Compiler.Syntax.SynAttributeList: Microsoft.FSharp.Collections.FSharpList FSharp.Compiler.Syntax.SynAttributeList: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttribute] get_Attributes() FSharp.Compiler.Syntax.SynAttributeList: System.String ToString() FSharp.Compiler.Syntax.SynAttributeList: Void .ctor(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttribute], FSharp.Compiler.Text.Range) -FSharp.Compiler.Syntax.SynBinding: Boolean IsSynBinding -FSharp.Compiler.Syntax.SynBinding: Boolean get_IsSynBinding() FSharp.Compiler.Syntax.SynBinding: Boolean get_isInline() FSharp.Compiler.Syntax.SynBinding: Boolean get_isMutable() FSharp.Compiler.Syntax.SynBinding: Boolean isInline @@ -6188,8 +6239,6 @@ FSharp.Compiler.Syntax.SynBindingKind: Int32 GetHashCode(System.Collections.IEqu FSharp.Compiler.Syntax.SynBindingKind: Int32 Tag FSharp.Compiler.Syntax.SynBindingKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynBindingKind: System.String ToString() -FSharp.Compiler.Syntax.SynBindingReturnInfo: Boolean IsSynBindingReturnInfo -FSharp.Compiler.Syntax.SynBindingReturnInfo: Boolean get_IsSynBindingReturnInfo() FSharp.Compiler.Syntax.SynBindingReturnInfo: FSharp.Compiler.Syntax.SynBindingReturnInfo NewSynBindingReturnInfo(FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.SyntaxTrivia.SynBindingReturnInfoTrivia) FSharp.Compiler.Syntax.SynBindingReturnInfo: FSharp.Compiler.Syntax.SynType get_typeName() FSharp.Compiler.Syntax.SynBindingReturnInfo: FSharp.Compiler.Syntax.SynType typeName @@ -6224,8 +6273,6 @@ FSharp.Compiler.Syntax.SynByteStringKind: Int32 GetHashCode(System.Collections.I FSharp.Compiler.Syntax.SynByteStringKind: Int32 Tag FSharp.Compiler.Syntax.SynByteStringKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynByteStringKind: System.String ToString() -FSharp.Compiler.Syntax.SynComponentInfo: Boolean IsSynComponentInfo -FSharp.Compiler.Syntax.SynComponentInfo: Boolean get_IsSynComponentInfo() FSharp.Compiler.Syntax.SynComponentInfo: Boolean get_preferPostfix() FSharp.Compiler.Syntax.SynComponentInfo: Boolean preferPostfix FSharp.Compiler.Syntax.SynComponentInfo: FSharp.Compiler.Syntax.SynComponentInfo NewSynComponentInfo(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynTyparDecls], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynTypeConstraint], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], FSharp.Compiler.Xml.PreXmlDoc, Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) @@ -6425,8 +6472,6 @@ FSharp.Compiler.Syntax.SynConst: FSharp.Compiler.Text.Range Range(FSharp.Compile FSharp.Compiler.Syntax.SynConst: Int32 Tag FSharp.Compiler.Syntax.SynConst: Int32 get_Tag() FSharp.Compiler.Syntax.SynConst: System.String ToString() -FSharp.Compiler.Syntax.SynEnumCase: Boolean IsSynEnumCase -FSharp.Compiler.Syntax.SynEnumCase: Boolean get_IsSynEnumCase() FSharp.Compiler.Syntax.SynEnumCase: FSharp.Compiler.Syntax.SynEnumCase NewSynEnumCase(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynIdent, FSharp.Compiler.Syntax.SynExpr, FSharp.Compiler.Xml.PreXmlDoc, FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynEnumCaseTrivia) FSharp.Compiler.Syntax.SynEnumCase: FSharp.Compiler.Syntax.SynExpr get_valueExpr() FSharp.Compiler.Syntax.SynEnumCase: FSharp.Compiler.Syntax.SynExpr valueExpr @@ -6445,8 +6490,6 @@ FSharp.Compiler.Syntax.SynEnumCase: Int32 get_Tag() FSharp.Compiler.Syntax.SynEnumCase: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList] attributes FSharp.Compiler.Syntax.SynEnumCase: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList] get_attributes() FSharp.Compiler.Syntax.SynEnumCase: System.String ToString() -FSharp.Compiler.Syntax.SynExceptionDefn: Boolean IsSynExceptionDefn -FSharp.Compiler.Syntax.SynExceptionDefn: Boolean get_IsSynExceptionDefn() FSharp.Compiler.Syntax.SynExceptionDefn: FSharp.Compiler.Syntax.SynExceptionDefn NewSynExceptionDefn(FSharp.Compiler.Syntax.SynExceptionDefnRepr, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynExceptionDefn: FSharp.Compiler.Syntax.SynExceptionDefnRepr exnRepr FSharp.Compiler.Syntax.SynExceptionDefn: FSharp.Compiler.Syntax.SynExceptionDefnRepr get_exnRepr() @@ -6461,8 +6504,6 @@ FSharp.Compiler.Syntax.SynExceptionDefn: Microsoft.FSharp.Collections.FSharpList FSharp.Compiler.Syntax.SynExceptionDefn: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] get_withKeyword() FSharp.Compiler.Syntax.SynExceptionDefn: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range] withKeyword FSharp.Compiler.Syntax.SynExceptionDefn: System.String ToString() -FSharp.Compiler.Syntax.SynExceptionDefnRepr: Boolean IsSynExceptionDefnRepr -FSharp.Compiler.Syntax.SynExceptionDefnRepr: Boolean get_IsSynExceptionDefnRepr() FSharp.Compiler.Syntax.SynExceptionDefnRepr: FSharp.Compiler.Syntax.SynExceptionDefnRepr NewSynExceptionDefnRepr(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynUnionCase, Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident]], FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynExceptionDefnRepr: FSharp.Compiler.Syntax.SynUnionCase caseName FSharp.Compiler.Syntax.SynExceptionDefnRepr: FSharp.Compiler.Syntax.SynUnionCase get_caseName() @@ -6481,8 +6522,6 @@ FSharp.Compiler.Syntax.SynExceptionDefnRepr: Microsoft.FSharp.Core.FSharpOption` FSharp.Compiler.Syntax.SynExceptionDefnRepr: Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident]] get_longId() FSharp.Compiler.Syntax.SynExceptionDefnRepr: Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident]] longId FSharp.Compiler.Syntax.SynExceptionDefnRepr: System.String ToString() -FSharp.Compiler.Syntax.SynExceptionSig: Boolean IsSynExceptionSig -FSharp.Compiler.Syntax.SynExceptionSig: Boolean get_IsSynExceptionSig() FSharp.Compiler.Syntax.SynExceptionSig: FSharp.Compiler.Syntax.SynExceptionDefnRepr exnRepr FSharp.Compiler.Syntax.SynExceptionSig: FSharp.Compiler.Syntax.SynExceptionDefnRepr get_exnRepr() FSharp.Compiler.Syntax.SynExceptionSig: FSharp.Compiler.Syntax.SynExceptionSig NewSynExceptionSig(FSharp.Compiler.Syntax.SynExceptionDefnRepr, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberSig], FSharp.Compiler.Text.Range) @@ -7417,8 +7456,6 @@ FSharp.Compiler.Syntax.SynExpr: FSharp.Compiler.Text.Range get_RangeWithoutAnyEx FSharp.Compiler.Syntax.SynExpr: Int32 Tag FSharp.Compiler.Syntax.SynExpr: Int32 get_Tag() FSharp.Compiler.Syntax.SynExpr: System.String ToString() -FSharp.Compiler.Syntax.SynExprAndBang: Boolean IsSynExprAndBang -FSharp.Compiler.Syntax.SynExprAndBang: Boolean get_IsSynExprAndBang() FSharp.Compiler.Syntax.SynExprAndBang: Boolean get_isFromSource() FSharp.Compiler.Syntax.SynExprAndBang: Boolean get_isUse() FSharp.Compiler.Syntax.SynExprAndBang: Boolean isFromSource @@ -7437,8 +7474,7 @@ FSharp.Compiler.Syntax.SynExprAndBang: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynExprAndBang: Int32 Tag FSharp.Compiler.Syntax.SynExprAndBang: Int32 get_Tag() FSharp.Compiler.Syntax.SynExprAndBang: System.String ToString() -FSharp.Compiler.Syntax.SynExprRecordField: Boolean IsSynExprRecordField -FSharp.Compiler.Syntax.SynExprRecordField: Boolean get_IsSynExprRecordField() +FSharp.Compiler.Syntax.SynExprModule: Boolean shouldBeParenthesizedInContext(Microsoft.FSharp.Core.FSharpFunc`2[System.Int32,System.String], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynExpr) FSharp.Compiler.Syntax.SynExprRecordField: FSharp.Compiler.Syntax.SynExprRecordField NewSynExprRecordField(System.Tuple`2[FSharp.Compiler.Syntax.SynLongIdent,System.Boolean], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr], Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`2[FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Position]]]) FSharp.Compiler.Syntax.SynExprRecordField: Int32 Tag FSharp.Compiler.Syntax.SynExprRecordField: Int32 get_Tag() @@ -7451,8 +7487,6 @@ FSharp.Compiler.Syntax.SynExprRecordField: Microsoft.FSharp.Core.FSharpOption`1[ FSharp.Compiler.Syntax.SynExprRecordField: System.String ToString() FSharp.Compiler.Syntax.SynExprRecordField: System.Tuple`2[FSharp.Compiler.Syntax.SynLongIdent,System.Boolean] fieldName FSharp.Compiler.Syntax.SynExprRecordField: System.Tuple`2[FSharp.Compiler.Syntax.SynLongIdent,System.Boolean] get_fieldName() -FSharp.Compiler.Syntax.SynField: Boolean IsSynField -FSharp.Compiler.Syntax.SynField: Boolean get_IsSynField() FSharp.Compiler.Syntax.SynField: Boolean get_isMutable() FSharp.Compiler.Syntax.SynField: Boolean get_isStatic() FSharp.Compiler.Syntax.SynField: Boolean isMutable @@ -7477,8 +7511,6 @@ FSharp.Compiler.Syntax.SynField: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Com FSharp.Compiler.Syntax.SynField: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess] accessibility FSharp.Compiler.Syntax.SynField: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess] get_accessibility() FSharp.Compiler.Syntax.SynField: System.String ToString() -FSharp.Compiler.Syntax.SynIdent: Boolean IsSynIdent -FSharp.Compiler.Syntax.SynIdent: Boolean get_IsSynIdent() FSharp.Compiler.Syntax.SynIdent: FSharp.Compiler.Syntax.Ident get_ident() FSharp.Compiler.Syntax.SynIdent: FSharp.Compiler.Syntax.Ident ident FSharp.Compiler.Syntax.SynIdent: FSharp.Compiler.Syntax.SynIdent NewSynIdent(FSharp.Compiler.Syntax.Ident, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia]) @@ -7487,8 +7519,6 @@ FSharp.Compiler.Syntax.SynIdent: Int32 get_Tag() FSharp.Compiler.Syntax.SynIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia] get_trivia() FSharp.Compiler.Syntax.SynIdent: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia] trivia FSharp.Compiler.Syntax.SynIdent: System.String ToString() -FSharp.Compiler.Syntax.SynInterfaceImpl: Boolean IsSynInterfaceImpl -FSharp.Compiler.Syntax.SynInterfaceImpl: Boolean get_IsSynInterfaceImpl() FSharp.Compiler.Syntax.SynInterfaceImpl: FSharp.Compiler.Syntax.SynInterfaceImpl NewSynInterfaceImpl(FSharp.Compiler.Syntax.SynType, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynBinding], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynInterfaceImpl: FSharp.Compiler.Syntax.SynType get_interfaceTy() FSharp.Compiler.Syntax.SynInterfaceImpl: FSharp.Compiler.Syntax.SynType interfaceTy @@ -7525,9 +7555,7 @@ FSharp.Compiler.Syntax.SynInterpolatedStringPart: FSharp.Compiler.Syntax.SynInte FSharp.Compiler.Syntax.SynInterpolatedStringPart: Int32 Tag FSharp.Compiler.Syntax.SynInterpolatedStringPart: Int32 get_Tag() FSharp.Compiler.Syntax.SynInterpolatedStringPart: System.String ToString() -FSharp.Compiler.Syntax.SynLongIdent: Boolean IsSynLongIdent FSharp.Compiler.Syntax.SynLongIdent: Boolean ThereIsAnExtraDotAtTheEnd -FSharp.Compiler.Syntax.SynLongIdent: Boolean get_IsSynLongIdent() FSharp.Compiler.Syntax.SynLongIdent: Boolean get_ThereIsAnExtraDotAtTheEnd() FSharp.Compiler.Syntax.SynLongIdent: FSharp.Compiler.Syntax.SynLongIdent NewSynLongIdent(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Collections.FSharpList`1[Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SyntaxTrivia.IdentTrivia]]) FSharp.Compiler.Syntax.SynLongIdent: FSharp.Compiler.Text.Range Range @@ -7553,8 +7581,6 @@ FSharp.Compiler.Syntax.SynLongIdent: Microsoft.FSharp.Collections.FSharpList`1[M FSharp.Compiler.Syntax.SynLongIdent: System.String ToString() FSharp.Compiler.Syntax.SynLongIdentHelpers: FSharp.Compiler.Syntax.SynLongIdent LongIdentWithDots(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range]) FSharp.Compiler.Syntax.SynLongIdentHelpers: System.Tuple`2[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident],Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range]] |LongIdentWithDots|(FSharp.Compiler.Syntax.SynLongIdent) -FSharp.Compiler.Syntax.SynMatchClause: Boolean IsSynMatchClause -FSharp.Compiler.Syntax.SynMatchClause: Boolean get_IsSynMatchClause() FSharp.Compiler.Syntax.SynMatchClause: FSharp.Compiler.Syntax.DebugPointAtTarget debugPoint FSharp.Compiler.Syntax.SynMatchClause: FSharp.Compiler.Syntax.DebugPointAtTarget get_debugPoint() FSharp.Compiler.Syntax.SynMatchClause: FSharp.Compiler.Syntax.SynExpr get_resultExpr() @@ -7708,8 +7734,8 @@ FSharp.Compiler.Syntax.SynMemberDefn+GetSetMember: Microsoft.FSharp.Core.FSharpO 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.Syntax.SynPat ctorArgs +FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.Syntax.SynPat get_ctorArgs() FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia get_trivia() FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia trivia FSharp.Compiler.Syntax.SynMemberDefn+ImplicitCtor: FSharp.Compiler.Text.Range get_range() @@ -7809,7 +7835,7 @@ 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.SyntaxTrivia.SynMemberDefnAbstractSlotTrivia) 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, FSharp.Compiler.Syntax.SynMemberFlags, FSharp.Compiler.Syntax.SynMemberFlags, FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Syntax.SynExpr, FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynMemberDefnAutoPropertyTrivia) 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.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia) +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.SynPat, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident], FSharp.Compiler.Xml.PreXmlDoc, FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynMemberDefnImplicitCtorTrivia) 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) FSharp.Compiler.Syntax.SynMemberDefn: FSharp.Compiler.Syntax.SynMemberDefn NewInterface(FSharp.Compiler.Syntax.SynType, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Text.Range], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn]], FSharp.Compiler.Text.Range) @@ -8052,8 +8078,6 @@ FSharp.Compiler.Syntax.SynModuleDecl: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynModuleDecl: Int32 Tag FSharp.Compiler.Syntax.SynModuleDecl: Int32 get_Tag() FSharp.Compiler.Syntax.SynModuleDecl: System.String ToString() -FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean IsSynModuleOrNamespace -FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean get_IsSynModuleOrNamespace() FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean get_isRecursive() FSharp.Compiler.Syntax.SynModuleOrNamespace: Boolean isRecursive FSharp.Compiler.Syntax.SynModuleOrNamespace: FSharp.Compiler.Syntax.SynModuleOrNamespace NewSynModuleOrNamespace(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.Ident], Boolean, FSharp.Compiler.Syntax.SynModuleOrNamespaceKind, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynModuleDecl], FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynModuleOrNamespaceTrivia) @@ -8112,8 +8136,6 @@ FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: Int32 GetHashCode(System.Collec FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: Int32 Tag FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynModuleOrNamespaceKind: System.String ToString() -FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean IsSynModuleOrNamespaceSig -FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean get_IsSynModuleOrNamespaceSig() FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean get_isRecursive() FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: Boolean isRecursive FSharp.Compiler.Syntax.SynModuleOrNamespaceSig: FSharp.Compiler.Syntax.SynModuleOrNamespaceKind get_kind() @@ -8466,6 +8488,7 @@ FSharp.Compiler.Syntax.SynPat: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynPat: Int32 Tag FSharp.Compiler.Syntax.SynPat: Int32 get_Tag() FSharp.Compiler.Syntax.SynPat: System.String ToString() +FSharp.Compiler.Syntax.SynPatModule: Boolean shouldBeParenthesizedInContext(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynPat) FSharp.Compiler.Syntax.SynRationalConst+Integer: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.SynRationalConst+Integer: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynRationalConst+Integer: Int32 get_value() @@ -8514,8 +8537,6 @@ FSharp.Compiler.Syntax.SynRationalConst: FSharp.Compiler.Syntax.SynRationalConst FSharp.Compiler.Syntax.SynRationalConst: Int32 Tag FSharp.Compiler.Syntax.SynRationalConst: Int32 get_Tag() FSharp.Compiler.Syntax.SynRationalConst: System.String ToString() -FSharp.Compiler.Syntax.SynReturnInfo: Boolean IsSynReturnInfo -FSharp.Compiler.Syntax.SynReturnInfo: Boolean get_IsSynReturnInfo() FSharp.Compiler.Syntax.SynReturnInfo: FSharp.Compiler.Syntax.SynReturnInfo NewSynReturnInfo(System.Tuple`2[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Syntax.SynArgInfo], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynReturnInfo: FSharp.Compiler.Text.Range Range FSharp.Compiler.Syntax.SynReturnInfo: FSharp.Compiler.Text.Range get_Range() @@ -8589,8 +8610,6 @@ FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: FSharp.Compiler.Syntax.Syn FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: Int32 Tag FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: Int32 get_Tag() FSharp.Compiler.Syntax.SynSimplePatAlternativeIdInfo: System.String ToString() -FSharp.Compiler.Syntax.SynSimplePats: Boolean IsSimplePats -FSharp.Compiler.Syntax.SynSimplePats: Boolean get_IsSimplePats() FSharp.Compiler.Syntax.SynSimplePats: FSharp.Compiler.Syntax.SynSimplePats NewSimplePats(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynSimplePat], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Text.Range], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynSimplePats: FSharp.Compiler.Text.Range Range FSharp.Compiler.Syntax.SynSimplePats: FSharp.Compiler.Text.Range get_Range() @@ -8681,8 +8700,6 @@ FSharp.Compiler.Syntax.SynTupleTypeSegment: FSharp.Compiler.Text.Range get_Range FSharp.Compiler.Syntax.SynTupleTypeSegment: Int32 Tag FSharp.Compiler.Syntax.SynTupleTypeSegment: Int32 get_Tag() FSharp.Compiler.Syntax.SynTupleTypeSegment: System.String ToString() -FSharp.Compiler.Syntax.SynTypar: Boolean IsSynTypar -FSharp.Compiler.Syntax.SynTypar: Boolean get_IsSynTypar() FSharp.Compiler.Syntax.SynTypar: Boolean get_isCompGen() FSharp.Compiler.Syntax.SynTypar: Boolean isCompGen FSharp.Compiler.Syntax.SynTypar: FSharp.Compiler.Syntax.Ident get_ident() @@ -8695,8 +8712,6 @@ FSharp.Compiler.Syntax.SynTypar: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynTypar: Int32 Tag FSharp.Compiler.Syntax.SynTypar: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypar: System.String ToString() -FSharp.Compiler.Syntax.SynTyparDecl: Boolean IsSynTyparDecl -FSharp.Compiler.Syntax.SynTyparDecl: Boolean get_IsSynTyparDecl() FSharp.Compiler.Syntax.SynTyparDecl: FSharp.Compiler.Syntax.SynTypar get_typar() FSharp.Compiler.Syntax.SynTyparDecl: FSharp.Compiler.Syntax.SynTypar typar FSharp.Compiler.Syntax.SynTyparDecl: FSharp.Compiler.Syntax.SynTyparDecl NewSynTyparDecl(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynTypar, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynType], FSharp.Compiler.SyntaxTrivia.SynTyparDeclTrivia) @@ -9129,8 +9144,6 @@ FSharp.Compiler.Syntax.SynTypeConstraint: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynTypeConstraint: Int32 Tag FSharp.Compiler.Syntax.SynTypeConstraint: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypeConstraint: System.String ToString() -FSharp.Compiler.Syntax.SynTypeDefn: Boolean IsSynTypeDefn -FSharp.Compiler.Syntax.SynTypeDefn: Boolean get_IsSynTypeDefn() FSharp.Compiler.Syntax.SynTypeDefn: FSharp.Compiler.Syntax.SynComponentInfo get_typeInfo() FSharp.Compiler.Syntax.SynTypeDefn: FSharp.Compiler.Syntax.SynComponentInfo typeInfo FSharp.Compiler.Syntax.SynTypeDefn: FSharp.Compiler.Syntax.SynTypeDefn NewSynTypeDefn(FSharp.Compiler.Syntax.SynComponentInfo, FSharp.Compiler.Syntax.SynTypeDefnRepr, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberDefn], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberDefn], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynTypeDefnTrivia) @@ -9247,8 +9260,6 @@ FSharp.Compiler.Syntax.SynTypeDefnRepr: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SynTypeDefnRepr: Int32 Tag FSharp.Compiler.Syntax.SynTypeDefnRepr: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypeDefnRepr: System.String ToString() -FSharp.Compiler.Syntax.SynTypeDefnSig: Boolean IsSynTypeDefnSig -FSharp.Compiler.Syntax.SynTypeDefnSig: Boolean get_IsSynTypeDefnSig() FSharp.Compiler.Syntax.SynTypeDefnSig: FSharp.Compiler.Syntax.SynComponentInfo get_typeInfo() FSharp.Compiler.Syntax.SynTypeDefnSig: FSharp.Compiler.Syntax.SynComponentInfo typeInfo FSharp.Compiler.Syntax.SynTypeDefnSig: FSharp.Compiler.Syntax.SynTypeDefnSig NewSynTypeDefnSig(FSharp.Compiler.Syntax.SynComponentInfo, FSharp.Compiler.Syntax.SynTypeDefnSigRepr, Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynMemberSig], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynTypeDefnSigTrivia) @@ -9318,8 +9329,8 @@ FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collectio FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`2[FSharp.Compiler.Syntax.SynValSig,FSharp.Compiler.Syntax.SynMemberFlags]] slotsigs FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]] get_inherits() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]] inherits -FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynSimplePats] get_implicitCtorSynPats() -FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynSimplePats] implicitCtorSynPats +FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynPat] get_implicitCtorSynPats() +FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+General: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynPat] implicitCtorSynPats FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+LibraryOnlyILAssembly: FSharp.Compiler.Text.Range get_range() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+LibraryOnlyILAssembly: FSharp.Compiler.Text.Range range FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr+LibraryOnlyILAssembly: System.Object get_ilType() @@ -9370,7 +9381,7 @@ FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Boolean get_IsTypeAbbrev() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Boolean get_IsUnion() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewEnum(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynEnumCase], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewException(FSharp.Compiler.Syntax.SynExceptionDefnRepr) -FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewGeneral(FSharp.Compiler.Syntax.SynTypeDefnKind, Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]], Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`2[FSharp.Compiler.Syntax.SynValSig,FSharp.Compiler.Syntax.SynMemberFlags]], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], Boolean, Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynSimplePats], FSharp.Compiler.Text.Range) +FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewGeneral(FSharp.Compiler.Syntax.SynTypeDefnKind, Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`3[FSharp.Compiler.Syntax.SynType,FSharp.Compiler.Text.Range,Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]]], Microsoft.FSharp.Collections.FSharpList`1[System.Tuple`2[FSharp.Compiler.Syntax.SynValSig,FSharp.Compiler.Syntax.SynMemberFlags]], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], Boolean, Boolean, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynPat], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewLibraryOnlyILAssembly(System.Object, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewNone(FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr NewRecord(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], FSharp.Compiler.Text.Range) @@ -9390,8 +9401,6 @@ FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: FSharp.Compiler.Text.Range get_Ran FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Int32 Tag FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: Int32 get_Tag() FSharp.Compiler.Syntax.SynTypeDefnSimpleRepr: System.String ToString() -FSharp.Compiler.Syntax.SynUnionCase: Boolean IsSynUnionCase -FSharp.Compiler.Syntax.SynUnionCase: Boolean get_IsSynUnionCase() FSharp.Compiler.Syntax.SynUnionCase: FSharp.Compiler.Syntax.SynIdent get_ident() FSharp.Compiler.Syntax.SynUnionCase: FSharp.Compiler.Syntax.SynIdent ident FSharp.Compiler.Syntax.SynUnionCase: FSharp.Compiler.Syntax.SynUnionCase NewSynUnionCase(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList], FSharp.Compiler.Syntax.SynIdent, FSharp.Compiler.Syntax.SynUnionCaseKind, FSharp.Compiler.Xml.PreXmlDoc, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynAccess], FSharp.Compiler.Text.Range, FSharp.Compiler.SyntaxTrivia.SynUnionCaseTrivia) @@ -9432,8 +9441,6 @@ FSharp.Compiler.Syntax.SynUnionCaseKind: FSharp.Compiler.Syntax.SynUnionCaseKind FSharp.Compiler.Syntax.SynUnionCaseKind: Int32 Tag FSharp.Compiler.Syntax.SynUnionCaseKind: Int32 get_Tag() FSharp.Compiler.Syntax.SynUnionCaseKind: System.String ToString() -FSharp.Compiler.Syntax.SynValData: Boolean IsSynValData -FSharp.Compiler.Syntax.SynValData: Boolean get_IsSynValData() FSharp.Compiler.Syntax.SynValData: FSharp.Compiler.Syntax.SynValData NewSynValData(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberFlags], FSharp.Compiler.Syntax.SynValInfo, Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.Ident]) FSharp.Compiler.Syntax.SynValData: FSharp.Compiler.Syntax.SynValInfo SynValInfo FSharp.Compiler.Syntax.SynValData: FSharp.Compiler.Syntax.SynValInfo get_SynValInfo() @@ -9446,8 +9453,6 @@ FSharp.Compiler.Syntax.SynValData: Microsoft.FSharp.Core.FSharpOption`1[FSharp.C FSharp.Compiler.Syntax.SynValData: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberFlags] get_memberFlags() FSharp.Compiler.Syntax.SynValData: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynMemberFlags] memberFlags FSharp.Compiler.Syntax.SynValData: System.String ToString() -FSharp.Compiler.Syntax.SynValInfo: Boolean IsSynValInfo -FSharp.Compiler.Syntax.SynValInfo: Boolean get_IsSynValInfo() FSharp.Compiler.Syntax.SynValInfo: FSharp.Compiler.Syntax.SynArgInfo get_returnInfo() FSharp.Compiler.Syntax.SynValInfo: FSharp.Compiler.Syntax.SynArgInfo returnInfo FSharp.Compiler.Syntax.SynValInfo: FSharp.Compiler.Syntax.SynValInfo NewSynValInfo(Microsoft.FSharp.Collections.FSharpList`1[Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynArgInfo]], FSharp.Compiler.Syntax.SynArgInfo) @@ -9460,8 +9465,6 @@ FSharp.Compiler.Syntax.SynValInfo: Microsoft.FSharp.Collections.FSharpList`1[Mic FSharp.Compiler.Syntax.SynValInfo: Microsoft.FSharp.Collections.FSharpList`1[System.String] ArgNames FSharp.Compiler.Syntax.SynValInfo: Microsoft.FSharp.Collections.FSharpList`1[System.String] get_ArgNames() FSharp.Compiler.Syntax.SynValInfo: System.String ToString() -FSharp.Compiler.Syntax.SynValSig: Boolean IsSynValSig -FSharp.Compiler.Syntax.SynValSig: Boolean get_IsSynValSig() FSharp.Compiler.Syntax.SynValSig: Boolean get_isInline() FSharp.Compiler.Syntax.SynValSig: Boolean get_isMutable() FSharp.Compiler.Syntax.SynValSig: Boolean isInline @@ -9496,9 +9499,7 @@ FSharp.Compiler.Syntax.SynValSig: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Co FSharp.Compiler.Syntax.SynValSig: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr] get_synExpr() FSharp.Compiler.Syntax.SynValSig: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr] synExpr FSharp.Compiler.Syntax.SynValSig: System.String ToString() -FSharp.Compiler.Syntax.SynValTyparDecls: Boolean IsSynValTyparDecls FSharp.Compiler.Syntax.SynValTyparDecls: Boolean canInfer -FSharp.Compiler.Syntax.SynValTyparDecls: Boolean get_IsSynValTyparDecls() FSharp.Compiler.Syntax.SynValTyparDecls: Boolean get_canInfer() FSharp.Compiler.Syntax.SynValTyparDecls: FSharp.Compiler.Syntax.SynValTyparDecls NewSynValTyparDecls(Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynTyparDecls], Boolean) FSharp.Compiler.Syntax.SynValTyparDecls: Int32 Tag @@ -9605,9 +9606,12 @@ FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+SynTypeDefn FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+SynTypeDefnSig FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+SynValSig FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Syntax.SyntaxNode+Tags +FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Text.Range Range +FSharp.Compiler.Syntax.SyntaxNode: FSharp.Compiler.Text.Range get_Range() FSharp.Compiler.Syntax.SyntaxNode: Int32 Tag FSharp.Compiler.Syntax.SyntaxNode: Int32 get_Tag() FSharp.Compiler.Syntax.SyntaxNode: System.String ToString() +FSharp.Compiler.Syntax.SyntaxNodeModule: Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynAttributeList] |Attributes|(FSharp.Compiler.Syntax.SyntaxNode) FSharp.Compiler.Syntax.SyntaxTraversal: Microsoft.FSharp.Core.FSharpOption`1[T] Traverse[T](FSharp.Compiler.Text.Position, FSharp.Compiler.Syntax.ParsedInput, FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitAttributeApplication(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynAttributeList) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitBinding(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SynBinding,Microsoft.FSharp.Core.FSharpOption`1[T]], FSharp.Compiler.Syntax.SynBinding) @@ -9627,7 +9631,7 @@ FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOptio FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitPat(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SynPat,Microsoft.FSharp.Core.FSharpOption`1[T]], FSharp.Compiler.Syntax.SynPat) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitRecordDefn(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynField], FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitRecordField(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynExpr], Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Syntax.SynLongIdent]) -FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitSimplePats(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynSimplePat]) +FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitSimplePats(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynPat) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitType(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Core.FSharpFunc`2[FSharp.Compiler.Syntax.SynType,Microsoft.FSharp.Core.FSharpOption`1[T]], FSharp.Compiler.Syntax.SynType) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitTypeAbbrev(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], FSharp.Compiler.Syntax.SynType, FSharp.Compiler.Text.Range) FSharp.Compiler.Syntax.SyntaxVisitorBase`1[T]: Microsoft.FSharp.Core.FSharpOption`1[T] VisitUnionDefn(Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SyntaxNode], Microsoft.FSharp.Collections.FSharpList`1[FSharp.Compiler.Syntax.SynUnionCase], FSharp.Compiler.Text.Range) @@ -10344,6 +10348,7 @@ FSharp.Compiler.Text.ISourceText: System.String GetSubTextFromRange(FSharp.Compi FSharp.Compiler.Text.ISourceText: System.String GetSubTextString(Int32, Int32) FSharp.Compiler.Text.ISourceText: System.Tuple`2[System.Int32,System.Int32] GetLastCharacterPosition() FSharp.Compiler.Text.ISourceText: Void CopyTo(Int32, Char[], Int32, Int32) +FSharp.Compiler.Text.ISourceTextNew: System.Collections.Immutable.ImmutableArray`1[System.Byte] GetChecksum() FSharp.Compiler.Text.Line: Int32 fromZ(Int32) FSharp.Compiler.Text.Line: Int32 toZ(Int32) FSharp.Compiler.Text.NavigableTaggedText: FSharp.Compiler.Text.Range Range @@ -10423,6 +10428,8 @@ FSharp.Compiler.Text.RangeModule: System.Tuple`2[System.String,System.Tuple`2[Sy FSharp.Compiler.Text.RangeModule: System.Tuple`2[System.Tuple`2[System.Int32,System.Int32],System.Tuple`2[System.Int32,System.Int32]] toZ(FSharp.Compiler.Text.Range) FSharp.Compiler.Text.RangeModule: Void outputRange(System.IO.TextWriter, FSharp.Compiler.Text.Range) FSharp.Compiler.Text.SourceText: FSharp.Compiler.Text.ISourceText ofString(System.String) +FSharp.Compiler.Text.SourceTextNew: FSharp.Compiler.Text.ISourceTextNew ofISourceText(FSharp.Compiler.Text.ISourceText) +FSharp.Compiler.Text.SourceTextNew: FSharp.Compiler.Text.ISourceTextNew ofString(System.String) FSharp.Compiler.Text.TaggedText: FSharp.Compiler.Text.TextTag Tag FSharp.Compiler.Text.TaggedText: FSharp.Compiler.Text.TextTag get_Tag() FSharp.Compiler.Text.TaggedText: System.String Text 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 9281c75120e..0c042c439ae 100644 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj @@ -5,13 +5,6 @@ Exe net472;net8.0 net8.0 - - $(NoWarn);NU1505 $(NoWarn);44;75; true false @@ -99,7 +92,8 @@ - + + Program.fs diff --git a/tests/FSharp.Compiler.Service.Tests/SynExprTests.fs b/tests/FSharp.Compiler.Service.Tests/SynExprTests.fs new file mode 100644 index 00000000000..1e402a1d252 --- /dev/null +++ b/tests/FSharp.Compiler.Service.Tests/SynExprTests.fs @@ -0,0 +1,88 @@ +module FSharp.Compiler.Syntax.Tests.SynExpr + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text +open NUnit.Framework + +type Parenthesization = Needed | Unneeded + +module Parenthesization = + let ofBool shouldParenthesize = + if shouldParenthesize then Needed + else Unneeded + +let exprs: obj array list = + [ + [|([] : Parenthesization list); "()"|] + [|[Needed]; "(1 + 2) * 3"|] + [|[Unneeded]; "1 + (2 * 3)"|] + [|[Unneeded]; "1 * (2 * 3)"|] + [|[Unneeded]; "(1 * 2) * 3"|] + [|[Needed]; "1 / (2 / 3)"|] + [|[Unneeded]; "(1 / 2) / 3"|] + [|[Unneeded]; "(printfn \"Hello, world.\")"|] + [|[Needed]; "let (~-) x = x in id -(<@ 3 @>)"|] + [|[Unneeded; Unneeded]; "let (~-) x = x in id (-(<@ 3 @>))"|] + [|[Unneeded]; "(())"|] + [|[Unneeded]; "(3)"|] + [|[Needed]; + " + let x = (x + + y) + in x + " + |] + [|[Unneeded]; + " + let x = (x + + y) + in x + " + |] + [|[Needed]; + " + async { + return ( + 1 + ) + } + " + |] + [|[Unneeded]; + " + async { + return ( + 1 + ) + } + " + |] + ] + +#if !NET6_0_OR_GREATER +open System + +type String with + // This is not a true polyfill, but it suffices for the .NET Framework target. + member this.ReplaceLineEndings() = this.Replace("\r", "") +#endif + +// `expected` represents whether each parenthesized expression, from the inside outward, requires its parentheses. +[] +let shouldBeParenthesizedInContext (expected: Parenthesization list) src = + let ast = getParseResults src + + let getSourceLineStr = + let lines = src.ReplaceLineEndings().Split '\n' + Line.toZ >> Array.get lines + + let actual = + ([], ast) + ||> ParsedInput.fold (fun actual path node -> + match node, path with + | SyntaxNode.SynExpr expr, SyntaxNode.SynExpr(SynExpr.Paren _) :: path -> + Parenthesization.ofBool (SynExpr.shouldBeParenthesizedInContext getSourceLineStr path expr) :: actual + | _ -> actual) + + CollectionAssert.AreEqual(expected, actual) diff --git a/tests/FSharp.Compiler.Service.Tests/SynPatTests.fs b/tests/FSharp.Compiler.Service.Tests/SynPatTests.fs new file mode 100644 index 00000000000..42a5e8711e0 --- /dev/null +++ b/tests/FSharp.Compiler.Service.Tests/SynPatTests.fs @@ -0,0 +1,36 @@ +module FSharp.Compiler.Syntax.Tests.SynPat + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open NUnit.Framework + +type Parenthesization = Needed | Unneeded + +module Parenthesization = + let ofBool shouldParenthesize = + if shouldParenthesize then Needed + else Unneeded + +let pats: obj array list = + [ + [|[Needed]; "match () with () -> ()"|] + [|[Needed]; "let (Lazy x) = lazy 1"|] + [|[Unneeded; Unneeded]; "let ((Lazy x)) = lazy 1"|] + [|[Needed; Unneeded]; "let (()) = ()"|] + [|[Needed; Unneeded; Unneeded]; "let ((())) = ()"|] + ] + +// `expected` represents whether each parenthesized pattern, from the inside outward, requires its parentheses. +[] +let shouldBeParenthesizedInContext (expected: Parenthesization list) src = + let ast = getParseResults src + + let actual = + ([], ast) + ||> ParsedInput.fold (fun actual path node -> + match node, path with + | SyntaxNode.SynPat pat, SyntaxNode.SynPat(SynPat.Paren _) :: path -> + Parenthesization.ofBool (SynPat.shouldBeParenthesizedInContext path pat) :: actual + | _ -> actual) + + CollectionAssert.AreEqual(expected, actual) \ No newline at end of file diff --git a/tests/FSharp.Compiler.Service.Tests/UnnecessaryParenthesesTests.fs b/tests/FSharp.Compiler.Service.Tests/UnnecessaryParenthesesTests.fs deleted file mode 100644 index 4ccbe93e470..00000000000 --- a/tests/FSharp.Compiler.Service.Tests/UnnecessaryParenthesesTests.fs +++ /dev/null @@ -1,52 +0,0 @@ -module FSharp.Compiler.EditorServices.Tests.UnnecessaryParenthesesTests - -open FSharp.Compiler.EditorServices -open FSharp.Compiler.Service.Tests.Common -open NUnit.Framework - -let noUnneededParens = - [ - "printfn \"Hello, world.\"" - "()" - "(1 + 2) * 3" - "let (~-) x = x in id -(<@ 3 @>)" - ] - -[] -let ``No results returned when there are no unnecessary parentheses`` src = - task { - let ast = getParseResults src - let! unnecessaryParentheses = UnnecessaryParentheses.getUnnecessaryParentheses (fun _ -> src) ast - Assert.IsEmpty unnecessaryParentheses - } - -let unneededParens = - [ - "(printfn \"Hello, world.\")" - "(())" - "(1 * 2) * 3" - "let (~-) x = x in -(<@ 3 @>)" - ] - -[] -let ``Results returned when there are unnecessary parentheses`` src = - task { - let ast = getParseResults src - let! unnecessaryParentheses = UnnecessaryParentheses.getUnnecessaryParentheses (fun _ -> src) ast - Assert.AreEqual(1, Seq.length unnecessaryParentheses, $"Expected one range but got: %A{unnecessaryParentheses}.") - } - -let nestedUnneededParens = - [ - "((printfn \"Hello, world.\"))" - "((3))" - "let (~-) x = x in id (-(<@ 3 @>))" - ] - -[] -let ``Results returned for nested, potentially mutually-exclusive, unnecessary parentheses`` src = - task { - let ast = getParseResults src - let! unnecessaryParentheses = UnnecessaryParentheses.getUnnecessaryParentheses (fun _ -> src) ast - Assert.AreEqual(2, Seq.length unnecessaryParentheses, $"Expected two ranges but got: %A{unnecessaryParentheses}.") - } diff --git a/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj b/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj index 915332ac4ac..0e4b91b42a7 100644 --- a/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj +++ b/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj @@ -74,6 +74,7 @@ CompilerService\ServiceUntypedParseTests.fs + diff --git a/tests/FSharp.Compiler.UnitTests/ParsedInputModuleTests.fs b/tests/FSharp.Compiler.UnitTests/ParsedInputModuleTests.fs new file mode 100644 index 00000000000..635c000f4af --- /dev/null +++ b/tests/FSharp.Compiler.UnitTests/ParsedInputModuleTests.fs @@ -0,0 +1,449 @@ +module Tests.Service.ParsedInputModuleTests + +open FSharp.Compiler.Service.Tests.Common +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text.Position +open Xunit + +[] +let ``tryPick type test`` () = + let source = "123 :? int" + let parseTree = parseSourceCode ("C:\\test.fs", source) + + (mkPos 1 11, parseTree) + ||> ParsedInput.tryPick (fun _path node -> match node with SyntaxNode.SynType _ -> Some() | _ -> None) + |> Option.defaultWith (fun _ -> failwith "Did not visit type") + + (mkPos 1 3, parseTree) + ||> ParsedInput.tryPick (fun _path node -> match node with SyntaxNode.SynType _ -> Some() | _ -> None) + |> Option.iter (fun _ -> failwith "Should not visit type") + +[] +let ``tryPick record definition test`` () = + let source = "type R = { A: int; B: string }" + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let fields = + (pos0, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn(SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFields = fields), _))) -> Some fields + | _ -> None) + + match fields with + | Some [ SynField (idOpt = Some id1); SynField (idOpt = Some id2) ] when id1.idText = "A" && id2.idText = "B" -> () + | _ -> failwith "Did not visit record definition" + +[] +let ``tryPick union definition test`` () = + let source = "type U = A | B of string" + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let cases = + (pos0, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn(SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Union(unionCases = cases), _))) -> Some cases + | _ -> None) + + match cases with + | Some [ SynUnionCase (ident = SynIdent(id1,_)); SynUnionCase (ident = SynIdent(id2,_)) ] when id1.idText = "A" && id2.idText = "B" -> () + | _ -> failwith "Did not visit union definition" + +[] +let ``tryPick enum definition test`` () = + let source = "type E = A = 0 | B = 1" + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let cases = + (pos0, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynTypeDefn(SynTypeDefn(typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Enum(cases = cases), _))) -> Some cases + | _ -> None) + + match cases with + | Some [ SynEnumCase (ident = SynIdent (id1, _)); SynEnumCase (ident = SynIdent (id2, _)) ] when id1.idText = "A" && id2.idText = "B" -> () + | _ -> failwith "Did not visit enum definition" + +[] +let ``tryPick recursive let binding`` () = + let source = "let rec fib n = if n < 2 then n else fib (n - 1) + fib (n - 2) in fib 10" + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let bindings = + (pos0, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.LetOrUse(isRecursive = false)) -> failwith "isRecursive should be true" + | SyntaxNode.SynExpr(SynExpr.LetOrUse(isRecursive = true; bindings = bindings)) -> Some bindings + | _ -> None) + + match bindings with + | Some [ SynBinding(valData = SynValData(valInfo = SynValInfo(curriedArgInfos = [ [ SynArgInfo(ident = Some id) ] ]))) ] when id.idText = "n" -> () + | _ -> failwith "Did not visit recursive let binding" + +[] +let ``tryPick ValSig`` () = + let source = """ +module X + +val y: int -> int +""" + + let parseTree = parseSourceCode ("C:\\test.fsi", source) + + let ident = + (pos0, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynValSig(SynValSig(ident = SynIdent(ident = ident))) -> Some ident.idText + | _ -> None) + + match ident with + | Some "y" -> () + | _ -> failwith "Did not visit SynValSig" + +[] +let ``tryPick nested ValSig`` () = + let source = """ +module X + +module Y = + val z: int -> int +""" + + let parseTree = parseSourceCode ("C:\\test.fsi", source) + + let ident = + (pos0, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynValSig(SynValSig(ident = SynIdent(ident = ident))) -> Some ident.idText + | _ -> None) + + match ident with + | Some "z" -> () + | _ -> failwith "Did not visit SynValSig" + +[] +let ``tryPick Record in SynTypeDefnSig`` () = + let source = """ +module X + +type Y = + { + A: int + B: char + C: string + } +""" + + let parseTree = parseSourceCode ("C:\\test.fsi", source) + + let ident = + (pos0, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynTypeDefnSig(SynTypeDefnSig(typeRepr = SynTypeDefnSigRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFields = fields), _))) -> + fields + |> List.choose (function SynField(idOpt = Some ident) -> Some ident.idText | _ -> None) + |> String.concat "," + |> Some + | _ -> None) + + match ident with + | Some "A,B,C" -> () + | _ -> failwith "Did not visit SynTypeDefnSimpleRepr.Record in SynTypeDefnSig" + +[] +let ``tryPick SynValSig in SynMemberSig`` () = + let source = """ +module Lib + +type Meh = + new: unit -> Meh + member Foo: y: int -> int +""" + + let parseTree = parseSourceCode ("C:\\test.fsi", source) + let pos = mkPos 6 4 + + let ident = + (pos, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynValSig(SynValSig(ident = SynIdent(ident = valIdent))) -> Some valIdent.idText + | _ -> None) + + match ident with + | Some "Foo" -> () + | _ -> failwith "Did not visit SynValSig in SynMemberSig.Member" + +[] +let ``tryPick picks the first matching node`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let ``module`` = + (mkPos 6 28, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + Some(longIdent |> List.map (fun ident -> ident.idText)) + | _ -> None) + + Assert.Equal(Some ["N"], ``module``) + +[] +let ``tryPick falls back to the nearest matching node to the left if pos is out of range`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let ``module`` = + (mkPos 7 30, parseTree) + ||> ParsedInput.tryPick (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + Some(longIdent |> List.map (fun ident -> ident.idText)) + | _ -> None) + + Assert.Equal(Some ["N"], ``module``) + +[] +let ``tryPickLast picks the last matching node`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let ``module`` = + (mkPos 6 28, parseTree) + ||> ParsedInput.tryPickLast (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + Some(longIdent |> List.map (fun ident -> ident.idText)) + | _ -> None) + + Assert.Equal(Some ["P"], ``module``) + +[] +let ``tryPickLast falls back to the nearest matching node to the left if pos is out of range`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let ``module`` = + (mkPos 7 30, parseTree) + ||> ParsedInput.tryPickLast (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + Some(longIdent |> List.map (fun ident -> ident.idText)) + | _ -> None) + + Assert.Equal(Some ["P"], ``module``) + +[] +let ``exists returns true for the first matching node`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let mutable start = 0, 0 + + let found = + (mkPos 6 28, parseTree) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + start <- node.Range.StartLine, node.Range.StartColumn + true + | _ -> false) + + Assert.True found + Assert.Equal((4, 0), start) + +[] +let ``exists falls back to the nearest matching node to the left if pos is out of range`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let mutable start = 0, 0 + + let found = + (mkPos 7 30, parseTree) + ||> ParsedInput.exists (fun _path node -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + start <- node.Range.StartLine, node.Range.StartColumn + true + | _ -> false) + + Assert.True found + Assert.Equal((4, 0), start) + +[] +let ``tryNode picks the last node containing the given position`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let ``module`` = + parseTree + |> ParsedInput.tryNode (mkPos 6 28) + |> Option.bind (fun (node, _path) -> + match node with + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + Some(longIdent |> List.map (fun ident -> ident.idText)) + | _ -> None) + + Assert.Equal(Some ["P"], ``module``) + +[] +let ``tryNode returns None if no node contains the given position`` () = + let source = """ +module M + +module N = + module O = + module P = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let ``module`` = parseTree |> ParsedInput.tryNode (mkPos 6 30) + + Assert.Equal(None, ``module``) + +[] +let ``fold traverses nodes in order`` () = + let source = """ +module M + +module N = + module O = + module P = begin end + +module Q = + module R = + module S = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let modules = + ([], parseTree) + ||> ParsedInput.fold (fun acc _path node -> + match node with + | SyntaxNode.SynModuleOrNamespace(SynModuleOrNamespace(longId = longIdent)) + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + (longIdent |> List.map (fun ident -> ident.idText)) :: acc + | _ -> acc) + + Assert.Equal( + [["M"]; ["N"]; ["O"]; ["P"]; ["Q"]; ["R"]; ["S"]], + List.rev modules) + +[] +let ``foldWhile traverses nodes in order`` () = + let source = """ +module M + +module N = + module O = + module P = begin end + +module Q = + module R = + module S = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let modules = + ([], parseTree) + ||> ParsedInput.foldWhile (fun acc _path node -> + match node with + | SyntaxNode.SynModuleOrNamespace(SynModuleOrNamespace(longId = longIdent)) + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + Some((longIdent |> List.map (fun ident -> ident.idText)) :: acc) + | _ -> Some acc) + + Assert.Equal( + [["M"]; ["N"]; ["O"]; ["P"]; ["Q"]; ["R"]; ["S"]], + List.rev modules) + +[] +let ``foldWhile traverses nodes in order until the folder returns None`` () = + let source = """ +module M + +module N = + module O = + module P = begin end + +module Q = + module R = + module S = begin end +""" + + let parseTree = parseSourceCode ("C:\\test.fs", source) + + let modules = + ([], parseTree) + ||> ParsedInput.foldWhile (fun acc _path node -> + if posGt node.Range.Start (mkPos 7 0) then None + else + match node with + | SyntaxNode.SynModuleOrNamespace(SynModuleOrNamespace(longId = longIdent)) + | SyntaxNode.SynModule(SynModuleDecl.NestedModule(moduleInfo = SynComponentInfo(longId = longIdent))) -> + Some((longIdent |> List.map (fun ident -> ident.idText)) :: acc) + | _ -> Some acc) + + Assert.Equal( + [["M"]; ["N"]; ["O"]; ["P"]], + List.rev modules) diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.debug.bsl b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.debug.bsl index 4f43f18a283..eeea1540744 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.debug.bsl +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.debug.bsl @@ -672,12 +672,14 @@ Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Contro Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpAsync`1[T] Scan[T](Microsoft.FSharp.Core.FSharpFunc`2[TMsg,Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Control.FSharpAsync`1[T]]], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpHandler`1[System.Exception] Error Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg] Start(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg],Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit]], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.CancellationToken]) +Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg] StartImmediate(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg],Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit]], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.CancellationToken]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Core.FSharpOption`1[TReply] TryPostAndReply[TReply](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpAsyncReplyChannel`1[TReply],TMsg], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: TReply PostAndReply[TReply](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpAsyncReplyChannel`1[TReply],TMsg], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void .ctor(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg],Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit]], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.CancellationToken]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void Dispose() Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void Post(TMsg) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void Start() +Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void StartImmediate() Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void add_Error(Microsoft.FSharp.Control.FSharpHandler`1[System.Exception]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void remove_Error(Microsoft.FSharp.Control.FSharpHandler`1[System.Exception]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void set_DefaultTimeout(Int32) @@ -950,6 +952,7 @@ Microsoft.FSharp.Core.CustomOperationAttribute: System.String JoinConditionWord Microsoft.FSharp.Core.CustomOperationAttribute: System.String Name Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_JoinConditionWord() Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_Name() +Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor() Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor(System.String) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_AllowIntoPattern(Boolean) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_IsLikeGroupJoin(Boolean) diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.release.bsl b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.release.bsl index 9053702b59d..5b8c8858e96 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.release.bsl +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard20.release.bsl @@ -952,6 +952,7 @@ Microsoft.FSharp.Core.CustomOperationAttribute: System.String JoinConditionWord Microsoft.FSharp.Core.CustomOperationAttribute: System.String Name Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_JoinConditionWord() Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_Name() +Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor() Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor(System.String) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_AllowIntoPattern(Boolean) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_IsLikeGroupJoin(Boolean) diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.debug.bsl b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.debug.bsl index 32481f9c338..5a5008e7218 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.debug.bsl +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.debug.bsl @@ -672,12 +672,14 @@ Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Contro Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpAsync`1[T] Scan[T](Microsoft.FSharp.Core.FSharpFunc`2[TMsg,Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Control.FSharpAsync`1[T]]], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpHandler`1[System.Exception] Error Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg] Start(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg],Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit]], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.CancellationToken]) +Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg] StartImmediate(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg],Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit]], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.CancellationToken]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Microsoft.FSharp.Core.FSharpOption`1[TReply] TryPostAndReply[TReply](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpAsyncReplyChannel`1[TReply],TMsg], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: TReply PostAndReply[TReply](Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpAsyncReplyChannel`1[TReply],TMsg], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void .ctor(Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg],Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit]], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.CancellationToken]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void Dispose() Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void Post(TMsg) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void Start() +Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void StartImmediate() Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void add_Error(Microsoft.FSharp.Control.FSharpHandler`1[System.Exception]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void remove_Error(Microsoft.FSharp.Control.FSharpHandler`1[System.Exception]) Microsoft.FSharp.Control.FSharpMailboxProcessor`1[TMsg]: Void set_DefaultTimeout(Int32) @@ -951,6 +953,7 @@ Microsoft.FSharp.Core.CustomOperationAttribute: System.String JoinConditionWord Microsoft.FSharp.Core.CustomOperationAttribute: System.String Name Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_JoinConditionWord() Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_Name() +Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor() Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor(System.String) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_AllowIntoPattern(Boolean) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_IsLikeGroupJoin(Boolean) diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.release.bsl b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.release.bsl index dd392757335..12f8380fbfb 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.release.bsl +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.SurfaceArea.netstandard21.release.bsl @@ -953,6 +953,7 @@ Microsoft.FSharp.Core.CustomOperationAttribute: System.String JoinConditionWord Microsoft.FSharp.Core.CustomOperationAttribute: System.String Name Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_JoinConditionWord() Microsoft.FSharp.Core.CustomOperationAttribute: System.String get_Name() +Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor() Microsoft.FSharp.Core.CustomOperationAttribute: Void .ctor(System.String) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_AllowIntoPattern(Boolean) Microsoft.FSharp.Core.CustomOperationAttribute: Void set_IsLikeGroupJoin(Boolean) diff --git a/tests/FSharp.Test.Utilities/Compiler.fs b/tests/FSharp.Test.Utilities/Compiler.fs index d021fecc953..6d1eb1b0707 100644 --- a/tests/FSharp.Test.Utilities/Compiler.fs +++ b/tests/FSharp.Test.Utilities/Compiler.fs @@ -27,6 +27,7 @@ open TestFramework open System.Runtime.CompilerServices open System.Runtime.InteropServices +open FSharp.Compiler.CodeAnalysis module rec Compiler = @@ -920,7 +921,7 @@ module rec Compiler = CompilerAssert.TypeCheck(options, fileName, source) | _ -> failwith "Typecheck only supports F#" - let typecheckProject enablePartialTypeChecking (cUnit: CompilationUnit) : FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults = + let typecheckProject enablePartialTypeChecking useTransparentCompiler (cUnit: CompilationUnit) : FSharp.Compiler.CodeAnalysis.FSharpCheckProjectResults = match cUnit with | FS fsSource -> let options = fsSource.Options |> Array.ofList @@ -938,7 +939,8 @@ module rec Compiler = |> async.Return let sourceFiles = Array.map fst sourceFiles - CompilerAssert.TypeCheckProject(options, sourceFiles, getSourceText, enablePartialTypeChecking) + + CompilerAssert.TypeCheckProject(options, sourceFiles, getSourceText, enablePartialTypeChecking, useTransparentCompiler) | _ -> failwith "Typecheck only supports F#" let run (result: CompilationResult) : CompilationResult = diff --git a/tests/FSharp.Test.Utilities/CompilerAssert.fs b/tests/FSharp.Test.Utilities/CompilerAssert.fs index 1dcbcb846ff..7951ba31d5d 100644 --- a/tests/FSharp.Test.Utilities/CompilerAssert.fs +++ b/tests/FSharp.Test.Utilities/CompilerAssert.fs @@ -11,6 +11,7 @@ open System.Reflection open FSharp.Compiler.Interactive.Shell open FSharp.Compiler.IO open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CodeAnalysis.ProjectSnapshot open FSharp.Compiler.Diagnostics open FSharp.Compiler.Text #if NETCOREAPP @@ -258,7 +259,8 @@ and Compilation = module rec CompilerAssertHelpers = - let checker = FSharpChecker.Create(suggestNamesForErrors=true) + let useTransparentCompiler = FSharp.Compiler.CompilerConfig.FSharpExperimentalFeaturesEnabledAutomatically + let checker = FSharpChecker.Create(suggestNamesForErrors=true, useTransparentCompiler=useTransparentCompiler) // Unlike C# whose entrypoint is always string[] F# can make an entrypoint with 0 args, or with an array of string[] let mkDefaultArgs (entryPoint:MethodBase) : obj[] = [| @@ -386,7 +388,7 @@ module rec CompilerAssertHelpers = let name = match nameOpt with | Some name -> name - | _ -> tryCreateTemporaryFileName() + | _ -> tryCreateTemporaryFileNameInDirectory(outputDirectory) let outputFilePath = Path.ChangeExtension (Path.Combine(outputDirectory.FullName, name), if isExe then ".exe" else ".dll") disposals.Add(disposeFile outputFilePath) @@ -886,14 +888,31 @@ Updated automatically, please check diffs in your pull request, changes must be static member TypeCheckSingleError (source: string) (expectedSeverity: FSharpDiagnosticSeverity) (expectedErrorNumber: int) (expectedErrorRange: int * int * int * int) (expectedErrorMsg: string) = CompilerAssert.TypeCheckWithErrors source [| expectedSeverity, expectedErrorNumber, expectedErrorRange, expectedErrorMsg |] - static member TypeCheckProject(options: string array, sourceFiles: string array, getSourceText, enablePartialTypeChecking) : FSharpCheckProjectResults = - let checker = FSharpChecker.Create(documentSource = DocumentSource.Custom getSourceText, enablePartialTypeChecking = enablePartialTypeChecking) + static member TypeCheckProject(options: string array, sourceFiles: string array, getSourceText, enablePartialTypeChecking, useTransparentCompiler) : FSharpCheckProjectResults = + let checker = FSharpChecker.Create(documentSource = DocumentSource.Custom getSourceText, enablePartialTypeChecking = enablePartialTypeChecking, useTransparentCompiler = useTransparentCompiler) let defaultOptions = defaultProjectOptions TargetFramework.Current let projectOptions = { defaultOptions with OtherOptions = Array.append options defaultOptions.OtherOptions; SourceFiles = sourceFiles } - checker.ParseAndCheckProject(projectOptions) + if useTransparentCompiler then + let getFileSnapshot _ fileName = + async.Return + (FSharpFileSnapshot( + FileName = fileName, + Version = "1", + GetSource = fun () -> task { + match! getSourceText fileName with + | Some source -> return SourceTextNew.ofISourceText source + | None -> return failwith $"couldn't get source for {fileName}" + } + )) + + let snapshot = FSharpProjectSnapshot.FromOptions(projectOptions, getFileSnapshot) |> Async.RunSynchronously + + checker.ParseAndCheckProject(snapshot) + else + checker.ParseAndCheckProject(projectOptions) |> Async.RunImmediate - + static member CompileExeWithOptions(options, (source: SourceCodeFileKind)) = compile true options source (fun (errors, _, _) -> if errors.Length > 0 then diff --git a/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj b/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj index 6867d180ae9..5cfcba98ca7 100644 --- a/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj +++ b/tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj @@ -73,6 +73,18 @@ + + + + + + + + + + + + @@ -88,6 +100,7 @@ + diff --git a/tests/FSharp.Test.Utilities/ProjectGeneration.fs b/tests/FSharp.Test.Utilities/ProjectGeneration.fs index 73f7fd1f0e4..54c00ebe544 100644 --- a/tests/FSharp.Test.Utilities/ProjectGeneration.fs +++ b/tests/FSharp.Test.Utilities/ProjectGeneration.fs @@ -25,6 +25,7 @@ open System.Threading.Tasks open System.Xml open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CodeAnalysis.ProjectSnapshot open FSharp.Compiler.Diagnostics open FSharp.Compiler.Text @@ -41,7 +42,7 @@ let private projectRoot = "test-projects" let private defaultFunctionName = "f" type Reference = { - Name: string + Name: string Version: string option } module ReferenceHelpers = @@ -68,13 +69,13 @@ module ReferenceHelpers = } |> String.concat "\n" - let runtimeList = lazy ( + let runtimeList = lazy ( // You can see which versions of the .NET runtime are currently installed with the following command. let psi = ProcessStartInfo("dotnet", "--list-runtimes", RedirectStandardOutput = true, UseShellExecute = false) let proc = Process.Start(psi) - proc.WaitForExit() + proc.WaitForExit(1000) |> ignore let output = seq { @@ -92,7 +93,8 @@ module ReferenceHelpers = { Name = matches.Groups.[1].Value Version = version - Path = DirectoryInfo(Path.Combine(matches.Groups[3].Value, version)) })) + Path = DirectoryInfo(Path.Combine(matches.Groups[3].Value, version)) }) + |> Seq.toList) let getFrameworkReference (reference: Reference) = @@ -540,10 +542,45 @@ module ProjectOperations = filePath |> project.FindByPath |> renderSourceFile project - |> SourceText.ofString + |> SourceTextNew.ofString + + let internal getFileSnapshot (project: SyntheticProject) _options (path: string) = + async { + let project, filePath = + if path.EndsWith(".fsi") then + let implFilePath = path[..path.Length - 2] + let p, f = project.FindInAllProjectsByPath implFilePath + p, getSignatureFilePath p f + else + let p, f = project.FindInAllProjectsByPath path + p, getFilePath p f + + let source = getSourceText project path + use md5 = System.Security.Cryptography.MD5.Create() + let inputBytes = Encoding.UTF8.GetBytes(source.ToString()) + let hash = md5.ComputeHash(inputBytes) |> Array.map (fun b -> b.ToString("X2")) |> String.concat "" + + return FSharpFileSnapshot( + FileName = filePath, + Version = hash, + GetSource = fun () -> source |> Task.FromResult + ) + } + + let checkFileWithTransparentCompiler fileId (project: SyntheticProject) (checker: FSharpChecker) = + async { + let file = project.Find fileId + let absFileName = getFilePath project file + let options = project.GetProjectOptions checker + let! projectSnapshot = FSharpProjectSnapshot.FromOptions(options, getFileSnapshot project) + return! checker.ParseAndCheckFileInProject(absFileName, projectSnapshot) + } let checkFile fileId (project: SyntheticProject) (checker: FSharpChecker) = - checkFileWithIncrementalBuilder fileId project checker + (if checker.UsesTransparentCompiler then + checkFileWithTransparentCompiler + else + checkFileWithIncrementalBuilder) fileId project checker let getTypeCheckResult (parseResults: FSharpParseFileResults, checkResults: FSharpCheckFileAnswer) = Assert.True(not parseResults.ParseHadErrors) @@ -680,7 +717,7 @@ module ProjectOperations = module Helpers = - let getSymbolUse fileName (source: string) (symbolName: string) options (checker: FSharpChecker) = + let internal getSymbolUse fileName (source: string) (symbolName: string) snapshot (checker: FSharpChecker) = async { let lines = source.Split '\n' |> Seq.skip 1 // module definition let lineNumber, fullLine, colAtEndOfNames = @@ -694,8 +731,7 @@ module Helpers = |> Seq.tryPick id |> Option.defaultValue (-1, "", -1) - let! results = checker.ParseAndCheckFileInProject( - fileName, 0, SourceText.ofString source, options) + let! results = checker.ParseAndCheckFileInProject(fileName, snapshot) let typeCheckResults = getTypeCheckResult results @@ -706,18 +742,23 @@ module Helpers = failwith $"No symbol found in {fileName} at {lineNumber}:{colAtEndOfNames}\nFile contents:\n\n{source}\n") } - let singleFileChecker source = + let internal singleFileChecker source = let fileName = "test.fs" - let getSource _ = source |> SourceText.ofString |> Some |> async.Return + let getSource _ fileName = + FSharpFileSnapshot( + FileName = fileName, + Version = "1", + GetSource = fun () -> source |> SourceTextNew.ofString |> Task.FromResult ) + |> async.Return let checker = FSharpChecker.Create( keepAllBackgroundSymbolUses = false, enableBackgroundItemKeyStoreAndSemanticClassification = true, enablePartialTypeChecking = true, captureIdentifiersWhenParsing = true, - documentSource = DocumentSource.Custom getSource) + useTransparentCompiler = true) let options = let baseOptions, _ = @@ -739,7 +780,9 @@ module Helpers = OriginalLoadReferences = [] Stamp = None } - fileName, options, checker + let snapshot = FSharpProjectSnapshot.FromOptions(options, getSource) |> Async.RunSynchronously + + fileName, snapshot, checker open Helpers @@ -757,8 +800,9 @@ let SaveAndCheckProject project checker = do! saveProject project true checker let options = project.GetProjectOptions checker + let! snapshot = FSharpProjectSnapshot.FromOptions(options, getFileSnapshot project) - let! results = checker.ParseAndCheckProject(options) + let! results = checker.ParseAndCheckProject(snapshot) if not (Array.isEmpty results.Diagnostics || project.SkipInitialCheck) then failwith $"Project {project.Name} failed initial check: \n%A{results.Diagnostics}" @@ -778,6 +822,8 @@ let SaveAndCheckProject project checker = Cursor = None } } +type MoveFileDirection = Up | Down + type ProjectWorkflowBuilder ( initialProject: SyntheticProject, @@ -791,7 +837,7 @@ type ProjectWorkflowBuilder ?autoStart ) = - let useTransparentCompiler = defaultArg useTransparentCompiler false + let useTransparentCompiler = defaultArg useTransparentCompiler FSharp.Compiler.CompilerConfig.FSharpExperimentalFeaturesEnabledAutomatically let useGetSource = not useTransparentCompiler && defaultArg useGetSource false let useChangeNotifications = not useTransparentCompiler && defaultArg useChangeNotifications false let autoStart = defaultArg autoStart true @@ -800,7 +846,7 @@ type ProjectWorkflowBuilder let mutable activity = None let mutable tracerProvider = None - let getSource f = f |> getSourceText latestProject |> Some |> async.Return + let getSource f = f |> getSourceText latestProject :> ISourceText |> Some |> async.Return let checker = defaultArg @@ -811,7 +857,9 @@ type ProjectWorkflowBuilder enablePartialTypeChecking = true, captureIdentifiersWhenParsing = true, documentSource = (if useGetSource then DocumentSource.Custom getSource else DocumentSource.FileSystem), - useSyntaxTreeCache = defaultArg useSyntaxTreeCache false)) + useSyntaxTreeCache = defaultArg useSyntaxTreeCache false, + useTransparentCompiler = useTransparentCompiler + )) let mapProjectAsync f workflow = async { @@ -859,7 +907,9 @@ type ProjectWorkflowBuilder member this.DeleteProjectDir() = if Directory.Exists initialProject.ProjectDir then - Directory.Delete(initialProject.ProjectDir, true) + try + Directory.Delete(initialProject.ProjectDir, true) + with _ -> () member this.Execute(workflow: Async) = try @@ -1000,6 +1050,30 @@ type ProjectWorkflowBuilder return { ctx with Signatures = ctx.Signatures.Add(fileId, newSignature) } } + [] + member this.MoveFile(workflow: Async, fileId: string, count, direction: MoveFileDirection) = + + workflow + |> mapProject (fun project -> + let index = + project.SourceFiles + |> List.tryFindIndex (fun f -> f.Id = fileId) + |> Option.defaultWith (fun () -> failwith $"File {fileId} not found") + + let dir = if direction = Up then -1 else 1 + let newIndex = index + count * dir + + if newIndex < 0 || newIndex > project.SourceFiles.Length - 1 then + failwith $"Cannot move file {fileId} {count} times {direction} as it would be out of bounds" + + let file = project.SourceFiles.[index] + let newFiles = + project.SourceFiles + |> List.filter (fun f -> f.Id <> fileId) + |> List.insertAt newIndex file + + { project with SourceFiles = newFiles }) + /// Find a symbol using the provided range, mimicking placing a cursor on it in IDE scenarios [] member this.PlaceCursor(workflow: Async, fileId, line, colAtEndOfNames, fullLine, symbolNames) = @@ -1025,8 +1099,9 @@ type ProjectWorkflowBuilder let project, file = ctx.Project.FindInAllProjects fileId let fileName = project.ProjectDir ++ file.FileName let source = renderSourceFile project file - let options= project.GetProjectOptions checker - return! getSymbolUse fileName source symbolName options checker + let options = project.GetProjectOptions checker + let! snapshot = FSharpProjectSnapshot.FromOptions(options, getFileSnapshot ctx.Project) + return! getSymbolUse fileName source symbolName snapshot checker } /// Find a symbol by finding the first occurrence of the symbol name in the file @@ -1085,7 +1160,10 @@ type ProjectWorkflowBuilder [ for p, f in ctx.Project.GetAllFiles() do let options = p.GetProjectOptions checker for fileName in [getFilePath p f; if f.SignatureFile <> No then getSignatureFilePath p f] do - checker.FindBackgroundReferencesInFile(fileName, options, symbolUse.Symbol, fastCheck = true) ] + async { + let! snapshot = FSharpProjectSnapshot.FromOptions(options, getFileSnapshot ctx.Project) + return! checker.FindBackgroundReferencesInFile(fileName, snapshot, symbolUse.Symbol) + } ] |> Async.Parallel results |> Seq.collect id |> Seq.toList |> processResults @@ -1210,7 +1288,7 @@ type SyntheticProject with projectDir ++ node.Attributes["Include"].InnerText ] |> List.partition (fun path -> path.EndsWith ".fsi") let signatureFiles = set signatureFiles - + let parseReferences refType = [ for node in fsproj.DocumentElement.SelectNodes($"//{refType}") do { Name = node.Attributes["Include"].InnerText diff --git a/tests/FSharp.Test.Utilities/TestFramework.fs b/tests/FSharp.Test.Utilities/TestFramework.fs index e5af95432b0..f7ec7f48001 100644 --- a/tests/FSharp.Test.Utilities/TestFramework.fs +++ b/tests/FSharp.Test.Utilities/TestFramework.fs @@ -28,12 +28,11 @@ let tryCreateTemporaryFileName () = filePath // Create a temporaryFileName -- newGuid is random --- there is no point validating the file alread exists because: threading and Path.ChangeExtension() is commonly used after this API -let tryCreateTemporaryFileNameInDirectory (directory) = +let tryCreateTemporaryFileNameInDirectory (directory: DirectoryInfo) = let fileName = ("Temp-" + Guid.NewGuid().ToString() + ".tmp").Replace('-', '_') - let filePath = Path.Combine(directory, fileName) + let filePath = Path.Combine(directory.FullName, fileName) filePath - [] module Commands = diff --git a/tests/FSharp.Test.Utilities/Utilities.fs b/tests/FSharp.Test.Utilities/Utilities.fs index a2a84a5b725..d434d837485 100644 --- a/tests/FSharp.Test.Utilities/Utilities.fs +++ b/tests/FSharp.Test.Utilities/Utilities.fs @@ -15,6 +15,10 @@ open Microsoft.CodeAnalysis.CSharp open TestFramework open NUnit.Framework open System.Collections.Generic +open FSharp.Compiler.CodeAnalysis +open Newtonsoft.Json +open Newtonsoft.Json.Linq + type TheoryForNETCOREAPPAttribute() = inherit Xunit.TheoryAttribute() @@ -104,12 +108,12 @@ module Utilities = let outputLines = StringBuilder() let errorLines = StringBuilder() - do redirector.OutputProduced.Add (fun line -> outputLines.AppendLine line |>ignore) - do redirector.ErrorProduced.Add(fun line -> errorLines.AppendLine line |>ignore) + do redirector.OutputProduced.Add (fun line -> lock outputLines <| fun () -> outputLines.AppendLine line |>ignore) + do redirector.ErrorProduced.Add(fun line -> lock errorLines <| fun () -> errorLines.AppendLine line |>ignore) - member _.Output () = outputLines.ToString() + member _.Output () = lock outputLines outputLines.ToString - member _.ErrorOutput () = errorLines.ToString() + member _.ErrorOutput () = lock errorLines errorLines.ToString interface IDisposable with member _.Dispose() = (redirector :> IDisposable).Dispose() @@ -381,3 +385,10 @@ An error occurred getting netcoreapp references: %A{e} | TargetFramework.NetStandard20 -> netStandard20Files.Value |> Seq.toArray | TargetFramework.NetCoreApp31 -> [||] //ToDo --- Perhaps NetCoreApp31Files | TargetFramework.Current -> currentReferences + + +module internal FSharpProjectSnapshotSerialization = + + let serializeSnapshotToJson (snapshot: FSharpProjectSnapshot) = + + JsonConvert.SerializeObject(snapshot, Formatting.Indented, new JsonSerializerSettings(ReferenceLoopHandling = ReferenceLoopHandling.Ignore)) \ No newline at end of file diff --git a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Async.fs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Async.fs index 704b0723c94..4e7028e692e 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Async.fs +++ b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Async.fs @@ -8,7 +8,7 @@ open BenchmarkDotNet.Attributes [] type AsyncWhileMemoryBench() = - [] + [] member val Length = 0 with get, set [] diff --git a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Benchmarks.fs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Benchmarks.fs index 366efa97439..a081437e1f0 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Benchmarks.fs +++ b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Benchmarks.fs @@ -1,8 +1,3 @@ -(* -msbuild tests\fsharp\perf\tasks\FS\TaskPerf.fsproj /p:Configuration=Release -dotnet artifacts\bin\TaskPerf\Release\netcoreapp2.1\TaskPerf.dll -*) - namespace TaskPerf open BenchmarkDotNet.Running @@ -10,9 +5,7 @@ open BenchmarkDotNet.Running module Main = [] - let main argv = + let main _ = printfn "Running benchmarks..." - //let results = BenchmarkRunner.Run() - //let results = BenchmarkRunner.Run() - let results = BenchmarkRunner.Run() + let _ = BenchmarkRunner.Run() 0 diff --git a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.cs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.cs index 409ed07ac55..93d5833555d 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.cs +++ b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.cs @@ -4,7 +4,7 @@ public class MicroPerfCSharp { // - // FSharp will not inline the code so we shouldn't eiter. + // FSharp will not inline the code so we shouldn't either. // [MethodImpl(MethodImplOptions.NoInlining)] public static int Cond(int x) diff --git a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.csproj b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.csproj index 96ac25da87b..50bba8f6f23 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.csproj +++ b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/CS/MicroPerfCSharp.csproj @@ -6,11 +6,10 @@ 8.0 - - - - - + + + $(NoWarn);CS1591 + diff --git a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Collections.fs b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Collections.fs index 1fdacc37fd9..fa6178e6778 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Collections.fs +++ b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/Collections.fs @@ -1,10 +1,6 @@ module Collections open BenchmarkDotNet.Attributes -open BenchmarkDotNet.Running -open BenchmarkDotNet.Configs -open BenchmarkDotNet.Diagnosers -open System.Runtime.CompilerServices [] [] @@ -15,7 +11,7 @@ type CollectionsBenchmark() = let mutable list = [] let mutable array = [||] - [] + [] member this.Length with get () = length and set (value) = diff --git a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/MicroPerf.fsproj b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/MicroPerf.fsproj index 81866aa5676..919c4cc073c 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/MicroPerf.fsproj +++ b/tests/benchmarks/CompiledCodeBenchmarks/MicroPerf/MicroPerf.fsproj @@ -2,13 +2,6 @@ net8.0 Exe - - $(NoWarn);NU1505 true $(OtherFlags) --nowarn:1204 @@ -16,13 +9,6 @@ $(OtherFlags) --nowarn:57 $(OtherFlags) --langversion:preview $(OtherFlags) --define:PREVIEW - - - @@ -30,6 +16,7 @@ + diff --git a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fs index 7f03c4d636b..6f89f4fd6eb 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fs +++ b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fs @@ -1,19 +1,11 @@ -(* -msbuild tests\benchmarks\CompiledCodeBenchmarks\TaskPerf\TaskPerf\TaskPerf.fsproj /p:Configuration=Release -dotnet artifacts\bin\TaskPerf\Release\net7.0\TaskPerf.dll -*) - namespace TaskPerf -//open FSharp.Control.Tasks open System -open System.Diagnostics open System.Threading.Tasks open System.IO open BenchmarkDotNet.Attributes open BenchmarkDotNet.Running open TaskBuilderTasks //.ContextSensitive // TaskBuilder.fs extension members -//open FSharp.Control.ContextSensitiveTasks // the default open FSharp.Control // AsyncSeq open Tests.SyncBuilder open BenchmarkDotNet.Configs diff --git a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fsproj b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fsproj index 4d29d42c536..9706167ff62 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fsproj +++ b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerf/TaskPerf.fsproj @@ -3,13 +3,6 @@ net8.0 Exe - - NU1505 true $(OtherFlags) --nowarn:1204 @@ -23,9 +16,6 @@ - @@ -37,14 +27,9 @@ - - - - + diff --git a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.csproj b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.csproj index 323d4d5ce6f..d23714e40f2 100644 --- a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.csproj +++ b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfCSharp/TaskPerfCSharp.csproj @@ -1,13 +1,18 @@  - net7.0 + net8.0 Library 8.0 + + + $(NoWarn);CS1591 + + - + diff --git a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/TaskPerfPreviousCompiler.fsproj b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/TaskPerfPreviousCompiler.fsproj deleted file mode 100644 index b71c47ac821..00000000000 --- a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/TaskPerfPreviousCompiler.fsproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net8.0 - Exe - true - $(OtherFlags) --define:ASYNC_PERF - true - - C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\FSharp - fsc.exe - - - - - - - - - - - - - - - - - - - diff --git a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/defs.fs b/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/defs.fs deleted file mode 100644 index 42cea70022c..00000000000 --- a/tests/benchmarks/CompiledCodeBenchmarks/TaskPerf/TaskPerfPreviousCompiler/defs.fs +++ /dev/null @@ -1,14 +0,0 @@ - -namespace Tests - -open System - -#if !PREVIEW - -[] -[] -type InlineIfLambdaAttribute() = - inherit Attribute() - -#endif - diff --git a/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/HistoricalBenchmark.fsproj b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/HistoricalBenchmark.fsproj index a477f61af81..2534ba292b5 100644 --- a/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/HistoricalBenchmark.fsproj +++ b/tests/benchmarks/FCSBenchmarks/BenchmarkComparison/HistoricalBenchmark.fsproj @@ -5,13 +5,6 @@ net8.0 true Release - - $(NoWarn);NU1505 diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/BackgroundCompilerBenchmarks.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/BackgroundCompilerBenchmarks.fs index 3b44c1d37bf..d7d643ab915 100644 --- a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/BackgroundCompilerBenchmarks.fs +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/BackgroundCompilerBenchmarks.fs @@ -6,6 +6,7 @@ open FSharp.Compiler.CodeAnalysis open FSharp.Compiler.Text open FSharp.Compiler.Diagnostics open FSharp.Test.ProjectGeneration +open BenchmarkDotNet.Engines [] @@ -152,10 +153,7 @@ type NoFileSystemCheckerBenchmark() = let mutable benchmark : ProjectWorkflowBuilder = Unchecked.defaultof<_> [] - member val UseGetSource = true with get,set - - [] - member val UseChangeNotifications = true with get,set + member val UseInMemoryDocuments = true with get,set [] member val EmptyCache = true with get,set @@ -165,8 +163,8 @@ type NoFileSystemCheckerBenchmark() = benchmark <- ProjectWorkflowBuilder( project, - useGetSource = this.UseGetSource, - useChangeNotifications = this.UseChangeNotifications).CreateBenchmarkBuilder() + useGetSource = this.UseInMemoryDocuments, + useChangeNotifications = this.UseInMemoryDocuments).CreateBenchmarkBuilder() [] member this.EditFirstFile_OnlyInternalChange() = @@ -178,15 +176,14 @@ type NoFileSystemCheckerBenchmark() = member this.ExampleWorkflow() = use _ = Activity.start "Benchmark" [ - "UseGetSource", this.UseGetSource.ToString() - "UseChangeNotifications", this.UseChangeNotifications.ToString() + "UseInMemoryDocuments", this.UseInMemoryDocuments.ToString() ] let first = "File001" let middle = $"File%03d{size / 2}" let last = $"File%03d{size}" - if this.UseGetSource && this.UseChangeNotifications then + if this.UseInMemoryDocuments then benchmark { updateFile first updatePublicSurface @@ -221,3 +218,215 @@ type NoFileSystemCheckerBenchmark() = [] member this.Cleanup() = benchmark.DeleteProjectDir() + + + +type TestProjectType = + | DependencyChain = 1 + | DependentGroups = 2 + | ParallelGroups = 3 + + +[] +[] +[] +[] +type TransparentCompilerBenchmark() = + + let size = 30 + + let groups = 6 + let filesPerGroup = size / groups + let somethingToCompile = File.ReadAllText (__SOURCE_DIRECTORY__ ++ "SomethingToCompileSmaller.fs") + + let projects = Map [ + + TestProjectType.DependencyChain, + SyntheticProject.Create("SingleDependencyChain", [| + sourceFile $"File%03d{0}" [] + for i in 1..size do + { sourceFile $"File%03d{i}" [$"File%03d{i-1}"] with ExtraSource = somethingToCompile } + |]) + + TestProjectType.DependentGroups, + SyntheticProject.Create("GroupDependenciesProject", [| + for group in 1..groups do + for i in 1..filesPerGroup do + { sourceFile $"G{group}_F%03d{i}" [ + if group > 1 then $"G1_F%03d{1}" + if i > 1 then $"G{group}_F%03d{i - 1}" ] + with ExtraSource = somethingToCompile } + |]) + + TestProjectType.ParallelGroups, + SyntheticProject.Create("ParallelGroupsProject", [| + for group in 1..groups do + for i in 1..filesPerGroup do + { sourceFile $"G{group}_F%03d{i}" [ + if group > 1 then + for i in 1..filesPerGroup do + $"G{group-1}_F%03d{i}" ] + with ExtraSource = somethingToCompile } + |]) + ] + + let mutable benchmark : ProjectWorkflowBuilder = Unchecked.defaultof<_> + + member val UseGetSource = true with get,set + + member val UseChangeNotifications = true with get,set + + //[] + member val EmptyCache = false with get,set + + [] + member val UseTransparentCompiler = true with get,set + + [] + member val ProjectType = TestProjectType.ParallelGroups with get,set + + member this.Project = projects[this.ProjectType] + + [] + member this.Setup() = + benchmark <- + ProjectWorkflowBuilder( + this.Project, + useGetSource = this.UseGetSource, + useChangeNotifications = this.UseChangeNotifications, + useTransparentCompiler = this.UseTransparentCompiler, + runTimeout = 15_000).CreateBenchmarkBuilder() + + [] + member this.EditFirstFile_OnlyInternalChange() = + if this.EmptyCache then + benchmark.Checker.InvalidateAll() + benchmark.Checker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() + + [] + member this.ExampleWorkflow() = + + use _ = Activity.start "Benchmark" [ + "UseTransparentCompiler", this.UseTransparentCompiler.ToString() + ] + + let first = this.Project.SourceFiles[0].Id + let middle = this.Project.SourceFiles[size / 2].Id + let last = this.Project.SourceFiles |> List.last |> fun f -> f.Id + + benchmark { + updateFile first updatePublicSurface + checkFile first expectSignatureChanged + checkFile last expectSignatureChanged + updateFile middle updatePublicSurface + checkFile last expectOk + addFileAbove middle (sourceFile "addedFile" [first]) + updateFile middle (addDependency "addedFile") + checkFile middle expectSignatureChanged + checkFile last expectOk + } + + [] + member this.Cleanup() = + benchmark.DeleteProjectDir() + + +[] +[] +[] +[] +type TransparentCompilerGiraffeBenchmark() = + + let mutable benchmark : ProjectWorkflowBuilder = Unchecked.defaultof<_> + + let rng = System.Random() + + let addComment s = $"{s}\n// {rng.NextDouble().ToString()}" + let prependSlash s = $"/{s}\n// {rng.NextDouble()}" + + let modify (sourceFile: SyntheticSourceFile) = + { sourceFile with Source = addComment sourceFile.Source } + + let break' (sourceFile: SyntheticSourceFile) = + { sourceFile with Source = prependSlash sourceFile.Source } + + let fix (sourceFile: SyntheticSourceFile) = + { sourceFile with Source = sourceFile.Source.Substring 1 } + + [] + member val UseTransparentCompiler = true with get,set + + [] + member val SignatureFiles = true with get,set + + member this.Project = + let projectDir = if this.SignatureFiles then "Giraffe-signatures" else "Giraffe" + + let project = SyntheticProject.CreateFromRealProject (__SOURCE_DIRECTORY__ ++ ".." ++ ".." ++ ".." ++ ".." ++ ".." ++ projectDir ++ "src/Giraffe") + { project with OtherOptions = "--nowarn:FS3520"::project.OtherOptions } + + [] + member this.Setup() = + benchmark <- + ProjectWorkflowBuilder( + this.Project, + useGetSource = true, + useChangeNotifications = true, + useTransparentCompiler = this.UseTransparentCompiler, + runTimeout = 15_000).CreateBenchmarkBuilder() + + //[] + member this.ChangeFirstCheckLast() = + + use _ = Activity.start "Benchmark" [ + "UseTransparentCompiler", this.UseTransparentCompiler.ToString() + ] + + benchmark { + updateFile this.Project.SourceFiles.Head.Id modify + checkFile (this.Project.SourceFiles |> List.last).Id expectOk + } + + //[] + member this.ChangeSecondCheckLast() = + + use _ = Activity.start "Benchmark" [ + "UseTransparentCompiler", this.UseTransparentCompiler.ToString() + ] + + benchmark { + updateFile this.Project.SourceFiles[1].Id modify + checkFile (this.Project.SourceFiles |> List.last).Id expectOk + } + + [] + member this.SomeWorkflow() = + + use _ = Activity.start "Benchmark" [ + "UseTransparentCompiler", this.UseTransparentCompiler.ToString() + ] + + benchmark { + updateFile "Json" modify + checkFile "Json" expectOk + checkFile "ModelValidation" expectOk + updateFile "ModelValidation" modify + checkFile "ModelValidation" expectOk + updateFile "Xml" modify + checkFile "Xml" expectOk + updateFile "ModelValidation" modify + checkFile "ModelValidation" expectOk + + updateFile "Core" break' + checkFile "Core" expectErrors + checkFile "Routing" (if this.SignatureFiles then expectOk else expectErrors) + updateFile "Routing" modify + checkFile "Streaming" (if this.SignatureFiles then expectOk else expectErrors) + checkFile "EndpointRouting" (if this.SignatureFiles then expectOk else expectErrors) + + updateFile "Core" fix + checkFile "Core" expectOk + checkFile "Routing" expectOk + checkFile "Streaming" expectOk + checkFile "EndpointRouting" expectOk + } \ No newline at end of file diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Benchmarks.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Benchmarks.fs deleted file mode 100644 index 5f282702bb0..00000000000 --- a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/Benchmarks.fs +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/CompilerServiceBenchmarks.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/CompilerServiceBenchmarks.fs index 679989520c2..4910b2e19eb 100644 --- a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/CompilerServiceBenchmarks.fs +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/CompilerServiceBenchmarks.fs @@ -124,13 +124,13 @@ type CompilerServiceBenchmarks() = |> Some [] - member _.ParsingTypeCheckerFs() = + member _.ParsingCheckExpressionsFs() = let config = getConfig() let results = config.Checker.ParseFile("CheckExpressions.fs", config.Source |> SourceText.toFSharpSourceText, parsingOptions) |> Async.RunSynchronously if results.ParseHadErrors then failwithf $"parse had errors: %A{results.Diagnostics}" - [] - member _.ParsingTypeCheckerFsSetup() = + [] + member _.ParsingCheckExpressionsFsSetup() = let checker = getConfig().Checker checker.InvalidateAll() checker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ComputationExpressionBenchmarks.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ComputationExpressionBenchmarks.fs new file mode 100644 index 00000000000..92a7141822d --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ComputationExpressionBenchmarks.fs @@ -0,0 +1,53 @@ +module FSharp.Benchmarks.ComputationExpressionBenchmarks + +open System.IO +open BenchmarkDotNet.Attributes +open FSharp.Compiler.CodeAnalysis +open FSharp.Test.ProjectGeneration + +[] +let FSharpCategory = "fsharp" + +[] +[] +type ComputationExpressionBenchmarks() = + + let mutable sourceFileName = "" + + [] + member public this.Source + with get () = File.ReadAllText(__SOURCE_DIRECTORY__ ++ "ce" ++ sourceFileName) + and set f = sourceFileName <- f + + member val Benchmark = Unchecked.defaultof<_> with get, set + + member this.setup(project) = + let checker = FSharpChecker.Create() + this.Benchmark <- ProjectWorkflowBuilder(project, checker = checker).CreateBenchmarkBuilder() + saveProject project false checker |> Async.RunSynchronously + + [] + member this.SetupWithSource() = + this.setup + { SyntheticProject.Create() with + SourceFiles = + [ + + { sourceFile "File" [] with + ExtraSource = this.Source + } + ] + OtherOptions = [] + } + + [] + member this.CheckCE() = + this.Benchmark { checkFile "File" expectOk } + + [] + member this.CompileCE() = this.Benchmark { compileWithFSC } diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/DecentlySizedStandAloneFileBenchmark.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/DecentlySizedStandAloneFileBenchmark.fs index f1525cfc734..58dcb885e50 100644 --- a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/DecentlySizedStandAloneFileBenchmark.fs +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/DecentlySizedStandAloneFileBenchmark.fs @@ -1,22 +1,61 @@ namespace FSharp.Compiler.Benchmarks open System.IO -open HistoricalBenchmark +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Text open BenchmarkDotNet.Attributes -type SingleFileCompilerWithILCacheClearing(file, options) = - inherit SingleFileCompiler(file, options) - - override this.Cleanup() = - base.Cleanup() - FSharp.Compiler.AbstractIL.ILBinaryReader.ClearAllILModuleReaderCache() +type private SingleFileCompilerConfig = + { + Checker : FSharpChecker + Options : FSharpProjectOptions + } [] type DecentlySizedStandAloneFileBenchmark() = - inherit SingleFileCompilerBenchmarkBase( - SingleFileCompilerWithILCacheClearing( - Path.Combine(__SOURCE_DIRECTORY__, "../decentlySizedStandAloneFile.fs"), - OptionsCreationMethod.FromScript - ) - ) + let mutable configOpt : SingleFileCompilerConfig option = None + let filePath = Path.Combine(__SOURCE_DIRECTORY__, "../decentlySizedStandAloneFile.fs") + + let getFileSourceText (filePath : string) = + let text = File.ReadAllText(filePath) + SourceText.ofString text + + let getConfig () = + configOpt + |> Option.defaultWith (fun () -> failwith "Setup not run") + + [] + member _.Setup() = + configOpt <- + match configOpt with + | Some _ -> configOpt + | None -> + let checker = FSharpChecker.Create(projectCacheSize = 200) + let options = + checker.GetProjectOptionsFromScript(filePath, getFileSourceText filePath) + |> Async.RunSynchronously + |> fst + { + Checker = checker + Options = options + } + |> Some + + [] + member _.Run() = + let config = getConfig() + let _, result = + config.Checker.ParseAndCheckFileInProject(filePath, 0, getFileSourceText filePath, config.Options) + |> Async.RunSynchronously + + match result with + | FSharpCheckFileAnswer.Aborted -> failwith "checker aborted" + | FSharpCheckFileAnswer.Succeeded results -> + if results.Diagnostics.Length > 0 then failwithf $"had errors: %A{results.Diagnostics}" + + [] + member _.Cleanup() = + let checker = getConfig().Checker + checker.InvalidateAll() + checker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj index a8c8ff31bc6..55968edddaf 100644 --- a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FSharp.Compiler.Benchmarks.fsproj @@ -4,13 +4,6 @@ Exe net8.0 true - - $(NoWarn);NU1505 false @@ -21,18 +14,17 @@ + - - diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FileCascadeBenchmarks.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FileCascadeBenchmarks.fs index 17822adeb96..686153577fa 100644 --- a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FileCascadeBenchmarks.fs +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/FileCascadeBenchmarks.fs @@ -68,7 +68,7 @@ let processFunc{number} (x) (func:MyFunctionType{number}) = }} //$COMMENTAREA$""" -/// Code create using FSharpCheckFileResults.GenerateSignature() +/// Code created using FSharpCheckFileResults.GenerateSignature() let generateFsi number = $""" module Benchmark{number} diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/benchmarks.ipynb b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/benchmarks.ipynb deleted file mode 100644 index 5fae6333c77..00000000000 --- a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/benchmarks.ipynb +++ /dev/null @@ -1,117 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "pwsh" - }, - "vscode": { - "languageId": "polyglot-notebook" - } - }, - "outputs": [], - "source": [ - "#!pwsh\n", - "dotnet build -c release\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "fsharp" - }, - "vscode": { - "languageId": "polyglot-notebook" - } - }, - "outputs": [], - "source": [ - "#r \"../../../artifacts/bin/FSharp.Compiler.Benchmarks/Release/net8.0/FSharp.Compiler.Benchmarks.dll\"\n", - "#r \"../../../artifacts/bin/FSharp.Compiler.Benchmarks/Release/net8.0/BenchmarkDotNet.dll\"" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "fsharp" - }, - "vscode": { - "languageId": "polyglot-notebook" - } - }, - "outputs": [], - "source": [ - "open BenchmarkDotNet.Running\n", - "open FSharp.Compiler.Benchmarks\n", - "\n", - "let summary = BenchmarkRunner.Run()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "fsharp" - }, - "vscode": { - "languageId": "polyglot-notebook" - } - }, - "outputs": [], - "source": [ - "// https://benchmarkdotnet.org/api/BenchmarkDotNet.Reports.BenchmarkReport.html\n", - "#r \"nuget: XPlot.Plotly.Interactive, 4.0.2\"\n", - "\n", - "open XPlot.Plotly\n", - "\n", - "let gcStats = summary.Reports |> Seq.map (fun x -> x.GcStats)\n", - "\n", - "let gen0Series =\n", - " Bar(\n", - " name = \"Gen 0\",\n", - " y = (gcStats |> Seq.map (fun x -> x.Gen0Collections))\n", - " )\n", - "\n", - "let gen1Series =\n", - " Bar(\n", - " name = \"Gen 1\",\n", - " y = (gcStats |> Seq.map (fun x -> x.Gen1Collections))\n", - " )\n", - "\n", - "let gen2Series =\n", - " Bar(\n", - " name = \"Gen 2\",\n", - " y = (gcStats |> Seq.map (fun x -> x.Gen2Collections))\n", - " )\n", - "\n", - "[gen0Series;gen1Series;gen2Series]\n", - "|> Chart.Plot\n", - "|> Chart.WithTitle(\"F# Type-Checking Benchmark 1 - GC Collection Counts\")" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": ".NET (C#)", - "language": "C#", - "name": ".net-csharp" - }, - "language_info": { - "file_extension": ".cs", - "mimetype": "text/x-csharp", - "name": "C#", - "pygments_lexer": "csharp", - "version": "9.0" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest1.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest1.fs new file mode 100644 index 00000000000..094513ff80c --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest1.fs @@ -0,0 +1,115 @@ +module SomeModule = + + type StrChainBuilder() = + member this.Zero() = "" + member this.Delay(f) = f () + member this.Yield(x: string) = x + member this.Combine(a, b) = a + b + + let strchain = StrChainBuilder() + + let test = + // 100 x nesting of 1 + strchain { + "test0" + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + strchain { "test1" } + } diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest10.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest10.fs new file mode 100644 index 00000000000..0afe4a1d3f6 --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest10.fs @@ -0,0 +1,3616 @@ +module SomeModule = + + type StrChainBuilder() = + member this.Zero() = "" + member this.Delay(f) = f () + member this.Yield(x: string) = x + member this.Combine(a, b) = a + b + + let strchain = StrChainBuilder() + + // 100 x nesting of 10 + let test = + strchain { + "test0" + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { + "test5" + + strchain { + "test6" + + strchain { + "test7" + + strchain { + "test8" + + strchain { + "test9" + strchain { "test10" } + } + } + } + } + } + } + } + } + } + } diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest5.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest5.fs new file mode 100644 index 00000000000..28ccd4c1593 --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE100xnest5.fs @@ -0,0 +1,1615 @@ +module SomeModule = + + type StrChainBuilder() = + member this.Zero() = "" + member this.Delay(f) = f () + member this.Yield(x: string) = x + member this.Combine(a, b) = a + b + + let strchain = StrChainBuilder() + + // 100 x nesting of 5 + let test = + strchain { + "test0" + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + strchain { "test5" } + } + } + } + } + } diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE200xnest5.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE200xnest5.fs new file mode 100644 index 00000000000..0295cec82cf --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CE200xnest5.fs @@ -0,0 +1,3615 @@ +module SomeModule = + + type StrChainBuilder() = + member this.Zero() = "" + member this.Delay(f) = f () + member this.Yield(x: string) = x + member this.Combine(a, b) = a + b + + let strchain = StrChainBuilder() + + // 200 x nesting of 5 + let test = + strchain { + "test0" + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + + strchain { + "test1" + + strchain { + "test2" + + strchain { + "test3" + + strchain { + "test4" + + strchain { "test5" } + } + } + } + } + } diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CEwCO100xnest5.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CEwCO100xnest5.fs new file mode 100644 index 00000000000..d196ed0d91a --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CEwCO100xnest5.fs @@ -0,0 +1,2937 @@ +module CalculationCE = + + type CalcState = { r: int } + + type CalculationBuilder() = + member _.Yield _ = { r = 0 } + member _.Return(x: int) = { r = x } + member _.ReturnFrom(x) = x + + [] + member _.Add(state: CalcState, x) = { r = state.r + x } + + [] + member _.Sub(state: CalcState, x) = { r = state.r - x } + + [] + member _.Mul(state: CalcState, x) = { r = state.r * x } + + [] + member _.Div(state: CalcState, x) = + if x = 0 then + failwith "can't divide by 0" + + { r = state.r / x } + + let calculation = CalculationBuilder() + +open CalculationCE + +// 100 x nesting of 5 +let c = + calculation { + + let c1 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c2 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c3 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c4 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c5 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c6 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c7 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c8 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c9 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c10 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c11 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c12 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c13 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c14 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c15 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c16 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c17 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c18 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c19 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c20 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c21 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c22 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c23 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c24 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c25 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c26 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c27 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c28 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c29 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c30 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c31 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c32 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c33 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c34 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c35 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c36 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c37 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c38 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c39 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c40 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c41 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c42 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c43 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c44 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c45 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c46 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c47 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c48 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c49 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c50 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c51 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c52 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c53 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c54 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c55 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c56 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c57 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c58 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c59 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c60 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c61 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c62 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c63 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c64 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c65 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c66 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c67 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c68 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c69 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c70 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c71 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c72 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c73 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c74 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c75 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c76 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c77 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c78 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c79 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c80 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c81 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c82 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c83 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c84 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c85 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c86 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c87 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c88 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c89 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c90 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c91 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c92 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c93 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c94 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c95 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c96 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c97 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c98 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c99 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let c100 = + calculation { + let nest2 = + calculation { + let nest3 = + calculation { + let nest4 = + calculation { + let nest5 = + calculation { + add 1 + sub 1 + mul 1 + div 1 + } + + return! nest5 + } + + return! nest4 + } + + return! nest3 + } + + return! nest2 + } + + let s = + [ c1.r + c2.r + c3.r + c4.r + c5.r + c6.r + c7.r + c8.r + c9.r + c10.r + c11.r + c12.r + c13.r + c14.r + c15.r + c16.r + c17.r + c18.r + c19.r + c20.r + c21.r + c22.r + c23.r + c24.r + c25.r + c26.r + c27.r + c28.r + c29.r + c30.r + c31.r + c32.r + c33.r + c34.r + c35.r + c36.r + c37.r + c38.r + c39.r + c40.r + c41.r + c42.r + c43.r + c44.r + c45.r + c46.r + c47.r + c48.r + c49.r + c50.r + c51.r + c52.r + c53.r + c54.r + c55.r + c56.r + c57.r + c58.r + c59.r + c60.r + c61.r + c62.r + c63.r + c64.r + c65.r + c66.r + c67.r + c68.r + c69.r + c70.r + c71.r + c72.r + c73.r + c74.r + c75.r + c76.r + c77.r + c78.r + c79.r + c80.r + c81.r + c82.r + c83.r + c84.r + c85.r + c86.r + c87.r + c88.r + c89.r + c90.r + c91.r + c92.r + c93.r + c94.r + c95.r + c96.r + c97.r + c98.r + c99.r + c100.r ] + + return! s |> List.sum + } diff --git a/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CEwCO500xnest1.fs b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CEwCO500xnest1.fs new file mode 100644 index 00000000000..c67f8e73528 --- /dev/null +++ b/tests/benchmarks/FCSBenchmarks/CompilerServiceBenchmarks/ce/CEwCO500xnest1.fs @@ -0,0 +1,539 @@ +module CalculationCE = + + type CalcState = + { r: int } + + type CalculationBuilder() = + member _.Yield _ = + { r = 0 } + + [] + member _.Add(state: CalcState, x) = + { state with + r = state.r + x } + + [] + member _.Sub(state: CalcState, x) = + { state with + r = state.r - x } + + [] + member _.Mul(state: CalcState, x) = + { state with + r = state.r * x } + + [] + member _.Div(state: CalcState, x) = + if x = 0 then + failwith "can't divide by 0" + { state with + r = state.r / x } + + let calculation = CalculationBuilder() + +open CalculationCE + +let c = + // 500 applications of custom operations + calculation { + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + add 1 + sub 1 + mul 1 + div 1 + } diff --git a/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/FCSSourceFiles.fsproj b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/FCSSourceFiles.fsproj index 5f0d38af2ef..3774aa87023 100644 --- a/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/FCSSourceFiles.fsproj +++ b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/FCSSourceFiles.fsproj @@ -3,6 +3,7 @@ Exe net8.0 + true diff --git a/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/Program.fs b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/Program.fs index 136897e081b..9c8148ed4da 100644 --- a/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/Program.fs +++ b/tests/benchmarks/FCSBenchmarks/FCSSourceFiles/Program.fs @@ -270,7 +270,7 @@ module Project = OriginalLoadReferences = [] Stamp = None } - FSharpReferencedProject.CreateFSharp( + FSharpReferencedProject.FSharpReference( __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\bin\FSharp.Core\Debug\netstandard2.1\FSharp.Core.dll", projectOptions ) @@ -459,7 +459,7 @@ module Project = OriginalLoadReferences = [] Stamp = None } - FSharpReferencedProject.CreateFSharp( + FSharpReferencedProject.FSharpReference( __SOURCE_DIRECTORY__ + @"\..\..\..\..\artifacts\bin\FSharp.DependencyManager.Nuget\Debug\netstandard2.0\FSharp.DependencyManager.Nuget.dll", projectOptions ) @@ -890,8 +890,7 @@ type CompilerService() = | 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.filter (fun filePath -> filePath.EndsWith("CheckDeclarations.fs")) |> Array.map (fun filePath -> filePath, SourceText.ofString (File.ReadAllText(filePath))) |> Some | _ -> () diff --git a/tests/benchmarks/Fsharp.ProfilingStartpointProject/Fsharp.ProfilingStartpointProject.fsproj b/tests/benchmarks/Fsharp.ProfilingStartpointProject/Fsharp.ProfilingStartpointProject.fsproj deleted file mode 100644 index 6cb9e4bd78c..00000000000 --- a/tests/benchmarks/Fsharp.ProfilingStartpointProject/Fsharp.ProfilingStartpointProject.fsproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - net8.0 - - - - - - - - - - - diff --git a/tests/benchmarks/Fsharp.ProfilingStartpointProject/Program.fs b/tests/benchmarks/Fsharp.ProfilingStartpointProject/Program.fs deleted file mode 100644 index 5d851e60865..00000000000 --- a/tests/benchmarks/Fsharp.ProfilingStartpointProject/Program.fs +++ /dev/null @@ -1,47 +0,0 @@ -open FSharp.Compiler.Benchmarks - -open System -open System.IO -open System.Text -open FSharp.Compiler.CodeAnalysis -open FSharp.Compiler.Diagnostics -open FSharp.Compiler.EditorServices -open FSharp.Compiler.Text -open FSharp.Compiler.AbstractIL.IL -open FSharp.Compiler.AbstractIL.ILBinaryReader -open BenchmarkDotNet.Attributes -open FSharp.Compiler.Benchmarks -open Microsoft.CodeAnalysis.Text -open BenchmarkDotNet.Order -open BenchmarkDotNet.Mathematics - -let bench = new FileCascadeBenchmarks() -bench.GenerateFSI <- true -do bench.Setup() - -(* -This project was created as an easy entry point for low-level profiling of FCS operations. -The only purpose is the easy of setup (simply set as startup project and launch) so that a profiler can be connected. -There is definitely no harm in deleting it if it starts bothering anyone. -*) - - -[] -let main args = - - match args |> Array.toList with - | ["no-change"] -> - for i=1 to 256 do - printfn "***************************" - printfn "ITERATION %i" i - printfn "***************************" - bench.ParseAndCheckLastFileProjectAsIs() |> ignore - | ["mid-change"] -> - for i=1 to 16 do - printfn "***************************" - printfn "ITERATION %i" i - printfn "***************************" - bench.ParseProjectWithChangingMiddleFile() |> ignore - | _ -> failwith "Invalid args. Use cache-clear or mid-change" - |> ignore - 0 diff --git a/tests/fsharp/Compiler/Libraries/Core/Operators/AbsTests.fs b/tests/fsharp/Compiler/Libraries/Core/Operators/AbsTests.fs index ca2f753de4e..a6e07ba38e4 100644 --- a/tests/fsharp/Compiler/Libraries/Core/Operators/AbsTests.fs +++ b/tests/fsharp/Compiler/Libraries/Core/Operators/AbsTests.fs @@ -29,7 +29,7 @@ abs -1uy |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'byte' does not support the operator 'Abs'" + "The type 'byte' does not support the operator 'abs'" [] let ``Abs of uint16``() = @@ -40,7 +40,7 @@ abs -1us |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'uint16' does not support the operator 'Abs'" + "The type 'uint16' does not support the operator 'abs'" [] let ``Abs of uint32``() = @@ -51,7 +51,7 @@ abs -1ul |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'uint32' does not support the operator 'Abs'" + "The type 'uint32' does not support the operator 'abs'" CompilerAssert.TypeCheckSingleError """ @@ -60,7 +60,7 @@ abs -1u |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 8) - "The type 'uint32' does not support the operator 'Abs'" + "The type 'uint32' does not support the operator 'abs'" [] let ``Abs of unativeint``() = @@ -71,7 +71,7 @@ abs -1un |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'unativeint' does not support the operator 'Abs'" + "The type 'unativeint' does not support the operator 'abs'" [] let ``Abs of uint64``() = @@ -82,7 +82,7 @@ abs -1uL |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'uint64' does not support the operator 'Abs'" + "The type 'uint64' does not support the operator 'abs'" CompilerAssert.TypeCheckSingleError """ @@ -91,4 +91,4 @@ abs -1UL |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'uint64' does not support the operator 'Abs'" \ No newline at end of file + "The type 'uint64' does not support the operator 'abs'" \ No newline at end of file diff --git a/tests/fsharp/Compiler/Libraries/Core/Operators/SignTests.fs b/tests/fsharp/Compiler/Libraries/Core/Operators/SignTests.fs index 2c67b1d1b8d..ca3edf8b377 100644 --- a/tests/fsharp/Compiler/Libraries/Core/Operators/SignTests.fs +++ b/tests/fsharp/Compiler/Libraries/Core/Operators/SignTests.fs @@ -45,7 +45,7 @@ sign 0uy |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'byte' does not support the operator 'get_Sign'" + "The type 'byte' does not support the operator 'sign'" [] let ``Sign of uint16``() = @@ -56,7 +56,7 @@ sign 0us |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'uint16' does not support the operator 'get_Sign'" + "The type 'uint16' does not support the operator 'sign'" [] let ``Sign of uint32``() = @@ -67,7 +67,7 @@ sign 0u |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 8) - "The type 'uint32' does not support the operator 'get_Sign'" + "The type 'uint32' does not support the operator 'sign'" [] let ``Sign of uint64``() = @@ -78,4 +78,4 @@ sign 0uL |> ignore FSharpDiagnosticSeverity.Error 1 (2, 6, 2, 9) - "The type 'uint64' does not support the operator 'get_Sign'" \ No newline at end of file + "The type 'uint64' does not support the operator 'sign'" \ No newline at end of file diff --git a/tests/fsharp/typecheck/sigs/neg06.bsl b/tests/fsharp/typecheck/sigs/neg06.bsl index 0443bd5c4a9..d55e3e948d2 100644 --- a/tests/fsharp/typecheck/sigs/neg06.bsl +++ b/tests/fsharp/typecheck/sigs/neg06.bsl @@ -64,27 +64,27 @@ neg06.fs(128,53,128,61): typecheck error FS0043: A type parameter is missing a c neg06.fs(141,10,141,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(148,13,148,21): typecheck error FS0039: The value or constructor 'BadType1' is not defined. +neg06.fs(148,13,148,21): typecheck error FS0800: Invalid use of a type name neg06.fs(150,10,150,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(157,13,157,21): typecheck error FS0039: The value or constructor 'BadType2' is not defined. +neg06.fs(157,13,157,21): typecheck error FS0800: Invalid use of a type name neg06.fs(159,10,159,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(166,13,166,21): typecheck error FS0039: The value or constructor 'BadType3' is not defined. +neg06.fs(166,13,166,21): typecheck error FS0800: Invalid use of a type name neg06.fs(195,10,195,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(203,13,203,21): typecheck error FS0039: The value or constructor 'BadType1' is not defined. +neg06.fs(203,13,203,21): typecheck error FS0800: Invalid use of a type name neg06.fs(205,10,205,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(213,13,213,21): typecheck error FS0039: The value or constructor 'BadType2' is not defined. +neg06.fs(213,13,213,21): typecheck error FS0800: Invalid use of a type name neg06.fs(215,10,215,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(223,13,223,21): typecheck error FS0039: The value or constructor 'BadType3' is not defined. +neg06.fs(223,13,223,21): typecheck error FS0800: Invalid use of a type name neg06.fs(300,10,300,12): typecheck error FS0009: Uses of this construct may result in the generation of unverifiable .NET IL code. This warning can be disabled using '--nowarn:9' or '#nowarn "9"'. @@ -100,11 +100,11 @@ neg06.fs(320,10,320,12): typecheck error FS0937: Only structs and classes withou neg06.fs(326,10,326,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(335,13,335,21): typecheck error FS0039: The value or constructor 'BadType4' is not defined. +neg06.fs(335,13,335,21): typecheck error FS0800: Invalid use of a type name neg06.fs(340,10,340,18): typecheck error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation -neg06.fs(350,13,350,21): typecheck error FS0039: The value or constructor 'BadType4' is not defined. +neg06.fs(350,13,350,21): typecheck error FS0800: Invalid use of a type name neg06.fs(375,9,375,10): typecheck error FS1197: The parameter 'x' was inferred to have byref type. Parameters of byref type must be given an explicit type annotation, e.g. 'x1: byref'. When used, a byref parameter is implicitly dereferenced. diff --git a/tests/fsharp/typecheck/sigs/neg61.bsl b/tests/fsharp/typecheck/sigs/neg61.bsl index b1ba15a77ad..e0b2fb5eafb 100644 --- a/tests/fsharp/typecheck/sigs/neg61.bsl +++ b/tests/fsharp/typecheck/sigs/neg61.bsl @@ -71,7 +71,7 @@ neg61.fs(111,13,111,24): typecheck error FS3144: 'return' and 'return!' may not neg61.fs(114,13,114,21): typecheck error FS3145: This is not a known query operator. Query operators are identifiers such as 'select', 'where', 'sortBy', 'thenBy', 'groupBy', 'groupValBy', 'join', 'groupJoin', 'sumBy' and 'averageBy', defined using corresponding methods on the 'QueryBuilder' type. -neg61.fs(114,22,114,23): typecheck error FS0001: The type 'int' does not support the operator 'Truncate' +neg61.fs(114,22,114,23): typecheck error FS0001: The type 'int' does not support the operator 'truncate' neg61.fs(133,17,133,20): typecheck error FS3147: This 'let' definition may not be used in a query. Only simple value definitions may be used in queries. diff --git a/tests/fsharpqa/Source/Conformance/Expressions/ExpressionQuotations/Baselines/E_Cast.fs b/tests/fsharpqa/Source/Conformance/Expressions/ExpressionQuotations/Baselines/E_Cast.fs index fdfeed0171e..bd3772bf30c 100644 --- a/tests/fsharpqa/Source/Conformance/Expressions/ExpressionQuotations/Baselines/E_Cast.fs +++ b/tests/fsharpqa/Source/Conformance/Expressions/ExpressionQuotations/Baselines/E_Cast.fs @@ -1,7 +1,6 @@ // #Regression #Conformance #Quotations // Verify type annotation is required for casting quotes -//Value restriction\. The value 'tq' has been inferred to have generic type. val tq: Expr<'_a> .Either define 'tq' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation\.$ -// +//Value restriction: The value 'tq' has an inferred generic type val tq: Expr<'_a>However, values cannot have generic type variables like '_a in "let x: '_a"\. You can do one of the following:- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"- Add an explicit type annotation like "let x : int"- Use the value as a non-generic type in later code for type inference like "do x"or if you still want type-dependent results, you can define 'tq' as a function instead by doing either:- Add a unit parameter like "let x\(\)"- Write explicit type parameters like "let x<'a>".This error is because a let binding without parameters defines a value, not a function\. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results\.$ open Microsoft.FSharp.Quotations diff --git a/tests/fsharpqa/Source/Conformance/InferenceProcedures/ConstraintSolving/E_ValueRestriction01.fs b/tests/fsharpqa/Source/Conformance/InferenceProcedures/ConstraintSolving/E_ValueRestriction01.fs index d66cc047dc4..cf485b37d8c 100644 --- a/tests/fsharpqa/Source/Conformance/InferenceProcedures/ConstraintSolving/E_ValueRestriction01.fs +++ b/tests/fsharpqa/Source/Conformance/InferenceProcedures/ConstraintSolving/E_ValueRestriction01.fs @@ -3,13 +3,16 @@ // Verify error associated with open type variable -(* -error FS0030: Value restriction. The value 'x' has been inferred to have generic type - val x : '_a list ref -Either define 'x' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type constraint. -*) -//Value restriction. The value - +//Value restriction: The value 'x' has an inferred generic type +// val x: '_a list ref +//However, values cannot have generic type variables like '_a in "let x: '_a"\. You can do one of the following: +//- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1" +//- Add an explicit type annotation like "let x : int" +//- Use the value as a non-generic type in later code for type inference like "do x" +//or if you still want type-dependent results, you can define 'x' as a function instead by doing either: +//- Add a unit parameter like "let x()" +//- Write explicit type parameters like "let x<'a>"\. +//This error is because a let binding without parameters defines a value, not a function\. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results\.$ let x = ref [] exit 1 diff --git a/tests/fsharpqa/Source/Conformance/InferenceProcedures/DispatchSlotInference/E_GenInterfaceWGenMethods01.fs b/tests/fsharpqa/Source/Conformance/InferenceProcedures/DispatchSlotInference/E_GenInterfaceWGenMethods01.fs index 5d87e71957e..8a65831546e 100644 --- a/tests/fsharpqa/Source/Conformance/InferenceProcedures/DispatchSlotInference/E_GenInterfaceWGenMethods01.fs +++ b/tests/fsharpqa/Source/Conformance/InferenceProcedures/DispatchSlotInference/E_GenInterfaceWGenMethods01.fs @@ -1,7 +1,7 @@ // #Regression #Conformance #TypeInference // FSHARP1.0:1445. See also FSHARP1.0:4721 // Failure when generating code for generic interface with generic method -//Value restriction\. The value 'result' has been inferred to have generic type. val result: '_a array when '_a: equality and '_a: null .Either define 'result' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation\.$ +//Value restriction: The value 'result' has an inferred generic type val result: '_a array when '_a: equality and '_a: nullHowever, values cannot have generic type variables like '_a in "let x: '_a"\. You can do one of the following:- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"- Add an explicit type annotation like "let x : int"- Use the value as a non-generic type in later code for type inference like "do x"or if you still want type-dependent results, you can define 'result' as a function instead by doing either:- Add a unit parameter like "let x\(\)"- Write explicit type parameters like "let x<'a>".This error is because a let binding without parameters defines a value, not a function\. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results\.$ type 'a IFoo = interface abstract DoStuff<'b> : 'a -> 'b array end diff --git a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/ClassTypes/ValueRestriction/E_NotMemberOrFunction01.fsx b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/ClassTypes/ValueRestriction/E_NotMemberOrFunction01.fsx index 182fb04be48..a33da54e3f9 100644 --- a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/ClassTypes/ValueRestriction/E_NotMemberOrFunction01.fsx +++ b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/ClassTypes/ValueRestriction/E_NotMemberOrFunction01.fsx @@ -1,6 +1,6 @@ // #Conformance #ObjectOrientedTypes #Classes #TypeInference #ValueRestriction -//Value restriction\. The value 'x1' has been inferred to have generic type. val x1: \('_a -> unit\) .Either make the arguments to 'x1' explicit or, if you do not intend for it to be generic, add a type annotation\.$ +//Value restriction: The value 'x1' has an inferred generic function type val x1: \('_a -> unit\)However, values cannot have generic type variables like '_a in "let f: '_a". You should define 'x1' as a function instead by doing one of the following:- Add an explicit parameter that is applied instead of using a partial application "let f param"- Add a unit parameter like "let f\(\)"- Write explicit type parameters like "let f<'a>"or if you do not intend for it to be generic, either:- Add an explicit type annotation like "let f : obj -> obj"- Apply arguments of non-generic types to the function value in later code for type inference like "do f\(\)"\.This error is because a let binding without parameters defines a value, not a function\. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results\.$ // We expect a value restriction here. The inferred signature is: // val x1: (?1 -> unit) @@ -8,4 +8,4 @@ // variable could have feasibly be genrealized at 'x1' (c.f. the case above, where it // was generalized). let f1 (x:obj) = () -let x1 = ((); f1) \ No newline at end of file +let x1 = ((); f1) diff --git a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/EnumTypes/E_NoMethodsOnEnums01.fs b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/EnumTypes/E_NoMethodsOnEnums01.fs index b4e05661698..dca7226146d 100644 --- a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/EnumTypes/E_NoMethodsOnEnums01.fs +++ b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/EnumTypes/E_NoMethodsOnEnums01.fs @@ -1,6 +1,5 @@ // #Regression #Conformance #ObjectOrientedTypes #Enums -//Enumerations cannot have members$ -//The type 'Season' does not support the operator 'get_One'$ +//Enumerations cannot have members$ type Season = Spring=0 | Summer=1 | Autumn=2 | Winter=3 with @@ -8,5 +7,3 @@ type Season = Spring=0 | Summer=1 | Autumn=2 | Winter=3 let starti = Enum.to_int start let stopi = Enum.to_int stop { for i in starti .. stopi -> Enum.of_int i } - -printfn "%A" [Season.Spring .. Season.Autumn] diff --git a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric01.fs b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric01.fs index 2d426f6244f..9324d3e4902 100644 --- a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric01.fs +++ b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric01.fs @@ -3,7 +3,7 @@ // Regression for FSB 3417 //This type definition involves an immediate cyclic reference through a struct field or inheritance relation -//The value or constructor 'BadType4' is not defined +//Invalid use of a type name type BadType4 = struct diff --git a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric02.fs b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric02.fs index 21854ced87a..f90ab777f41 100644 --- a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric02.fs +++ b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_InvalidRecursiveGeneric02.fs @@ -3,7 +3,7 @@ // Regression for FSB 3417 //This type definition involves an immediate cyclic reference through a struct field or inheritance relation -//The value or constructor 'BadType4' is not defined +//Invalid use of a type name type BadType4 = struct diff --git a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_StructConstruction03.fs b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_StructConstruction03.fs index de295146093..0ee07b3415e 100644 --- a/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_StructConstruction03.fs +++ b/tests/fsharpqa/Source/Conformance/ObjectOrientedTypeDefinitions/StructTypes/E_StructConstruction03.fs @@ -2,8 +2,8 @@ // Regression test for FSHARP1.0:3143 //This type definition involves an immediate cyclic reference through a struct field or inheritance relation$ //This declaration element is not permitted in an augmentation$ -//The value or constructor 'S' is not defined -//The value or constructor 'S' is not defined +//Invalid use of a type name +//Invalid use of a type name type S(x:S) = struct end diff --git a/tests/fsharpqa/Source/Conformance/UnitsOfMeasure/Diagnostics/W_NonGenVarInValueRestrictionWarning.fs b/tests/fsharpqa/Source/Conformance/UnitsOfMeasure/Diagnostics/W_NonGenVarInValueRestrictionWarning.fs index 12ca2be2ce8..6552aa57379 100644 --- a/tests/fsharpqa/Source/Conformance/UnitsOfMeasure/Diagnostics/W_NonGenVarInValueRestrictionWarning.fs +++ b/tests/fsharpqa/Source/Conformance/UnitsOfMeasure/Diagnostics/W_NonGenVarInValueRestrictionWarning.fs @@ -1,7 +1,7 @@ // #Regression #Conformance #UnitsOfMeasure #Diagnostics // Regression test for FSHARP1.0:4969 // Non-generalized unit-of-measure variables should display with "_" in value restriction warning -//.+val x: float<'_u> list ref -//.+val y: '_a list ref +//Value restriction: The value 'x' has an inferred generic type val x: float<'_u> list refHowever, values cannot have generic type variables like '_a in "let x: '_a"\. You can do one of the following:- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"- Add an explicit type annotation like "let x : int"- Use the value as a non-generic type in later code for type inference like "do x"or if you still want type-dependent results, you can define 'x' as a function instead by doing either:- Add a unit parameter like "let x\(\)"- Write explicit type parameters like "let x<'a>".This error is because a let binding without parameters defines a value, not a function\. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results\. +//Value restriction: The value 'y' has an inferred generic type val y: '_a list refHowever, values cannot have generic type variables like '_a in "let x: '_a"\. You can do one of the following:- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"- Add an explicit type annotation like "let x : int"- Use the value as a non-generic type in later code for type inference like "do x"or if you still want type-dependent results, you can define 'y' as a function instead by doing either:- Add a unit parameter like "let x\(\)"- Write explicit type parameters like "let x<'a>".This error is because a let binding without parameters defines a value, not a function\. Values cannot be generic because reading a value is assumed to result in the same everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results\.$ let x = ref ([] : float<_> list) let y = ref ([] : _ list) diff --git a/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01.fs b/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01.fs index 8e2724f49ce..cfbd4185bd4 100644 --- a/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01.fs +++ b/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01.fs @@ -1,8 +1,8 @@ // #Regression #Diagnostics // Regression test for DevDiv:64339 // Note that the bug still repros in CHK/DBG bits - we will knownfail it -//Unexpected keyword 'lazy' in type definition$ -//Unexpected keyword 'lazy'$ +//Unexpected keyword 'lazy' in pattern$ +//Unexpected keyword 'lazy' in pattern$ // 5 elements -> ok type Ok(a, b, c, d, e : lazy) = class end diff --git a/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01b.fs b/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01b.fs index 8e2724f49ce..cfbd4185bd4 100644 --- a/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01b.fs +++ b/tests/fsharpqa/Source/Diagnostics/NONTERM/tuplewithlazy01b.fs @@ -1,8 +1,8 @@ // #Regression #Diagnostics // Regression test for DevDiv:64339 // Note that the bug still repros in CHK/DBG bits - we will knownfail it -//Unexpected keyword 'lazy' in type definition$ -//Unexpected keyword 'lazy'$ +//Unexpected keyword 'lazy' in pattern$ +//Unexpected keyword 'lazy' in pattern$ // 5 elements -> ok type Ok(a, b, c, d, e : lazy) = class end diff --git a/tests/projects/Sample_Local_Compiler_and_FSLib/LocalCompilerAndFslib.fsproj b/tests/projects/Sample_Local_Compiler_and_FSLib/LocalCompilerAndFslib.fsproj new file mode 100644 index 00000000000..c2164b65666 --- /dev/null +++ b/tests/projects/Sample_Local_Compiler_and_FSLib/LocalCompilerAndFslib.fsproj @@ -0,0 +1,23 @@ + + + + Exe + net8.0 + preview + true + + + + true + $(MSBuildThisFileDirectory)../../../artifacts/bin/fsc/Debug/net8.0/fsc.dll + $(MSBuildThisFileDirectory)../../../artifacts/bin/fsc/Debug/net8.0/fsc.dll + False + True + + + + + + + + diff --git a/tests/projects/Sample_Local_Compiler_and_FSLib/Program.fs b/tests/projects/Sample_Local_Compiler_and_FSLib/Program.fs new file mode 100644 index 00000000000..1ffa8063569 --- /dev/null +++ b/tests/projects/Sample_Local_Compiler_and_FSLib/Program.fs @@ -0,0 +1,25 @@ +module Program + +type CBuilder() = + [] + member this.Foo _ = "Foo" + [] + member this.foo _ = "foo" + member this.Yield _ = () + member this.Zero _ = () + + +[] +let main _ = + let cb = CBuilder() + + let x = cb { Foo } + let y = cb { foo } + printfn $"{x}" + printfn $"{y}" + + if x <> "Foo" then + failwith "not Foo" + if y <> "foo" then + failwith "not foo" + 0 diff --git a/tests/projects/misc/SelfDefinedTailCallAttribute/Attribute.fs b/tests/projects/misc/SelfDefinedTailCallAttribute/Attribute.fs new file mode 100644 index 00000000000..afa7331896d --- /dev/null +++ b/tests/projects/misc/SelfDefinedTailCallAttribute/Attribute.fs @@ -0,0 +1,6 @@ +module Microsoft.FSharp.Core + + open System + + [] + type TailCallAttribute() = inherit Attribute() diff --git a/tests/projects/misc/SelfDefinedTailCallAttribute/Program.fs b/tests/projects/misc/SelfDefinedTailCallAttribute/Program.fs new file mode 100644 index 00000000000..7652c7c2ecb --- /dev/null +++ b/tests/projects/misc/SelfDefinedTailCallAttribute/Program.fs @@ -0,0 +1,13 @@ +namespace N + + module M = + + open Microsoft.FSharp.Core + + [] + let rec f x = 1 + f x + + [] + let main argv = + printfn "Hello from F#" + 0 diff --git a/tests/projects/misc/SelfDefinedTailCallAttribute/tailcallaltattr.fsproj b/tests/projects/misc/SelfDefinedTailCallAttribute/tailcallaltattr.fsproj new file mode 100644 index 00000000000..92c5ae861d4 --- /dev/null +++ b/tests/projects/misc/SelfDefinedTailCallAttribute/tailcallaltattr.fsproj @@ -0,0 +1,20 @@ + + + Exe + net6.0 + true + preview + + + + $(MSBuildThisFileDirectory)../../../../artifacts/bin/fsc/Debug/net8.0/fsc.dll + + + + + + + + + + \ No newline at end of file diff --git a/tests/service/Common.fs b/tests/service/Common.fs index a8d4782de0d..8516948626a 100644 --- a/tests/service/Common.fs +++ b/tests/service/Common.fs @@ -31,7 +31,7 @@ type Async with task.Result // Create one global interactive checker instance -let checker = FSharpChecker.Create() +let checker = FSharpChecker.Create(useTransparentCompiler=FSharp.Compiler.CompilerConfig.FSharpExperimentalFeaturesEnabledAutomatically) type TempFile(ext, contents: string) = let tmpFile = Path.ChangeExtension(tryCreateTemporaryFileName (), ext) @@ -137,8 +137,8 @@ let mkTestFileAndOptions source additionalArgs = let fileSource1 = "module M" FileSystem.OpenFileForWriteShim(fileName).Write(fileSource1) - let args = Array.append (mkProjectCommandLineArgs (dllName, [fileName])) additionalArgs - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let args = Array.append (mkProjectCommandLineArgs (dllName, [])) additionalArgs + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = [| fileName |] } fileName, options let parseAndCheckFile fileName source options = @@ -158,7 +158,7 @@ let parseAndCheckScriptWithOptions (file:string, input, opts) = let fname = Path.Combine(path, Path.GetFileName(file)) let dllName = Path.ChangeExtension(fname, ".dll") let projName = Path.ChangeExtension(fname, ".fsproj") - let args = mkProjectCommandLineArgsForScript (dllName, [file]) + let args = mkProjectCommandLineArgsForScript (dllName, []) printfn "file = %A, args = %A" file args checker.GetProjectOptionsFromCommandLineArgs (projName, args) @@ -171,7 +171,7 @@ let parseAndCheckScriptWithOptions (file:string, input, opts) = //printfn "projectOptions = %A" projectOptions #endif - let projectOptions = { projectOptions with OtherOptions = Array.append opts projectOptions.OtherOptions } + let projectOptions = { projectOptions with OtherOptions = Array.append opts projectOptions.OtherOptions; SourceFiles = [|file|] } let parseResult, typedRes = checker.ParseAndCheckFileInProject(file, 0, SourceText.ofString input, projectOptions) |> Async.RunImmediate // if parseResult.Errors.Length > 0 then diff --git a/tests/service/ExprTests.fs b/tests/service/ExprTests.fs index 662a60edc80..7b35568e38d 100644 --- a/tests/service/ExprTests.fs +++ b/tests/service/ExprTests.fs @@ -364,8 +364,8 @@ let createOptionsAux fileSources extraArgs = Utils.createTempDir() for fileSource: string, fileName in List.zip fileSources fileNames do FileSystem.OpenFileForWriteShim(fileName).Write(fileSource) - let args = [| yield! extraArgs; yield! mkProjectCommandLineArgs (dllName, fileNames) |] - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let args = [| yield! extraArgs; yield! mkProjectCommandLineArgs (dllName, []) |] + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames |> List.toArray } Utils.cleanupTempFiles (fileNames @ [dllName; projFileName]), options @@ -732,11 +732,13 @@ let ignoreTestIfStackOverflowExpected () = #endif /// This test is run in unison with its optimized counterpart below +[] +[] [] -let ``Test Unoptimized Declarations Project1`` () = +let ``Test Unoptimized Declarations Project1`` useTransparentCompiler = let cleanup, options = Project1.createOptionsWithArgs [ "--langversion:preview" ] use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -871,11 +873,13 @@ let ``Test Unoptimized Declarations Project1`` () = () +[] +[] [] -let ``Test Optimized Declarations Project1`` () = +let ``Test Optimized Declarations Project1`` useTransparentCompiler = let cleanup, options = Project1.createOptionsWithArgs [ "--langversion:preview" ] use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -1017,7 +1021,7 @@ let testOperators dnName fsName excludedTests expectedUnoptimized expectedOptimi let filePath = Utils.getTempFilePathChangeExt tempFileName ".fs" let dllPath =Utils.getTempFilePathChangeExt tempFileName ".dll" let projFilePath = Utils.getTempFilePathChangeExt tempFileName ".fsproj" - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=true) begin use _cleanup = Utils.cleanupTempFiles [filePath; dllPath; projFilePath] @@ -1027,9 +1031,9 @@ let testOperators dnName fsName excludedTests expectedUnoptimized expectedOptimi let fileSource = excludedTests |> List.fold replace source FileSystem.OpenFileForWriteShim(filePath).Write(fileSource) - let args = mkProjectCommandLineArgsSilent (dllPath, [filePath]) + let args = mkProjectCommandLineArgsSilent (dllPath, []) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFilePath, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFilePath, args) with SourceFiles = [|filePath|] } let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate let referencedAssemblies = wholeProjectResults.ProjectContext.GetReferencedAssemblies() @@ -3206,12 +3210,14 @@ let BigSequenceExpression(outFileOpt,docFileOpt,baseAddressOpt) = let createOptions() = createOptionsAux [fileSource1] [] +[] +[] [] -let ``Test expressions of declarations stress big expressions`` () = +let ``Test expressions of declarations stress big expressions`` useTransparentCompiler = ignoreTestIfStackOverflowExpected () let cleanup, options = ProjectStressBigExpressions.createOptions() use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate wholeProjectResults.Diagnostics.Length |> shouldEqual 0 @@ -3223,12 +3229,14 @@ let ``Test expressions of declarations stress big expressions`` () = printDeclarations None (List.ofSeq file1.Declarations) |> Seq.toList |> ignore +[] +[] [] -let ``Test expressions of optimized declarations stress big expressions`` () = +let ``Test expressions of optimized declarations stress big expressions`` useTransparentCompiler = ignoreTestIfStackOverflowExpected () let cleanup, options = ProjectStressBigExpressions.createOptions() use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate wholeProjectResults.Diagnostics.Length |> shouldEqual 0 @@ -3284,11 +3292,13 @@ let f8() = callXY (D()) (C()) let createOptions() = createOptionsAux [fileSource1] ["--langversion:7.0"] +[] +[] [] -let ``Test ProjectForWitnesses1`` () = +let ``Test ProjectForWitnesses1`` useTransparentCompiler = let cleanup, options = ProjectForWitnesses1.createOptions() use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -3328,11 +3338,13 @@ let ``Test ProjectForWitnesses1`` () = |> shouldPairwiseEqual expected +[] +[] [] -let ``Test ProjectForWitnesses1 GetWitnessPassingInfo`` () = +let ``Test ProjectForWitnesses1 GetWitnessPassingInfo`` useTransparentCompiler = let cleanup, options = ProjectForWitnesses1.createOptions() use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -3408,11 +3420,13 @@ type MyNumberWrapper = let createOptions() = createOptionsAux [fileSource1] ["--langversion:7.0"] +[] +[] [] -let ``Test ProjectForWitnesses2`` () = +let ``Test ProjectForWitnesses2`` useTransparentCompiler = let cleanup, options = ProjectForWitnesses2.createOptions() use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -3428,7 +3442,6 @@ let ``Test ProjectForWitnesses2`` () = "member Neg(p) = {x = Operators.op_UnaryNegation (fun arg0_0 -> LanguagePrimitives.UnaryNegationDynamic (arg0_0),p.x); y = Operators.op_UnaryNegation (fun arg0_0 -> LanguagePrimitives.UnaryNegationDynamic (arg0_0),p.y)} @ (7,34--7,56)"; "member op_Addition(p1,p2) = {x = Operators.op_Addition (fun arg0_0 -> fun arg1_0 -> LanguagePrimitives.AdditionDynamic (arg0_0,arg1_0),p1.x,p2.x); y = Operators.op_Addition (fun arg0_0 -> fun arg1_0 -> LanguagePrimitives.AdditionDynamic (arg0_0,arg1_0),p1.y,p2.y)} @ (8,33--8,68)"; "type MyNumber"; - "member get_IsMyNumber(this) (unitArg) = (if this.IsMyNumber then True else False) @ (10,5--10,13)"; "member get_Zero(unitVar0) = MyNumber(0) @ (12,25--12,35)"; "member op_Addition(_arg1,_arg2) = let x: Microsoft.FSharp.Core.int = _arg1.Item in let y: Microsoft.FSharp.Core.int = _arg2.Item in MyNumber(Operators.op_Addition (fun arg0_0 -> fun arg1_0 -> LanguagePrimitives.AdditionDynamic (arg0_0,arg1_0),x,y)) @ (13,23--13,33)"; "member DivideByInt(_arg3,i) = let x: Microsoft.FSharp.Core.int = _arg3.Item in MyNumber(Operators.op_Division (fun arg0_0 -> fun arg1_0 -> LanguagePrimitives.DivisionDynamic (arg0_0,arg1_0),x,i)) @ (15,31--15,41)"; @@ -3465,11 +3478,13 @@ let s2 = sign p1 let createOptions() = createOptionsAux [fileSource1] ["--langversion:7.0"] +[] +[] [] -let ``Test ProjectForWitnesses3`` () = +let ``Test ProjectForWitnesses3`` useTransparentCompiler = let cleanup, options = createOptionsAux [ ProjectForWitnesses3.fileSource1 ] ["--langversion:7.0"] use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -3496,11 +3511,13 @@ let ``Test ProjectForWitnesses3`` () = actual |> shouldPairwiseEqual expected +[] +[] [] -let ``Test ProjectForWitnesses3 GetWitnessPassingInfo`` () = +let ``Test ProjectForWitnesses3 GetWitnessPassingInfo`` useTransparentCompiler = let cleanup, options = ProjectForWitnesses3.createOptions() use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -3559,11 +3576,13 @@ let isNullQuoted (ts : 't[]) = let createOptions() = createOptionsAux [fileSource1] ["--langversion:7.0"] +[] +[] [] -let ``Test ProjectForWitnesses4 GetWitnessPassingInfo`` () = +let ``Test ProjectForWitnesses4 GetWitnessPassingInfo`` useTransparentCompiler = let cleanup, options = ProjectForWitnesses4.createOptions() use _holder = cleanup - let exprChecker = FSharpChecker.Create(keepAssemblyContents=true) + let exprChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = exprChecker.ParseAndCheckProject(options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do diff --git a/tests/service/ModuleReaderCancellationTests.fs b/tests/service/ModuleReaderCancellationTests.fs index 434ddca02db..a401c637fe6 100644 --- a/tests/service/ModuleReaderCancellationTests.fs +++ b/tests/service/ModuleReaderCancellationTests.fs @@ -135,7 +135,7 @@ let createPreTypeDefs typeData = |> Array.ofList |> Array.map (fun data -> PreTypeDef data :> ILPreTypeDef) -let referenceReaderProject getPreTypeDefs (cancelOnModuleAccess: bool) options = +let referenceReaderProject getPreTypeDefs (cancelOnModuleAccess: bool) (options: FSharpProjectOptions) = let reader = new ModuleReader("Reference", mkILTypeDefsComputed getPreTypeDefs, cancelOnModuleAccess) let project = FSharpReferencedProject.ILModuleReference( diff --git a/tests/service/MultiProjectAnalysisTests.fs b/tests/service/MultiProjectAnalysisTests.fs index eab86f98324..a306107eb36 100644 --- a/tests/service/MultiProjectAnalysisTests.fs +++ b/tests/service/MultiProjectAnalysisTests.fs @@ -23,6 +23,7 @@ open TestFramework let toIList (x: _ array) = x :> IList<_> let numProjectsForStressTest = 100 let internal checker = FSharpChecker.Create(projectCacheSize=numProjectsForStressTest + 10) +let internal transparentCompilerChecker = FSharpChecker.Create(projectCacheSize=numProjectsForStressTest + 10, useTransparentCompiler=true) /// Extract range info let internal tups (m:range) = (m.StartLine, m.StartColumn), (m.EndLine, m.EndColumn) @@ -67,9 +68,9 @@ type U = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } @@ -95,9 +96,9 @@ let x = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } // A project referencing two sub-projects @@ -120,11 +121,12 @@ let u = Case1 3 """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] + let fileNames = [|fileName1|] let args = mkProjectCommandLineArgs (dllName, fileNames) let options = - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } { options with + SourceFiles = fileNames OtherOptions = Array.append options.OtherOptions [| ("-r:" + Project1A.dllName); ("-r:" + Project1B.dllName) |] ReferencedProjects = [| FSharpReferencedProject.FSharpReference(Project1A.dllName, Project1A.options); FSharpReferencedProject.FSharpReference(Project1B.dllName, Project1B.options); |] } @@ -144,7 +146,11 @@ let ``Test multi project 1 basic`` () = |> shouldEqual ["p"; "c"; "u"] [] -let ``Test multi project 1 all symbols`` () = +[] +[] +let ``Test multi project 1 all symbols`` useTransparentCompiler = + + let checker = if useTransparentCompiler then transparentCompilerChecker else checker let p1A = checker.ParseAndCheckProject(Project1A.options) |> Async.RunImmediate let p1B = checker.ParseAndCheckProject(Project1B.options) |> Async.RunImmediate @@ -182,7 +188,11 @@ let ``Test multi project 1 all symbols`` () = usesOfx1FromProject1AInMultiProject1 |> shouldEqual usesOfx1FromMultiProject1InMultiProject1 [] -let ``Test multi project 1 xmldoc`` () = +[] +[] +let ``Test multi project 1 xmldoc`` useTransparentCompiler = + + let checker = if useTransparentCompiler then transparentCompilerChecker else checker let p1A = checker.ParseAndCheckProject(Project1A.options) |> Async.RunImmediate let p1B = checker.ParseAndCheckProject(Project1B.options) |> Async.RunImmediate @@ -284,9 +294,9 @@ let p = C.Print() let baseName = tryCreateTemporaryFileName () let dllName = Path.ChangeExtension(baseName, ".dll") let projFileName = Path.ChangeExtension(baseName, ".fsproj") - let fileNames = [fileName1 ] + let fileNames = [|fileName1|] let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } yield { ModuleName = moduleName; FileName=fileName1; Options = options; DllName=dllName } ] let jointProject = @@ -305,10 +315,10 @@ let p = (""" + String.concat ",\r\n " [ for p in projects -> p.ModuleName + ".v" ] + ")" FileSystem.OpenFileForWriteShim(fileName).Write(fileSource) - let fileNames = [fileName] + let fileNames = [|fileName|] let args = mkProjectCommandLineArgs (dllName, fileNames) let options = - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } { options with OtherOptions = Array.append options.OtherOptions [| for p in projects -> ("-r:" + p.DllName) |] ReferencedProjects = [| for p in projects -> FSharpReferencedProject.FSharpReference(p.DllName, p.Options); |] } @@ -319,14 +329,16 @@ let p = (""" |> function Some x -> x | None -> if a = jointProject.FileName then "fileN" else "??" - let makeCheckerForStressTest ensureBigEnough = + let makeCheckerForStressTest ensureBigEnough useTransparentCompiler = let size = (if ensureBigEnough then numProjectsForStressTest + 10 else numProjectsForStressTest / 2 ) - FSharpChecker.Create(projectCacheSize=size) + FSharpChecker.Create(projectCacheSize=size, useTransparentCompiler=useTransparentCompiler) [] -let ``Test ManyProjectsStressTest basic`` () = +[] +[] +let ``Test ManyProjectsStressTest basic`` useTransparentCompiler = - let checker = ManyProjectsStressTest.makeCheckerForStressTest true + let checker = ManyProjectsStressTest.makeCheckerForStressTest true useTransparentCompiler let wholeProjectResults = checker.ParseAndCheckProject(ManyProjectsStressTest.jointProject.Options) |> Async.RunImmediate @@ -338,9 +350,11 @@ let ``Test ManyProjectsStressTest basic`` () = |> shouldEqual ["p"] [] -let ``Test ManyProjectsStressTest cache too small`` () = +[] +[] +let ``Test ManyProjectsStressTest cache too small`` useTransparentCompiler = - let checker = ManyProjectsStressTest.makeCheckerForStressTest false + let checker = ManyProjectsStressTest.makeCheckerForStressTest false useTransparentCompiler let wholeProjectResults = checker.ParseAndCheckProject(ManyProjectsStressTest.jointProject.Options) |> Async.RunImmediate @@ -352,9 +366,11 @@ let ``Test ManyProjectsStressTest cache too small`` () = |> shouldEqual ["p"] [] -let ``Test ManyProjectsStressTest all symbols`` () = +[] +[] +let ``Test ManyProjectsStressTest all symbols`` useTransparentCompiler = - let checker = ManyProjectsStressTest.makeCheckerForStressTest true + let checker = ManyProjectsStressTest.makeCheckerForStressTest true useTransparentCompiler for i in 1 .. 10 do printfn "stress test iteration %d (first may be slow, rest fast)" i let projectsResults = [ for p in ManyProjectsStressTest.projects -> p, checker.ParseAndCheckProject(p.Options) |> Async.RunImmediate ] @@ -397,11 +413,11 @@ let x = "F#" let cleanFileName a = if a = fileName1 then "Project1" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] let getOptions() = let args = mkProjectCommandLineArgs (dllName, fileNames) - checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } module internal MultiProjectDirty2 = @@ -422,17 +438,21 @@ let z = Project1.x let cleanFileName a = if a = fileName1 then "Project2" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] let getOptions() = let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } { options with OtherOptions = Array.append options.OtherOptions [| ("-r:" + MultiProjectDirty1.dllName) |] ReferencedProjects = [| FSharpReferencedProject.FSharpReference(MultiProjectDirty1.dllName, MultiProjectDirty1.getOptions()) |] } [] -let ``Test multi project symbols should pick up changes in dependent projects`` () = +[] +[] +let ``Test multi project symbols should pick up changes in dependent projects`` useTransparentCompiler = + + let checker = if useTransparentCompiler then transparentCompilerChecker else checker // register to count the file checks let count = ref 0 @@ -614,9 +634,9 @@ type C() = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } //Project2A.fileSource1 // A project referencing Project2A @@ -633,10 +653,10 @@ let v = Project2A.C().InternalMember // access an internal symbol """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, [||]) let options = - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } { options with OtherOptions = Array.append options.OtherOptions [| ("-r:" + Project2A.dllName); |] ReferencedProjects = [| FSharpReferencedProject.FSharpReference(Project2A.dllName, Project2A.options); |] } @@ -657,17 +677,21 @@ let v = Project2A.C().InternalMember // access an internal symbol """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, [||]) let options = - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } { options with OtherOptions = Array.append options.OtherOptions [| ("-r:" + Project2A.dllName); |] ReferencedProjects = [| FSharpReferencedProject.FSharpReference(Project2A.dllName, Project2A.options); |] } let cleanFileName a = if a = fileName1 then "file1" else "??" [] -let ``Test multi project2 errors`` () = +[] +[] +let ``Test multi project2 errors`` useTransparentCompiler = + + let checker = if useTransparentCompiler then transparentCompilerChecker else checker let wholeProjectResults = checker.ParseAndCheckProject(Project2B.options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -725,9 +749,9 @@ let (|DivisibleBy|_|) by n = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } // A project referencing a sub-project @@ -750,17 +774,22 @@ let fizzBuzz = function """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, [||]) let options = - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } { options with + SourceFiles = fileNames OtherOptions = Array.append options.OtherOptions [| ("-r:" + Project3A.dllName) |] ReferencedProjects = [| FSharpReferencedProject.FSharpReference(Project3A.dllName, Project3A.options) |] } let cleanFileName a = if a = fileName1 then "file1" else "??" [] -let ``Test multi project 3 whole project errors`` () = +[] +[] +let ``Test multi project 3 whole project errors`` useTransparentCompiler = + + let checker = if useTransparentCompiler then transparentCompilerChecker else checker let wholeProjectResults = checker.ParseAndCheckProject(MultiProject3.options) |> Async.RunImmediate for e in wholeProjectResults.Diagnostics do @@ -769,7 +798,11 @@ let ``Test multi project 3 whole project errors`` () = wholeProjectResults.Diagnostics.Length |> shouldEqual 0 [] -let ``Test active patterns' XmlDocSig declared in referenced projects`` () = +[] +[] +let ``Test active patterns' XmlDocSig declared in referenced projects`` useTransparentCompiler = + + let checker = if useTransparentCompiler then transparentCompilerChecker else checker let wholeProjectResults = checker.ParseAndCheckProject(MultiProject3.options) |> Async.RunImmediate let backgroundParseResults1, backgroundTypedParse1 = diff --git a/tests/service/PatternMatchCompilationTests.fs b/tests/service/PatternMatchCompilationTests.fs index 04da829f524..c75225aae0c 100644 --- a/tests/service/PatternMatchCompilationTests.fs +++ b/tests/service/PatternMatchCompilationTests.fs @@ -611,16 +611,17 @@ let x as () = y let z as """ dumpDiagnostics checkResults |> shouldEqual [ - "(10,9--10,10): Unexpected symbol ',' in binding"; - "(11,9--11,10): Unexpected symbol ':' in binding"; - "(12,9--12,11): Unexpected symbol '::' in binding"; - "(13,9--13,10): Unexpected symbol '&' in binding"; - "(14,9--14,10): Unexpected symbol '|' in binding"; + "(10,6--10,8): Expecting pattern"; + "(11,6--11,8): Expecting pattern"; + "(12,6--12,8): Expecting pattern"; + "(13,6--13,8): Expecting pattern"; + "(14,6--14,8): Expecting pattern"; "(15,13--15,14): Unexpected symbol '=' in pattern. Expected ')' or other token."; "(15,9--15,10): Unmatched '('"; "(16,0--16,3): Unexpected syntax or possible incorrect indentation: this token is offside of context started at position (15:1). Try indenting this further.\u001dTo continue using non-conforming indentation, pass the '--strict-indentation-' flag to the compiler, or set the language version to F# 7."; "(17,16--17,17): Unexpected identifier in pattern. Expected '(' or other token."; - "(20,0--20,0): Incomplete structured construct at or before this point in binding"; + "(19,6--19,8): Expecting pattern"; + "(20,0--20,0): Incomplete structured construct at or before this point in binding. Expected '=' or other token."; "(3,13--3,17): This expression was expected to have type\u001d 'int' \u001dbut here has type\u001d 'bool'"; "(3,4--3,10): Incomplete pattern matches on this expression. For example, the value '0' may indicate a case not covered by the pattern(s)."; "(4,16--4,17): This expression was expected to have type\u001d 'bool' \u001dbut here has type\u001d 'int'"; @@ -629,6 +630,11 @@ let z as "(6,9--6,15): This runtime coercion or type test from type\u001d 'a \u001d to \u001d int \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; "(8,29--8,30): This expression was expected to have type\u001d 'unit' \u001dbut here has type\u001d 'int'"; "(9,26--9,27): This expression was expected to have type\u001d 'unit' \u001dbut here has type\u001d 'int'"; + "(10,15--10,16): This expression was expected to have type\u001d ''a * 'b' \u001dbut here has type\u001d 'int'"; + "(11,11--11,12): The type 'k' is not defined."; + "(12,16--12,18): This expression was expected to have type\u001d ''a list' \u001dbut here has type\u001d 'int'"; + "(12,4--12,13): Incomplete pattern matches on this expression. For example, the value '[]' may indicate a case not covered by the pattern(s)."; + "(14,4--14,12): The two sides of this 'or' pattern bind different sets of variables"; "(18,14--18,15): The value or constructor 'y' is not defined." ] @@ -943,16 +949,17 @@ let :? x as () = y let :? z as """ dumpDiagnostics checkResults |> shouldEqual [ - "(10,12--10,13): Unexpected symbol ',' in binding"; - "(11,12--11,13): Unexpected symbol ':' in binding"; - "(12,12--12,14): Unexpected symbol '::' in binding"; - "(13,12--13,13): Unexpected symbol '&' in binding"; - "(14,12--14,13): Unexpected symbol '|' in binding"; + "(10,9--10,11): Expecting pattern"; + "(11,9--11,11): Expecting pattern"; + "(12,9--12,11): Expecting pattern"; + "(13,9--13,11): Expecting pattern"; + "(14,9--14,11): Expecting pattern"; "(15,16--15,17): Unexpected symbol '=' in pattern. Expected ')' or other token."; "(15,12--15,13): Unmatched '('"; "(16,0--16,3): Unexpected syntax or possible incorrect indentation: this token is offside of context started at position (15:1). Try indenting this further.\u001dTo continue using non-conforming indentation, pass the '--strict-indentation-' flag to the compiler, or set the language version to F# 7."; "(17,19--17,20): Unexpected identifier in pattern. Expected '(' or other token."; - "(20,0--20,0): Incomplete structured construct at or before this point in binding"; + "(19,9--19,11): Expecting pattern"; + "(20,0--20,0): Incomplete structured construct at or before this point in binding. Expected '=' or other token."; "(3,7--3,8): The type 'a' is not defined."; "(3,4--3,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; "(4,7--4,8): The type 'b' is not defined."; @@ -967,10 +974,26 @@ let :? z as "(8,4--8,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; "(9,7--9,8): The type 'g' is not defined."; "(9,4--9,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(10,7--10,8): The type 'h' is not defined."; + "(10,4--10,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(10,7--10,8): The type 'h' is not defined."; + "(10,4--10,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(11,7--11,8): The type 'j' is not defined."; + "(11,4--11,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(12,7--12,8): The type 'l' is not defined."; + "(12,4--12,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(13,7--13,8): The type 'n' is not defined."; + "(13,4--13,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(14,7--14,8): The type 'p' is not defined."; + "(14,4--14,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; "(15,7--15,8): The type 'r' is not defined."; "(15,4--15,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(17,7--17,8): The type 'v' is not defined."; + "(17,4--17,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; "(18,7--18,8): The type 'x' is not defined."; - "(18,4--18,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed." + "(18,4--18,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed."; + "(19,7--19,8): The type 'z' is not defined."; + "(19,4--19,8): This runtime coercion or type test from type\u001d 'a \u001d to \u001d 'b \u001dinvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed." ] [] @@ -1207,7 +1230,8 @@ let y as ?z = 8 () """ dumpDiagnostics checkResults |> shouldEqual [ - "(7,9--7,11): Unexpected symbol '[<' in binding" + "(7,6--7,8): Expecting pattern"; + "(7,9--7,11): Unexpected symbol '[<' in binding. Expected '=' or other token." "(8,4--8,11): This is not a valid pattern" "(8,4--8,16): Incomplete pattern matches on this expression." "(9,9--9,16): This is not a valid pattern" diff --git a/tests/service/ProjectAnalysisTests.fs b/tests/service/ProjectAnalysisTests.fs index dab349fd0ab..a1a58a709b2 100644 --- a/tests/service/ProjectAnalysisTests.fs +++ b/tests/service/ProjectAnalysisTests.fs @@ -90,9 +90,10 @@ let mmmm2 : M.CAbbrev = new M.CAbbrev() // note, these don't count as uses of C FileSystem.OpenFileForWriteShim(fileName2).Write(fileSource2Text) let fileNames = [fileName1; fileName2] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) - let parsingOptions, _ = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames |> List.toArray } + let parsingOptions', _ = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) + let parsingOptions = { parsingOptions' with SourceFiles = fileNames |> List.toArray } let cleanFileName a = if a = fileName1 then "file1" else if a = fileName2 then "file2" else "??" [] @@ -675,9 +676,9 @@ let _ = GenericFunction(3, 4) """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } @@ -713,11 +714,11 @@ let ``Test project2 all symbols in signature`` () = "DUWithNormalFields"; "member get_IsD"; "member get_IsDU1"; "member get_IsDU2"; "property IsD"; "property IsDU1"; "property IsDU2"; "DU1"; "field Item1"; "field Item2"; "DU2"; "field Item1"; "field Item2"; "D"; "field Item1"; - "field Item2"; "DUWithNamedFields"; "member get_IsDU"; "property IsDU"; "DU"; + "field Item2"; "DUWithNamedFields"; "DU"; "field x"; "field y"; "GenericClass`1"; "generic parameter T"; "member .ctor"; "member GenericMethod"; "generic parameter U"] |> List.sort - shouldEqual e r + shouldPairwiseEqual e r [] let ``Test project2 all uses of all signature symbols`` () = @@ -735,12 +736,10 @@ let ``Test project2 all uses of all signature symbols`` () = ("generic parameter T", [("file1", ((22, 23), (22, 25))); ("file1", ((22, 30), (22, 32))); ("file1", ((22, 45), (22, 47))); ("file1", ((22, 50), (22, 52)))]); - ("member get_IsD", []); - ("member get_IsDU", []); + ("member get_IsD", []); ("member get_IsDU1", []); ("member get_IsDU2", []); - ("property IsD", []); - ("property IsDU", []); + ("property IsD", []); ("property IsDU1", []); ("property IsDU2", []); ("DUWithNormalFields", [("file1", ((3, 5), (3, 23)))]); @@ -928,9 +927,9 @@ let getM (foo: IFoo) = foo.InterfaceMethod("d") """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } @@ -1297,9 +1296,9 @@ let inline twice(x : ^U, y : ^U) = x + y """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } @@ -1471,9 +1470,9 @@ let parseNumeric str = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -1683,9 +1682,9 @@ let f () = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -1739,9 +1738,9 @@ let x2 = C.M(arg1 = 3, arg2 = 4, ?arg3 = Some 5) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -1800,9 +1799,9 @@ let x = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -1880,9 +1879,9 @@ let inline check< ^T when ^T : (static member IsInfinity : ^T -> bool)> (num: ^T let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -1959,9 +1958,9 @@ C.M("http://goo", query = 1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2039,9 +2038,9 @@ let fff (x:System.Collections.Generic.Dictionary.Enumerator) = () let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2108,9 +2107,9 @@ let x2 = query { for i in 0 .. 100 do let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2175,9 +2174,9 @@ let x3 = new System.DateTime() let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2334,9 +2333,9 @@ let x2 = S(3) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2401,9 +2400,9 @@ let f x = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2488,9 +2487,9 @@ and G = Case1 | Case2 of int FileSystem.OpenFileForWriteShim(sigFileName1).Write(sigFileSource1Text) let cleanFileName a = if a = fileName1 then "file1" elif a = sigFileName1 then "sig1" else "??" - let fileNames = [sigFileName1; fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|sigFileName1; fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2754,9 +2753,9 @@ let f3 (x: System.Exception) = x.HelpLink <- "" // check use of .NET setter prop FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2841,9 +2840,9 @@ let _ = list<_>.Empty FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2897,9 +2896,9 @@ let s = System.DayOfWeek.Monday FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -2972,9 +2971,9 @@ type A<'T>() = FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -3033,9 +3032,9 @@ let _ = { new IMyInterface with FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -3107,9 +3106,9 @@ let f5 (x: int[,,]) = () // test a multi-dimensional array FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } @@ -3254,9 +3253,9 @@ module Setter = FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test Project23 whole project errors`` () = @@ -3425,9 +3424,9 @@ TypeWithProperties.StaticAutoPropGetSet <- 3 FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test Project24 whole project errors`` () = @@ -3682,12 +3681,12 @@ let _ = XmlProvider<"13">.GetSample() FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] let args = - [| yield! mkProjectCommandLineArgs (dllName, fileNames) + [| yield! mkProjectCommandLineArgs (dllName, []) yield @"-r:" + Path.Combine(__SOURCE_DIRECTORY__, Path.Combine("data", "FSharp.Data.dll")) yield @"-r:" + sysLib "System.Xml.Linq" |] - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] #if NETCOREAPP @@ -3822,9 +3821,9 @@ type Class() = let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -3912,9 +3911,9 @@ type CFooImpl() = """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test project27 whole project errors`` () = @@ -3977,9 +3976,9 @@ type Use() = """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } #if !NO_TYPEPROVIDERS [] let ``Test project28 all symbols in signature`` () = @@ -4055,9 +4054,9 @@ let f (x: INotifyPropertyChanged) = failwith "" """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -4114,9 +4113,9 @@ type T() = """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let ``Test project30 whole project errors`` () = @@ -4174,10 +4173,9 @@ let g = Console.ReadKey() """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let ``Test project31 whole project errors`` () = let wholeProjectResults = checker.ParseAndCheckProject(Project31.options) |> Async.RunImmediate @@ -4317,9 +4315,9 @@ val func : int -> int FileSystem.OpenFileForWriteShim(sigFileName1).Write(sigFileSource1) let cleanFileName a = if a = fileName1 then "file1" elif a = sigFileName1 then "sig1" else "??" - let fileNames = [sigFileName1; fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|sigFileName1; fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -4385,9 +4383,9 @@ type System.Int32 with FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test Project33 whole project errors`` () = @@ -4424,17 +4422,17 @@ module internal Project34 = FileSystem.OpenFileForWriteShim(sourceFileName).Write(fileSource) let cleanFileName a = if a = sourceFileName then "file1" else "??" - let fileNames = [sourceFileName] + let fileNames = [|sourceFileName|] let args = [| - yield! mkProjectCommandLineArgs (dllName, fileNames) + yield! mkProjectCommandLineArgs (dllName, []) // We use .NET-built version of System.Data.dll since the tests depend on implementation details // i.e. the private type System.Data.Listeners may not be available on Mono. yield @"-r:" + Path.Combine(__SOURCE_DIRECTORY__, Path.Combine("data", "System.Data.dll")) |] |> Array.filter(fun arg -> not((arg.Contains("System.Data")) && not (arg.Contains(@"service\data\System.Data.dll")))) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test Project34 whole project errors`` () = @@ -4502,9 +4500,9 @@ type Test = FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] @@ -4574,13 +4572,13 @@ module internal Project35b = FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1Text) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] + let fileNames = [|fileName1|] #if NETCOREAPP let projPath = Path.ChangeExtension(fileName1, ".fsproj") let dllPath = Path.ChangeExtension(fileName1, ".dll") let args = mkProjectCommandLineArgs(dllPath, fileNames) let args2 = Array.append args [| "-r:notexist.dll" |] - let options = checker.GetProjectOptionsFromCommandLineArgs (projPath, args2) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projPath, args2) with SourceFiles = fileNames } #else let options = checker.GetProjectOptionsFromScript(fileName1, fileSource1) |> Async.RunImmediate |> fst #endif @@ -4641,13 +4639,15 @@ let callToOverload = B(5).Overload(4) FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) let cleanFileName a = if a = fileName1 then "file1" else "??" - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) [] -let ``Test project36 FSharpMemberOrFunctionOrValue.IsBaseValue`` () = - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) - let options = keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (Project36.projFileName, Project36.args) +[] +[] +let ``Test project36 FSharpMemberOrFunctionOrValue.IsBaseValue`` useTransparentCompiler = + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) + let options = { keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (Project36.projFileName, Project36.args) with SourceFiles = Project36.fileNames } let wholeProjectResults = keepAssemblyContentsChecker.ParseAndCheckProject(options) |> Async.RunImmediate @@ -4660,9 +4660,11 @@ let ``Test project36 FSharpMemberOrFunctionOrValue.IsBaseValue`` () = |> fun baseSymbol -> shouldEqual true baseSymbol.IsBaseValue [] -let ``Test project36 FSharpMemberOrFunctionOrValue.IsConstructorThisValue & IsMemberThisValue`` () = - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) - let options = keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (Project36.projFileName, Project36.args) +[] +[] +let ``Test project36 FSharpMemberOrFunctionOrValue.IsConstructorThisValue & IsMemberThisValue`` useTransparentCompiler = + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) + let options = { keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (Project36.projFileName, Project36.args) with SourceFiles = Project36.fileNames } let wholeProjectResults = keepAssemblyContentsChecker.ParseAndCheckProject(options) |> Async.RunImmediate let declarations = let checkedFile = wholeProjectResults.AssemblyContents.ImplementationFiles[0] @@ -4697,9 +4699,11 @@ let ``Test project36 FSharpMemberOrFunctionOrValue.IsConstructorThisValue & IsMe |> shouldEqual true [] -let ``Test project36 FSharpMemberOrFunctionOrValue.LiteralValue`` () = - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) - let options = keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (Project36.projFileName, Project36.args) +[] +[] +let ``Test project36 FSharpMemberOrFunctionOrValue.LiteralValue`` useTransparentCompiler = + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) + let options = { keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (Project36.projFileName, Project36.args) with SourceFiles = Project36.fileNames } let wholeProjectResults = keepAssemblyContentsChecker.ParseAndCheckProject(options) |> Async.RunImmediate let project36Module = wholeProjectResults.AssemblySignature.Entities[0] let lit = project36Module.MembersFunctionsAndValues[0] @@ -4760,9 +4764,9 @@ namespace AttrTests do () """ FileSystem.OpenFileForWriteShim(fileName2).Write(fileSource2) - let fileNames = [fileName1; fileName2] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1; fileName2|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test project37 typeof and arrays in attribute constructor arguments`` () = @@ -4902,9 +4906,9 @@ type A<'XX, 'YY>() = member this.Property = 1 """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test project38 abstract slot information`` () = @@ -4988,9 +4992,9 @@ let uses () = C().CurriedMemberWithIncompleteSignature (failwith "x1") (failwith "x2") (failwith "x3", failwith "x4") """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let cleanFileName a = if a = fileName1 then "file1" else "??" [] @@ -5063,9 +5067,9 @@ let g (x: C) = x.IsItAnA,x.IsItAnAMethod() """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let cleanFileName a = if a = fileName1 then "file1" else "??" [] @@ -5134,9 +5138,9 @@ module M if true then Foo else Bar """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let cleanFileName a = if a = fileName1 then "file1" else "??" [] @@ -5226,9 +5230,9 @@ open File1 let test2() = test() """ FileSystem.OpenFileForWriteShim(fileName2).Write(fileSource2) - let fileNames = [fileName1;fileName2] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1;fileName2|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test project42 to ensure cached checked results are invalidated`` () = @@ -5261,21 +5265,21 @@ module internal ProjectBig = let fileSources2 = [ for i,f in fileSources -> SourceText.ofString f ] let fileNames = [ for _,f in fileNamesI -> f ] - let args = mkProjectCommandLineArgs (dllName, fileNames) + let args = mkProjectCommandLineArgs (dllName, []) let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) - let parsingOptions, _ = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) - + let parsingOptions', _ = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) + let parsingOptions = { parsingOptions' with SourceFiles = fileNames |> List.toArray } [] // Simplified repro for https://github.com/dotnet/fsharp/issues/2679 let ``add files with same name from different folders`` () = let fileNames = - [ __SOURCE_DIRECTORY__ + "/data/samename/folder1/a.fs" - __SOURCE_DIRECTORY__ + "/data/samename/folder2/a.fs" ] + [| __SOURCE_DIRECTORY__ + "/data/samename/folder1/a.fs" + __SOURCE_DIRECTORY__ + "/data/samename/folder2/a.fs" |] let projFileName = __SOURCE_DIRECTORY__ + "/data/samename/tempet.fsproj" let args = mkProjectCommandLineArgs ("test.dll", fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let wholeProjectResults = checker.ParseAndCheckProject(options) |> Async.RunImmediate let errors = wholeProjectResults.Diagnostics @@ -5308,13 +5312,15 @@ let foo (a: Foo): bool = """ FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] -let ``Test typed AST for struct unions`` () = // See https://github.com/fsharp/FSharp.Compiler.Service/issues/756 - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) +[] +[] +let ``Test typed AST for struct unions`` useTransparentCompiler = // See https://github.com/fsharp/FSharp.Compiler.Service/issues/756 + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) let wholeProjectResults = keepAssemblyContentsChecker.ParseAndCheckProject(ProjectStructUnions.options) |> Async.RunImmediate let declarations = @@ -5350,9 +5356,9 @@ let x = (1 = 3.0) """ let fileSource1 = SourceText.ofString fileSource1Text FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1Text) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let options = checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [| fileName1 |] + let args = mkProjectCommandLineArgs (dllName, []) + let options = { checker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } [] let ``Test diagnostics with line directives active`` () = @@ -5401,7 +5407,9 @@ let ``Test diagnostics with line directives ignored`` () = //------------------------------------------------------ [] -let ``ParseAndCheckFileResults contains ImplFile list if FSharpChecker is created with keepAssemblyContent flag set to true``() = +[] +[] +let ``ParseAndCheckFileResults contains ImplFile list if FSharpChecker is created with keepAssemblyContent flag set to true`` useTransparentCompiler = let fileName1 = Path.ChangeExtension(tryCreateTemporaryFileName (), ".fs") let base2 = tryCreateTemporaryFileName () @@ -5414,10 +5422,10 @@ type A(i:int) = let fileSource1 = SourceText.ofString fileSource1Text FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1Text) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) - let options = keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) + let options = { keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let fileCheckResults = keepAssemblyContentsChecker.ParseAndCheckFileInProject(fileName1, 0, fileSource1, options) |> Async.RunImmediate @@ -5459,7 +5467,9 @@ let ``#4030, Incremental builder creation warnings`` (args, errorSeverities) = //------------------------------------------------------ [] -let ``Unused opens in rec module smoke test 1``() = +[] +[] +let ``Unused opens in rec module smoke test 1`` useTransparentCompiler = let fileName1 = Path.ChangeExtension(tryCreateTemporaryFileName (), ".fs") let base2 = tryCreateTemporaryFileName () @@ -5505,10 +5515,10 @@ type UseTheThings(i:int) = let fileSource1 = SourceText.ofString fileSource1Text FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1Text) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) - let options = keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) + let options = { keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let fileCheckResults = keepAssemblyContentsChecker.ParseAndCheckFileInProject(fileName1, 0, fileSource1, options) |> Async.RunImmediate @@ -5532,7 +5542,9 @@ type UseTheThings(i:int) = unusedOpensData |> shouldEqual expected [] -let ``Unused opens in non rec module smoke test 1``() = +[] +[] +let ``Unused opens in non rec module smoke test 1`` useTransparentCompiler = let fileName1 = Path.ChangeExtension(tryCreateTemporaryFileName (), ".fs") let base2 = tryCreateTemporaryFileName () @@ -5578,10 +5590,10 @@ type UseTheThings(i:int) = let fileSource1 = SourceText.ofString fileSource1Text FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1Text) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) - let options = keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) + let options = { keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let fileCheckResults = keepAssemblyContentsChecker.ParseAndCheckFileInProject(fileName1, 0, fileSource1, options) |> Async.RunImmediate @@ -5605,7 +5617,9 @@ type UseTheThings(i:int) = unusedOpensData |> shouldEqual expected [] -let ``Unused opens smoke test auto open``() = +[] +[] +let ``Unused opens smoke test auto open`` useTransparentCompiler = let fileName1 = Path.ChangeExtension(tryCreateTemporaryFileName (), ".fs") let base2 = tryCreateTemporaryFileName () @@ -5659,10 +5673,10 @@ module M2 = let fileSource1 = SourceText.ofString fileSource1Text FileSystem.OpenFileForWriteShim(fileName1).Write(fileSource1Text) - let fileNames = [fileName1] - let args = mkProjectCommandLineArgs (dllName, fileNames) - let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true) - let options = keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) + let fileNames = [|fileName1|] + let args = mkProjectCommandLineArgs (dllName, []) + let keepAssemblyContentsChecker = FSharpChecker.Create(keepAssemblyContents=true, useTransparentCompiler=useTransparentCompiler) + let options = { keepAssemblyContentsChecker.GetProjectOptionsFromCommandLineArgs (projFileName, args) with SourceFiles = fileNames } let fileCheckResults = keepAssemblyContentsChecker.ParseAndCheckFileInProject(fileName1, 0, fileSource1, options) |> Async.RunImmediate diff --git a/tests/service/ScriptOptionsTests.fs b/tests/service/ScriptOptionsTests.fs index 6b692543572..4cdeaa5c3c2 100644 --- a/tests/service/ScriptOptionsTests.fs +++ b/tests/service/ScriptOptionsTests.fs @@ -50,9 +50,9 @@ let ``can generate options for different frameworks regardless of execution envi [] [] let ``can resolve nuget packages to right target framework for different frameworks regardless of execution environment``(flags) = - let path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + let path = DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) let file = tryCreateTemporaryFileNameInDirectory(path) + ".fsx" - let scriptFullPath = Path.Combine(path, file) + let scriptFullPath = Path.Combine(path.FullName, file) let scriptSource = """ #r "nuget: FSharp.Data, 3.3.3" open System diff --git a/tests/service/ServiceUntypedParseTests.fs b/tests/service/ServiceUntypedParseTests.fs index 7255773d2e0..25417a31d96 100644 --- a/tests/service/ServiceUntypedParseTests.fs +++ b/tests/service/ServiceUntypedParseTests.fs @@ -839,7 +839,7 @@ add2 1 2 | Some range -> range |> tups - |> shouldEqual ((3, 18), (3, 18)) + |> shouldEqual ((3, 17), (3, 18)) [] let ``TryRangeOfFunctionOrMethodBeingApplied - inside CE``() = diff --git a/tests/service/Symbols.fs b/tests/service/Symbols.fs index f4c417c909d..b3d6261d60a 100644 --- a/tests/service/Symbols.fs +++ b/tests/service/Symbols.fs @@ -301,6 +301,75 @@ type E = Ns1.Ns2.T | _ -> Assert.Fail (sprintf "Couldn't get entity: %s" symbolName)) + [] + let ``Interface 01`` () = + let _, checkResults = getParseAndCheckResults """ +open System + +IDisposable +""" + findSymbolUseByName "IDisposable" checkResults |> ignore + + [] + let ``Interface 02`` () = + let _, checkResults = getParseAndCheckResults """ +System.IDisposable +""" + findSymbolUseByName "IDisposable" checkResults |> ignore + + [] + let ``Interface 03`` () = + let _, checkResults = getParseAndCheckResults """ +open System + +{ new IDisposable with } +""" + findSymbolUseByName "IDisposable" checkResults |> ignore + + + [] + let ``Interface 04 - Type arg`` () = + let _, checkResults = getParseAndCheckResults """ +open System.Collections.Generic + +IList +""" + let symbolUse = findSymbolUseByName "IList`1" checkResults + let _, typeArg = symbolUse.GenericArguments[0] + typeArg.Format(symbolUse.DisplayContext) |> shouldEqual "int" + + [] + let ``Interface 05 - Type arg`` () = + let _, checkResults = getParseAndCheckResults """ +type I<'T> = + abstract M: 'T -> unit + +{ new I<_> with + member this.M(i: int) = () } +""" + let symbolUse = + getSymbolUses checkResults + |> Seq.findBack (fun symbolUse -> symbolUse.Symbol.DisplayName = "I") + + let _, typeArg = symbolUse.GenericArguments[0] + typeArg.Format(symbolUse.DisplayContext) |> shouldEqual "int" + + [] + let ``Interface 06 - Type arg`` () = + let _, checkResults = getParseAndCheckResults """ +type I<'T> = + abstract M: 'T -> unit + +{ new I with + member this.M _ = () } +""" + let symbolUse = + getSymbolUses checkResults + |> Seq.findBack (fun symbolUse -> symbolUse.Symbol.DisplayName = "I") + + let _, typeArg = symbolUse.GenericArguments[0] + typeArg.Format(symbolUse.DisplayContext) |> shouldEqual "int" + [] let ``FSharpType.Format can use prefix representations`` () = let _, checkResults = getParseAndCheckResults """ @@ -1123,3 +1192,14 @@ let z = builder if symbolUse.Symbol.DisplayName = "builder" then (symbolUse.Range.StartLine, symbolUse.Range.StartColumn), symbolUse.IsFromComputationExpression ] + +module Member = + [] + let ``Inherit 01`` () = + let _, checkResults = getParseAndCheckResults """ +type T() = + inherit Foo() + + let i = 1 +""" + assertHasSymbolUsages ["i"] checkResults diff --git a/tests/service/data/SyntaxTree/Binding/RangeOfAttributeShouldBeIncludedInSecondaryConstructor.fs.bsl b/tests/service/data/SyntaxTree/Binding/RangeOfAttributeShouldBeIncludedInSecondaryConstructor.fs.bsl index 2b1943b2d20..ceff4f8e244 100644 --- a/tests/service/data/SyntaxTree/Binding/RangeOfAttributeShouldBeIncludedInSecondaryConstructor.fs.bsl +++ b/tests/service/data/SyntaxTree/Binding/RangeOfAttributeShouldBeIncludedInSecondaryConstructor.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); Member @@ -109,7 +109,7 @@ ImplFile (3,4--11,12)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--11,12), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBinding.fs.bsl b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBinding.fs.bsl index e76316e2210..9e0bd27f359 100644 --- a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBinding.fs.bsl +++ b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBinding.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); Member @@ -41,7 +41,7 @@ ImplFile (3,4--3,21)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--3,21), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithParameters.fs.bsl b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithParameters.fs.bsl index b9aa74e11b9..463fcef24ba 100644 --- a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithParameters.fs.bsl +++ b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithParameters.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); Member @@ -48,7 +48,7 @@ ImplFile (3,4--3,24)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--3,24), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithReturnType.fs.bsl b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithReturnType.fs.bsl index 2458900141d..49eeec4d346 100644 --- a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithReturnType.fs.bsl +++ b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInMemberBindingWithReturnType.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); Member @@ -57,7 +57,7 @@ ImplFile (3,4--3,33)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--3,33), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInProperty.fs.bsl b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInProperty.fs.bsl index 92929b73a08..32f9f50c83a 100644 --- a/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInProperty.fs.bsl +++ b/tests/service/data/SyntaxTree/Binding/RangeOfEqualSignShouldBePresentInProperty.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); GetSetMember @@ -88,7 +88,7 @@ ImplFile (3,4--5,50)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--5,50), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Expression/Object - Class 08.fs.bsl b/tests/service/data/SyntaxTree/Expression/Object - Class 08.fs.bsl index b4a5df07136..da2aa3f44bc 100644 --- a/tests/service/data/SyntaxTree/Expression/Object - Class 08.fs.bsl +++ b/tests/service/data/SyntaxTree/Expression/Object - Class 08.fs.bsl @@ -24,7 +24,7 @@ ImplFile SynArgInfo ([], false, None)), None), Named (SynIdent (this, None), false, None, (4,12--4,16)), None, ArbitraryAfterError ("memberCore2", (4,16--4,16)), - (4,12--4,19), NoneAtInvisible, + (4,12--4,16), NoneAtInvisible, { LeadingKeyword = Member (4,5--4,11) InlineKeyword = None EqualsRange = None }), (4,5--4,16))], [], (3,2--3,9), diff --git a/tests/service/data/SyntaxTree/Expression/Object - Class 13.fs.bsl b/tests/service/data/SyntaxTree/Expression/Object - Class 13.fs.bsl index 3e636b4785c..6567abe2e7b 100644 --- a/tests/service/data/SyntaxTree/Expression/Object - Class 13.fs.bsl +++ b/tests/service/data/SyntaxTree/Expression/Object - Class 13.fs.bsl @@ -24,7 +24,7 @@ ImplFile SynArgInfo ([], false, None)), None), Named (SynIdent (this, None), false, None, (4,12--4,16)), None, ArbitraryAfterError ("memberCore1", (4,16--4,16)), - (4,12--5,5), NoneAtInvisible, + (4,12--4,16), NoneAtInvisible, { LeadingKeyword = Member (4,5--4,11) InlineKeyword = None EqualsRange = None }), (4,5--4,16)); diff --git a/tests/service/data/SyntaxTree/Expression/SynExprObjWithSetter.fs.bsl b/tests/service/data/SyntaxTree/Expression/SynExprObjWithSetter.fs.bsl index 717ef3af2f2..8e4beda60ed 100644 --- a/tests/service/data/SyntaxTree/Expression/SynExprObjWithSetter.fs.bsl +++ b/tests/service/data/SyntaxTree/Expression/SynExprObjWithSetter.fs.bsl @@ -20,7 +20,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,9--3,11)), None, + (None, [], Const (Unit, (3,9--3,11)), None, PreXmlDoc ((3,9), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,9), { AsKeyword = None }); AbstractSlot @@ -46,7 +46,7 @@ ImplFile (4,4--4,54)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,9--3,11)), None, + (None, [], Const (Unit, (3,9--3,11)), None, PreXmlDoc ((3,9), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,9), { AsKeyword = None })), (2,0--4,54), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Expression/Unfinished escaped ident 02.fs.bsl b/tests/service/data/SyntaxTree/Expression/Unfinished escaped ident 02.fs.bsl index 669efb602f1..d85ff5016bd 100644 --- a/tests/service/data/SyntaxTree/Expression/Unfinished escaped ident 02.fs.bsl +++ b/tests/service/data/SyntaxTree/Expression/Unfinished escaped ident 02.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None }); Member @@ -73,7 +73,7 @@ ImplFile (4,4--6,27)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--6,27), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/LeadingKeyword/NewKeyword.fs.bsl b/tests/service/data/SyntaxTree/LeadingKeyword/NewKeyword.fs.bsl index bc62b3fc078..1e408d27f4b 100644 --- a/tests/service/data/SyntaxTree/LeadingKeyword/NewKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/LeadingKeyword/NewKeyword.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); Member @@ -53,7 +53,7 @@ ImplFile (3,4--3,30)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--3,30), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Member/Auto property 07.fs.bsl b/tests/service/data/SyntaxTree/Member/Auto property 07.fs.bsl index f2be39aed6e..492124d31f0 100644 --- a/tests/service/data/SyntaxTree/Member/Auto property 07.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Auto property 07.fs.bsl @@ -12,7 +12,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None }); AutoProperty @@ -42,7 +42,7 @@ ImplFile (4,4--4,38)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--4,38), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/GetSetMember 01.fs.bsl b/tests/service/data/SyntaxTree/Member/GetSetMember 01.fs.bsl index 3d88c0ff50d..55fb27c87bd 100644 --- a/tests/service/data/SyntaxTree/Member/GetSetMember 01.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/GetSetMember 01.fs.bsl @@ -12,7 +12,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,8--3,10)), None, + (None, [], Const (Unit, (3,8--3,10)), None, PreXmlDoc ((3,8), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,8), { AsKeyword = None }); GetSetMember @@ -194,7 +194,7 @@ ImplFile (4,4--5,92)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,8--3,10)), None, + (None, [], Const (Unit, (3,8--3,10)), None, PreXmlDoc ((3,8), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,8), { AsKeyword = None })), (3,5--5,92), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 01.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 01.fs.bsl index 028662608dc..d603121ea71 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 01.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 01.fs.bsl @@ -14,20 +14,22 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - FromParseError (3,9--3,9), (3,7--3,9))], [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + FromParseError (3,9--3,9), (3,7--3,9)), (3,6--3,10)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,13--3,22)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - FromParseError (3,9--3,9), (3,7--3,9))], [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + FromParseError (3,9--3,9), (3,7--3,9)), (3,6--3,10)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,22), @@ -39,4 +41,4 @@ ImplFile { ConditionalDirectives = [] CodeComments = [] }, set [])) -(3,9)-(3,10) parse error Unexpected symbol ')' in type definition +(3,9)-(3,10) parse error Unexpected symbol ')' in pattern diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 02.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 02.fs.bsl index a6f09e6b1ff..d963c4115e8 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 02.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Missing type 02.fs.bsl @@ -14,23 +14,32 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - FromParseError (3,9--3,9), (3,7--3,9)); - Id (j, None, false, false, false, (3,11--3,12))], - [(3,9--3,10)], (3,6--3,13)), None, + Paren + (Tuple + (false, + [Typed + (Named + (SynIdent (i, None), false, None, + (3,7--3,8)), FromParseError (3,9--3,9), + (3,7--3,9)); + Named + (SynIdent (j, None), false, None, (3,11--3,12))], + [(3,9--3,10)], (3,7--3,12)), (3,6--3,13)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,16--3,25)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - FromParseError (3,9--3,9), (3,7--3,9)); - Id (j, None, false, false, false, (3,11--3,12))], - [(3,9--3,10)], (3,6--3,13)), None, + Paren + (Tuple + (false, + [Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + FromParseError (3,9--3,9), (3,7--3,9)); + Named + (SynIdent (j, None), false, None, (3,11--3,12))], + [(3,9--3,10)], (3,7--3,12)), (3,6--3,13)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,25), { LeadingKeyword = Type (3,0--3,4) @@ -41,4 +50,4 @@ ImplFile { ConditionalDirectives = [] CodeComments = [] }, set [])) -(3,9)-(3,10) parse error Unexpected symbol ',' in type definition +(3,9)-(3,10) parse error Unexpected symbol ',' in pattern diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 01.fs b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 01.fs new file mode 100644 index 00000000000..29b287b3212 --- /dev/null +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 01.fs @@ -0,0 +1,3 @@ +module Module + +type T(a, (b, c: string), d) = class end diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 01.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 01.fs.bsl new file mode 100644 index 00000000000..2bc4b5f488f --- /dev/null +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 01.fs.bsl @@ -0,0 +1,76 @@ +ImplFile + (ParsedImplFileInput + ("/root/Member/Implicit ctor - Pat - Tuple 01.fs", false, + QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [T], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + ObjectModel + (Class, + [ImplicitCtor + (None, [], + Paren + (Tuple + (false, + [Named + (SynIdent (a, None), false, None, (3,7--3,8)); + Paren + (Tuple + (false, + [Named + (SynIdent (b, None), false, None, + (3,11--3,12)); + Typed + (Named + (SynIdent (c, None), false, None, + (3,14--3,15)), + LongIdent + (SynLongIdent ([string], [], [None])), + (3,14--3,23))], [(3,12--3,13)], + (3,11--3,23)), (3,10--3,24)); + Named + (SynIdent (d, None), false, None, (3,26--3,27))], + [(3,8--3,9); (3,24--3,25)], (3,7--3,27)), + (3,6--3,28)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,31--3,40)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Tuple + (false, + [Named + (SynIdent (a, None), false, None, (3,7--3,8)); + Paren + (Tuple + (false, + [Named + (SynIdent (b, None), false, None, + (3,11--3,12)); + Typed + (Named + (SynIdent (c, None), false, None, + (3,14--3,15)), + LongIdent + (SynLongIdent ([string], [], [None])), + (3,14--3,23))], [(3,12--3,13)], + (3,11--3,23)), (3,10--3,24)); + Named + (SynIdent (d, None), false, None, (3,26--3,27))], + [(3,8--3,9); (3,24--3,25)], (3,7--3,27)), + (3,6--3,28)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })), (3,5--3,40), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,29--3,30) + WithKeyword = None })], (3,0--3,40))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--3,40), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 02.fs b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 02.fs new file mode 100644 index 00000000000..058d241942c --- /dev/null +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 02.fs @@ -0,0 +1,3 @@ +module Module + +type T(a, , c) = class end diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 02.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 02.fs.bsl new file mode 100644 index 00000000000..35502745762 --- /dev/null +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Pat - Tuple 02.fs.bsl @@ -0,0 +1,52 @@ +ImplFile + (ParsedImplFileInput + ("/root/Member/Implicit ctor - Pat - Tuple 02.fs", false, + QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [T], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + ObjectModel + (Class, + [ImplicitCtor + (None, [], + Paren + (Tuple + (false, + [Named + (SynIdent (a, None), false, None, (3,7--3,8)); + Wild (3,10--3,10); + Named + (SynIdent (c, None), false, None, (3,12--3,13))], + [(3,8--3,9); (3,10--3,11)], (3,7--3,13)), + (3,6--3,14)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,17--3,26)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Tuple + (false, + [Named + (SynIdent (a, None), false, None, (3,7--3,8)); + Wild (3,10--3,10); + Named + (SynIdent (c, None), false, None, (3,12--3,13))], + [(3,8--3,9); (3,10--3,11)], (3,7--3,13)), + (3,6--3,14)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })), (3,5--3,26), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,15--3,16) + WithKeyword = None })], (3,0--3,26))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--3,26), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(3,10)-(3,11) parse error Expecting pattern diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 01.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 01.fs.bsl index 055f0279f10..424a3619305 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 01.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 01.fs.bsl @@ -14,27 +14,29 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - LongIdent (SynLongIdent ([b], [], [None])), - (3,10--3,16), { ArrowRange = (3,12--3,14) }), - (3,7--3,16))], [], (3,6--3,17)), None, + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + LongIdent (SynLongIdent ([b], [], [None])), + (3,10--3,16), { ArrowRange = (3,12--3,14) }), + (3,7--3,16)), (3,6--3,17)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,20--3,29)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - LongIdent (SynLongIdent ([b], [], [None])), - (3,10--3,16), { ArrowRange = (3,12--3,14) }), - (3,7--3,16))], [], (3,6--3,17)), None, + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + LongIdent (SynLongIdent ([b], [], [None])), + (3,10--3,16), { ArrowRange = (3,12--3,14) }), + (3,7--3,16)), (3,6--3,17)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,29), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 02.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 02.fs.bsl index d8fda81fe3e..0146ad5a153 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 02.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 02.fs.bsl @@ -14,26 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - Fun - (LongIdent (SynLongIdent ([b], [], [None])), - LongIdent (SynLongIdent ([c], [], [None])), - (3,15--3,21), - { ArrowRange = (3,17--3,19) }), - (3,10--3,21), { ArrowRange = (3,12--3,14) }), - (3,7--3,21))], [], (3,6--3,22)), None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,25--3,34)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Fun (LongIdent (SynLongIdent ([a], [], [None])), Fun @@ -41,7 +25,24 @@ ImplFile LongIdent (SynLongIdent ([c], [], [None])), (3,15--3,21), { ArrowRange = (3,17--3,19) }), (3,10--3,21), { ArrowRange = (3,12--3,14) }), - (3,7--3,21))], [], (3,6--3,22)), None, + (3,7--3,21)), (3,6--3,22)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,25--3,34)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + Fun + (LongIdent (SynLongIdent ([b], [], [None])), + LongIdent (SynLongIdent ([c], [], [None])), + (3,15--3,21), { ArrowRange = (3,17--3,19) }), + (3,10--3,21), { ArrowRange = (3,12--3,14) }), + (3,7--3,21)), (3,6--3,22)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,34), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 03.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 03.fs.bsl index 5dc98d09cc2..61b3b7f3776 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 03.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 03.fs.bsl @@ -14,26 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - Fun - (LongIdent (SynLongIdent ([b], [], [None])), - LongIdent (SynLongIdent ([c], [], [None])), - (3,15--3,21), - { ArrowRange = (3,17--3,19) }), - (3,10--3,21), { ArrowRange = (3,12--3,14) }), - (3,7--3,21))], [], (3,6--3,22)), None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,25--3,34)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Fun (LongIdent (SynLongIdent ([a], [], [None])), Fun @@ -41,7 +25,24 @@ ImplFile LongIdent (SynLongIdent ([c], [], [None])), (3,15--3,21), { ArrowRange = (3,17--3,19) }), (3,10--3,21), { ArrowRange = (3,12--3,14) }), - (3,7--3,21))], [], (3,6--3,22)), None, + (3,7--3,21)), (3,6--3,22)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,25--3,34)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + Fun + (LongIdent (SynLongIdent ([b], [], [None])), + LongIdent (SynLongIdent ([c], [], [None])), + (3,15--3,21), { ArrowRange = (3,17--3,19) }), + (3,10--3,21), { ArrowRange = (3,12--3,14) }), + (3,7--3,21)), (3,6--3,22)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,34), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 04.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 04.fs.bsl index b230c775e10..ca30a8c2327 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 04.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 04.fs.bsl @@ -14,27 +14,29 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - FromParseError (3,14--3,14), (3,10--3,14), - { ArrowRange = (3,12--3,14) }), (3,7--3,16))], - [], (3,6--3,16)), None, + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + FromParseError (3,14--3,14), (3,10--3,14), + { ArrowRange = (3,12--3,14) }), (3,7--3,16)), + (3,6--3,16)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,19--3,28)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - FromParseError (3,14--3,14), (3,10--3,14), - { ArrowRange = (3,12--3,14) }), (3,7--3,16))], - [], (3,6--3,16)), None, + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + FromParseError (3,14--3,14), (3,10--3,14), + { ArrowRange = (3,12--3,14) }), (3,7--3,16)), + (3,6--3,16)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,28), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 05.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 05.fs.bsl index 00c2967df77..bd89bbaf94e 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 05.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 05.fs.bsl @@ -14,26 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - Fun - (FromParseError (3,15--3,15), - LongIdent (SynLongIdent ([c], [], [None])), - (3,15--3,19), - { ArrowRange = (3,15--3,17) }), - (3,10--3,19), { ArrowRange = (3,12--3,14) }), - (3,7--3,19))], [], (3,6--3,20)), None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,23--3,32)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Fun (LongIdent (SynLongIdent ([a], [], [None])), Fun @@ -41,7 +25,24 @@ ImplFile LongIdent (SynLongIdent ([c], [], [None])), (3,15--3,19), { ArrowRange = (3,15--3,17) }), (3,10--3,19), { ArrowRange = (3,12--3,14) }), - (3,7--3,19))], [], (3,6--3,20)), None, + (3,7--3,19)), (3,6--3,20)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,23--3,32)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + Fun + (FromParseError (3,15--3,15), + LongIdent (SynLongIdent ([c], [], [None])), + (3,15--3,19), { ArrowRange = (3,15--3,17) }), + (3,10--3,19), { ArrowRange = (3,12--3,14) }), + (3,7--3,19)), (3,6--3,20)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,32), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 06.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 06.fs.bsl index 781136aa263..ac58a094acb 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 06.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Fun 06.fs.bsl @@ -14,32 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Fun - (LongIdent (SynLongIdent ([a], [], [None])), - Fun - (FromParseError (3,15--3,15), - Tuple - (false, - [Type - (LongIdent - (SynLongIdent ([c], [], [None]))); - Star (3,20--3,21); - Type (FromParseError (3,21--3,21))], - (3,18--3,21)), (3,15--3,21), - { ArrowRange = (3,15--3,17) }), - (3,10--3,21), { ArrowRange = (3,12--3,14) }), - (3,7--3,23))], [], (3,6--3,23)), None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,26--3,35)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Fun (LongIdent (SynLongIdent ([a], [], [None])), Fun @@ -54,7 +32,31 @@ ImplFile (3,18--3,21)), (3,15--3,21), { ArrowRange = (3,15--3,17) }), (3,10--3,21), { ArrowRange = (3,12--3,14) }), - (3,7--3,23))], [], (3,6--3,23)), None, + (3,7--3,23)), (3,6--3,23)), None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,26--3,35)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Fun + (LongIdent (SynLongIdent ([a], [], [None])), + Fun + (FromParseError (3,15--3,15), + Tuple + (false, + [Type + (LongIdent + (SynLongIdent ([c], [], [None]))); + Star (3,20--3,21); + Type (FromParseError (3,21--3,21))], + (3,18--3,21)), (3,15--3,21), + { ArrowRange = (3,15--3,17) }), (3,10--3,21), + { ArrowRange = (3,12--3,14) }), (3,7--3,23)), + (3,6--3,23)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,35), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 01.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 01.fs.bsl index b8315229b80..473bd768b3c 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 01.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 01.fs.bsl @@ -14,28 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Tuple - (false, - [Type - (LongIdent - (SynLongIdent ([a], [], [None]))); - Star (3,12--3,13); - Type - (LongIdent - (SynLongIdent ([b], [], [None])))], - (3,10--3,15)), (3,7--3,15))], [], (3,6--3,16)), - None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,19--3,28)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Tuple (false, [Type @@ -43,8 +25,25 @@ ImplFile Star (3,12--3,13); Type (LongIdent (SynLongIdent ([b], [], [None])))], - (3,10--3,15)), (3,7--3,15))], [], (3,6--3,16)), - None, + (3,10--3,15)), (3,7--3,15)), (3,6--3,16)), + None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,19--3,28)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Tuple + (false, + [Type + (LongIdent (SynLongIdent ([a], [], [None]))); + Star (3,12--3,13); + Type + (LongIdent (SynLongIdent ([b], [], [None])))], + (3,10--3,15)), (3,7--3,15)), (3,6--3,16)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,28), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 02.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 02.fs.bsl index 80b2ad46a8d..57b5279161a 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 02.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 02.fs.bsl @@ -14,32 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Tuple - (false, - [Type - (LongIdent - (SynLongIdent ([a], [], [None]))); - Star (3,12--3,13); - Type - (LongIdent - (SynLongIdent ([b], [], [None]))); - Star (3,16--3,17); - Type - (LongIdent - (SynLongIdent ([c], [], [None])))], - (3,10--3,19)), (3,7--3,19))], [], (3,6--3,20)), - None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,23--3,32)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Tuple (false, [Type @@ -50,8 +28,28 @@ ImplFile Star (3,16--3,17); Type (LongIdent (SynLongIdent ([c], [], [None])))], - (3,10--3,19)), (3,7--3,19))], [], (3,6--3,20)), - None, + (3,10--3,19)), (3,7--3,19)), (3,6--3,20)), + None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,23--3,32)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Tuple + (false, + [Type + (LongIdent (SynLongIdent ([a], [], [None]))); + Star (3,12--3,13); + Type + (LongIdent (SynLongIdent ([b], [], [None]))); + Star (3,16--3,17); + Type + (LongIdent (SynLongIdent ([c], [], [None])))], + (3,10--3,19)), (3,7--3,19)), (3,6--3,20)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,32), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 03.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 03.fs.bsl index ada1502d243..92b69f0c2b2 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 03.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 03.fs.bsl @@ -14,34 +14,34 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Tuple - (false, - [Type - (LongIdent - (SynLongIdent ([a], [], [None]))); - Star (3,12--3,13); - Type (FromParseError (3,13--3,13))], - (3,10--3,13)), (3,7--3,15))], [], (3,6--3,15)), - None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,18--3,27)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Tuple (false, [Type (LongIdent (SynLongIdent ([a], [], [None]))); Star (3,12--3,13); Type (FromParseError (3,13--3,13))], - (3,10--3,13)), (3,7--3,15))], [], (3,6--3,15)), - None, + (3,10--3,13)), (3,7--3,15)), (3,6--3,15)), + None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,18--3,27)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Tuple + (false, + [Type + (LongIdent (SynLongIdent ([a], [], [None]))); + Star (3,12--3,13); + Type (FromParseError (3,13--3,13))], + (3,10--3,13)), (3,7--3,15)), (3,6--3,15)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,27), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 04.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 04.fs.bsl index e6bbfcbcb71..5ff10cae81b 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 04.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 04.fs.bsl @@ -14,30 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Tuple - (false, - [Type - (LongIdent - (SynLongIdent ([a], [], [None]))); - Star (3,12--3,13); - Type - (LongIdent - (SynLongIdent ([b], [], [None]))); - Star (3,16--3,17); - Type (FromParseError (3,17--3,17))], - (3,10--3,17)), (3,7--3,19))], [], (3,6--3,19)), - None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,22--3,31)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Tuple (false, [Type @@ -47,8 +27,27 @@ ImplFile (LongIdent (SynLongIdent ([b], [], [None]))); Star (3,16--3,17); Type (FromParseError (3,17--3,17))], - (3,10--3,17)), (3,7--3,19))], [], (3,6--3,19)), - None, + (3,10--3,17)), (3,7--3,19)), (3,6--3,19)), + None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,22--3,31)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Tuple + (false, + [Type + (LongIdent (SynLongIdent ([a], [], [None]))); + Star (3,12--3,13); + Type + (LongIdent (SynLongIdent ([b], [], [None]))); + Star (3,16--3,17); + Type (FromParseError (3,17--3,17))], + (3,10--3,17)), (3,7--3,19)), (3,6--3,19)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,31), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 05.fs.bsl b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 05.fs.bsl index dfcd368eb5c..a39da9cc29e 100644 --- a/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 05.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Implicit ctor - Type - Tuple 05.fs.bsl @@ -14,30 +14,10 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - Tuple - (false, - [Type - (LongIdent - (SynLongIdent ([a], [], [None]))); - Star (3,12--3,13); - Type (FromParseError (3,15--3,15)); - Star (3,14--3,15); - Type - (LongIdent - (SynLongIdent ([c], [], [None])))], - (3,10--3,17)), (3,7--3,17))], [], (3,6--3,19)), - None, - PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), - (3,5--3,6), { AsKeyword = None })], (3,22--3,31)), [], - Some - (ImplicitCtor - (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), Tuple (false, [Type @@ -47,8 +27,27 @@ ImplFile Star (3,14--3,15); Type (LongIdent (SynLongIdent ([c], [], [None])))], - (3,10--3,17)), (3,7--3,17))], [], (3,6--3,19)), - None, + (3,10--3,17)), (3,7--3,17)), (3,6--3,19)), + None, + PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), + (3,5--3,6), { AsKeyword = None })], (3,22--3,31)), [], + Some + (ImplicitCtor + (None, [], + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + Tuple + (false, + [Type + (LongIdent (SynLongIdent ([a], [], [None]))); + Star (3,12--3,13); + Type (FromParseError (3,15--3,15)); + Star (3,14--3,15); + Type + (LongIdent (SynLongIdent ([c], [], [None])))], + (3,10--3,17)), (3,7--3,17)), (3,6--3,19)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,31), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/ImplicitCtorWithAsKeyword.fs.bsl b/tests/service/data/SyntaxTree/Member/ImplicitCtorWithAsKeyword.fs.bsl index 7f97fd1c420..61f182611f8 100644 --- a/tests/service/data/SyntaxTree/Member/ImplicitCtorWithAsKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/ImplicitCtorWithAsKeyword.fs.bsl @@ -14,58 +14,64 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id - (readAllBytes, None, false, false, false, - (2,33--2,45)), - Fun - (LongIdent - (SynLongIdent ([string], [], [None])), - Array - (1, - LongIdent - (SynLongIdent ([byte], [], [None])), - (2,57--2,63)), (2,47--2,63), - { ArrowRange = (2,54--2,56) }), (2,33--2,63)); - Typed - (Id - (projectOptions, None, false, false, false, - (2,65--2,79)), - LongIdent - (SynLongIdent - ([FSharpProjectOptions], [], [None])), - (2,65--2,101))], [(2,63--2,64)], (2,32--2,102)), - Some this, + Paren + (Tuple + (false, + [Typed + (Named + (SynIdent (readAllBytes, None), false, None, + (2,33--2,45)), + Fun + (LongIdent + (SynLongIdent ([string], [], [None])), + Array + (1, + LongIdent + (SynLongIdent ([byte], [], [None])), + (2,57--2,63)), (2,47--2,63), + { ArrowRange = (2,54--2,56) }), + (2,33--2,63)); + Typed + (Named + (SynIdent (projectOptions, None), false, + None, (2,65--2,79)), + LongIdent + (SynLongIdent + ([FSharpProjectOptions], [], [None])), + (2,65--2,101))], [(2,63--2,64)], + (2,33--2,101)), (2,32--2,102)), Some this, PreXmlDoc ((2,32), FSharp.Compiler.Xml.XmlDocCollector), (2,14--2,32), { AsKeyword = Some (4,4--4,6) })], (8,4--8,13)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Typed - (Id - (readAllBytes, None, false, false, false, - (2,33--2,45)), - Fun - (LongIdent - (SynLongIdent ([string], [], [None])), - Array - (1, - LongIdent - (SynLongIdent ([byte], [], [None])), - (2,57--2,63)), (2,47--2,63), - { ArrowRange = (2,54--2,56) }), (2,33--2,63)); - Typed - (Id - (projectOptions, None, false, false, false, - (2,65--2,79)), - LongIdent - (SynLongIdent - ([FSharpProjectOptions], [], [None])), - (2,65--2,101))], [(2,63--2,64)], (2,32--2,102)), - Some this, + Paren + (Tuple + (false, + [Typed + (Named + (SynIdent (readAllBytes, None), false, None, + (2,33--2,45)), + Fun + (LongIdent + (SynLongIdent ([string], [], [None])), + Array + (1, + LongIdent + (SynLongIdent ([byte], [], [None])), + (2,57--2,63)), (2,47--2,63), + { ArrowRange = (2,54--2,56) }), + (2,33--2,63)); + Typed + (Named + (SynIdent (projectOptions, None), false, + None, (2,65--2,79)), + LongIdent + (SynLongIdent + ([FSharpProjectOptions], [], [None])), + (2,65--2,101))], [(2,63--2,64)], (2,33--2,101)), + (2,32--2,102)), Some this, PreXmlDoc ((2,32), FSharp.Compiler.Xml.XmlDocCollector), (2,14--2,32), { AsKeyword = Some (4,4--4,6) })), (2,5--8,13), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Member/Member 03.fs.bsl b/tests/service/data/SyntaxTree/Member/Member 03.fs.bsl index 09fde9d81da..cb85a85bfc7 100644 --- a/tests/service/data/SyntaxTree/Member/Member 03.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Member 03.fs.bsl @@ -66,7 +66,7 @@ ImplFile (SynIdent (this, None), false, None, (5,17--5,21)), None, ArbitraryAfterError ("memberCore1", (5,21--5,21)), - (5,4--6,4), NoneAtInvisible, + (5,4--5,21), NoneAtInvisible, { LeadingKeyword = Member (5,10--5,16) InlineKeyword = None EqualsRange = None }), (5,4--5,21)); diff --git a/tests/service/data/SyntaxTree/Member/Member 07.fs.bsl b/tests/service/data/SyntaxTree/Member/Member 07.fs.bsl index 53fff4c46e5..5e5c51e0f2b 100644 --- a/tests/service/data/SyntaxTree/Member/Member 07.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Member 07.fs.bsl @@ -64,7 +64,7 @@ ImplFile SynArgInfo ([], false, None)), None), Named (SynIdent (this, None), false, None, (5,17--5,21)), - None, Const (Int32 2, (5,25--5,26)), (5,4--5,24), + None, Const (Int32 2, (5,25--5,26)), (5,4--5,21), NoneAtInvisible, { LeadingKeyword = Member (5,10--5,16) InlineKeyword = None diff --git a/tests/service/data/SyntaxTree/Member/Member 12.fs.bsl b/tests/service/data/SyntaxTree/Member/Member 12.fs.bsl index c20d46b6107..94ece410c41 100644 --- a/tests/service/data/SyntaxTree/Member/Member 12.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Member 12.fs.bsl @@ -29,7 +29,7 @@ ImplFile (SynIdent (this, None), false, None, (4,11--4,15)), None, ArbitraryAfterError ("memberCore2", (4,15--4,15)), - (4,11--6,1), NoneAtInvisible, + (4,11--4,15), NoneAtInvisible, { LeadingKeyword = Member (4,4--4,10) InlineKeyword = None EqualsRange = None }), (4,4--4,15))], (4,4--4,15)), diff --git a/tests/service/data/SyntaxTree/Member/Read-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl b/tests/service/data/SyntaxTree/Member/Read-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl index 780fb23542d..6692c520246 100644 --- a/tests/service/data/SyntaxTree/Member/Read-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Read-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,8--3,10)), None, + (None, [], Const (Unit, (3,8--3,10)), None, PreXmlDoc ((3,8), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,8), { AsKeyword = None }); GetSetMember @@ -56,7 +56,7 @@ ImplFile SetKeyword = None })], (5,4--5,60)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,8--3,10)), None, + (None, [], Const (Unit, (3,8--3,10)), None, PreXmlDoc ((3,8), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,8), { AsKeyword = None })), (3,5--5,60), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/ReadwritePropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl b/tests/service/data/SyntaxTree/Member/ReadwritePropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl index a4240a8a27e..8319d790680 100644 --- a/tests/service/data/SyntaxTree/Member/ReadwritePropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/ReadwritePropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl @@ -17,7 +17,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None }); GetSetMember @@ -92,7 +92,7 @@ ImplFile (4,4--6,50)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None })), (2,5--6,50), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAbstractSlotContainsTheRangeOfTheWithKeyword.fs.bsl b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAbstractSlotContainsTheRangeOfTheWithKeyword.fs.bsl index ea8c1ef757c..f3b24278efa 100644 --- a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAbstractSlotContainsTheRangeOfTheWithKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAbstractSlotContainsTheRangeOfTheWithKeyword.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None }); AbstractSlot @@ -44,7 +44,7 @@ ImplFile (3,4--3,42)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None })), (2,5--3,42), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheEqualsSign.fs.bsl b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheEqualsSign.fs.bsl index e9d5adcfd5b..7cfa4c283eb 100644 --- a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheEqualsSign.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheEqualsSign.fs.bsl @@ -17,18 +17,23 @@ ImplFile (Unspecified, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id - (name, None, false, false, false, (3,12--3,16)), - LongIdent (SynLongIdent ([string], [], [None])), - (3,12--3,25)); - Typed - (Id - (age, None, false, false, false, (3,27--3,30)), - LongIdent (SynLongIdent ([int], [], [None])), - (3,27--3,36))], [(3,25--3,26)], (3,11--3,37)), - None, + Paren + (Tuple + (false, + [Typed + (Named + (SynIdent (name, None), false, None, + (3,12--3,16)), + LongIdent + (SynLongIdent ([string], [], [None])), + (3,12--3,25)); + Typed + (Named + (SynIdent (age, None), false, None, + (3,27--3,30)), + LongIdent (SynLongIdent ([int], [], [None])), + (3,27--3,36))], [(3,25--3,26)], (3,12--3,36)), + (3,11--3,37)), None, PreXmlDoc ((3,11), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,11), { AsKeyword = None }); AutoProperty @@ -57,17 +62,23 @@ ImplFile Some (ImplicitCtor (None, [], - SimplePats - ([Typed - (Id - (name, None, false, false, false, (3,12--3,16)), - LongIdent (SynLongIdent ([string], [], [None])), - (3,12--3,25)); - Typed - (Id (age, None, false, false, false, (3,27--3,30)), - LongIdent (SynLongIdent ([int], [], [None])), - (3,27--3,36))], [(3,25--3,26)], (3,11--3,37)), - None, + Paren + (Tuple + (false, + [Typed + (Named + (SynIdent (name, None), false, None, + (3,12--3,16)), + LongIdent + (SynLongIdent ([string], [], [None])), + (3,12--3,25)); + Typed + (Named + (SynIdent (age, None), false, None, + (3,27--3,30)), + LongIdent (SynLongIdent ([int], [], [None])), + (3,27--3,36))], [(3,25--3,26)], (3,12--3,36)), + (3,11--3,37)), None, PreXmlDoc ((3,11), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,11), { AsKeyword = None })), (2,0--5,40), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheWithKeyword.fs.bsl b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheWithKeyword.fs.bsl index 2cbc0581a65..0bef3c32697 100644 --- a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheWithKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithAutoPropertyContainsTheRangeOfTheWithKeyword.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None }); AutoProperty @@ -64,7 +64,7 @@ ImplFile GetSetKeywords = None })], (3,4--4,39)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None })), (2,5--4,39), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithMemberWithSetget.fs.bsl b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithMemberWithSetget.fs.bsl index 85520b1de87..e3fe9618a23 100644 --- a/tests/service/data/SyntaxTree/Member/SynTypeDefnWithMemberWithSetget.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/SynTypeDefnWithMemberWithSetget.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); GetSetMember @@ -104,7 +104,7 @@ ImplFile (3,4--3,62)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--3,62), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Member/Write-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl b/tests/service/data/SyntaxTree/Member/Write-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl index 9dad153789c..79a865c5eed 100644 --- a/tests/service/data/SyntaxTree/Member/Write-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/Member/Write-onlyPropertyInSynMemberDefnMemberContainsTheRangeOfTheWithKeyword.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,8--3,10)), None, + (None, [], Const (Unit, (3,8--3,10)), None, PreXmlDoc ((3,8), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,8), { AsKeyword = None }); GetSetMember @@ -63,7 +63,7 @@ ImplFile (5,4--5,79)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,8--3,10)), None, + (None, [], Const (Unit, (3,8--3,10)), None, PreXmlDoc ((3,8), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,8), { AsKeyword = None })), (3,5--5,79), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Nullness/AbstractClassProperty.fs.bsl b/tests/service/data/SyntaxTree/Nullness/AbstractClassProperty.fs.bsl index 2bc15f69175..a319c237e5d 100644 --- a/tests/service/data/SyntaxTree/Nullness/AbstractClassProperty.fs.bsl +++ b/tests/service/data/SyntaxTree/Nullness/AbstractClassProperty.fs.bsl @@ -20,7 +20,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,17--2,19)), None, + (None, [], Const (Unit, (2,17--2,19)), None, PreXmlDoc ((2,17), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,17), { AsKeyword = None }); AbstractSlot @@ -49,7 +49,7 @@ ImplFile (3,3--3,51)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,17--2,19)), None, + (None, [], Const (Unit, (2,17--2,19)), None, PreXmlDoc ((2,17), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,17), { AsKeyword = None })), (1,0--3,51), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Nullness/SignatureInAbstractMember.fs.bsl b/tests/service/data/SyntaxTree/Nullness/SignatureInAbstractMember.fs.bsl index b7cfdabef4f..f6aca925483 100644 --- a/tests/service/data/SyntaxTree/Nullness/SignatureInAbstractMember.fs.bsl +++ b/tests/service/data/SyntaxTree/Nullness/SignatureInAbstractMember.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (1,17--1,19)), None, + (None, [], Const (Unit, (1,17--1,19)), None, PreXmlDoc ((1,17), FSharp.Compiler.Xml.XmlDocCollector), (1,5--1,17), { AsKeyword = None }); AbstractSlot @@ -49,7 +49,7 @@ ImplFile { GetSetKeywords = None })], (2,3--2,61)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (1,17--1,19)), None, + (None, [], Const (Unit, (1,17--1,19)), None, PreXmlDoc ((1,17), FSharp.Compiler.Xml.XmlDocCollector), (1,5--1,17), { AsKeyword = None })), (1,5--2,61), { LeadingKeyword = Type (1,0--1,4) diff --git a/tests/service/data/SyntaxTree/OperatorName/ActivePatternIdentifierInPrivateMember.fs.bsl b/tests/service/data/SyntaxTree/OperatorName/ActivePatternIdentifierInPrivateMember.fs.bsl index f78ea9234b9..a91a973e4e5 100644 --- a/tests/service/data/SyntaxTree/OperatorName/ActivePatternIdentifierInPrivateMember.fs.bsl +++ b/tests/service/data/SyntaxTree/OperatorName/ActivePatternIdentifierInPrivateMember.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); Member @@ -51,7 +51,7 @@ ImplFile (3,4--7,6)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--7,6), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/OperatorName/ObjectModelWithTwoMembers.fs.bsl b/tests/service/data/SyntaxTree/OperatorName/ObjectModelWithTwoMembers.fs.bsl index 2679d87a302..760c3f64ca3 100644 --- a/tests/service/data/SyntaxTree/OperatorName/ObjectModelWithTwoMembers.fs.bsl +++ b/tests/service/data/SyntaxTree/OperatorName/ObjectModelWithTwoMembers.fs.bsl @@ -13,7 +13,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None }); LetBindings @@ -103,7 +103,7 @@ ImplFile (3,4--4,79)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,6--2,8)), None, + (None, [], Const (Unit, (2,6--2,8)), None, PreXmlDoc ((2,6), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,6), { AsKeyword = None })), (2,5--4,79), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/OperatorName/PartialActivePatternDefinitionWithoutParameters.fs.bsl b/tests/service/data/SyntaxTree/OperatorName/PartialActivePatternDefinitionWithoutParameters.fs.bsl index 62cede07065..d3f6d9d59f8 100644 --- a/tests/service/data/SyntaxTree/OperatorName/PartialActivePatternDefinitionWithoutParameters.fs.bsl +++ b/tests/service/data/SyntaxTree/OperatorName/PartialActivePatternDefinitionWithoutParameters.fs.bsl @@ -21,7 +21,7 @@ ImplFile (false, SynLongIdent ([Boolean; parse], [(2,27--2,28)], [None; None]), None, - (2,20--2,33)), (2,4--2,17), Yes (2,0--2,33), + (2,20--2,33)), (2,5--2,16), Yes (2,0--2,33), { LeadingKeyword = Let (2,0--2,3) InlineKeyword = None EqualsRange = Some (2,18--2,19) })], (2,0--2,33))], diff --git a/tests/service/data/SyntaxTree/Pattern/As 01.fs b/tests/service/data/SyntaxTree/Pattern/As 01.fs new file mode 100644 index 00000000000..9c3786b2552 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 01.fs @@ -0,0 +1,4 @@ +module Module + +match Some 1 with +| _ as _ -> () diff --git a/tests/service/data/SyntaxTree/Pattern/As 01.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 01.fs.bsl new file mode 100644 index 00000000000..f0277e7a075 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 01.fs.bsl @@ -0,0 +1,22 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 01.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Expr + (Match + (Yes (3,0--3,17), + App + (NonAtomic, false, Ident Some, Const (Int32 1, (3,11--3,12)), + (3,6--3,12)), + [SynMatchClause + (As (Wild (4,2--4,3), Wild (4,7--4,8), (4,2--4,8)), None, + Const (Unit, (4,12--4,14)), (4,2--4,14), Yes, + { ArrowRange = Some (4,9--4,11) + BarRange = Some (4,0--4,1) })], (3,0--4,14), + { MatchKeyword = (3,0--3,5) + WithKeyword = (3,13--3,17) }), (3,0--4,14))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--4,14), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) diff --git a/tests/service/data/SyntaxTree/Pattern/As 02.fs b/tests/service/data/SyntaxTree/Pattern/As 02.fs new file mode 100644 index 00000000000..2a098980177 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 02.fs @@ -0,0 +1,4 @@ +module Module + +match Some 1 with +| _ as -> () diff --git a/tests/service/data/SyntaxTree/Pattern/As 02.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 02.fs.bsl new file mode 100644 index 00000000000..a39bda6bb7c --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 02.fs.bsl @@ -0,0 +1,24 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 02.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Expr + (Match + (Yes (3,0--3,17), + App + (NonAtomic, false, Ident Some, Const (Int32 1, (3,11--3,12)), + (3,6--3,12)), + [SynMatchClause + (As (Wild (4,2--4,3), Wild (4,6--4,6), (4,2--4,6)), None, + Const (Unit, (4,10--4,12)), (4,2--4,12), Yes, + { ArrowRange = Some (4,7--4,9) + BarRange = Some (4,0--4,1) })], (3,0--4,12), + { MatchKeyword = (3,0--3,5) + WithKeyword = (3,13--3,17) }), (3,0--4,12))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--4,12), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(4,7)-(4,9) parse error Unexpected symbol '->' in pattern diff --git a/tests/service/data/SyntaxTree/Pattern/As 03.fs b/tests/service/data/SyntaxTree/Pattern/As 03.fs new file mode 100644 index 00000000000..6986fa365c0 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 03.fs @@ -0,0 +1,3 @@ +module Module + +let _ as _ = () diff --git a/tests/service/data/SyntaxTree/Pattern/As 03.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 03.fs.bsl new file mode 100644 index 00000000000..87eeb9e821a --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 03.fs.bsl @@ -0,0 +1,21 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 03.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + As (Wild (3,4--3,5), Wild (3,9--3,10), (3,4--3,10)), None, + Const (Unit, (3,13--3,15)), (3,4--3,10), Yes (3,0--3,15), + { LeadingKeyword = Let (3,0--3,3) + InlineKeyword = None + EqualsRange = Some (3,11--3,12) })], (3,0--3,15))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--3,15), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) diff --git a/tests/service/data/SyntaxTree/Pattern/As 04.fs b/tests/service/data/SyntaxTree/Pattern/As 04.fs new file mode 100644 index 00000000000..9235d0a7966 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 04.fs @@ -0,0 +1,3 @@ +module Module + +let _ as = () diff --git a/tests/service/data/SyntaxTree/Pattern/As 04.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 04.fs.bsl new file mode 100644 index 00000000000..dbbdbdd9f3e --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 04.fs.bsl @@ -0,0 +1,23 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 04.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + As (Wild (3,4--3,5), Wild (3,8--3,8), (3,4--3,8)), None, + Const (Unit, (3,11--3,13)), (3,4--3,8), Yes (3,0--3,13), + { LeadingKeyword = Let (3,0--3,3) + InlineKeyword = None + EqualsRange = Some (3,9--3,10) })], (3,0--3,13))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--3,13), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(3,6)-(3,8) parse error Expecting pattern diff --git a/tests/service/data/SyntaxTree/Pattern/As 05.fs b/tests/service/data/SyntaxTree/Pattern/As 05.fs new file mode 100644 index 00000000000..66705b3f1a7 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 05.fs @@ -0,0 +1,4 @@ +module Module + +match Some 1 with +| _ as diff --git a/tests/service/data/SyntaxTree/Pattern/As 05.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 05.fs.bsl new file mode 100644 index 00000000000..1e26e340c11 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 05.fs.bsl @@ -0,0 +1,25 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 05.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Expr + (Match + (Yes (3,0--3,17), + App + (NonAtomic, false, Ident Some, Const (Int32 1, (3,11--3,12)), + (3,6--3,12)), + [SynMatchClause + (As (Wild (4,2--4,3), Wild (4,6--4,6), (4,2--4,6)), None, + ArbitraryAfterError ("patternClauses2", (4,6--4,6)), + (4,2--4,6), Yes, { ArrowRange = None + BarRange = Some (4,0--4,1) })], + (3,0--4,6), { MatchKeyword = (3,0--3,5) + WithKeyword = (3,13--3,17) }), (3,0--4,6))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--4,6), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(5,0)-(5,0) parse error Incomplete structured construct at or before this point in pattern +(3,13)-(3,17) parse error Unexpected end of input in 'match' or 'try' expression diff --git a/tests/service/data/SyntaxTree/Pattern/As 06.fs b/tests/service/data/SyntaxTree/Pattern/As 06.fs new file mode 100644 index 00000000000..e58ff922dbd --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 06.fs @@ -0,0 +1,3 @@ +module Module + +let _ as diff --git a/tests/service/data/SyntaxTree/Pattern/As 06.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 06.fs.bsl new file mode 100644 index 00000000000..5ce6e55db4d --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 06.fs.bsl @@ -0,0 +1,24 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 06.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + As (Wild (3,4--3,5), Wild (3,8--3,8), (3,4--3,8)), None, + ArbitraryAfterError ("localBinding2", (3,8--3,8)), (3,4--3,8), + Yes (3,0--3,8), { LeadingKeyword = Let (3,0--3,3) + InlineKeyword = None + EqualsRange = None })], (3,0--3,8))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--3,8), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(3,6)-(3,8) parse error Expecting pattern +(4,0)-(4,0) parse error Incomplete structured construct at or before this point in binding. Expected '=' or other token. diff --git a/tests/service/data/SyntaxTree/Pattern/As 07.fs b/tests/service/data/SyntaxTree/Pattern/As 07.fs new file mode 100644 index 00000000000..7c22e88390c --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 07.fs @@ -0,0 +1,5 @@ +module Module + +let _ as + +() diff --git a/tests/service/data/SyntaxTree/Pattern/As 07.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 07.fs.bsl new file mode 100644 index 00000000000..b462b81d90b --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 07.fs.bsl @@ -0,0 +1,25 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 07.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + As (Wild (3,4--3,5), Wild (3,8--3,8), (3,4--3,8)), None, + ArbitraryAfterError ("localBinding2", (3,8--3,8)), (3,4--3,8), + Yes (3,0--3,8), { LeadingKeyword = Let (3,0--3,3) + InlineKeyword = None + EqualsRange = None })], (3,0--3,8)); + Expr (Const (Unit, (5,0--5,2)), (5,0--5,2))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--5,2), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(3,6)-(3,8) parse error Expecting pattern +(5,0)-(5,1) parse error Incomplete structured construct at or before this point in binding. Expected '=' or other token. diff --git a/tests/service/data/SyntaxTree/Pattern/As 08.fs b/tests/service/data/SyntaxTree/Pattern/As 08.fs new file mode 100644 index 00000000000..6dfd373aec5 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 08.fs @@ -0,0 +1,5 @@ +module Module + +match () with +| _ as +| _ -> () diff --git a/tests/service/data/SyntaxTree/Pattern/As 08.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 08.fs.bsl new file mode 100644 index 00000000000..48501827087 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 08.fs.bsl @@ -0,0 +1,23 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 08.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Expr + (Match + (Yes (3,0--3,13), Const (Unit, (3,6--3,8)), + [SynMatchClause + (Or + (As (Wild (4,2--4,3), Wild (4,6--4,6), (4,2--4,6)), + Wild (5,2--5,3), (4,2--5,3), { BarRange = (5,0--5,1) }), + None, Const (Unit, (5,7--5,9)), (4,2--5,9), Yes, + { ArrowRange = Some (5,4--5,6) + BarRange = Some (4,0--4,1) })], (3,0--5,9), + { MatchKeyword = (3,0--3,5) + WithKeyword = (3,9--3,13) }), (3,0--5,9))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--5,9), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(5,0)-(5,1) parse error Unexpected symbol '|' in pattern diff --git a/tests/service/data/SyntaxTree/Pattern/As 09.fs b/tests/service/data/SyntaxTree/Pattern/As 09.fs new file mode 100644 index 00000000000..21cb82c90e6 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 09.fs @@ -0,0 +1,5 @@ +module Module + +let _ as + +let _ = () diff --git a/tests/service/data/SyntaxTree/Pattern/As 09.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 09.fs.bsl new file mode 100644 index 00000000000..ad9aa2247c1 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 09.fs.bsl @@ -0,0 +1,36 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 09.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + As (Wild (3,4--3,5), Wild (3,8--3,8), (3,4--3,8)), None, + ArbitraryAfterError ("localBinding2", (3,8--3,8)), (3,4--3,8), + Yes (3,0--3,8), { LeadingKeyword = Let (3,0--3,3) + InlineKeyword = None + EqualsRange = None })], (3,0--3,8)); + Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((5,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + Wild (5,4--5,5), None, Const (Unit, (5,8--5,10)), (5,4--5,5), + Yes (5,0--5,10), { LeadingKeyword = Let (5,0--5,3) + InlineKeyword = None + EqualsRange = Some (5,6--5,7) })], + (5,0--5,10))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--5,10), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(3,6)-(3,8) parse error Expecting pattern +(5,0)-(5,3) parse error Incomplete structured construct at or before this point in binding. Expected '=' or other token. diff --git a/tests/service/data/SyntaxTree/Pattern/As 10.fs b/tests/service/data/SyntaxTree/Pattern/As 10.fs new file mode 100644 index 00000000000..29def47e36b --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 10.fs @@ -0,0 +1,3 @@ +module Module + +let (_ as ) = () diff --git a/tests/service/data/SyntaxTree/Pattern/As 10.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 10.fs.bsl new file mode 100644 index 00000000000..2b44d412f46 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 10.fs.bsl @@ -0,0 +1,25 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 10.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + Paren + (As (Wild (3,5--3,6), Wild (3,9--3,9), (3,5--3,9)), + (3,4--3,11)), None, Const (Unit, (3,14--3,16)), (3,4--3,11), + Yes (3,0--3,16), { LeadingKeyword = Let (3,0--3,3) + InlineKeyword = None + EqualsRange = Some (3,12--3,13) })], + (3,0--3,16))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--3,16), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(3,10)-(3,11) parse error Unexpected symbol ')' in pattern diff --git a/tests/service/data/SyntaxTree/Pattern/As 11.fs b/tests/service/data/SyntaxTree/Pattern/As 11.fs new file mode 100644 index 00000000000..53c1496b72c --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 11.fs @@ -0,0 +1,3 @@ +module Module + +let 1 as , 3 = () diff --git a/tests/service/data/SyntaxTree/Pattern/As 11.fs.bsl b/tests/service/data/SyntaxTree/Pattern/As 11.fs.bsl new file mode 100644 index 00000000000..84773ba8ee6 --- /dev/null +++ b/tests/service/data/SyntaxTree/Pattern/As 11.fs.bsl @@ -0,0 +1,28 @@ +ImplFile + (ParsedImplFileInput + ("/root/Pattern/As 11.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Let + (false, + [SynBinding + (None, Normal, false, false, [], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + SynValData + (None, SynValInfo ([], SynArgInfo ([], false, None)), None), + Tuple + (false, + [As + (Const (Int32 1, (3,4--3,5)), Wild (3,8--3,8), + (3,4--3,8)); Const (Int32 3, (3,11--3,12))], + [(3,9--3,10)], (3,4--3,12)), None, + Const (Unit, (3,15--3,17)), (3,4--3,12), Yes (3,0--3,17), + { LeadingKeyword = Let (3,0--3,3) + InlineKeyword = None + EqualsRange = Some (3,13--3,14) })], (3,0--3,17))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--3,17), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(3,6)-(3,8) parse error Expecting pattern diff --git a/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 01.fs.bsl b/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 01.fs.bsl index da447d5434b..39999d8f69c 100644 --- a/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 01.fs.bsl +++ b/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 01.fs.bsl @@ -17,13 +17,13 @@ ImplFile (FromParseError (3,6--3,6), (3,6--3,6), [], { ColonRange = Some (3,5--3,6) })), Typed - (ArbitraryAfterError ("localBinding2", (5,1--5,1)), - FromParseError (3,6--3,6), (5,1--5,1)), (3,4--3,5), - Yes (3,0--5,1), { LeadingKeyword = Let (3,0--3,3) + (ArbitraryAfterError ("localBinding2", (3,6--3,6)), + FromParseError (3,6--3,6), (3,6--3,6)), (3,4--3,5), + Yes (3,0--3,6), { LeadingKeyword = Let (3,0--3,3) InlineKeyword = None - EqualsRange = None })], (3,0--5,1))], + EqualsRange = None })], (3,0--3,6))], PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, - (1,0--5,1), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + (1,0--3,6), { LeadingKeyword = Module (1,0--1,6) })], (true, true), { ConditionalDirectives = [] CodeComments = [] }, set [])) diff --git a/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 05.fs.bsl b/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 05.fs.bsl index 89f2ca602eb..54749497087 100644 --- a/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 05.fs.bsl +++ b/tests/service/data/SyntaxTree/Pattern/Typed - Missing type 05.fs.bsl @@ -22,17 +22,18 @@ ImplFile (FromParseError (4,10--4,10), (4,10--4,10), [], { ColonRange = Some (4,9--4,10) })), Typed - (ArbitraryAfterError ("localBinding2", (6,5--6,5)), - FromParseError (4,10--4,10), (6,5--6,5)), - (4,8--4,9), Yes (4,4--6,5), + (ArbitraryAfterError + ("localBinding2", (4,10--4,10)), + FromParseError (4,10--4,10), (4,10--4,10)), + (4,8--4,9), Yes (4,4--4,10), { LeadingKeyword = Let (4,4--4,7) InlineKeyword = None EqualsRange = None })], - ArbitraryAfterError ("seqExpr", (6,5--6,5)), (4,4--6,5), - { InKeyword = None }), (4,4--6,5)), (3,0--6,5)), - (3,0--6,5))], + ArbitraryAfterError ("seqExpr", (4,10--4,10)), + (4,4--4,10), { InKeyword = None }), (4,4--4,10)), + (3,0--4,10)), (3,0--4,10))], PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, - (1,0--6,5), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + (1,0--4,10), { LeadingKeyword = Module (1,0--1,6) })], (true, true), { ConditionalDirectives = [] CodeComments = [] }, set [])) diff --git a/tests/service/data/SyntaxTree/SimplePats/SimplePats 02.fs.bsl b/tests/service/data/SyntaxTree/SimplePats/SimplePats 02.fs.bsl index 4a993df804c..fc92f2e4767 100644 --- a/tests/service/data/SyntaxTree/SimplePats/SimplePats 02.fs.bsl +++ b/tests/service/data/SyntaxTree/SimplePats/SimplePats 02.fs.bsl @@ -14,21 +14,23 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - LongIdent (SynLongIdent ([int], [], [None])), - (3,7--3,13))], [], (3,6--3,14)), None, + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + LongIdent (SynLongIdent ([int], [], [None])), + (3,7--3,13)), (3,6--3,14)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,17--3,26)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Typed - (Id (i, None, false, false, false, (3,7--3,8)), - LongIdent (SynLongIdent ([int], [], [None])), - (3,7--3,13))], [], (3,6--3,14)), None, + Paren + (Typed + (Named + (SynIdent (i, None), false, None, (3,7--3,8)), + LongIdent (SynLongIdent ([int], [], [None])), + (3,7--3,13)), (3,6--3,14)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,26), { LeadingKeyword = Type (3,0--3,4) @@ -44,19 +46,27 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Id (a, None, false, false, false, (4,7--4,8)); - Id (b, None, false, false, false, (4,9--4,10))], - [(4,8--4,9)], (4,6--4,11)), None, + Paren + (Tuple + (false, + [Named + (SynIdent (a, None), false, None, (4,7--4,8)); + Named + (SynIdent (b, None), false, None, (4,9--4,10))], + [(4,8--4,9)], (4,7--4,10)), (4,6--4,11)), None, PreXmlDoc ((4,6), FSharp.Compiler.Xml.XmlDocCollector), (4,5--4,6), { AsKeyword = None })], (4,14--4,23)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Id (a, None, false, false, false, (4,7--4,8)); - Id (b, None, false, false, false, (4,9--4,10))], - [(4,8--4,9)], (4,6--4,11)), None, + Paren + (Tuple + (false, + [Named + (SynIdent (a, None), false, None, (4,7--4,8)); + Named + (SynIdent (b, None), false, None, (4,9--4,10))], + [(4,8--4,9)], (4,7--4,10)), (4,6--4,11)), None, PreXmlDoc ((4,6), FSharp.Compiler.Xml.XmlDocCollector), (4,5--4,6), { AsKeyword = None })), (4,5--4,23), { LeadingKeyword = Type (4,0--4,4) @@ -72,64 +82,73 @@ ImplFile (Class, [ImplicitCtor (None, [], - SimplePats - ([Attrib - (Id - (bar, None, false, false, false, (5,15--5,18)), - [{ Attributes = - [{ TypeName = - SynLongIdent ([Foo], [], [None]) - ArgExpr = Const (Unit, (5,9--5,12)) - Target = None - AppliesToGetterAndSetter = false - Range = (5,9--5,12) }] - Range = (5,7--5,14) }], (5,7--5,18)); - Attrib - (Typed - (Id - (v, None, false, false, false, (5,28--5,29)), - LongIdent (SynLongIdent ([V], [], [None])), - (5,28--5,32)), - [{ Attributes = - [{ TypeName = - SynLongIdent ([Foo], [], [None]) - ArgExpr = Const (Unit, (5,22--5,25)) - Target = None - AppliesToGetterAndSetter = false - Range = (5,22--5,25) }] - Range = (5,20--5,27) }], (5,20--5,32))], - [(5,18--5,19)], (5,6--5,33)), None, + Paren + (Tuple + (false, + [Attrib + (Named + (SynIdent (bar, None), false, None, + (5,15--5,18)), + [{ Attributes = + [{ TypeName = + SynLongIdent ([Foo], [], [None]) + ArgExpr = Const (Unit, (5,9--5,12)) + Target = None + AppliesToGetterAndSetter = false + Range = (5,9--5,12) }] + Range = (5,7--5,14) }], (5,7--5,18)); + Attrib + (Typed + (Named + (SynIdent (v, None), false, None, + (5,28--5,29)), + LongIdent (SynLongIdent ([V], [], [None])), + (5,28--5,32)), + [{ Attributes = + [{ TypeName = + SynLongIdent ([Foo], [], [None]) + ArgExpr = Const (Unit, (5,22--5,25)) + Target = None + AppliesToGetterAndSetter = false + Range = (5,22--5,25) }] + Range = (5,20--5,27) }], (5,20--5,32))], + [(5,18--5,19)], (5,7--5,32)), (5,6--5,33)), None, PreXmlDoc ((5,6), FSharp.Compiler.Xml.XmlDocCollector), (5,5--5,6), { AsKeyword = None })], (5,36--5,45)), [], Some (ImplicitCtor (None, [], - SimplePats - ([Attrib - (Id (bar, None, false, false, false, (5,15--5,18)), - [{ Attributes = - [{ TypeName = - SynLongIdent ([Foo], [], [None]) - ArgExpr = Const (Unit, (5,9--5,12)) - Target = None - AppliesToGetterAndSetter = false - Range = (5,9--5,12) }] - Range = (5,7--5,14) }], (5,7--5,18)); - Attrib - (Typed - (Id - (v, None, false, false, false, (5,28--5,29)), - LongIdent (SynLongIdent ([V], [], [None])), - (5,28--5,32)), - [{ Attributes = - [{ TypeName = - SynLongIdent ([Foo], [], [None]) - ArgExpr = Const (Unit, (5,22--5,25)) - Target = None - AppliesToGetterAndSetter = false - Range = (5,22--5,25) }] - Range = (5,20--5,27) }], (5,20--5,32))], - [(5,18--5,19)], (5,6--5,33)), None, + Paren + (Tuple + (false, + [Attrib + (Named + (SynIdent (bar, None), false, None, + (5,15--5,18)), + [{ Attributes = + [{ TypeName = + SynLongIdent ([Foo], [], [None]) + ArgExpr = Const (Unit, (5,9--5,12)) + Target = None + AppliesToGetterAndSetter = false + Range = (5,9--5,12) }] + Range = (5,7--5,14) }], (5,7--5,18)); + Attrib + (Typed + (Named + (SynIdent (v, None), false, None, + (5,28--5,29)), + LongIdent (SynLongIdent ([V], [], [None])), + (5,28--5,32)), + [{ Attributes = + [{ TypeName = + SynLongIdent ([Foo], [], [None]) + ArgExpr = Const (Unit, (5,22--5,25)) + Target = None + AppliesToGetterAndSetter = false + Range = (5,22--5,25) }] + Range = (5,20--5,27) }], (5,20--5,32))], + [(5,18--5,19)], (5,7--5,32)), (5,6--5,33)), None, PreXmlDoc ((5,6), FSharp.Compiler.Xml.XmlDocCollector), (5,5--5,6), { AsKeyword = None })), (5,5--5,45), { LeadingKeyword = Type (5,0--5,4) @@ -144,12 +163,12 @@ ImplFile ObjectModel (Class, [ImplicitCtor - (None, [], SimplePats ([], [], (6,9--6,11)), None, + (None, [], Const (Unit, (6,9--6,11)), None, PreXmlDoc ((6,9), FSharp.Compiler.Xml.XmlDocCollector), (6,5--6,9), { AsKeyword = None })], (6,14--6,23)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (6,9--6,11)), None, + (None, [], Const (Unit, (6,9--6,11)), None, PreXmlDoc ((6,9), FSharp.Compiler.Xml.XmlDocCollector), (6,5--6,9), { AsKeyword = None })), (6,5--6,23), { LeadingKeyword = Type (6,0--6,4) diff --git a/tests/service/data/SyntaxTree/Type/As 01.fs.bsl b/tests/service/data/SyntaxTree/Type/As 01.fs.bsl index 84f8bb3c3a7..bec2d3a7121 100644 --- a/tests/service/data/SyntaxTree/Type/As 01.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/As 01.fs.bsl @@ -12,13 +12,13 @@ ImplFile ObjectModel (Class, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), Some this, + (None, [], Const (Unit, (3,6--3,8)), Some this, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })], (3,19--3,28)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), Some this, + (None, [], Const (Unit, (3,6--3,8)), Some this, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })), (3,5--3,28), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/As 02.fs.bsl b/tests/service/data/SyntaxTree/Type/As 02.fs.bsl index b1a6a433c9c..f40ff1a13d0 100644 --- a/tests/service/data/SyntaxTree/Type/As 02.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/As 02.fs.bsl @@ -12,13 +12,13 @@ ImplFile ObjectModel (Class, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })], (3,14--3,23)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })), (3,5--3,23), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/As 05.fs.bsl b/tests/service/data/SyntaxTree/Type/As 05.fs.bsl index 8c216721fbb..52ea9524fef 100644 --- a/tests/service/data/SyntaxTree/Type/As 05.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/As 05.fs.bsl @@ -11,7 +11,7 @@ ImplFile false, None, (3,5--3,6)), Simple (None (3,5--3,6), (3,5--3,6)), [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), Some this, + (None, [], Const (Unit, (3,6--3,8)), Some this, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })], None, (3,5--3,6), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/As 06.fs.bsl b/tests/service/data/SyntaxTree/Type/As 06.fs.bsl index f7f827efbb1..ed933552272 100644 --- a/tests/service/data/SyntaxTree/Type/As 06.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/As 06.fs.bsl @@ -11,7 +11,7 @@ ImplFile false, None, (3,5--3,6)), Simple (None (3,5--3,6), (3,5--3,6)), [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })], None, (3,5--3,6), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/As 07.fs.bsl b/tests/service/data/SyntaxTree/Type/As 07.fs.bsl index 59cc29788eb..a491491159b 100644 --- a/tests/service/data/SyntaxTree/Type/As 07.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/As 07.fs.bsl @@ -11,7 +11,7 @@ ImplFile false, None, (3,5--3,6)), Simple (None (3,5--3,6), (3,5--3,6)), [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), Some this, + (None, [], Const (Unit, (3,6--3,8)), Some this, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })], None, (3,5--3,6), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/As 08.fs.bsl b/tests/service/data/SyntaxTree/Type/As 08.fs.bsl index 3894e1a4c18..24254ea6064 100644 --- a/tests/service/data/SyntaxTree/Type/As 08.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/As 08.fs.bsl @@ -11,7 +11,7 @@ ImplFile false, None, (3,5--3,6)), Simple (None (3,5--3,6), (3,5--3,6)), [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = Some (3,9--3,11) })], None, (3,5--3,6), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Class 03.fs.bsl b/tests/service/data/SyntaxTree/Type/Class 03.fs.bsl index e3e58a8b719..77f8ca8cea0 100644 --- a/tests/service/data/SyntaxTree/Type/Class 03.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Class 03.fs.bsl @@ -12,12 +12,12 @@ ImplFile ObjectModel (Class, [ImplicitCtor - (None, [], SimplePats ([], [], (3,7--3,9)), None, + (None, [], Const (Unit, (3,7--3,9)), None, PreXmlDoc ((3,7), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (4,4--5,7)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,7--3,9)), None, + (None, [], Const (Unit, (3,7--3,9)), None, PreXmlDoc ((3,7), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--5,7), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Class 04.fs.bsl b/tests/service/data/SyntaxTree/Type/Class 04.fs.bsl index e137aa4ebfc..80c75b7d5da 100644 --- a/tests/service/data/SyntaxTree/Type/Class 04.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Class 04.fs.bsl @@ -13,13 +13,13 @@ ImplFile (Class, [ImplicitCtor (Some (Private (3,7--3,14)), [], - SimplePats ([], [], (3,15--3,17)), None, + Const (Unit, (3,15--3,17)), None, PreXmlDoc ((3,7), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (4,4--5,7)), [], Some (ImplicitCtor (Some (Private (3,7--3,14)), [], - SimplePats ([], [], (3,15--3,17)), None, + Const (Unit, (3,15--3,17)), None, PreXmlDoc ((3,7), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--5,7), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Class 05.fs.bsl b/tests/service/data/SyntaxTree/Type/Class 05.fs.bsl index 903fa37b286..6516bdc8320 100644 --- a/tests/service/data/SyntaxTree/Type/Class 05.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Class 05.fs.bsl @@ -19,8 +19,8 @@ ImplFile Target = None AppliesToGetterAndSetter = false Range = (3,9--3,10) }] - Range = (3,7--3,12) }], - SimplePats ([], [], (3,13--3,15)), None, + Range = (3,7--3,12) }], Const (Unit, (3,13--3,15)), + None, PreXmlDoc ((3,7), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (4,4--5,7)), [], Some @@ -32,8 +32,8 @@ ImplFile Target = None AppliesToGetterAndSetter = false Range = (3,9--3,10) }] - Range = (3,7--3,12) }], - SimplePats ([], [], (3,13--3,15)), None, + Range = (3,7--3,12) }], Const (Unit, (3,13--3,15)), + None, PreXmlDoc ((3,7), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--5,7), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Enum 01.fs b/tests/service/data/SyntaxTree/Type/Enum 01.fs new file mode 100644 index 00000000000..a860ed5d529 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 01.fs @@ -0,0 +1,6 @@ +module Module + +type E = + | A = 1 + +() diff --git a/tests/service/data/SyntaxTree/Type/Enum 01.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 01.fs.bsl new file mode 100644 index 00000000000..e10f9194831 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 01.fs.bsl @@ -0,0 +1,28 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 01.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + Const (Int32 1, (4,10--4,11)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,6--4,11), { BarRange = Some (4,4--4,5) + EqualsRange = (4,8--4,9) })], + (4,4--4,11)), (4,4--4,11)), [], None, (3,5--4,11), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,11)); + Expr (Const (Unit, (6,0--6,2)), (6,0--6,2))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--6,2), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) diff --git a/tests/service/data/SyntaxTree/Type/Enum 02.fs b/tests/service/data/SyntaxTree/Type/Enum 02.fs new file mode 100644 index 00000000000..9249fabeb7e --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 02.fs @@ -0,0 +1,6 @@ +module Module + +type E = + A = 1 + +() diff --git a/tests/service/data/SyntaxTree/Type/Enum 02.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 02.fs.bsl new file mode 100644 index 00000000000..e586e137997 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 02.fs.bsl @@ -0,0 +1,27 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 02.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), Const (Int32 1, (4,8--4,9)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,4--4,9), { BarRange = None + EqualsRange = (4,6--4,7) })], + (4,4--4,9)), (4,4--4,9)), [], None, (3,5--4,9), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,9)); + Expr (Const (Unit, (6,0--6,2)), (6,0--6,2))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--6,2), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) diff --git a/tests/service/data/SyntaxTree/Type/Enum 03.fs b/tests/service/data/SyntaxTree/Type/Enum 03.fs new file mode 100644 index 00000000000..4824f909c87 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 03.fs @@ -0,0 +1,6 @@ +module Module + +type E = + | A = + +() diff --git a/tests/service/data/SyntaxTree/Type/Enum 03.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 03.fs.bsl new file mode 100644 index 00000000000..17ed2baa172 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 03.fs.bsl @@ -0,0 +1,31 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 03.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("attrUnionCaseDecl", (4,9--4,9)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,6--4,9), { BarRange = Some (4,4--4,5) + EqualsRange = (4,8--4,9) })], + (4,4--4,9)), (4,4--4,9)), [], None, (3,5--4,9), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,9)); + Expr (Const (Unit, (6,0--6,2)), (6,0--6,2))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--6,2), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(6,0)-(6,1) parse error Incomplete structured construct at or before this point in union case diff --git a/tests/service/data/SyntaxTree/Type/Enum 04.fs b/tests/service/data/SyntaxTree/Type/Enum 04.fs new file mode 100644 index 00000000000..98244e15ee3 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 04.fs @@ -0,0 +1,7 @@ +module Module + +type E = + | A = + | B = 2 + +() diff --git a/tests/service/data/SyntaxTree/Type/Enum 04.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 04.fs.bsl new file mode 100644 index 00000000000..faed14098e3 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 04.fs.bsl @@ -0,0 +1,37 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 04.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("attrUnionCaseDecl", (4,9--4,9)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,6--4,9), { BarRange = Some (4,4--4,5) + EqualsRange = (4,8--4,9) }); + SynEnumCase + ([], SynIdent (B, None), + Const (Int32 2, (5,10--5,11)), + PreXmlDoc ((5,4), FSharp.Compiler.Xml.XmlDocCollector), + (5,6--5,11), { BarRange = Some (5,4--5,5) + EqualsRange = (5,8--5,9) })], + (4,4--5,11)), (4,4--5,11)), [], None, (3,5--5,11), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--5,11)); + Expr (Const (Unit, (7,0--7,2)), (7,0--7,2))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--7,2), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(5,4)-(5,5) parse error Unexpected symbol '|' in union case diff --git a/tests/service/data/SyntaxTree/Type/Enum 05.fs b/tests/service/data/SyntaxTree/Type/Enum 05.fs new file mode 100644 index 00000000000..191e3b2f926 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 05.fs @@ -0,0 +1,6 @@ +module Module + +type E = + A = + +() diff --git a/tests/service/data/SyntaxTree/Type/Enum 05.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 05.fs.bsl new file mode 100644 index 00000000000..fd808927027 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 05.fs.bsl @@ -0,0 +1,31 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 05.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("firstUnionCaseDecl", (4,7--4,7)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,4--4,7), { BarRange = None + EqualsRange = (4,6--4,7) })], + (4,4--4,7)), (4,4--4,7)), [], None, (3,5--4,7), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,7)); + Expr (Const (Unit, (6,0--6,2)), (6,0--6,2))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--6,2), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(6,0)-(6,1) parse error Incomplete structured construct at or before this point in type definition diff --git a/tests/service/data/SyntaxTree/Type/Enum 06.fs b/tests/service/data/SyntaxTree/Type/Enum 06.fs new file mode 100644 index 00000000000..5c2fb93e2b1 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 06.fs @@ -0,0 +1,7 @@ +module Module + +type E = + A = + | B = 2 + +() diff --git a/tests/service/data/SyntaxTree/Type/Enum 06.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 06.fs.bsl new file mode 100644 index 00000000000..b7fd06cbbd2 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 06.fs.bsl @@ -0,0 +1,37 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 06.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("firstUnionCaseDeclOfMany1", (4,9--4,9)), + PreXmlDoc ((4,6), FSharp.Compiler.Xml.XmlDocCollector), + (4,6--4,9), { BarRange = None + EqualsRange = (4,8--4,9) }); + SynEnumCase + ([], SynIdent (B, None), + Const (Int32 2, (5,10--5,11)), + PreXmlDoc ((5,4), FSharp.Compiler.Xml.XmlDocCollector), + (5,6--5,11), { BarRange = Some (5,4--5,5) + EqualsRange = (5,8--5,9) })], + (4,6--5,11)), (4,6--5,11)), [], None, (3,5--5,11), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--5,11)); + Expr (Const (Unit, (7,0--7,2)), (7,0--7,2))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--7,2), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(5,4)-(5,5) parse error Unexpected symbol '|' in type definition diff --git a/tests/service/data/SyntaxTree/Type/Enum 07 - Eof.fs b/tests/service/data/SyntaxTree/Type/Enum 07 - Eof.fs new file mode 100644 index 00000000000..87cd5255650 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 07 - Eof.fs @@ -0,0 +1,4 @@ +module Module + +type E = + | A = diff --git a/tests/service/data/SyntaxTree/Type/Enum 07 - Eof.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 07 - Eof.fs.bsl new file mode 100644 index 00000000000..5278e60ecd8 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 07 - Eof.fs.bsl @@ -0,0 +1,30 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 07 - Eof.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("attrUnionCaseDecl", (4,9--4,9)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,6--4,9), { BarRange = Some (4,4--4,5) + EqualsRange = (4,8--4,9) })], + (4,4--4,9)), (4,4--4,9)), [], None, (3,5--4,9), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,9))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--4,9), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(5,0)-(5,0) parse error Incomplete structured construct at or before this point in union case diff --git a/tests/service/data/SyntaxTree/Type/Enum 08 - Eof.fs b/tests/service/data/SyntaxTree/Type/Enum 08 - Eof.fs new file mode 100644 index 00000000000..e66175c3823 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 08 - Eof.fs @@ -0,0 +1,4 @@ +module Module + +type E = + A = diff --git a/tests/service/data/SyntaxTree/Type/Enum 08 - Eof.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 08 - Eof.fs.bsl new file mode 100644 index 00000000000..b715aa57067 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 08 - Eof.fs.bsl @@ -0,0 +1,30 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 08 - Eof.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("firstUnionCaseDecl", (4,7--4,7)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,4--4,7), { BarRange = None + EqualsRange = (4,6--4,7) })], + (4,4--4,7)), (4,4--4,7)), [], None, (3,5--4,7), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,7))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--4,7), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(5,0)-(5,0) parse error Incomplete structured construct at or before this point in type definition diff --git a/tests/service/data/SyntaxTree/Type/Enum 09 - Eof.fs b/tests/service/data/SyntaxTree/Type/Enum 09 - Eof.fs new file mode 100644 index 00000000000..cb185c00cd5 --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 09 - Eof.fs @@ -0,0 +1,4 @@ +module Module + +type E = + | A = \ No newline at end of file diff --git a/tests/service/data/SyntaxTree/Type/Enum 09 - Eof.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 09 - Eof.fs.bsl new file mode 100644 index 00000000000..c1756aeb77a --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 09 - Eof.fs.bsl @@ -0,0 +1,30 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 09 - Eof.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("attrUnionCaseDecl", (4,9--4,9)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,6--4,9), { BarRange = Some (4,4--4,5) + EqualsRange = (4,8--4,9) })], + (4,4--4,9)), (4,4--4,9)), [], None, (3,5--4,9), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,9))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--4,9), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(4,0)-(4,9) parse error Incomplete structured construct at or before this point in union case diff --git a/tests/service/data/SyntaxTree/Type/Enum 10 - Eof.fs b/tests/service/data/SyntaxTree/Type/Enum 10 - Eof.fs new file mode 100644 index 00000000000..0f08891b10e --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 10 - Eof.fs @@ -0,0 +1,4 @@ +module Module + +type E = + A = \ No newline at end of file diff --git a/tests/service/data/SyntaxTree/Type/Enum 10 - Eof.fs.bsl b/tests/service/data/SyntaxTree/Type/Enum 10 - Eof.fs.bsl new file mode 100644 index 00000000000..6a6bf175b1d --- /dev/null +++ b/tests/service/data/SyntaxTree/Type/Enum 10 - Eof.fs.bsl @@ -0,0 +1,30 @@ +ImplFile + (ParsedImplFileInput + ("/root/Type/Enum 10 - Eof.fs", false, QualifiedNameOfFile Module, [], [], + [SynModuleOrNamespace + ([Module], false, NamedModule, + [Types + ([SynTypeDefn + (SynComponentInfo + ([], None, [], [E], + PreXmlDoc ((3,0), FSharp.Compiler.Xml.XmlDocCollector), + false, None, (3,5--3,6)), + Simple + (Enum + ([SynEnumCase + ([], SynIdent (A, None), + ArbitraryAfterError + ("firstUnionCaseDecl", (4,7--4,7)), + PreXmlDoc ((4,4), FSharp.Compiler.Xml.XmlDocCollector), + (4,4--4,7), { BarRange = None + EqualsRange = (4,6--4,7) })], + (4,4--4,7)), (4,4--4,7)), [], None, (3,5--4,7), + { LeadingKeyword = Type (3,0--3,4) + EqualsRange = Some (3,7--3,8) + WithKeyword = None })], (3,0--4,7))], + PreXmlDoc ((1,0), FSharp.Compiler.Xml.XmlDocCollector), [], None, + (1,0--4,7), { LeadingKeyword = Module (1,0--1,6) })], (true, true), + { ConditionalDirectives = [] + CodeComments = [] }, set [])) + +(4,0)-(4,7) parse error Incomplete structured construct at or before this point in type definition diff --git a/tests/service/data/SyntaxTree/Type/Primary ctor 01.fs.bsl b/tests/service/data/SyntaxTree/Type/Primary ctor 01.fs.bsl index 24fbd4e7c8f..6717cb55b41 100644 --- a/tests/service/data/SyntaxTree/Type/Primary ctor 01.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Primary ctor 01.fs.bsl @@ -12,12 +12,12 @@ ImplFile ObjectModel (Class, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,11--3,20)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,20), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Primary ctor 02.fs.bsl b/tests/service/data/SyntaxTree/Type/Primary ctor 02.fs.bsl index a770ed3442e..fbb48e2fd0a 100644 --- a/tests/service/data/SyntaxTree/Type/Primary ctor 02.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Primary ctor 02.fs.bsl @@ -12,12 +12,12 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,5--3,10)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,10), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Primary ctor 03.fs.bsl b/tests/service/data/SyntaxTree/Type/Primary ctor 03.fs.bsl index 882320fe29f..7bf4dedee58 100644 --- a/tests/service/data/SyntaxTree/Type/Primary ctor 03.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Primary ctor 03.fs.bsl @@ -11,7 +11,7 @@ ImplFile false, None, (3,5--3,6)), Simple (None (3,5--3,6), (3,5--3,6)), [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], None, (3,5--3,6), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Primary ctor 04.fs.bsl b/tests/service/data/SyntaxTree/Type/Primary ctor 04.fs.bsl index 6505497c378..a46c198cdfe 100644 --- a/tests/service/data/SyntaxTree/Type/Primary ctor 04.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Primary ctor 04.fs.bsl @@ -12,12 +12,12 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,5--3,10)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,10), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/Primary ctor 05.fs.bsl b/tests/service/data/SyntaxTree/Type/Primary ctor 05.fs.bsl index 352346a2396..17215f552fc 100644 --- a/tests/service/data/SyntaxTree/Type/Primary ctor 05.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Primary ctor 05.fs.bsl @@ -11,7 +11,7 @@ ImplFile false, None, (3,5--3,6)), Simple (None (3,5--3,6), (3,5--3,6)), [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], None, (3,5--3,6), { LeadingKeyword = Type (3,0--3,4) diff --git a/tests/service/data/SyntaxTree/Type/SynMemberDefnInterfaceContainsTheRangeOfTheWithKeyword.fs.bsl b/tests/service/data/SyntaxTree/Type/SynMemberDefnInterfaceContainsTheRangeOfTheWithKeyword.fs.bsl index ed20d359009..cc2e1a3997f 100644 --- a/tests/service/data/SyntaxTree/Type/SynMemberDefnInterfaceContainsTheRangeOfTheWithKeyword.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/SynMemberDefnInterfaceContainsTheRangeOfTheWithKeyword.fs.bsl @@ -16,7 +16,7 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None }); Interface @@ -57,7 +57,7 @@ ImplFile None, (5,4--5,19))], (3,4--5,19)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (2,8--2,10)), None, + (None, [], Const (Unit, (2,8--2,10)), None, PreXmlDoc ((2,8), FSharp.Compiler.Xml.XmlDocCollector), (2,5--2,8), { AsKeyword = None })), (2,5--5,19), { LeadingKeyword = Type (2,0--2,4) diff --git a/tests/service/data/SyntaxTree/Type/Type 11.fs.bsl b/tests/service/data/SyntaxTree/Type/Type 11.fs.bsl index fb9f7a3d57e..074cead59e8 100644 --- a/tests/service/data/SyntaxTree/Type/Type 11.fs.bsl +++ b/tests/service/data/SyntaxTree/Type/Type 11.fs.bsl @@ -12,12 +12,12 @@ ImplFile ObjectModel (Unspecified, [ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })], (3,5--3,10)), [], Some (ImplicitCtor - (None, [], SimplePats ([], [], (3,6--3,8)), None, + (None, [], Const (Unit, (3,6--3,8)), None, PreXmlDoc ((3,6), FSharp.Compiler.Xml.XmlDocCollector), (3,5--3,6), { AsKeyword = None })), (3,5--3,10), { LeadingKeyword = Type (3,0--3,4) diff --git a/vsintegration/readme.md b/vsintegration/readme.md index 4f929238bdc..b09865b8149 100644 --- a/vsintegration/readme.md +++ b/vsintegration/readme.md @@ -12,6 +12,10 @@ Top-level project for the Visual F# IDE tools. This project contains the follow In general, if something is implemented here and the logic becomes rather lengthy, it may be a good idea to push that logic down into the F# Compiler Service so that other editors can benefit. +# src/FSharp.VS.FSI + +F# Interactive implementation. + # src/FSharp.UIResources GUI controls and resources for Visual F# tooling. diff --git a/vsintegration/src/FSharp.Editor/Common/CancellableTasks.fs b/vsintegration/src/FSharp.Editor/Common/CancellableTasks.fs index 1cd71d4228e..0326688f987 100644 --- a/vsintegration/src/FSharp.Editor/Common/CancellableTasks.fs +++ b/vsintegration/src/FSharp.Editor/Common/CancellableTasks.fs @@ -1107,6 +1107,16 @@ module CancellableTasks = return! Task.WhenAll (tasks) } + let inline sequential (tasks: CancellableTask<'a> seq) = + cancellableTask { + let! ct = getCancellationToken () + let results = ResizeArray() + for task in tasks do + let! result = start ct task + results.Add(result) + return results + } + let inline ignore ([] ctask: CancellableTask<_>) = toUnit ctask /// diff --git a/vsintegration/src/FSharp.Editor/Common/Extensions.fs b/vsintegration/src/FSharp.Editor/Common/Extensions.fs index eb2f61c4147..b0eb7305713 100644 --- a/vsintegration/src/FSharp.Editor/Common/Extensions.fs +++ b/vsintegration/src/FSharp.Editor/Common/Extensions.fs @@ -87,7 +87,7 @@ module private SourceText = let combineValues (values: seq<'T>) = (0, values) ||> Seq.fold (fun hash value -> combine (value.GetHashCode()) hash) - let weakTable = ConditionalWeakTable() + let weakTable = ConditionalWeakTable() let create (sourceText: SourceText) = let sourceText = @@ -111,7 +111,9 @@ module private SourceText = |> Hash.combine encodingHash |> Hash.combine contentsHash |> Hash.combine sourceText.Length - interface ISourceText with + + override _.ToString() = sourceText.ToString() + interface ISourceTextNew with member _.Item with get index = sourceText.[index] @@ -197,6 +199,8 @@ module private SourceText = let lastLine = this.GetLineString(range.EndLine - 1) sb.Append(lastLine.Substring(0, range.EndColumn)).ToString() + + member _.GetChecksum() = sourceText.GetChecksum() } sourceText diff --git a/vsintegration/src/FSharp.Editor/Common/Logging.fs b/vsintegration/src/FSharp.Editor/Common/Logging.fs index 0ba681dc589..a69779e9acc 100644 --- a/vsintegration/src/FSharp.Editor/Common/Logging.fs +++ b/vsintegration/src/FSharp.Editor/Common/Logging.fs @@ -93,7 +93,10 @@ module Logging = let inline debug msg = Printf.kprintf Debug.WriteLine msg let private logger = lazy Logger(Logger.GlobalServiceProvider) - let private log logType msg = logger.Value.Log(logType, msg) + + let private log logType msg = + logger.Value.Log(logType, msg) + System.Diagnostics.Trace.TraceInformation(msg) let logMsg msg = log LogType.Message msg let logInfo msg = log LogType.Info msg diff --git a/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs b/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs index 0014f1d2397..a18987ac48c 100644 --- a/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs +++ b/vsintegration/src/FSharp.Editor/Completion/CompletionProvider.fs @@ -26,7 +26,12 @@ open CancellableTasks module Logger = Microsoft.VisualStudio.FSharp.Editor.Logger type internal FSharpCompletionProvider - (workspace: Workspace, serviceProvider: SVsServiceProvider, assemblyContentProvider: AssemblyContentProvider) = + ( + workspace: Workspace, + serviceProvider: SVsServiceProvider, + assemblyContentProvider: AssemblyContentProvider, + editorOptions: EditorOptions + ) = inherit FSharpCompletionProviderBase() @@ -380,7 +385,16 @@ type internal FSharpCompletionProvider let documentation = List() let collector = RoslynHelpers.CollectTaggedText documentation // mix main description and xmldoc by using one collector - XmlDocumentation.BuildDataTipText(documentationBuilder, collector, collector, collector, collector, collector, description) + XmlDocumentation.BuildDataTipText( + documentationBuilder, + collector, + collector, + collector, + collector, + collector, + description, + editorOptions.QuickInfo.ShowRemarks + ) Task.FromResult(CompletionDescription.Create(documentation.ToImmutableArray())) | _ -> diff --git a/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs b/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs index 7975b31b155..13f7e3d3b30 100644 --- a/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs +++ b/vsintegration/src/FSharp.Editor/Completion/CompletionService.fs @@ -24,7 +24,7 @@ type internal FSharpCompletionService let builtInProviders = ImmutableArray.Create( - FSharpCompletionProvider(workspace, serviceProvider, assemblyContentProvider), + FSharpCompletionProvider(workspace, serviceProvider, assemblyContentProvider, settings), FSharpCommonCompletionProvider.Create(HashDirectiveCompletionProvider.Create(workspace, projectInfoManager)) ) diff --git a/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs b/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs index 595f051900b..f00deaa9250 100644 --- a/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs +++ b/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs @@ -58,7 +58,7 @@ type SignatureHelpData = [] [)>] -type internal FSharpSignatureHelpProvider [] (serviceProvider: SVsServiceProvider) = +type internal FSharpSignatureHelpProvider [] (serviceProvider: SVsServiceProvider, editorOptions: EditorOptions) = let documentationBuilder = XmlDocumentation.CreateDocumentationBuilder(serviceProvider.XMLMemberIndexService) @@ -79,7 +79,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi documentationBuilder: IDocumentationBuilder, sourceText: SourceText, caretPosition: int, - triggerIsTypedChar: char option + triggerIsTypedChar: char option, + editorOptions: EditorOptions ) = asyncMaybe { let textLines = sourceText.Lines @@ -206,7 +207,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi RoslynHelpers.CollectTaggedText mainDescription, RoslynHelpers.CollectTaggedText documentation, method.Description, - false + false, + editorOptions.QuickInfo.ShowRemarks ) let parameters = @@ -225,7 +227,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi documentationBuilder, RoslynHelpers.CollectTaggedText doc, method.XmlDoc, - p.ParameterName + p.ParameterName, + editorOptions.QuickInfo.ShowRemarks ) p.Display |> Seq.iter (RoslynHelpers.CollectTaggedText parts) @@ -292,7 +295,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi sourceText: SourceText, caretPosition: int, adjustedColumnInSource: int, - filePath: string + filePath: string, + editorOptions: EditorOptions ) = asyncMaybe { let textLine = sourceText.Lines.GetLineFromPosition(adjustedColumnInSource) @@ -430,7 +434,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi typeParameterMap.Add, usage.Add, exceptions.Add, - tooltip + tooltip, + editorOptions.QuickInfo.ShowRemarks ) let fsharpDocs = @@ -606,7 +611,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi documentationBuilder: IDocumentationBuilder, caretPosition: int, triggerTypedChar: char option, - possibleCurrentSignatureHelpSessionKind: CurrentSignatureHelpSessionKind option + possibleCurrentSignatureHelpSessionKind: CurrentSignatureHelpSessionKind option, + editorOptions: EditorOptions ) = asyncMaybe { @@ -623,14 +629,18 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi let caretLineColumn = caretLinePos.Character let adjustedColumnInSource = - - let rec loop ch pos = - if Char.IsWhiteSpace(ch) then - loop sourceText.[pos - 1] (pos - 1) - else + let rec loop pos = + if pos = 0 then pos + else + let nextPos = pos - 1 + + if not (Char.IsWhiteSpace sourceText[nextPos]) then + pos + else + loop nextPos - loop sourceText.[caretPosition - 1] (caretPosition - 1) + loop (caretPosition - 1) let adjustedColumnChar = sourceText.[adjustedColumnInSource] @@ -655,7 +665,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi sourceText, caretPosition, adjustedColumnInSource, - document.FilePath + document.FilePath, + editorOptions ) | _, Some FunctionApplication when adjustedColumnChar <> ',' @@ -674,7 +685,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi sourceText, caretPosition, adjustedColumnInSource, - document.FilePath + document.FilePath, + editorOptions ) | _ -> let! paramInfoLocations = parseResults.FindParameterLocations(Position.fromZ caretLinePos.Line caretLineColumn) @@ -688,7 +700,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi documentationBuilder, sourceText, caretPosition, - triggerTypedChar + triggerTypedChar, + editorOptions ) } @@ -722,7 +735,8 @@ type internal FSharpSignatureHelpProvider [] (serviceProvi documentationBuilder, position, triggerTypedChar, - possibleCurrentSignatureHelpSessionKind + possibleCurrentSignatureHelpSessionKind, + editorOptions ) match signatureHelpDataOpt with diff --git a/vsintegration/src/FSharp.Editor/Diagnostics/UnnecessaryParenthesesDiagnosticAnalyzer.fs b/vsintegration/src/FSharp.Editor/Diagnostics/UnnecessaryParenthesesDiagnosticAnalyzer.fs index bc433015ec9..07201f8a0a3 100644 --- a/vsintegration/src/FSharp.Editor/Diagnostics/UnnecessaryParenthesesDiagnosticAnalyzer.fs +++ b/vsintegration/src/FSharp.Editor/Diagnostics/UnnecessaryParenthesesDiagnosticAnalyzer.fs @@ -3,11 +3,12 @@ namespace Microsoft.VisualStudio.FSharp.Editor open System.Composition +open System.Collections.Generic open System.Collections.Immutable open System.Runtime.Caching open System.Threading open System.Threading.Tasks -open FSharp.Compiler.EditorServices +open FSharp.Compiler.Syntax open FSharp.Compiler.Text open Microsoft.CodeAnalysis open Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics @@ -70,13 +71,31 @@ type internal UnnecessaryParenthesesDiagnosticAnalyzer [] let getLineString line = sourceText.Lines[Line.toZ line].ToString() - let! unnecessaryParentheses = UnnecessaryParentheses.getUnnecessaryParentheses getLineString parseResults.ParseTree + let unnecessaryParentheses = + (HashSet Range.comparer, parseResults.ParseTree) + ||> ParsedInput.fold (fun ranges path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; rightParenRange = Some _; range = range)) when + not (SynExpr.shouldBeParenthesizedInContext getLineString path inner) + -> + ignore (ranges.Add range) + ranges + + | SyntaxNode.SynPat(SynPat.Paren(inner, range)) when not (SynPat.shouldBeParenthesizedInContext path inner) -> + ignore (ranges.Add range) + ranges + + | _ -> ranges) let diagnostics = - unnecessaryParentheses - |> Seq.map (fun range -> - Diagnostic.Create(descriptor, RoslynHelpers.RangeToLocation(range, sourceText, document.FilePath))) - |> Seq.toImmutableArray + let builder = ImmutableArray.CreateBuilder unnecessaryParentheses.Count + + for range in unnecessaryParentheses do + builder.Add( + Diagnostic.Create(descriptor, RoslynHelpers.RangeToLocation(range, sourceText, document.FilePath)) + ) + + builder.MoveToImmutable() ignore (cache.Remove key) diff --git a/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs b/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs index 1c807bfad91..b3228180ff2 100644 --- a/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs +++ b/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs @@ -100,6 +100,7 @@ type internal IDocumentationBuilder = processedXml: string * showExceptions: bool * showParameters: bool * + showRemarks: bool * paramName: string option -> unit @@ -111,6 +112,7 @@ type internal IDocumentationBuilder = signature: string * showExceptions: bool * showParameters: bool * + showRemarks: bool * paramName: string option -> unit @@ -165,6 +167,7 @@ module internal XmlDocumentation = | "typeref" -> for attr in el.Attributes() do WriteAttribute collector attr "name" (tagParameter >> collector.Add) + | "br" -> AppendHardLine collector | _ -> WriteNodes collector (el.Nodes()) | _ -> () @@ -210,13 +213,34 @@ module internal XmlDocumentation = with _ -> None - member _.CollectSummary(collector: ITaggedTextCollector) = + member _.CollectSummary(collector: ITaggedTextCollector, showRemarks) = match Seq.tryHead (doc.Descendants(XName.op_Implicit "summary")) with | None -> () | Some el -> EnsureHardLine collector WriteElement collector el + match Seq.tryHead (doc.Descendants(XName.op_Implicit "returns")) with + | None -> () + | Some el -> + AppendHardLine collector + AppendHardLine collector + AppendOnNewLine collector (SR.ReturnsHeader()) + AppendHardLine collector + collector.Add(tagSpace " ") + WriteElement collector el + + if showRemarks then + match Seq.tryHead (doc.Descendants(XName.op_Implicit "remarks")) with + | None -> () + | Some el -> + AppendHardLine collector + AppendHardLine collector + AppendOnNewLine collector (SR.RemarksHeader()) + AppendHardLine collector + collector.Add(tagSpace " ") + WriteElement collector el + member this.CollectParameter(collector: ITaggedTextCollector, paramName: string) = match tryFindParameter paramName with | None -> () @@ -294,11 +318,12 @@ module internal XmlDocumentation = exnCollector: ITaggedTextCollector, xmlDocReader: XmlDocReader, showExceptions, - showParameters + showParameters, + showRemarks ) = AppendHardLine xmlCollector xmlCollector.StartXMLDoc() - xmlDocReader.CollectSummary(xmlCollector) + xmlDocReader.CollectSummary(xmlCollector, showRemarks) if (showParameters) then xmlDocReader.CollectParameters xmlCollector @@ -315,13 +340,14 @@ module internal XmlDocumentation = processedXml, showExceptions, showParameters, + showRemarks, paramName ) = match XmlDocReader.TryCreate processedXml with | Some xmlDocReader -> match paramName with | Some paramName -> xmlDocReader.CollectParameter(xmlCollector, paramName) - | None -> AppendMemberData(xmlCollector, exnCollector, xmlDocReader, showExceptions, showParameters) + | None -> AppendMemberData(xmlCollector, exnCollector, xmlDocReader, showExceptions, showParameters, showRemarks) | None -> () /// Append Xml documentation contents into the StringBuilder @@ -333,14 +359,15 @@ module internal XmlDocumentation = signature: string, showExceptions: bool, showParameters: bool, + showRemarks, paramName: string option ) = try match GetMemberIndexOfAssembly(fileName) with | Some(index) -> - let _, idx = index.ParseMemberSignature(signature) + let ok, idx = index.ParseMemberSignature(signature) - if idx <> 0u then + if Com.Succeeded(ok) then let ok, xml = index.GetMemberXML(idx) if Com.Succeeded(ok) then @@ -351,6 +378,7 @@ module internal XmlDocumentation = xml, showExceptions, showParameters, + showRemarks, paramName ) | None -> () @@ -367,6 +395,7 @@ module internal XmlDocumentation = xml, showExceptions, showParameters, + showRemarks, paramName ) = match xml with @@ -379,6 +408,7 @@ module internal XmlDocumentation = signature, showExceptions, showParameters, + showRemarks, paramName ) | FSharpXmlDoc.FromXmlText(xmlDoc) -> @@ -391,6 +421,7 @@ module internal XmlDocumentation = processedXml, showExceptions, showParameters, + showRemarks, paramName ) @@ -417,7 +448,13 @@ module internal XmlDocumentation = OverLoadsLimit = 5 } - let BuildSingleTipText (documentationProvider: IDocumentationBuilder, dataTipElement: ToolTipElement, limits: LineLimits) = + let BuildSingleTipText + ( + documentationProvider: IDocumentationBuilder, + dataTipElement: ToolTipElement, + limits: LineLimits, + showRemarks: bool + ) = let { LineLimit = lineLimit @@ -481,7 +518,7 @@ module internal XmlDocumentation = AppendHardLine usageCollector r |> Seq.iter usageCollector.Add) - AppendXmlComment(documentationProvider, xmlCollector, exnCollector, item0.XmlDoc, true, false, item0.ParamName) + AppendXmlComment(documentationProvider, xmlCollector, exnCollector, item0.XmlDoc, true, false, showRemarks, item0.ParamName) ProcessGenericParameters item0.TypeMapping @@ -505,7 +542,8 @@ module internal XmlDocumentation = exnCollector, showText, showExceptions, - showParameters + showParameters, + showRemarks ) = let textCollector: ITaggedTextCollector = TextSanitizingCollector(textCollector, lineLimit = 45) :> _ @@ -590,6 +628,7 @@ module internal XmlDocumentation = item0.XmlDoc, showExceptions, showParameters, + showRemarks, item0.ParamName ) @@ -614,7 +653,8 @@ module internal XmlDocumentation = typeParameterMapCollector, usageCollector, exnCollector, - ToolTipText(dataTipText) + ToolTipText(dataTipText), + showRemarks ) = BuildTipText( documentationProvider, @@ -626,10 +666,11 @@ module internal XmlDocumentation = exnCollector, true, true, - false + false, + showRemarks ) - let BuildMethodOverloadTipText (documentationProvider, textCollector, xmlCollector, ToolTipText(dataTipText), showParams) = + let BuildMethodOverloadTipText (documentationProvider, textCollector, xmlCollector, ToolTipText(dataTipText), showParams, showRemarks) = BuildTipText( documentationProvider, dataTipText, @@ -640,10 +681,11 @@ module internal XmlDocumentation = ignore, false, false, - showParams + showParams, + showRemarks ) - let BuildMethodParamText (documentationProvider, xmlCollector, xml, paramName) = + let BuildMethodParamText (documentationProvider, xmlCollector, xml, paramName, showRemarks) = AppendXmlComment( documentationProvider, TextSanitizingCollector(xmlCollector), @@ -651,6 +693,7 @@ module internal XmlDocumentation = xml, false, true, + showRemarks, Some paramName ) diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj index 60e86c9eb96..37bb02d43d2 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj @@ -99,6 +99,7 @@ + diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx index 4b41551aac0..6678a2d98e3 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx @@ -180,7 +180,8 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; +Dash underline; +Show remarks in Quick Info Add an assembly reference to '{0}' @@ -226,6 +227,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis @@ -352,7 +354,16 @@ Use live (unsaved) buffers for analysis Convert C# 'using' to F# 'open' + + Add return type annotation + Remove unnecessary parentheses + + Remarks: + + + Returns: + \ No newline at end of file diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 301428f69cb..b492cf1f35f 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -25,6 +25,7 @@ open Microsoft.CodeAnalysis.ExternalAccess.FSharp open Microsoft.CodeAnalysis.Host.Mef open Microsoft.VisualStudio.FSharp.Editor.Telemetry open CancellableTasks +open FSharp.Compiler.Text #nowarn "9" // NativePtr.toNativeInt #nowarn "57" // Experimental stuff @@ -147,6 +148,8 @@ type internal FSharpWorkspaceServiceFactory [] let enableBackgroundItemKeyStoreAndSemanticClassification = editorOptions.LanguageServicePerformance.EnableBackgroundItemKeyStoreAndSemanticClassification + let useTransparentCompiler = editorOptions.Advanced.UseTransparentCompiler + // Default is false here let solutionCrawler = editorOptions.Advanced.SolutionBackgroundAnalysis @@ -168,6 +171,7 @@ type internal FSharpWorkspaceServiceFactory [] nameof enableBackgroundItemKeyStoreAndSemanticClassification, enableBackgroundItemKeyStoreAndSemanticClassification "captureIdentifiersWhenParsing", enableFastFindReferences + nameof useTransparentCompiler, useTransparentCompiler nameof solutionCrawler, solutionCrawler |], TelemetryThrottlingStrategy.NoThrottling @@ -187,13 +191,19 @@ type internal FSharpWorkspaceServiceFactory [] captureIdentifiersWhenParsing = enableFastFindReferences, documentSource = (if enableLiveBuffers then - DocumentSource.Custom getSource + (DocumentSource.Custom(fun filename -> + async { + match! getSource filename with + | Some source -> return Some(source :> ISourceText) + | None -> return None + })) else DocumentSource.FileSystem), - useSyntaxTreeCache = useSyntaxTreeCache + useSyntaxTreeCache = useSyntaxTreeCache, + useTransparentCompiler = useTransparentCompiler ) - if enableLiveBuffers then + if enableLiveBuffers && not useTransparentCompiler then workspace.WorkspaceChanged.Add(fun args -> if args.DocumentId <> null then cancellableTask { @@ -481,10 +491,10 @@ type internal HackCpsCommandLineChanges else Path.GetFileNameWithoutExtension projectFileName - [] /// 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, @@ -527,10 +537,10 @@ type internal HackCpsCommandLineChanges let sourcePaths = sources |> Seq.map (fun s -> getFullPath s.Path) |> Seq.toArray - /// 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. + // 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 = diff --git a/vsintegration/src/FSharp.Editor/LanguageService/SymbolHelpers.fs b/vsintegration/src/FSharp.Editor/LanguageService/SymbolHelpers.fs index 8a74c5ad795..261c4950ef9 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/SymbolHelpers.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/SymbolHelpers.fs @@ -3,6 +3,7 @@ namespace Microsoft.VisualStudio.FSharp.Editor open System.Collections.Concurrent +open System.Collections.Generic open System.Collections.Immutable open System.Threading.Tasks @@ -80,9 +81,19 @@ module internal SymbolHelpers = // TODO: this needs to be a single event with a duration TelemetryReporter.ReportSingleEvent(TelemetryEvents.GetSymbolUsesInProjectsStarted, props) + let snapshotAccumulator = Dictionary() + + let! projects = + projects + |> Seq.map (fun project -> + project.GetFSharpProjectSnapshot(snapshotAccumulator) + |> CancellableTask.map (fun s -> project, s)) + |> CancellableTask.sequential + do! projects - |> Seq.map (fun project -> project.FindFSharpReferencesAsync(symbol, onFound, "getSymbolUsesInProjects")) + |> Seq.map (fun (project, snapshot) -> + project.FindFSharpReferencesAsync(symbol, snapshot, onFound, "getSymbolUsesInProjects")) |> CancellableTask.whenAll TelemetryReporter.ReportSingleEvent(TelemetryEvents.GetSymbolUsesInProjectsFinished, props) diff --git a/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs b/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs index 891eb960ab3..c0682607360 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/WorkspaceExtensions.fs @@ -9,12 +9,326 @@ open Microsoft.VisualStudio.FSharp.Editor open FSharp.Compiler open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.CodeAnalysis.ProjectSnapshot open FSharp.Compiler.Symbols -open Microsoft.VisualStudio.FSharp.Editor.CancellableTasks +open FSharp.Compiler.BuildGraph + +open CancellableTasks + +open Internal.Utilities.Collections +open Newtonsoft.Json +open Newtonsoft.Json.Linq +open System.Text.Json.Nodes + +#nowarn "57" // Experimental stuff + +[] +module internal ProjectCache = + + /// This is a cache to maintain FSharpParsingOptions and FSharpProjectOptions per Roslyn Project. + /// The Roslyn Project is held weakly meaning when it is cleaned up by the GC, the FSharParsingOptions and FSharpProjectOptions will be cleaned up by the GC. + /// At some point, this will be the main caching mechanism for FCS projects instead of FCS itself. + let Projects = + ConditionalWeakTable() + +type Solution with + + /// Get the instance of IFSharpWorkspaceService. + member internal this.GetFSharpWorkspaceService() = + this.Workspace.Services.GetRequiredService() + +module internal FSharpProjectSnapshotSerialization = + + let serializeFileSnapshot (snapshot: FSharpFileSnapshot) = + let output = JObject() + output.Add("FileName", snapshot.FileName) + output.Add("Version", snapshot.Version) + output + + let serializeReferenceOnDisk (reference: ReferenceOnDisk) = + let output = JObject() + output.Add("Path", reference.Path) + output.Add("LastModified", reference.LastModified) + output + + let rec serializeReferencedProject (reference: FSharpReferencedProjectSnapshot) = + let output = JObject() + + match reference with + | FSharpReference(projectOutputFile, snapshot) -> + output.Add("projectOutputFile", projectOutputFile) + output.Add("snapshot", serializeSnapshot snapshot) + + output + + and serializeSnapshot (snapshot: FSharpProjectSnapshot) = + + let output = JObject() + let snapshot = snapshot.ProjectSnapshot + + output.Add("ProjectFileName", snapshot.ProjectFileName) + output.Add("ProjectId", (snapshot.ProjectId |> Option.defaultValue null |> JToken.FromObject)) + output.Add("SourceFiles", snapshot.SourceFiles |> Seq.map serializeFileSnapshot |> JArray) + output.Add("ReferencesOnDisk", snapshot.ReferencesOnDisk |> Seq.map serializeReferenceOnDisk |> JArray) + output.Add("OtherOptions", JArray(snapshot.OtherOptions)) + output.Add("ReferencedProjects", snapshot.ReferencedProjects |> Seq.map serializeReferencedProject |> JArray) + output.Add("IsIncompleteTypeCheckEnvironment", snapshot.IsIncompleteTypeCheckEnvironment) + output.Add("UseScriptResolutionRules", snapshot.UseScriptResolutionRules) + output.Add("LoadTime", snapshot.LoadTime) + // output.Add("UnresolvedReferences", snapshot.UnresolvedReferences) + output.Add( + "OriginalLoadReferences", + snapshot.OriginalLoadReferences + |> Seq.map (fun (r: Text.range, a, b) -> JArray(r.FileName, r.Start, r.End, a, b)) + |> JArray + ) + + output.Add("Stamp", (snapshot.Stamp |> (Option.defaultValue 0) |> JToken.FromObject)) + + output + + let dumpToJson (snapshot) = + + let jObject = serializeSnapshot snapshot + + let json = jObject.ToString(Formatting.Indented) + + json + +open FSharpProjectSnapshotSerialization +open System.Collections.Concurrent [] module private CheckerExtensions = + let snapshotCache = AsyncMemoize(1000, 500, "SnapshotCache") + + let latestSnapshots = ConcurrentDictionary<_, _>() + + let exist xs = xs |> Seq.isEmpty |> not + + let getFSharpOptionsForProject (this: Project) = + if not this.IsFSharp then + raise (OperationCanceledException("Project is not a FSharp project.")) + else + match ProjectCache.Projects.TryGetValue(this) with + | true, result -> CancellableTask.singleton result + | _ -> + cancellableTask { + + let! ct = CancellableTask.getCancellationToken () + + let service = this.Solution.GetFSharpWorkspaceService() + let projectOptionsManager = service.FSharpProjectOptionsManager + + match! projectOptionsManager.TryGetOptionsByProject(this, ct) with + | ValueNone -> return raise (OperationCanceledException("FSharp project options not found.")) + | ValueSome(parsingOptions, projectOptions) -> + let result = + (service.Checker, projectOptionsManager, parsingOptions, projectOptions) + + return ProjectCache.Projects.GetValue(this, ConditionalWeakTable<_, _>.CreateValueCallback(fun _ -> result)) + } + + let documentToSnapshot (document: Document) = + cancellableTask { + let! version = document.GetTextVersionAsync() + + let getSource () = + task { + let! sourceText = document.GetTextAsync() + return sourceText.ToFSharpSourceText() + } + + return FSharpFileSnapshot(FileName = document.FilePath, Version = version.ToString(), GetSource = getSource) + } + + let getReferencedProjectVersions (project: Project) = + project.GetAllProjectsThisProjectDependsOn() + |> Seq.map (fun r ct -> r.GetDependentSemanticVersionAsync(ct)) + |> CancellableTask.whenAll + |> CancellableTask.map (Seq.map (fun x -> x.ToString()) >> Set) + + let getOnDiskReferences (options: FSharpProjectOptions) = + options.OtherOptions + |> Seq.filter (fun x -> x.StartsWith("-r:")) + |> Seq.map (fun x -> + let path = x.Substring(3) + + { + Path = path + LastModified = System.IO.File.GetLastWriteTimeUtc path + }) + |> Seq.toList + + let createProjectSnapshot (snapshotAccumulatorOpt) (project: Project) (options: FSharpProjectOptions option) = + cancellableTask { + + let! options = + match options with + | Some options -> CancellableTask.singleton options + | None -> + cancellableTask { + let! _, _, _, options = getFSharpOptionsForProject project + return options + } + + let! projectVersion = project.GetDependentSemanticVersionAsync() + + let! referenceVersions = getReferencedProjectVersions project + + let updatedSnapshot = + match project.IsTransparentCompilerSnapshotReuseEnabled, latestSnapshots.TryGetValue project.Id with + | true, (true, (_, _, oldReferenceVersions, _, _)) when referenceVersions <> oldReferenceVersions -> + System.Diagnostics.Trace.TraceWarning "Reference versions changed" + None + + | true, (true, (_, _, _, _, oldSnapshot: FSharpProjectSnapshot)) when + oldSnapshot.ProjectSnapshot.ReferencesOnDisk <> (getOnDiskReferences options) + -> + System.Diagnostics.Trace.TraceWarning "References on disk changed" + None + + | true, (true, (_, oldProjectVersion, _, _, oldSnapshot: FSharpProjectSnapshot)) when projectVersion = oldProjectVersion -> + Some(CancellableTask.singleton oldSnapshot) + + | true, (true, (oldProject, _oldProjectVersion, _oldReferencesVersion, oldOptions, oldSnapshot: FSharpProjectSnapshot)) when + FSharpProjectOptions.AreSameForChecking(options, oldOptions) + -> + + let changes = project.GetChanges(oldProject) + + if + changes.GetAddedDocuments() |> exist + || changes.GetRemovedDocuments() |> exist + || changes.GetAddedMetadataReferences() |> exist + || changes.GetRemovedMetadataReferences() |> exist + || changes.GetAddedProjectReferences() |> exist + || changes.GetRemovedProjectReferences() |> exist + then + // if any of that happened, we create it from scratch + System.Diagnostics.Trace.TraceWarning "Project change not covered by options - suspicious" + None + + else + // we build it from the previous one + + let changedDocuments = changes.GetChangedDocuments() |> Seq.toList + + System.Diagnostics.Trace.TraceInformation + $"Incremental update of FSharpProjectSnapshot ({oldSnapshot.Label}) - {changedDocuments.Length} changed documents" + + if changedDocuments.Length = 0 then + // this is suspicious + let _breakpoint = "here" + () + + changedDocuments + |> Seq.map (project.GetDocument >> documentToSnapshot) + |> CancellableTask.whenAll + |> CancellableTask.map (Array.toList >> oldSnapshot.Replace) + |> Some + + | _ -> None + + let! newSnapshot = + + match updatedSnapshot with + | Some snapshot -> snapshot + | _ -> + cancellableTask { + + let solution = project.Solution + + let projects = + solution.Projects + |> Seq.map (fun p -> p.FilePath, p.Documents |> Seq.map (fun d -> d.FilePath, d) |> Map) + |> Map + + let getFileSnapshot (options: FSharpProjectOptions) path = + async { + let project = projects.TryFind options.ProjectFileName + + if project.IsNone then + System.Diagnostics.Trace.TraceError( + "Could not find project {0} in solution {1}", + options.ProjectFileName, + solution.FilePath + ) + + let documentOpt = project |> Option.bind (Map.tryFind path) + + let! version, getSource = + match documentOpt with + | Some document -> + async { + + let! version = document.GetTextVersionAsync() |> Async.AwaitTask + + let getSource () = + task { + let! sourceText = document.GetTextAsync() + return sourceText.ToFSharpSourceText() + } + + return version.ToString(), getSource + + } + | None -> + // This happens with files that are read from /obj + + // Fall back to file system + let version = System.IO.File.GetLastWriteTimeUtc(path) + + let getSource () = + task { return System.IO.File.ReadAllText(path) |> FSharp.Compiler.Text.SourceTextNew.ofString } + + async.Return(version.ToString(), getSource) + + return FSharpFileSnapshot(FileName = path, Version = version, GetSource = getSource) + } + + let! snapshot = + FSharpProjectSnapshot.FromOptions(options, getFileSnapshot, ?snapshotAccumulator = snapshotAccumulatorOpt) + + System.Diagnostics.Trace.TraceInformation $"Created new FSharpProjectSnapshot ({snapshot.Label})" + + return snapshot + } + + let latestSnapshotData = + project, projectVersion, referenceVersions, options, newSnapshot + + latestSnapshots.AddOrUpdate(project.Id, latestSnapshotData, (fun _ _ -> latestSnapshotData)) + |> ignore + + return newSnapshot + } + + let getOrCreateSnapshotForProject (project: Project) options snapshotAccumulatorOpt = + + let key = + { new ICacheKey<_, _> with + member _.GetKey() = project.Id + member _.GetVersion() = project + member _.GetLabel() = project.FilePath + } + + snapshotCache.Get( + key, + node { + let! ct = NodeCode.CancellationToken + + return! + createProjectSnapshot snapshotAccumulatorOpt project options ct + |> NodeCode.AwaitTask + } + ) + |> Async.AwaitNodeCode + + let getProjectSnapshotForDocument (document: Document, options: FSharpProjectOptions) = + getOrCreateSnapshotForProject document.Project (Some options) None + type FSharpChecker with /// Parse the source text from the Roslyn document. @@ -26,6 +340,32 @@ module private CheckerExtensions = return! checker.ParseFile(document.FilePath, sourceText.ToFSharpSourceText(), parsingOptions, userOpName = userOpName) } + member checker.ParseDocumentUsingTransparentCompiler(document: Document, options: FSharpProjectOptions, userOpName: string) = + cancellableTask { + let! projectSnapshot = getProjectSnapshotForDocument (document, options) + return! checker.ParseFile(document.FilePath, projectSnapshot, userOpName = userOpName) + } + + member checker.ParseAndCheckDocumentUsingTransparentCompiler + ( + document: Document, + options: FSharpProjectOptions, + userOpName: string + ) = + cancellableTask { + + checker.TransparentCompiler.SetCacheSizeFactor(document.Project.TransparentCompilerCacheFactor) + + let! projectSnapshot = getProjectSnapshotForDocument (document, options) + + let! (parseResults, checkFileAnswer) = checker.ParseAndCheckFileInProject(document.FilePath, projectSnapshot, userOpName) + + return + match checkFileAnswer with + | FSharpCheckFileAnswer.Aborted -> None + | FSharpCheckFileAnswer.Succeeded(checkFileResults) -> Some(parseResults, checkFileResults) + } + /// Parse and check the source text from the Roslyn document with possible stale results. member checker.ParseAndCheckDocumentWithPossibleStaleResults ( @@ -106,28 +446,18 @@ module private CheckerExtensions = ?allowStaleResults: bool ) = cancellableTask { - let allowStaleResults = - match allowStaleResults with - | Some b -> b - | _ -> document.Project.IsFSharpStaleCompletionResultsEnabled - - return! checker.ParseAndCheckDocumentWithPossibleStaleResults(document, options, allowStaleResults, userOpName = userOpName) - } -[] -module internal ProjectCache = - - /// This is a cache to maintain FSharpParsingOptions and FSharpProjectOptions per Roslyn Project. - /// The Roslyn Project is held weakly meaning when it is cleaned up by the GC, the FSharParsingOptions and FSharpProjectOptions will be cleaned up by the GC. - /// At some point, this will be the main caching mechanism for FCS projects instead of FCS itself. - let Projects = - ConditionalWeakTable() - -type Solution with + if document.Project.UseTransparentCompiler then + return! checker.ParseAndCheckDocumentUsingTransparentCompiler(document, options, userOpName) + else + let allowStaleResults = + match allowStaleResults with + | Some b -> b + | _ -> document.Project.IsFSharpStaleCompletionResultsEnabled - /// Get the instance of IFSharpWorkspaceService. - member internal this.GetFSharpWorkspaceService() = - this.Workspace.Services.GetRequiredService() + return! + checker.ParseAndCheckDocumentWithPossibleStaleResults(document, options, allowStaleResults, userOpName = userOpName) + } type Document with @@ -195,8 +525,12 @@ type Document with /// Parses the given F# document. member this.GetFSharpParseResultsAsync(userOpName) = cancellableTask { - let! checker, _, parsingOptions, _ = this.GetFSharpCompilationOptionsAsync(userOpName) - return! checker.ParseDocument(this, parsingOptions, userOpName) + let! checker, _, parsingOptions, options = this.GetFSharpCompilationOptionsAsync(userOpName) + + if this.Project.UseTransparentCompiler then + return! checker.ParseDocumentUsingTransparentCompiler(this, options, userOpName) + else + return! checker.ParseDocument(this, parsingOptions, userOpName) } /// Parses and checks the given F# document. @@ -213,7 +547,15 @@ type Document with member this.GetFSharpSemanticClassificationAsync(userOpName) = cancellableTask { let! checker, _, _, projectOptions = this.GetFSharpCompilationOptionsAsync(userOpName) - let! result = checker.GetBackgroundSemanticClassificationForFile(this.FilePath, projectOptions) + + let! result = + if this.Project.UseTransparentCompiler then + async { + let! projectSnapshot = getProjectSnapshotForDocument (this, projectOptions) + return! checker.GetBackgroundSemanticClassificationForFile(this.FilePath, projectSnapshot) + } + else + checker.GetBackgroundSemanticClassificationForFile(this.FilePath, projectOptions) return result @@ -221,18 +563,22 @@ type Document with } /// Find F# references in the given F# document. - member inline this.FindFSharpReferencesAsync(symbol, [] onFound, userOpName) = + member inline this.FindFSharpReferencesAsync(symbol, projectSnapshot: FSharpProjectSnapshot, [] onFound, userOpName) = cancellableTask { let! checker, _, _, projectOptions = this.GetFSharpCompilationOptionsAsync(userOpName) let! symbolUses = - checker.FindBackgroundReferencesInFile( - this.FilePath, - projectOptions, - symbol, - canInvalidateProject = false, - fastCheck = this.Project.IsFastFindReferencesEnabled - ) + + if this.Project.UseTransparentCompiler then + checker.FindBackgroundReferencesInFile(this.FilePath, projectSnapshot, symbol) + else + checker.FindBackgroundReferencesInFile( + this.FilePath, + projectOptions, + symbol, + canInvalidateProject = false, + fastCheck = this.Project.IsFastFindReferencesEnabled + ) do! symbolUses @@ -267,7 +613,7 @@ type Document with type Project with /// Find F# references in the given project. - member this.FindFSharpReferencesAsync(symbol: FSharpSymbol, onFound, userOpName) = + member this.FindFSharpReferencesAsync(symbol: FSharpSymbol, projectSnapshot, onFound, userOpName) = cancellableTask { let declarationLocation = @@ -307,32 +653,15 @@ type Project with if this.IsFastFindReferencesEnabled then do! documents - |> Seq.map (fun doc -> doc.FindFSharpReferencesAsync(symbol, (fun range -> onFound doc range), userOpName)) + |> Seq.map (fun doc -> + doc.FindFSharpReferencesAsync(symbol, projectSnapshot, (fun range -> onFound doc range), userOpName)) |> CancellableTask.whenAll else for doc in documents do - do! doc.FindFSharpReferencesAsync(symbol, (fun range -> onFound doc range), userOpName) + do! doc.FindFSharpReferencesAsync(symbol, projectSnapshot, (onFound doc), userOpName) } - member this.GetFSharpCompilationOptionsAsync() = - if not this.IsFSharp then - raise (OperationCanceledException("Project is not a FSharp project.")) - else - match ProjectCache.Projects.TryGetValue(this) with - | true, result -> CancellableTask.singleton result - | _ -> - cancellableTask { - - let! ct = CancellableTask.getCancellationToken () - - let service = this.Solution.GetFSharpWorkspaceService() - let projectOptionsManager = service.FSharpProjectOptionsManager + member this.GetFSharpCompilationOptionsAsync() = this |> getFSharpOptionsForProject - match! projectOptionsManager.TryGetOptionsByProject(this, ct) with - | ValueNone -> return raise (OperationCanceledException("FSharp project options not found.")) - | ValueSome(parsingOptions, projectOptions) -> - let result = - (service.Checker, projectOptionsManager, parsingOptions, projectOptions) - - return ProjectCache.Projects.GetValue(this, ConditionalWeakTable<_, _>.CreateValueCallback(fun _ -> result)) - } + member this.GetFSharpProjectSnapshot(?snapshotAccumulator) = + cancellableTask { return! getOrCreateSnapshotForProject this None snapshotAccumulator } diff --git a/vsintegration/src/FSharp.Editor/Options/EditorOptions.fs b/vsintegration/src/FSharp.Editor/Options/EditorOptions.fs index c531d386af3..e9b7f60252a 100644 --- a/vsintegration/src/FSharp.Editor/Options/EditorOptions.fs +++ b/vsintegration/src/FSharp.Editor/Options/EditorOptions.fs @@ -46,6 +46,7 @@ type QuickInfoOptions = DisplayLinks: bool UnderlineStyle: QuickInfoUnderlineStyle DescriptionWidth: int option + ShowRemarks: bool } static member Default = @@ -53,6 +54,7 @@ type QuickInfoOptions = DisplayLinks = true UnderlineStyle = QuickInfoUnderlineStyle.Solid DescriptionWidth = None + ShowRemarks = true } [] @@ -81,6 +83,7 @@ type CodeFixesOptions = type LanguageServicePerformanceOptions = { EnableInMemoryCrossProjectReferences: bool + TransparentCompilerCacheFactor: int AllowStaleCompletionResults: bool TimeUntilStaleCompletion: int EnableParallelReferenceResolution: bool @@ -95,6 +98,7 @@ type LanguageServicePerformanceOptions = static member Default = { EnableInMemoryCrossProjectReferences = true + TransparentCompilerCacheFactor = 100 AllowStaleCompletionResults = true TimeUntilStaleCompletion = 2000 // In ms, so this is 2 seconds EnableParallelReferenceResolution = false @@ -115,6 +119,8 @@ type AdvancedOptions = IsInlineParameterNameHintsEnabled: bool IsInlineReturnTypeHintsEnabled: bool IsUseLiveBuffersEnabled: bool + UseTransparentCompiler: bool + TransparentCompilerSnapshotReuse: bool SendAdditionalTelemetry: bool SolutionBackgroundAnalysis: bool } @@ -126,6 +132,8 @@ type AdvancedOptions = IsInlineTypeHintsEnabled = false IsInlineParameterNameHintsEnabled = false IsInlineReturnTypeHintsEnabled = false + UseTransparentCompiler = false + TransparentCompilerSnapshotReuse = false IsUseLiveBuffersEnabled = true SendAdditionalTelemetry = true SolutionBackgroundAnalysis = false @@ -199,6 +207,7 @@ module internal OptionsUI = bindRadioButton view.dash path QuickInfoUnderlineStyle.Dash bindCheckBox view.displayLinks (nameof QuickInfoOptions.Default.DisplayLinks) bindDescriptionWidthTextBox view.descriptionWidth (nameof QuickInfoOptions.Default.DescriptionWidth) + bindCheckBox view.showRemarks (nameof QuickInfoOptions.Default.ShowRemarks) upcast view [] @@ -262,3 +271,11 @@ module EditorOptionsExtensions = member this.IsFastFindReferencesEnabled = this.EditorOptions.LanguageServicePerformance.EnableFastFindReferencesAndRename + + member this.UseTransparentCompiler = this.EditorOptions.Advanced.UseTransparentCompiler + + member this.IsTransparentCompilerSnapshotReuseEnabled = + this.EditorOptions.Advanced.TransparentCompilerSnapshotReuse + + member this.TransparentCompilerCacheFactor = + this.EditorOptions.LanguageServicePerformance.TransparentCompilerCacheFactor diff --git a/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs b/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs index ae79300ee85..581a6a7fef3 100644 --- a/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs +++ b/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs @@ -31,7 +31,12 @@ type internal FSharpAsyncQuickInfoSource let getSingleContent (data: ToolTipElement) = let symbol, description, documentation = - XmlDocumentation.BuildSingleTipText(documentationBuilder, data, XmlDocumentation.DefaultLineLimits) + XmlDocumentation.BuildSingleTipText( + documentationBuilder, + data, + XmlDocumentation.DefaultLineLimits, + editorOptions.QuickInfo.ShowRemarks + ) let getLinkTooltip filePath = let solutionDir = Path.GetDirectoryName(document.Project.Solution.FilePath) diff --git a/vsintegration/src/FSharp.Editor/Refactor/AddReturnType.fs b/vsintegration/src/FSharp.Editor/Refactor/AddReturnType.fs new file mode 100644 index 00000000000..b3c586b445e --- /dev/null +++ b/vsintegration/src/FSharp.Editor/Refactor/AddReturnType.fs @@ -0,0 +1,118 @@ +namespace Microsoft.VisualStudio.FSharp.Editor + +open System.Composition +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Symbols +open FSharp.Compiler.Text + +open Microsoft.CodeAnalysis.Text +open Microsoft.CodeAnalysis.CodeRefactorings +open Microsoft.CodeAnalysis.CodeActions +open CancellableTasks + +[] +type internal AddReturnType [] () = + inherit CodeRefactoringProvider() + + static member isValidMethodWithoutTypeAnnotation + (symbolUse: FSharpSymbolUse) + (parseFileResults: FSharpParseFileResults) + (funcOrValue: FSharpMemberOrFunctionOrValue) + = + let typeAnnotationRange = + parseFileResults.TryRangeOfReturnTypeHint(symbolUse.Range.Start, false) + + let res = + funcOrValue.CompiledName = funcOrValue.DisplayName + && funcOrValue.IsFunction + && not (parseFileResults.IsBindingALambdaAtPosition symbolUse.Range.Start) + && not (funcOrValue.ReturnParameter.Type.IsUnresolved) + && not (parseFileResults.IsTypeAnnotationGivenAtPosition symbolUse.Range.Start) + && not typeAnnotationRange.IsNone + + match (res, typeAnnotationRange) with + | (true, Some tr) -> Some(funcOrValue, tr) + | (_, _) -> None + + static member refactor + (context: CodeRefactoringContext) + (memberFunc: FSharpMemberOrFunctionOrValue, typeRange: Range, symbolUse: FSharpSymbolUse) + = + let title = SR.AddReturnTypeAnnotation() + + let getChangedText (sourceText: SourceText) = + let returnType = memberFunc.ReturnParameter.Type + + let inferredType = + let res = returnType.Format symbolUse.DisplayContext + + if returnType.HasTypeDefinition then + res + else + $"({res})".Replace(" ", "") + + let textSpan = RoslynHelpers.FSharpRangeToTextSpan(sourceText, typeRange) + let textChange = TextChange(textSpan, $": {inferredType} ") + sourceText.WithChanges(textChange) + + let codeActionFunc = + cancellableTask { + let! cancellationToken = CancellableTask.getCancellationToken () + let! sourceText = context.Document.GetTextAsync(cancellationToken) + let changedText = getChangedText sourceText + + let newDocument = context.Document.WithText(changedText) + return newDocument + } + + let codeAction = CodeAction.Create(title, codeActionFunc, title) + + do context.RegisterRefactoring(codeAction) + + static member ofFSharpMemberOrFunctionOrValue(symbol: FSharpSymbol) = + match symbol with + | :? FSharpMemberOrFunctionOrValue as v -> Some v + | _ -> None + + override _.ComputeRefactoringsAsync context = + cancellableTask { + let document = context.Document + let position = context.Span.Start + let! sourceText = document.GetTextAsync() + let textLine = sourceText.Lines.GetLineFromPosition position + let textLinePos = sourceText.Lines.GetLinePosition position + let fcsTextLineNumber = Line.fromZ textLinePos.Line + + let! lexerSymbol = + document.TryFindFSharpLexerSymbolAsync(position, SymbolLookupKind.Greedy, false, false, nameof (AddReturnType)) + + let! (parseFileResults, checkFileResults) = document.GetFSharpParseAndCheckResultsAsync(nameof (AddReturnType)) + + let symbolUseOpt = + lexerSymbol + |> Option.bind (fun lexer -> + checkFileResults.GetSymbolUseAtLocation( + fcsTextLineNumber, + lexer.Ident.idRange.EndColumn, + textLine.ToString(), + lexer.FullIsland + )) + + let memberFuncOpt = + symbolUseOpt + |> Option.bind (fun sym -> sym.Symbol |> AddReturnType.ofFSharpMemberOrFunctionOrValue) + + match (symbolUseOpt, memberFuncOpt) with + | (Some symbolUse, Some memberFunc) -> + let isValidMethod = + memberFunc + |> AddReturnType.isValidMethodWithoutTypeAnnotation symbolUse parseFileResults + + match isValidMethod with + | Some(memberFunc, typeRange) -> do AddReturnType.refactor context (memberFunc, typeRange, symbolUse) + | None -> () + | _ -> () + + return () + } + |> CancellableTask.startAsTask context.CancellationToken diff --git a/vsintegration/src/FSharp.Editor/Telemetry/TelemetryReporter.fs b/vsintegration/src/FSharp.Editor/Telemetry/TelemetryReporter.fs index 2a520d72066..b841b7e8cd6 100644 --- a/vsintegration/src/FSharp.Editor/Telemetry/TelemetryReporter.fs +++ b/vsintegration/src/FSharp.Editor/Telemetry/TelemetryReporter.fs @@ -105,9 +105,11 @@ type TelemetryReporter private (name: string, props: (string * obj) array, stopw TelemetryService.DefaultSession.IsUserMicrosoftInternal else let workspace = componentModel.GetService() + let options = workspace.Services.GetService() TelemetryService.DefaultSession.IsUserMicrosoftInternal - || workspace.Services.GetService().Advanced.SendAdditionalTelemetry) + || options.Advanced.SendAdditionalTelemetry + || options.Advanced.UseTransparentCompiler) static member ReportFault(name, ?severity: FaultSeverity, ?e: exn) = if TelemetryReporter.SendAdditionalTelemetry.Value then diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf index 5db40f51628..182fc895c61 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf @@ -22,6 +22,11 @@ Přidejte klíčové slovo new. + + Add return type annotation + Add return type annotation + + Add type annotation Přidat anotaci typu @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Vodítka struktury bloků; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Formátování; +Dash underline; +Show remarks in Quick Info + Formátování; Upřednostňovaná šířka popisu ve znacích; Formátování podpisu na danou šířku přidáním konců řádků podle pravidel syntaxe F#; Navigační odkazy; @@ -206,6 +213,11 @@ Tečkované podtržení; Přerušované podtržení; + + Remarks: + Remarks: + + Remove 'return' Odebrat return @@ -241,6 +253,11 @@ Přerušované podtržení; Přejmenujte {0} na _. + + Returns: + Returns: + + Simplify name Zjednodušte název. diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf index 31ffc4c8342..5a8c128c134 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf @@ -22,6 +22,11 @@ Schlüsselwort "new" hinzufügen + + Add return type annotation + Add return type annotation + + Add type annotation Typanmerkung hinzufügen @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Führungslinien für Blockstruktur; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Formatierung; +Dash underline; +Show remarks in Quick Info + Formatierung; Bevorzugte Beschreibungsbreite in Zeichen; Signatur in der angegebenen Breite formatieren, indem Zeilenumbrüche hinzugefügt werden, die den F#-Syntaxregeln entsprechen; Navigationslinks; @@ -206,6 +213,11 @@ Punkt unterstrichen; Strich unterstrichen; + + Remarks: + Remarks: + + Remove 'return' "return" entfernen @@ -241,6 +253,11 @@ Strich unterstrichen; "{0}" in "_" umbenennen + + Returns: + Returns: + + Simplify name Namen vereinfachen diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf index dceb8706e99..e313f8ceefc 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf @@ -22,6 +22,11 @@ Agregar "nueva" palabra clave + + Add return type annotation + Add return type annotation + + Add type annotation Agregar una anotación de tipo @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Guías de estructura de bloques; @@ -197,8 +203,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Formato; +Dash underline; +Show remarks in Quick Info + Formato; Ancho de descripción preferido en caracteres; Dar formato a la firma con el ancho dado agregando saltos de línea que cumplan las reglas de sintaxis de F#; Vínculos de navegación; @@ -208,6 +215,11 @@ Subrayado de punto; Subrayado de guion; + + Remarks: + Remarks: + + Remove 'return' Quitar "return" @@ -243,6 +255,11 @@ Subrayado de guion; Cambiar nombre de "{0}" por "_" + + Returns: + Returns: + + Simplify name Simplificar nombre diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf index db53640c9a5..36245222af1 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf @@ -22,6 +22,11 @@ Ajouter le mot clé 'new' + + Add return type annotation + Add return type annotation + + Add type annotation Ajouter une annotation de type @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Guides de structure de bloc ; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Formatage; +Dash underline; +Show remarks in Quick Info + Formatage; Largeur de description préférée en caractères ; Mettre en forme la signature à la largeur donnée en ajoutant des sauts de ligne conformes aux règles de syntaxe F# ; Liens de navigation ; @@ -206,6 +213,11 @@ Soulignement pointé ; Soulignement en tirets ; + + Remarks: + Remarks: + + Remove 'return' Supprimer 'return' @@ -241,6 +253,11 @@ Soulignement en tirets ; Renommer '{0}' en '_' + + Returns: + Returns: + + Simplify name Simplifier le nom diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf index 97feb5816e2..12f274dffbd 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf @@ -22,6 +22,11 @@ Aggiungi la parola chiave 'new' + + Add return type annotation + Add return type annotation + + Add type annotation Aggiungere l'annotazione di tipo @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Guide per strutture a blocchi; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Formattazione; +Dash underline; +Show remarks in Quick Info + Formattazione; Larghezza descrizione preferita in caratteri; Formatta la firma in base alla larghezza specificata aggiungendo interruzioni di riga conformi alle regole di sintassi F#; Collegamenti di spostamento; @@ -206,6 +213,11 @@ Sottolineatura a punto; Sottolineatura a trattini; + + Remarks: + Remarks: + + Remove 'return' Rimuovi 'return' @@ -241,6 +253,11 @@ Sottolineatura a trattini; Rinomina '{0}' in '_' + + Returns: + Returns: + + Simplify name Semplifica nome diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf index f9682a8d5fd..1a23fcf5d9e 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf @@ -22,6 +22,11 @@ 'new' キーワードを追加する + + Add return type annotation + Add return type annotation + + Add type annotation 型の注釈の追加 @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis ブロック構造ガイド; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - 書式 設定; +Dash underline; +Show remarks in Quick Info + 書式 設定; 希望の説明の幅 (文字数); F# 構文規則に準拠するよう、改行を追加して指定された幅に署名を書式設定します; ナビゲーション リンク; @@ -206,6 +213,11 @@ F# 構文規則に準拠するよう、改行を追加して指定された幅 ダッシュ下線; + + Remarks: + Remarks: + + Remove 'return' 'return' の削除 @@ -241,6 +253,11 @@ F# 構文規則に準拠するよう、改行を追加して指定された幅 '{0}' から '_' に名前を変更する + + Returns: + Returns: + + Simplify name 名前を単純化する diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf index 638099fe0fb..1f58583afd2 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf @@ -22,6 +22,11 @@ 'new' 키워드 추가 + + Add return type annotation + Add return type annotation + + Add type annotation 형식 주석 추가 @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis 블록 구조 안내선; @@ -196,8 +202,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - 서식; +Dash underline; +Show remarks in Quick Info + 서식; 기본 설정 문자 설명 너비; F# 구문 규칙에 맞는 줄바꿈을 추가하여 지정된 너비에 서명 서식 지정; 탐색 링크; @@ -207,6 +214,11 @@ F# 구문 규칙에 맞는 줄바꿈을 추가하여 지정된 너비에 서명 대시 밑줄; + + Remarks: + Remarks: + + Remove 'return' 'return' 제거 @@ -242,6 +254,11 @@ F# 구문 규칙에 맞는 줄바꿈을 추가하여 지정된 너비에 서명 '{0}'의 이름을 '_'로 바꾸기 + + Returns: + Returns: + + Simplify name 이름 단순화 diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf index cc17e6d540e..24392a0e18e 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf @@ -22,6 +22,11 @@ Dodaj słowo kluczowe „new” + + Add return type annotation + Add return type annotation + + Add type annotation Dodaj adnotację typu @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Przewodniki po strukturze bloku; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Formatowanie; +Dash underline; +Show remarks in Quick Info + Formatowanie; Preferowana szerokość opisu w znakach; Sformatuj sygnaturę na daną szerokość, dodając podziały wierszy zgodne z regułami składni języka F#; Linki nawigacji; @@ -206,6 +213,11 @@ Podkreślenie kropką; Podkreślenie kreską; + + Remarks: + Remarks: + + Remove 'return' Usuń element „return” @@ -241,6 +253,11 @@ Podkreślenie kreską; Zmień nazwę z „{0}” na „_” + + Returns: + Returns: + + Simplify name Uprość nazwę diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf index 492073cacb0..85a79352133 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf @@ -22,6 +22,11 @@ Adicionar a palavra-chave 'new' + + Add return type annotation + Add return type annotation + + Add type annotation Adicionar uma anotação de tipo @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Guias de Estrutura de Bloco; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Formatação; +Dash underline; +Show remarks in Quick Info + Formatação; Largura da descrição preferida em caracteres; Formate a assinatura para a largura especificada adicionando quebras de linha em conformidade com as regras de sintaxe do F#; Links de navegação; @@ -206,6 +213,11 @@ Ponto sublinhado; Traço sublinhado; + + Remarks: + Remarks: + + Remove 'return' Remover 'return' @@ -241,6 +253,11 @@ Traço sublinhado; Renomear '{0}' para '_' + + Returns: + Returns: + + Simplify name Simplificar o nome diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf index b8549511a9f..357494b37b2 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf @@ -22,6 +22,11 @@ Добавить ключевое слово "new" + + Add return type annotation + Add return type annotation + + Add type annotation Добавить заметку типа @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Руководства по блочной структуре; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Форматирование; +Dash underline; +Show remarks in Quick Info + Форматирование; Предпочитаемая ширина описания в символах; Форматирование подписи до заданной ширины путем добавления разрывов строк в соответствии с правилами синтаксиса F#; Ссылки навигации; @@ -206,6 +213,11 @@ Dash underline; Штриховое подчеркивание; + + Remarks: + Remarks: + + Remove 'return' Удалить "return" @@ -241,6 +253,11 @@ Dash underline; Переименовать "{0}" в "_" + + Returns: + Returns: + + Simplify name Упростить имя diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf index e6e9332dc33..d720dc43d7d 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf @@ -22,6 +22,11 @@ 'new' anahtar sözcüğünü ekleme + + Add return type annotation + Add return type annotation + + Add type annotation Tür ek açıklaması ekle @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis Blok Yapısı Kılavuzları; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - Biçimlendirme; +Dash underline; +Show remarks in Quick Info + Biçimlendirme; Karakter olarak tercih edilen açıklama genişliği; F# söz dizimi kurallarına uyan satır sonları ekleyerek imzayı verilen genişliğe biçimlendir; Gezinti bağlantıları; @@ -206,6 +213,11 @@ Nokta alt çizgi; Tire alt çizgisi; + + Remarks: + Remarks: + + Remove 'return' 'return' öğesini kaldır @@ -241,6 +253,11 @@ Tire alt çizgisi; '{0}' öğesini '_' olarak yeniden adlandırma + + Returns: + Returns: + + Simplify name Adı basitleştirme diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf index 6df4f779a61..43eaadf6593 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf @@ -22,6 +22,11 @@ 添加“新”关键字 + + Add return type annotation + Add return type annotation + + Add type annotation 添加类型注释 @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis 块结构指南; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - 格式设置; +Dash underline; +Show remarks in Quick Info + 格式设置; 首选描述宽度 (以字符为单位); 通过添加符合 F# 语法规则的换行符,将签名格式设置为指定宽度; 导航链接; @@ -206,6 +213,11 @@ Dash underline; 短划线下划线; + + Remarks: + Remarks: + + Remove 'return' 删除 "return" @@ -241,6 +253,11 @@ Dash underline; 将“{0}”重命名为“_” + + Returns: + Returns: + + Simplify name 简化名称 diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf index d270271bb75..96f071fb27e 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf @@ -22,6 +22,11 @@ 新增 'new' 關鍵字 + + Add return type annotation + Add return type annotation + + Add type annotation 新增型別註解 @@ -36,6 +41,7 @@ Inline hints; Display inline type hints (preview); Display return type hints (preview); Display inline parameter name hints (preview); +Use Transparent Compiler (experimental); Live Buffers; Use live (unsaved) buffers for analysis 區塊結構輔助線; @@ -195,8 +201,9 @@ Navigation links; Show navigation links as; Solid underline; Dot underline; -Dash underline; - 格式化; +Dash underline; +Show remarks in Quick Info + 格式化; 慣用描述寬度 (以字元為單位); 透過新增符合 F# 語法規則的分行符號,將簽章格式設定為指定寬度; 瀏覽連結; @@ -206,6 +213,11 @@ Dash underline; 虛線底線; + + Remarks: + Remarks: + + Remove 'return' 移除 'return' @@ -241,6 +253,11 @@ Dash underline; 將 '{0}' 重新命名為 '_' + + Returns: + Returns: + + Simplify name 簡化名稱 diff --git a/vsintegration/src/FSharp.UIResources/AdvancedOptionsControl.xaml b/vsintegration/src/FSharp.UIResources/AdvancedOptionsControl.xaml index ecabe2a56fd..15397d068ec 100644 --- a/vsintegration/src/FSharp.UIResources/AdvancedOptionsControl.xaml +++ b/vsintegration/src/FSharp.UIResources/AdvancedOptionsControl.xaml @@ -38,6 +38,17 @@ + + + + diff --git a/vsintegration/src/FSharp.UIResources/LanguageServicePerformanceOptionControl.xaml b/vsintegration/src/FSharp.UIResources/LanguageServicePerformanceOptionControl.xaml index 96b8915b80e..a5c5f1c0b6f 100644 --- a/vsintegration/src/FSharp.UIResources/LanguageServicePerformanceOptionControl.xaml +++ b/vsintegration/src/FSharp.UIResources/LanguageServicePerformanceOptionControl.xaml @@ -23,6 +23,28 @@ IsChecked="{Binding EnableInMemoryCrossProjectReferences}" Content="{x:Static local:Strings.Enable_in_memory_cross_project_references}" ToolTip="{x:Static local:Strings.Tooltip_in_memory_cross_project_references}"/> + + + + + + @@ -46,7 +68,7 @@ Content="{x:Static local:Strings.Time_until_stale_completion}" Margin="15 0 0 0"/> diff --git a/vsintegration/src/FSharp.UIResources/QuickInfoOptionControl.xaml b/vsintegration/src/FSharp.UIResources/QuickInfoOptionControl.xaml index 528aa32b1cf..6b7c6531f48 100644 --- a/vsintegration/src/FSharp.UIResources/QuickInfoOptionControl.xaml +++ b/vsintegration/src/FSharp.UIResources/QuickInfoOptionControl.xaml @@ -1,16 +1,19 @@ - + - + @@ -20,21 +23,36 @@ - + - - - - + + + + + + + diff --git a/vsintegration/src/FSharp.UIResources/Strings.Designer.cs b/vsintegration/src/FSharp.UIResources/Strings.Designer.cs index a7bcaa08413..b166f234ccd 100644 --- a/vsintegration/src/FSharp.UIResources/Strings.Designer.cs +++ b/vsintegration/src/FSharp.UIResources/Strings.Designer.cs @@ -474,6 +474,15 @@ public static string Show_Outlining { } } + /// + /// Looks up a localized string similar to Show remarks in Quick Info. + /// + public static string Show_remarks_in_Quick_Info { + get { + return ResourceManager.GetString("Show_remarks_in_Quick_Info", resourceCulture); + } + } + /// /// Looks up a localized string similar to Display return type hints (preview). /// @@ -546,6 +555,69 @@ public static string Tooltip_preferred_description_width_in_characters { } } + /// + /// Looks up a localized string similar to Transparent Compiler Cache Factor. + /// + public static string Transparent_Compiler_Cache_Factor { + get { + return ResourceManager.GetString("Transparent_Compiler_Cache_Factor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Higher number means more memory will be used for caching. Changing the value wipes cache.. + /// + public static string Transparent_Compiler_Cache_Factor_Tooltip { + get { + return ResourceManager.GetString("Transparent_Compiler_Cache_Factor_Tooltip", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Create new project snapshots from existing ones. + /// + public static string Transparent_Compiler_Snapshot_Reuse { + get { + return ResourceManager.GetString("Transparent_Compiler_Snapshot_Reuse", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Transparent Compiler (experimental). + /// + public static string TransparentCompiler { + get { + return ResourceManager.GetString("TransparentCompiler", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results.. + /// + public static string TransparentCompiler_Discalimer1 { + get { + return ResourceManager.GetString("TransparentCompiler_Discalimer1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Use at your own risk!. + /// + public static string TransparentCompiler_Discalimer2 { + get { + return ResourceManager.GetString("TransparentCompiler_Discalimer2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By checking this you also opt-in for additional performance telemetry. + /// + public static string TransparentCompiler_Discalimer3 { + get { + return ResourceManager.GetString("TransparentCompiler_Discalimer3", resourceCulture); + } + } + /// /// Looks up a localized string similar to Analyze and suggest fixes for unused values. /// @@ -572,5 +644,14 @@ public static string Use_syntax_tree_cache { return ResourceManager.GetString("Use_syntax_tree_cache", resourceCulture); } } + + /// + /// Looks up a localized string similar to Use Transparent Compiler (restart required). + /// + public static string Use_Transparent_Compiler { + get { + return ResourceManager.GetString("Use_Transparent_Compiler", resourceCulture); + } + } } } diff --git a/vsintegration/src/FSharp.UIResources/Strings.resx b/vsintegration/src/FSharp.UIResources/Strings.resx index b1362651cb3..58821d8b8be 100644 --- a/vsintegration/src/FSharp.UIResources/Strings.resx +++ b/vsintegration/src/FSharp.UIResources/Strings.resx @@ -279,13 +279,40 @@ Display return type hints (preview) + + Transparent Compiler (experimental) + + + Use Transparent Compiler (restart required) + Keep analyzing the entire solution for diagnostics as a low priority background task (requires restart) Background analysis + + Transparent Compiler Cache Factor + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Remove unnecessary parentheses (experimental, might affect typing performance) + + Show remarks in Quick Info + + + Create new project snapshots from existing ones + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + Use at your own risk! + + + By checking this you also opt-in for additional performance telemetry + \ No newline at end of file diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.cs.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.cs.xlf index 4c1afb7bca0..c0072448173 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.cs.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.cs.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Pro kontrolu používat živé (neuložené) vyrovnávací paměti (vyžaduje se restartování) + Pro analýzu používat živé (neuložené) vyrovnávací paměti (vyžaduje se restartování) @@ -109,7 +109,7 @@ Live Buffers - Živé vyrovnávací paměti (experimentální) + Živé vyrovnávací paměti @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Odebrání nepotřebných závorek (experimentální, může mít vliv na výkon při psaní) @@ -177,6 +177,11 @@ Zo_brazit navigační odkazy jako + + Show remarks in Quick Info + Zobrazit poznámky v Rychlých informacích + + Simplify names (remove unnecessary qualifiers) Zjednodušit názvy (odebrat nepotřebné kvalifikátory) @@ -197,6 +202,41 @@ Umožňuje formátovat podpis na danou šířku přidáním konců řádků odpovídajících pravidlům syntaxe F#. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Odebrat nepoužívané otevřené výkazy @@ -282,6 +322,11 @@ Navrhovat názvy pro nerozpoznané identifikátory + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Výsledky analýzy mezipaměti (experimentální) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.de.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.de.xlf index f93c85b0afc..8afb1d8e999 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.de.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.de.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Livepuffer (nicht gespeichert) zur Überprüfung verwenden (Neustart erforderlich) + Livepuffer (nicht gespeichert) zur Analyse verwenden (Neustart erforderlich) @@ -109,7 +109,7 @@ Live Buffers - Livepuffer (experimentell) + Livepuffer @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Entfernen unnötiger Klammern (experimentell, kann sich auf die Eingabeleistung auswirken) @@ -177,6 +177,11 @@ Navigationslink_s anzeigen als + + Show remarks in Quick Info + Hinweise in QuickInfo anzeigen + + Simplify names (remove unnecessary qualifiers) Namen vereinfachen (unnötige Qualifizierer entfernen) @@ -197,6 +202,41 @@ Formatieren Sie die Signatur in der angegebenen Breite, indem Sie Zeilenumbrüche hinzufügen, die F#-Syntaxregeln entsprechen. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Nicht verwendete "open"-Anweisungen entfernen @@ -282,6 +322,11 @@ Namen für nicht aufgelöste Bezeichner vorschlagen + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Cacheanalyseergebnisse (experimentell) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.es.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.es.xlf index 3b65a70284b..eb0289c938c 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.es.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.es.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Utilizar buffers activos (no guardados) para la comprobación (es necesario reiniciar) + Utilizar buffers activos (no guardados) para el análisis (es necesario reiniciar) @@ -109,7 +109,7 @@ Live Buffers - Búferes activos (experimental) + Búferes activos @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Quitar paréntesis innecesarios (experimental, puede afectar al rendimiento de escritura) @@ -177,6 +177,11 @@ M_ostrar vínculos de navegación como + + Show remarks in Quick Info + Mostrar comentarios en Información rápida + + Simplify names (remove unnecessary qualifiers) Simplificar nombres (quitar calificadores innecesarios) @@ -197,6 +202,41 @@ Da formato a la firma al ancho dado agregando saltos de línea conforme a las reglas de sintaxis de F#. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Quitar instrucciones open no usadas @@ -282,6 +322,11 @@ Sugerir nombres para los identificadores no resueltos + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Resultados del análisis de la caché (experimental) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.fr.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.fr.xlf index 1fcb58d38a5..09430b644cc 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.fr.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.fr.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Utiliser des tampons en direct (non enregistrés) pour la vérification (redémarrage requis) + Utiliser des tampons en direct (non enregistrés) pour l’analysye (redémarrage requis) @@ -109,7 +109,7 @@ Live Buffers - Live Buffers (expérimental) + Tampons en direct @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Supprimer les parenthèses inutiles (expérimental, peut affecter les performances de saisie) @@ -177,6 +177,11 @@ Affic_her les liens de navigation en tant que + + Show remarks in Quick Info + Afficher les notes dans Info express + + Simplify names (remove unnecessary qualifiers) Simplifier les noms (supprimer les qualificateurs inutiles) @@ -197,6 +202,41 @@ Formatez la signature à la largeur donnée en ajoutant des sauts de ligne conformes aux règles de syntaxe F#. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Supprimer les instructions open inutilisées @@ -282,6 +322,11 @@ Suggérer des noms pour les identificateurs non résolus + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Résultats de l'analyse du cache (expérimental) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.it.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.it.xlf index ac84a49ac04..640894aac42 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.it.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.it.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Usa buffer in tempo reale (non salvati) per il controllo (riavvio necessario) + Usa buffer in tempo reale (non salvati) per l’analisi (riavvio necessario) @@ -109,7 +109,7 @@ Live Buffers - Buffer in tempo reale (sperimentale) + Buffer in tempo reale @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Rimuovi le parentesi non necessarie (sperimentale, potrebbe influire sulle prestazioni di digitazione) @@ -177,6 +177,11 @@ M_ostra collegamenti di navigazione come + + Show remarks in Quick Info + Mostra i commenti in Informazioni rapide + + Simplify names (remove unnecessary qualifiers) Semplifica nomi (rimuovi qualificatori non necessari) @@ -197,6 +202,41 @@ Consente di formattare la firma in base alla larghezza specificata aggiungendo interruzioni di riga conformi alle regole di sintassi F#. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Rimuovi istruzioni OPEN inutilizzate @@ -282,6 +322,11 @@ Suggerisci nomi per gli identificatori non risolti + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Risultati dell'analisi della cache (sperimentale) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.ja.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.ja.xlf index 76036894dcb..7267c7b7061 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.ja.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.ja.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - ライブ (未保存) バッファーをチェックに使用する (再起動が必要) + ライブ (未保存) バッファーをチェックに使用する (再起動が必要) @@ -109,7 +109,7 @@ Live Buffers - ライブ バッファー (試験段階) + ライブ バッファー @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + 不要なかっこを削除します (試験段階であり、入力のパフォーマンスに影響する可能性があります) @@ -177,6 +177,11 @@ 次としてナビゲーション リンクを表示する(_H) + + Show remarks in Quick Info + クイック ヒントに注釈を表示する + + Simplify names (remove unnecessary qualifiers) 名前の簡略化する (不要な修飾子の削除) @@ -197,6 +202,41 @@ F# 構文規則に準拠した改行を追加して、署名を指定された幅に書式設定します。 + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements 未使用の Open ステートメントを削除する @@ -282,6 +322,11 @@ 未解決の識別子の名前を提案します + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) キャッシュ解析の結果 (試験段階) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.ko.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.ko.xlf index f166bba08f3..cfb0da2f9b4 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.ko.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.ko.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - 확인에 라이브(저장되지 않은) 버퍼 사용(다시 시작 필요) + 분석에 라이브(저장되지 않은) 버퍼 사용(다시 시작 필요) @@ -109,7 +109,7 @@ Live Buffers - 라이브 버퍼(실험적) + 라이브 버퍼 @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + 불필요한 괄호 제거(실험적, 입력 성능에 영향을 줄 수 있음) @@ -177,6 +177,11 @@ 탐색 링크를 다음으로 표시(_H) + + Show remarks in Quick Info + 요약 정보에 설명 표시 + + Simplify names (remove unnecessary qualifiers) 이름 단순화(불필요한 한정자 제거) @@ -197,6 +202,41 @@ F# 구문 규칙에 맞는 줄 바꿈을 추가하여 지정된 너비에 시그니처의 서식을 지정합니다. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements 사용되지 않는 open 문 제거 @@ -282,6 +322,11 @@ 확인되지 않은 식별자의 이름 제안 + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) 캐시 구문 분석 결과(실험적) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.pl.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.pl.xlf index c4d70ab3a1f..4fb4ff03b40 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.pl.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.pl.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Użyj aktywnych (niezapisanych) buforów do sprawdzania (wymagane ponowne uruchomienie) + Użyj bieżących (niezapisanych) buforów do analizy (wymagane ponowne uruchomienie) @@ -109,7 +109,7 @@ Live Buffers - Aktywne bufory (eksperymentalne) + Bufory bieżące @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Usuń niepotrzebne nawiasy (eksperymentalne, może to wpłynąć na wydajność pisania) @@ -177,6 +177,11 @@ P_okaż linki nawigacyjne jako + + Show remarks in Quick Info + Pokaż uwagi w szybkich podpowiedziach + + Simplify names (remove unnecessary qualifiers) Uprość nazwy (usuń niepotrzebne kwalifikatory) @@ -197,6 +202,41 @@ Sformatuj sygnaturę na daną szerokość, dodając podziały wierszy zgodne z regułami składni języka F#. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Usuń nieużywane otwarte instrukcje @@ -282,6 +322,11 @@ Sugeruj nazwy w przypadku nierozpoznanych identyfikatorów + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Wyniki analizy pamięci podręcznej (eksperymentalne) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.pt-BR.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.pt-BR.xlf index f1ef03e827e..f2778bcbd8b 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.pt-BR.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.pt-BR.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Usar buffers dinâmicos (não salvos) para verificação (reinicialização necessária) + Usar buffers dinâmicos (não salvos) para verificação (reinicialização necessária) @@ -109,7 +109,7 @@ Live Buffers - Buffers Dinâmicos (experimental) + Buffers Dinâmicos @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Remover parênteses desnecessários (experimental, pode afetar o desempenho da digitação) @@ -177,6 +177,11 @@ E_xibir link de navegação como + + Show remarks in Quick Info + Mostrar os comentários nas Informações Rápidas + + Simplify names (remove unnecessary qualifiers) Simplificar nomes (remover qualificadores desnecessários) @@ -197,6 +202,41 @@ Formate a assinatura para a largura fornecida adicionando quebras de linha em conformidade com as regras de sintaxe F#. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Remover instruções abertas não usadas @@ -282,6 +322,11 @@ Sugerir nomes para identificadores não resolvidos + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Resultados da análise de cache (experimental) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.ru.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.ru.xlf index 4db5610e9bb..9b99816b43c 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.ru.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.ru.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Использовать динамические (несохраненные) буферы для проверки (требуется перезагрузка) + Используйте для анализа живые (несохраненные) буферы (требуется перезагрузка) @@ -109,7 +109,7 @@ Live Buffers - Динамические буферы (экспериментальная функция) + Живые буферы @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Удалите ненужные круглые скобки (экспериментально, может повлиять на производительность набора текста) @@ -177,6 +177,11 @@ П_оказать ссылки навигации как + + Show remarks in Quick Info + Показать заметки в кратких сведениях + + Simplify names (remove unnecessary qualifiers) Упростить имена (удалить ненужные квалификаторы) @@ -197,6 +202,41 @@ Форматирование подписи до заданной ширины путем добавления разрывов строк, соответствующих правилам синтаксиса F#. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Удалить неиспользуемые открытые операторы @@ -282,6 +322,11 @@ Предлагать имена для неразрешенных идентификаторов + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Результаты анализа кэша (экспериментальная функция) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.tr.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.tr.xlf index 95fa383de7e..e6afdd2e2b1 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.tr.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.tr.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - Denetim için canlı (kaydedilmemiş) arabellekler kullanın (yeniden başlatma gerekir) + Analiz için canlı (kaydedilmemiş) arabellekleri kullan (yeniden başlatma gerekir) @@ -109,7 +109,7 @@ Live Buffers - Canlı Arabellekler (deneysel) + Canlı Arabellekler @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + Gereksiz parantezleri kaldır (deneysel, yazma performansını etkileyebilir) @@ -177,6 +177,11 @@ Gezinti bağlantılarını farklı _göster + + Show remarks in Quick Info + Hızlı Bilgi notlarını göster + + Simplify names (remove unnecessary qualifiers) Adları basitleştir (gereksiz niteleyicileri kaldır) @@ -197,6 +202,41 @@ F# söz dizimi kurallarına uyan satır sonları ekleyerek imzayı belirtilen genişliğe biçimlendirin. + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements Kullanılmayan açık deyimleri kaldır @@ -282,6 +322,11 @@ Çözümlenmemiş tanımlayıcılar için ad öner + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) Ayrıştırma sonuçlarını önbelleğe al (deneysel) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hans.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hans.xlf index 3b45fdaf529..9bd919f4b51 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hans.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hans.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - 使用实时(未保存)缓冲区进行检查(需要重新启动) + 使用实时(未保存)缓冲区进行分析(需要重新启动) @@ -109,7 +109,7 @@ Live Buffers - 实时缓冲区(实验性) + 实时缓冲区 @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + 删除不必要的括号(实验性,可能会影响键入性能) @@ -177,6 +177,11 @@ 导航链接显示方式(_H) + + Show remarks in Quick Info + 在快速信息中显示备注 + + Simplify names (remove unnecessary qualifiers) 简化名称(删除不必要的限定符) @@ -197,6 +202,41 @@ 通过添加符合 F# 语法规则的换行符,将签名设置为给定宽度的格式。 + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements 删除未使用的 open 语句 @@ -282,6 +322,11 @@ 为未解析标识符建议名称 + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) 缓存分析结果(实验性) diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hant.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hant.xlf index 50aede6ee96..d537c05ffd2 100644 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hant.xlf +++ b/vsintegration/src/FSharp.UIResources/xlf/Strings.zh-Hant.xlf @@ -34,7 +34,7 @@ Use live (unsaved) buffers for analysis (restart required) - 使用即時 (未儲存) 緩衝區進行檢查 (需要重新啟動) + 使用即時 (未儲存) 緩衝區進行分析 (需要重新啟動) @@ -109,7 +109,7 @@ Live Buffers - 即時緩衝區 (實驗性) + 即時緩衝區 @@ -129,7 +129,7 @@ Remove unnecessary parentheses (experimental, might affect typing performance) - Remove unnecessary parentheses (experimental, might affect typing performance) + 移除實驗性 (不必要的括弧,可能會影響輸入效能) @@ -177,6 +177,11 @@ 顯示導覽連結為(_H) + + Show remarks in Quick Info + 在快速諮詢中顯示備註 + + Simplify names (remove unnecessary qualifiers) 簡化名稱 (移除不必要的限定詞) @@ -197,6 +202,41 @@ 透過新增符合 F# 語法規則的分行符號,將簽章格式設定為指定寬度。 + + Transparent Compiler (experimental) + Transparent Compiler (experimental) + + + + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + WARNING! Transparent Compiler does not yet support all features and can cause crashes or give incorrect results. + + + + Use at your own risk! + Use at your own risk! + + + + By checking this you also opt-in for additional performance telemetry + By checking this you also opt-in for additional performance telemetry + + + + Transparent Compiler Cache Factor + Transparent Compiler Cache Factor + + + + Higher number means more memory will be used for caching. Changing the value wipes cache. + Higher number means more memory will be used for caching. Changing the value wipes cache. + + + + Create new project snapshots from existing ones + Create new project snapshots from existing ones + + Remove unused open statements 移除未使用的 open 陳述式 @@ -282,6 +322,11 @@ 為未解析的識別碼建議名稱 + + Use Transparent Compiler (restart required) + Use Transparent Compiler (restart required) + + Cache parsing results (experimental) 快取剖析結果 (實驗性) diff --git a/vsintegration/tests/FSharp.Editor.Tests/CodeFixes/RemoveUnnecessaryParenthesesTests.fs b/vsintegration/tests/FSharp.Editor.Tests/CodeFixes/RemoveUnnecessaryParenthesesTests.fs index 8b9a4116264..69d6456e378 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/CodeFixes/RemoveUnnecessaryParenthesesTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/CodeFixes/RemoveUnnecessaryParenthesesTests.fs @@ -616,7 +616,8 @@ in x "([] : int list).Length", "([] : int list).Length" // DotLambda - "[{| A = x |}] |> List.map (_.A)", "[{| A = x |}] |> List.map _.A" + """_.ToString("x")""", """_.ToString("x")""" + """_.ToString(("x"))""", """_.ToString("x")""" // DotSet "(ref 3).Value <- (3)", "(ref 3).Value <- 3" @@ -1078,7 +1079,7 @@ in x |> id " - "x |> (id |> fun x -> x)", "x |> id |> fun x -> x" + "x |> (id |> fun x -> x)", "x |> (id |> fun x -> x)" "x |> (id <| fun x -> x)", "x |> (id <| fun x -> x)" "id <| (fun x -> x)", "id <| fun x -> x" "id <| (fun x -> x) |> id", "id <| (fun x -> x) |> id" @@ -1120,6 +1121,10 @@ in x "id (-(-x))", "id -(-x)" "id -(-x)", "id -(-x)" + "f <| (g << h)", "f <| (g << h)" + "x <> (y <> z)", "x <> (y <> z)" + "x > (y > z)", "x > (y > z)" + " let f x y = 0 f ((+) x y) z @@ -1191,6 +1196,8 @@ in x // DotLambda "[{| A = x |}] |> List.map (_.A)", "[{| A = x |}] |> List.map _.A" + """[1..10] |> List.map _.ToString("x")""", """[1..10] |> List.map _.ToString("x")""" + """[1..10] |> List.map _.ToString(("x"))""", """[1..10] |> List.map _.ToString("x")""" // DotSet "id ((ref x).Value <- y)", "id ((ref x).Value <- y)" @@ -1423,6 +1430,12 @@ let _ = (2 + 2) { return 5 } /// (x λ y) ρ z | OuterRight of l: string * r: string + /// Indicates whether both operators are the same exact symbolic operator. + member this.Identical = + match this with + | OuterLeft(l, r) + | OuterRight(l, r) -> l = r + override this.ToString() = match this with | OuterLeft(l, r) -> $"x {l} (y {r} z)" @@ -1471,11 +1484,11 @@ let _ = (2 + 2) { return 5 } | OuterLeft((":?" | ":>" | ":?>"), _) -> invalidPairing | OuterLeft(_, "**op") -> fixable pair | OuterLeft("**op", _) -> unfixable pair - | OuterLeft("*op", "*op") -> fixable pair + | OuterLeft("*op", "*op") -> if pair.Identical then fixable pair else unfixable pair | OuterLeft(("%op" | "/op" | "*op"), ("%op" | "/op" | "*op")) -> unfixable pair | OuterLeft(_, ("%op" | "/op" | "*op")) -> fixable pair | OuterLeft(("%op" | "/op" | "*op"), _) -> unfixable pair - | OuterLeft("+op", "+op") -> fixable pair + | OuterLeft("+op", "+op") -> if pair.Identical then fixable pair else unfixable pair | OuterLeft(("-op" | "+op"), ("-op" | "+op")) -> unfixable pair | OuterLeft(_, ("-op" | "+op")) -> fixable pair | OuterLeft(("-op" | "+op"), _) -> unfixable pair @@ -1484,14 +1497,15 @@ let _ = (2 + 2) { return 5 } | OuterLeft("::", _) -> unfixable pair | OuterLeft(_, ("^op" | "@op")) -> fixable pair | OuterLeft(("^op" | "@op"), _) -> unfixable pair - | OuterLeft(l & ("=op" | "|op" | "&op" | "$" | ">op" | "op" | " - if l = r then fixable pair else unfixable pair + | OuterLeft(("=op" | "|op" | "&op" | "$" | ">op" | "op" | " unfixable pair | OuterLeft(_, ("=op" | "|op" | "&op" | "$" | ">op" | " fixable pair | OuterLeft(("=op" | "|op" | "&op" | "$" | ">op" | " unfixable pair | OuterLeft(_, (":>" | ":?>")) -> fixable pair + | OuterLeft(("&" | "&&"), ("&" | "&&")) -> if pair.Identical then fixable pair else unfixable pair | OuterLeft(_, ("&" | "&&")) -> fixable pair | OuterLeft(("&" | "&&"), _) -> unfixable pair + | OuterLeft(("||" | "or"), ("||" | "or")) -> if pair.Identical then fixable pair else unfixable pair | OuterLeft(_, ("||" | "or")) -> fixable pair | OuterLeft(("||" | "or"), _) -> unfixable pair | OuterLeft(":=", ":=") -> fixable pair @@ -1524,11 +1538,14 @@ let _ = (2 + 2) { return 5 } let operators = [ "**" + "***" "*" + "*." "/" "%" "-" "+" + "++" ":?" "::" "^^^" diff --git a/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj b/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj index 77ce57f27e0..a180accc43f 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj +++ b/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj @@ -12,6 +12,7 @@ + @@ -71,6 +72,8 @@ + + diff --git a/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs b/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs index a0853ed83b9..ca113f72bf3 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Helpers/RoslynHelpers.fs @@ -304,6 +304,11 @@ type RoslynTestHelpers private () = let document = project.Documents |> Seq.exactlyOne document + static member GetLastDocument(solution: Solution) = + let project = solution.Projects |> Seq.exactlyOne + let document = project.Documents |> Seq.last + document + static member CreateSolution(syntheticProject: SyntheticProject) = let checker = syntheticProject.SaveAndCheck() diff --git a/vsintegration/tests/FSharp.Editor.Tests/QuickInfoTests.fs b/vsintegration/tests/FSharp.Editor.Tests/QuickInfoTests.fs index 083a25a07cf..8b24af5f117 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/QuickInfoTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/QuickInfoTests.fs @@ -50,12 +50,12 @@ module QuickInfo = | Some(ToolTipText elements) when not elements.IsEmpty -> let documentationBuilder = { new IDocumentationBuilder with - override _.AppendDocumentationFromProcessedXML(_, _, _, _, _, _) = () - override _.AppendDocumentation(_, _, _, _, _, _, _) = () + override _.AppendDocumentationFromProcessedXML(_, _, _, _, _, _, _) = () + override _.AppendDocumentation(_, _, _, _, _, _, _, _) = () } let _, mainDescription, docs = - XmlDocumentation.BuildSingleTipText(documentationBuilder, elements.Head, XmlDocumentation.DefaultLineLimits) + XmlDocumentation.BuildSingleTipText(documentationBuilder, elements.Head, XmlDocumentation.DefaultLineLimits, true) let mainTextItems = mainDescription |> Seq.map (fun x -> x.Text) let docTextItems = docs |> Seq.map (fun x -> x.Text) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/AddReturnTypeTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/AddReturnTypeTests.fs new file mode 100644 index 00000000000..5b81fb996da --- /dev/null +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/AddReturnTypeTests.fs @@ -0,0 +1,452 @@ +module FSharp.Editor.Tests.Refactors.AddReturnTypeTests + +open Microsoft.VisualStudio.FSharp.Editor +open Xunit +open FSharp.Editor.Tests.Refactors.RefactorTestFramework +open FSharp.Test.ProjectGeneration +open FSharp.Editor.Tests.Helpers + +[] +[] +[] +[] +[] +let ``Refactor should not trigger`` (shouldNotTrigger: string) = + let symbolName = "sum" + + let code = + $""" +let sum a b {shouldNotTrigger}= a + b + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let actions = tryGetRefactoringActions code spanStart context (new AddReturnType()) + + do Assert.Empty(actions) + +[] +let ``Refactor should not trigger on values`` () = + let symbolName = "example2" + + let code = + """ +let example2 = 42 // value + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let actions = tryGetRefactoringActions code spanStart context (new AddReturnType()) + + do Assert.Empty(actions) + +[] +let ``Refactor should not trigger on member values`` () = + let symbolName = "SomeProp" + + let code = + """ +type Example3() = + member _.SomeProp = 42 // property + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let actions = tryGetRefactoringActions code spanStart context (new AddReturnType()) + + do Assert.Empty(actions) + +[] +let ``Correctly infer int as return type`` () = + let symbolName = "sum" + + let code = + """ +let sum a b = a + b + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +let sum a b : int = a + b + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Correctly infer on next line arguments`` () = + let symbolName = "sum" + + let code = + """ +let sum + x y = + x + y + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +let sum + x y : int = + x + y + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Should not throw exception when binding another method`` () = + let symbolName = "addThings" + + let code = + """ +let add (x:int) (y:int) = (float(x + y)) + 0.1 +let addThings = add + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +let add (x:int) (y:int) = (float(x + y)) + 0.1 +let addThings : (int->int->float) = add + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Handle parantheses on the arguments`` () = + let symbolName = "sum" + + let code = + """ +let sum (a:float) (b:float) = a + b + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + """ +let sum (a:float) (b:float) : float = a + b + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Infer on rec method`` () = + let symbolName = "fib" + + let code = + $""" +let rec fib n = + if n < 2 then 1 + else fib (n - 1) + fib (n - 2) + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +let rec fib n : int = + if n < 2 then 1 + else fib (n - 1) + fib (n - 2) + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Infer with function parameter method`` () = + let symbolName = "apply1" + + let code = + $""" +let apply1 (transform: int -> int) y = transform y + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +let apply1 (transform: int -> int) y : int = transform y + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Infer on member function`` () = + let symbolName = "SomeMethod" + + let code = + $""" +type SomeType(factor0: int) = + let factor = factor0 + member this.SomeMethod(a, b, c) = (a + b + c) * factor + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +type SomeType(factor0: int) = + let factor = factor0 + member this.SomeMethod(a, b, c) : int = (a + b + c) * factor + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Binding another function doesnt crash`` () = + let symbolName = "getNow" + + let code = + $""" +let getNow() = + System.DateTime.Now + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +let getNow() : System.DateTime = + System.DateTime.Now + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Handle already existing opens for DateTime`` () = + let symbolName = "getNow" + + let code = + $""" +open System + +let getNow() = + DateTime.Now + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +open System + +let getNow() : DateTime = + DateTime.Now + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Binding linq function doesnt crash`` () = + let symbolName = "skip1" + + let code = + $""" +let skip1 elements = + System.Linq.Enumerable.Skip(elements, 1) + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +let skip1 elements : System.Collections.Generic.IEnumerable<'a> = + System.Linq.Enumerable.Skip(elements, 1) + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Handle already existing opens on Linq`` () = + let symbolName = "skip1" + + let code = + $""" +open System + +let skip1 elements = + Linq.Enumerable.Skip(elements, 1) + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +open System + +let skip1 elements : Collections.Generic.IEnumerable<'a> = + Linq.Enumerable.Skip(elements, 1) + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Handle already existing opens on Enumerable`` () = + let symbolName = "skip1" + + let code = + $""" +open System +open System.Linq + +let skip1 elements = + Enumerable.Skip(elements, 1) + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + $""" +open System +open System.Linq + +let skip1 elements : Collections.Generic.IEnumerable<'a> = + Enumerable.Skip(elements, 1) + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Correctly infer custom type that is declared earlier in file`` () = + let symbolName = "sum" + + let code = + """ +type MyType = { Value: int } +let sum a b = {Value=a+b} + """ + + use context = TestContext.CreateWithCode code + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + """ +type MyType = { Value: int } +let sum a b : MyType = {Value=a+b} + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode, resultText.ToString()) + +[] +let ``Correctly infer custom type that is declared earlier in project`` () = + let symbolName = "sum" + + let myModule = + """ +module ModuleFirst +type MyType = { Value: int } + """ + + let code = + """ +module ModuleSecond + +open ModuleFirst + +let sum a b = {Value=a+b} + """ + + let project = + { SyntheticProject.Create( + { sourceFile "First" [] with + Source = myModule + }, + { sourceFile "Second" [ "First" ] with + Source = code + } + ) with + AutoAddModules = false + } + + let solution, _ = RoslynTestHelpers.CreateSolution project + let context = new TestContext(solution) + + let spanStart = code.IndexOf symbolName + + let newDoc = tryRefactor code spanStart context (new AddReturnType()) + + let expectedCode = + """ +module ModuleSecond + +open ModuleFirst + +let sum a b : MyType = {Value=a+b} + """ + + let resultText = newDoc.GetTextAsync() |> GetTaskResult + Assert.Equal(expectedCode.Trim(' ', '\r', '\n'), resultText.ToString().Trim(' ', '\r', '\n')) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs new file mode 100644 index 00000000000..849da8c84ec --- /dev/null +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs @@ -0,0 +1,89 @@ +module FSharp.Editor.Tests.Refactors.RefactorTestFramework + +open System +open System.Linq +open System.Collections.Generic + +open Microsoft.CodeAnalysis +open Microsoft.CodeAnalysis.Text +open Microsoft.VisualStudio.FSharp.Editor.CancellableTasks + +open FSharp.Editor.Tests.Helpers +open Microsoft.CodeAnalysis.CodeRefactorings +open Microsoft.CodeAnalysis.CodeActions +open System.Threading + +let GetTaskResult (task: Tasks.Task<'T>) = task.GetAwaiter().GetResult() + +type TestContext(Solution: Solution) = + let mutable _solution = Solution + member _.CancellationToken = CancellationToken.None + + member _.Solution + with set value = _solution <- value + and get () = _solution + + interface IDisposable with + member _.Dispose() = Solution.Workspace.Dispose() + + static member CreateWithCode(code: string) = + let solution = RoslynTestHelpers.CreateSolution(code) + new TestContext(solution) + + static member CreateWithCodeAndDependency (code: string) (codeForPreviousFile: string) = + let mutable solution = RoslynTestHelpers.CreateSolution(codeForPreviousFile) + + let firstProject = solution.Projects.First() + solution <- solution.AddDocument(DocumentId.CreateNewId(firstProject.Id), "test2.fs", code, filePath = "C:\\test2.fs") + + new TestContext(solution) + +let tryRefactor (code: string) (cursorPosition) (context: TestContext) (refactorProvider: 'T :> CodeRefactoringProvider) = + cancellableTask { + let mutable action: CodeAction = null + let existingDocument = RoslynTestHelpers.GetLastDocument context.Solution + + context.Solution <- context.Solution.WithDocumentText(existingDocument.Id, SourceText.From(code)) + + let document = RoslynTestHelpers.GetLastDocument context.Solution + + let mutable workspace = context.Solution.Workspace + + let refactoringContext = + CodeRefactoringContext(document, TextSpan(cursorPosition, 1), (fun a -> action <- a), context.CancellationToken) + + do! refactorProvider.ComputeRefactoringsAsync refactoringContext + + let! operations = action.GetOperationsAsync context.CancellationToken + + for operation in operations do + let codeChangeOperation = operation :?> ApplyChangesOperation + codeChangeOperation.Apply(workspace, context.CancellationToken) + context.Solution <- codeChangeOperation.ChangedSolution + () + + let newDocument = context.Solution.GetDocument(document.Id) + return newDocument + + } + |> CancellableTask.startWithoutCancellation + |> GetTaskResult + +let tryGetRefactoringActions (code: string) (cursorPosition) (context: TestContext) (refactorProvider: 'T :> CodeRefactoringProvider) = + cancellableTask { + let refactoringActions = new List() + let existingDocument = RoslynTestHelpers.GetLastDocument context.Solution + + context.Solution <- context.Solution.WithDocumentText(existingDocument.Id, SourceText.From(code)) + + let document = RoslynTestHelpers.GetLastDocument context.Solution + + let refactoringContext = + CodeRefactoringContext(document, TextSpan(cursorPosition, 1), (fun a -> refactoringActions.Add a), context.CancellationToken) + + do! refactorProvider.ComputeRefactoringsAsync refactoringContext + + return refactoringActions + } + |> CancellableTask.startWithoutCancellation + |> fun task -> task.Result diff --git a/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs b/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs index d062f26a0bd..af66c01ed69 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/SignatureHelpProviderTests.fs @@ -16,8 +16,8 @@ open Microsoft.VisualStudio.FSharp.Editor.CancellableTasks module SignatureHelpProvider = let private DefaultDocumentationProvider = { new IDocumentationBuilder with - override doc.AppendDocumentationFromProcessedXML(_, _, _, _, _, _) = () - override doc.AppendDocumentation(_, _, _, _, _, _, _) = () + override doc.AppendDocumentationFromProcessedXML(_, _, _, _, _, _, _) = () + override doc.AppendDocumentation(_, _, _, _, _, _, _, _) = () } let checker = FSharpChecker.Create() @@ -56,7 +56,8 @@ module SignatureHelpProvider = DefaultDocumentationProvider, sourceText, caretPosition, - triggerChar + triggerChar, + EditorOptions() ) |> Async.RunSynchronously @@ -123,7 +124,8 @@ module SignatureHelpProvider = DefaultDocumentationProvider, sourceText, caretPosition, - triggerChar + triggerChar, + EditorOptions() ) |> Async.RunSynchronously @@ -155,13 +157,18 @@ module SignatureHelpProvider = |> CancellableTask.runSynchronouslyWithoutCancellation let adjustedColumnInSource = - let rec loop ch pos = - if Char.IsWhiteSpace(ch) then - loop sourceText.[pos - 1] (pos - 1) - else + let rec loop pos = + if pos = 0 then pos + else + let nextPos = pos - 1 - loop sourceText.[caretPosition - 1] (caretPosition - 1) + if not (Char.IsWhiteSpace sourceText[nextPos]) then + pos + else + loop nextPos + + loop (caretPosition - 1) let sigHelp = FSharpSignatureHelpProvider.ProvideParametersAsyncAux( @@ -175,7 +182,8 @@ module SignatureHelpProvider = sourceText, caretPosition, adjustedColumnInSource, - filePath + filePath, + EditorOptions() ) |> Async.RunSynchronously @@ -440,8 +448,8 @@ type foo5 = N1.T module ``Function argument applications`` = let private DefaultDocumentationProvider = { new IDocumentationBuilder with - override doc.AppendDocumentationFromProcessedXML(_, _, _, _, _, _) = () - override doc.AppendDocumentation(_, _, _, _, _, _, _) = () + override doc.AppendDocumentationFromProcessedXML(_, _, _, _, _, _, _) = () + override doc.AppendDocumentation(_, _, _, _, _, _, _, _) = () } [] @@ -518,7 +526,8 @@ M.f sourceText, caretPosition, adjustedColumnInSource, - filePath + filePath, + EditorOptions() ) |> Async.RunSynchronously @@ -548,6 +557,18 @@ M.f let marker = "List.map " assertSignatureHelpForFunctionApplication fileContents marker 1 0 "mapping" + [] + let ``function application in middle of pipeline with two additional arguments`` () = + let fileContents = + """ +[1..10] +|> List.fold (fun acc _ -> acc) +|> List.filter (fun x -> x > 3) + """ + + let marker = "List.fold (fun acc _ -> acc) " + assertSignatureHelpForFunctionApplication fileContents marker 2 1 "state" + [] let ``function application with function as parameter`` () = let fileContents =